当在页面上以通常的方式作为脚本运行时,此代码会在动态注入(inject)到页面后打印 jQuery 的版本。但是在我的 chrome 扩展中,当我在动态注入(inject) jQuery 后尝试打印它的版本时,输出是 未定义
。
// create iframe
var frame = document.createElement("iframe");
// when frame loads
frame.addEventListener("load", function() {
// create script to dynamically inject into DOM
var script = frame.contentWindow.document.createElement("script");
// when script loads print jquery version
script.addEventListener("load", function() {
console.log(frame.contentWindow.$.fn.jquery); // output -> 2.2.1
});
frame.contentWindow.document.head.appendChild(script);
script.src = "https://code.jquery.com/jquery-2.2.1.js";
});
document.body.appendChild(frame);
所以这是我的问题:
我必须动态地将一些代码(我使用 jQuery 作为示例)注入(inject)到 iframe 中,因为我需要它具有 iframe.contentWindow
的正确上下文作为窗口。
问题是,每当我尝试使用使用frame.contentWindow.someModule
(在本例中)的脚本创建的全局变量时,例如someModule.js它是 frame.contentWindow.$
因为我注入(inject)了 jQuery 源代码)它是未定义的。我认为这与它是一个 chrome 扩展有关(就像 chrome 扩展 javascript 与其他代码隔离一样)
我的问题:
为什么会发生这种情况?
如何绕过(或任何解决方案)它?
2.1.如何动态添加 JavaScript(文件或某些代码),以便它位于 iFrame 的上下文中(而不是父窗口)。我必须在运行时执行此操作,因为它是带有内容脚本的 chrome 扩展。
或者我可以直接在 iframe 中运行 chrome 扩展内容脚本吗?
修改上面的代码: https://jsfiddle.net/wj83oytd/5/
最佳答案
发现问题,
Content scripts execute in a special environment called an isolated world. They have access to the DOM of the page they are injected into, but not to any JavaScript variables or functions created by the page. It looks to each content script as if there is no other JavaScript executing on the page it is running on. The same is true in reverse: JavaScript running on the page cannot call any functions or access any variables defined by content scripts.
https://developer.chrome.com/extensions/content_scripts#execution-environment
解决方案,
动态注入(inject)您想要作为内联 JavaScript 代码运行的代码,而不是在内容脚本中运行
无效的代码:
// calling it in the content-script
console.log(frame.contentWindow.$.fn.jquery); // undefined
解决方案:
var script = frame.contentWindow.document.createElement("script");
script.innerHTML = "console.log(window.$.fn.jquery);"; // set script code
// adding it to the frame and running it in it's context
frame.contentWindow.document.body.appendChild(rmptipScript); // injects the code
// prints 2.2.1
关于javascript - 为什么从 Chrome 扩展的内容脚本动态注入(inject) jQuery 后我无法使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35665714/