Chrome 扩展:连接“内容脚本”注入 DOM
我意识到我们可以从内容脚本处理共享 DOM(根据手册)。
我们可以通过以下方式将注入的 DOM 内容与我们的内容脚本连接起来
element.addEventListener('click',function(){ ourController.fnCallback(); });
// or
element.onclick = ourController.fnCallback;
但是当注入的 DOM 实现类似这样的东西时:
<a href="javascript:ourController.fnCallback();">Click Me!</a>
抛出的错误是 cannot call fnCallback() on undefined ourController
(not strict rewriting error messages)
有没有办法我们可以像我在第二个例子中尝试的那样从注入的 dom 与我们的 javascript 对象进行通信吗?
对象在 content_script.js
中定义如下:
var ourController = {
fnCallback: function(){
// code here
}
};
并且此代码直接放置在根据清单加载的脚本中,如下所示:
"content_scripts": [ {
"js": [ "content_script.js" ],
"matches": [ "http://*/*", "https://*/*", "ftp://*/*" ],
"run_at": "document_start"
}],
I realized we can work at shared DOM (according to manual) from content scripts.
We can connect injected DOM content with our Content Scripts via
element.addEventListener('click',function(){ ourController.fnCallback(); });
// or
element.onclick = ourController.fnCallback;
But when injected DOM implements something like this:
<a href="javascript:ourController.fnCallback();">Click Me!</a>
thrown error is cannot call fnCallback() on undefined ourController
(not exactly rewritten error messages)
Is there aby way we can communicate with our javascript object from injected dom like i tried in second example?
Object is defined in content_script.js
like this:
var ourController = {
fnCallback: function(){
// code here
}
};
and this code is placed directly in script loaded according to manifest like this:
"content_scripts": [ {
"js": [ "content_script.js" ],
"matches": [ "http://*/*", "https://*/*", "ftp://*/*" ],
"run_at": "document_start"
}],
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这个问题的解决方案来自文档:
执行环境
因此任何注入的内容都无法与内容脚本一起使用。唯一的解决方案是使用这样的代码来自内容脚本
它将添加可以与content_script通信的点击事件函数
Solution to this problem comes out from documentation:
Execution environment
So any injected content is not able to work with content script. Only solution is to use code like this from withing content scripts
It will add click-event function which can communicate with content_script