javascript - 为什么从 Chrome 扩展的内容脚本动态注入(inject) jQuery 后我无法使用它?

标签 javascript google-chrome google-chrome-extension

当在页面上以通常的方式作为脚本运行时,此代码会在动态注入(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 与其他代码隔离一样)

我的问题:

  1. 为什么会发生这种情况?

  2. 如何绕过(或任何解决方案)它?
    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/

相关文章:

javascript - 如何优化 Canvas 上的动画? HTML 5

javascript - "Uncaught ReferenceError: $ is not defined"与另一个错误

javascript - jQuery UI Sortable,释放鼠标按钮事件?

css - 添加了 jQuery 填充的 HTML 更新行为很奇怪。 ( Chrome )

google-chrome - 如何调试 page_action chrome 扩展

javascript - Chrome 扩展解析 RSS

javascript - 退出前捕获 Electron 窗口的屏幕截图

javascript - 鼠标悬停在页面上的元素上是否刷新而不移动它?

iOS 共享扩展在 Chrome 中不起作用

javascript - 无法抓取网页上类元素中的文本 - Chrome 扩展