如何动态注入JavaScript函数?

Ang*_*ker 2 javascript google-chrome javascript-events userscripts

我在工作中使用具有可怕UI的产品并试图通过Chrome中的UserScripts使其变得美味.为此,我试图通过UserScripts机制将JavaScript函数注入页面:

// 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()' >";
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我正在注入一个按钮和一个函数(gotoIncident),当用户单击该按钮时它将触发.

按钮确实出现在屏幕上但是当我点击它时,javascript调试器告诉我gotoIncident没有定义.

我错过了什么?

Mat*_*all 7

<script>标记注入<head>包含自调用函数的标记:

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

script.src = 'path/to/script.js';    
head.appendChild(script);
Run Code Online (Sandbox Code Playgroud)

引用的脚本看起来像这样:

(function(){
    // do your stuff here    
})();
Run Code Online (Sandbox Code Playgroud)

编辑

如何将其作为内联脚本:

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

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

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

演示