Chrome扩展程序 - 从扩展程序访问文档/页面变量

Tom*_*iak 11 javascript google-chrome google-chrome-extension

我正在尝试开发仅适用于指定页面的扩展 - 如果页面所有者将全局变量添加到其代码中(例如.ACCEPT_STATS = true;)我想执行指定的代码.

我已经将我的函数绑定到onload事件,我还在Firefox中找到了解决方法:

var win = window.top.getBrowser().selectedBrowser.contentWindow;
if (typeof win.wrappedJSObject.ACCEPT_STATS !== 'undefined') {
    // code to run if global variable present
}
Run Code Online (Sandbox Code Playgroud)

但我无法在Chrome下完成这项工作.有没有可能访问文档的全局变量抛出Chrome扩展代码?

我的扩展程序代码作为内容脚本注入.

Pat*_*tCP 15

是的,包括页面中的脚本确实在页面运行时脚本的隔离上下文中运行.

但是,可以通过附加到文档的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].
});
Run Code Online (Sandbox Code Playgroud)


Tru*_*nse 3

页面上运行的 javascript 与您使用内容脚本注入的 javascript 运行在不同的“隔离世界”中。出于安全原因,Google Chrome 将这两个世界分开,因此您不能只在任何窗口上读取 window.XYZ。有关孤立世界如何运作的更多信息:http://www.youtube.com/watch? v=laLudeUmXHM

实现此目的的正确方法是通过 window.postMessage API 与页面进行通信。我将这样做:

  1. 将内容脚本注入每个选项卡
  2. 通过 window.postMessage 向选项卡发送消息
  3. 如果页面理解此消息,它将正确响应(再次通过 window.postMessage)
  4. 内容脚本执行它需要执行的代码。

华泰