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

时间:2014-02-12 15:06:37

标签: 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
}

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

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

2 个答案:

答案 0 :(得分: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].
});

答案 1 :(得分:2)

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

实现此目的的正确方法是通过window.postMessage API与页面进行通信。我将如何解决这个问题:

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

相关问题