问题
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 + " <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