是,包括脚本到页面并运行从网页运行脚本一个孤立的环境。
但是,可以通过将内联脚本通过附加到文档的html脚本标签推入运行时上下文来解决孤立的世界问题。该内联脚本然后可以抛出一个自定义事件。
孤立的上下文中包含的脚本可以监听该事件并相应地作出响应。
因此,在你包含脚本代码会是这个样子:
// inject code into "the other side" to talk back to this side;
var scr = document.createElement('script');
//appending text to a function to convert it's src to string only works in Chrome
scr.textContent = '(' + function() {
var check = [do your custom code here];
var event = document.createEvent("CustomEvent");
event.initCustomEvent("MyCustomEvent", true, true, {"passback":check});
window.dispatchEvent(event); } + ')();'
//cram that sucker in
(document.head || document.documentElement).appendChild(scr);
//and then hide the evidence as much as possible.
scr.parentNode.removeChild(scr);
//now listen for the message
window.addEventListener("MyCustomEvent", function (e) {
var check = e.detail.passback;
// [do what you need to here].
});
这听起来象是一个内容脚本应该做的,不是吗? https://developer.chrome.com/extensions/content_scripts.html –
“但是,内容脚本有一些限制,它们不能:[...] 使用由网页或其他内容脚本定义的变量或函数” – kmoe
内容脚本在_isolated world_中执行。你将不得不将代码注入页面。 –