How to dynamically inject a JavaScript function?

筅森魡賤 提交于 2019-12-09 07:55:57

问题


I am stuck using a product with a horrible UI at work and trying to make it palatable via UserScripts in Chrome. To that end, I am trying to inject a JavaScript function into the page via the UserScripts mechanism:

// find the div
var dropDown = document.getElementById("tstGlobalNavigation_ddlChooseProject");

// inject function
dropDown.innerHTML = dropDown.innerHTML + "<script>function gotoIncident(){alert('111')}</script>";        

// inject a button
dropDown.innerHTML = dropDown.innerHTML + "&nbsp;&nbsp;&nbsp;<input type='button' name='btnSearch' value='Go' onClick='javascript:gotoIncident()' >";

As you can see I am injecting a button and a function (gotoIncident) that should fire when the user clicks the button.

The button does appear on the screen but when I click it, the javascript debugger tells me that gotoIncident is not defined.

What am I missing?


回答1:


Inject a <script> tag into the <head> which contains a self-invoking function:

var head = document.getElementsByTagName('head')[0],
    script = document.createElement('script');

script.src = 'path/to/script.js';    
head.appendChild(script);

Where the referenced script looks something like this:

(function(){
    // do your stuff here    
})();

Edit

How to do it as an inline script:

function fn() {
    alert('hello JS');
}

var head = ...,
    script = ...;

// FF doesn't support innerText
script[script.innerText ? 'innerText' : 'textContent'] = '(' + fn + ')()';
head.appendChild(script);

Demo




回答2:


You need to define the function in the global scope (put it in the <head> section) to use it where you do.




回答3:


For reference I resolved it the following way:

myDiv.innerHTML = myDiv.innerHTML + " <input type='text' id='txtSearch' name='txtSearch' style='position:absolute;top:8px;left:800px;width:50px' >";
myDiv.innerHTML = myDiv.innerHTML + " <input type='button' name='btnSearch' value='Go' onclick='fn()' style='position:absolute;top:8px;left:860px;width:35px'>";

addScript("function fn() {var obj = document.getElementById('txtSearch'); "
  + "if (obj != null) { "
  + "  var incidentId = document.getElementById('txtSearch').value; "
  + "  var currentURL = location.href; "
  + "  var splitResult = currentURL.split('/'); "
  + "  var projectId = splitResult[4]; "
  + "  location.href = 'http://site/SpiraTeam/' + projectId + '/Incident/' + incidentId + '.aspx'; "
  + " } }"
  , "fn");

}



来源:https://stackoverflow.com/questions/5574231/how-to-dynamically-inject-a-javascript-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!