这是一个非常简单的例子:
list .json
{
...
"content_scripts": [
{
"js": [
"/js/external/jquery-2.1.3.min.js",
"/js/content_script.js"
],
...
}
],
...
}
content_script.js
function demo() {
alert('demo');
}
$(function() {
$( "body" ).prepend(
"<input type=\"button\" value=\"Press me\" onclick=\"demo()\" />"
);
});
我在控制台中收到此错误:
Uncaught ReferenceError: demo is not defined
如何让功能发挥作用?
最佳答案
这里的问题是Isolated Worlds .
内容脚本有自己的 JS 上下文。您定义 demo
在内容脚本上下文中。
但是,当添加这样的 DOM 节点时,onclick
属性将引用页面上下文,它没有 demo
功能。
这里有很多选择。
最简单的方法是在内容脚本上下文中将监听器附加到节点:
var node = $('<input type="button" value="Press me"/>').click(demo); $("body").prepend(node);
另一种方法是定义
demo()
在页面上下文中。为此,您需要 inject the code to the page context通过<script>
标签。var script = document.createElement('script'); script.textContent = demo.toString(); (document.head||document.documentElement).appendChild(script); script.parentNode.removeChild(script);
请注意,此代码无法访问内容脚本上下文和 Chrome API。但是,它可能会有用,因为它可以访问页面自己的 JavaScript。
如果您需要两者的结合(访问页面和内容脚本),您需要 make the two contexts communicate .
关于javascript - 从新的 dom 按钮调用内容脚本函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27984542/