如何动态注入JavaScript函数?
我在工作中一直使用一个 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 + " <input type='button' name='btnSearch' value='Go' onClick='javascript:gotoIncident()' >";
如您所见,我正在注入一个按钮和一个函数 (gotoIncident
),当用户单击按钮。
该按钮确实出现在屏幕上,但当我单击它时,JavaScript 调试器告诉我 gotoIncident
未定义。
我缺少什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将
标记插入到
中,其中包含自调用函数:
引用的脚本如下所示:
编辑
如何执行此操作内联脚本:
演示
Inject a
<script>
tag into the<head>
which contains a self-invoking function:Where the referenced script looks something like this:
Edit
How to do it as an inline script:
Demo
您需要在全局范围内定义该函数(将其放在 部分)才能在您执行的操作中使用它。
You need to define the function in the global scope (put it in the <head> section) to use it where you do.
作为参考,我通过以下方式解决了它:
}
For reference I resolved it the following way:
}