首页 文章

如何在Firefox Add On On中设置javascript变量使用Add On SDK创建? [重复]

提问于
浏览
4

这个问题在这里已有答案:

我正在尝试设置一个javascript变量来识别安装了Firefox扩展 . 想法是在页面上读取此变量 .

在使用XUL附加组件(Set an object in a page's window object from a Firefox extension?)时无法使用复杂的方法实现这一点,并在Firefox Add On SDK中找到适合该任务的contentScripts,我仍然无法访问页面上的contentScript中设置的javascript变量 .

我的main.js中有以下内容(使用此处提供的示例https://addons.mozilla.org/en-US/developers/docs/sdk/latest/modules/sdk/page-mod.html):

var pageMod = require("sdk/page-mod");

pageMod.PageMod({
  include: "*",
  contentScript: 'window.isInstalled=true;window.alert("Page matches ruleset");',
  contentScriptWhen: "ready"
});

但是,当我尝试在页面上的javascript中获取 window.isInstalled 变量时,尽管显示了警报,但它仍未定义 .

How to ensure that the value written by the content script will be available on a page?

1 回答

  • 6

    内容脚本中的 window 对象通常为 XRayWrapper ,这意味着您将看到对 window 对象所做的任何修改 .

    但是, unsafeWindow.isInstalled = ... 应该有效(尽管 .isInstalled 非常通用,因此可能与网站已经使用的变量发生冲突) .

    有关 XRayWrapperunsafeWindow ,请参阅docs .

    解决@canuckistani提出的非常有效的问题:

    unsafeWindow 读取数据或执行其功能是安全的,因为它不能直接导致在另一个(您的内容脚本)隔间中执行代码 . 蜘蛛侠's compartments will make sure of that. Everything else would be a security issue within either Spidermonkey or Gecko. (Please note that this refers to Spidermonkey only. IIRC it is the only engine to implement compartments or membranes or whatever you' d喜欢叫它 . 其他引擎可能具有其他安全属性) .

    但是,您绝不能信任来自网站的数据 . unsafeWindow 只是有更多方法可以帮助你 . 总是除了要抛出的代码,拒绝为您提供意外的无限循环或类似的东西,永远不会明确或隐含地评估您的上下文中的代码 .

    例如 . 这是一个安全漏洞,无论您使用window还是unsafeWindow:

    for (var el of window.document.querySelectorAll("*[onclick]")) {
      el.addEventListener("click", el.getAttribute("onclick"));
      el.removeAttribute("onclick");
    }
    

    这将在脚本上下文中从网站控制的字符串( .getAttribute )创建匿名函数(事件侦听器),而不是网站的上下文 .

    这也是不安全的,但这次只有在使用_719349时:

    for (var el of unsafeWindow.document.querySelectorAll("p")) {
      el.addEventListener("click", 'alert("I am ' + el.clientHeight + 'px tall");');
      el.removeAttribute("onclick");
    }
    

    使用 XRayWrapper 包装 window 时,可以确定 document 实际上是文档, document.querySelectorAll 实际上是一个函数吐出一些元素而 el.clientHeight 实际上是一个数值 .

    通过 unsafeWindow 所有这些假设可能都是不正确的 . 该网站可能做过这样的事情:

    document.querySelectorAll = function() {
      return [{
        clientHeight: 'a pwnd content script"); doSomethingEvil(); alert("Now I own you! And I am certainly not 0'
      }];
    };
    

    虽然在权限升级意义上执行 unsafeWindow.document.querySelectorAll 仍然是安全的,因为被覆盖的函数仍将在网站的隔离区(安全上下文)内运行,但返回值根本不可信 .

    或者脚本可能已经做了其他事情来破坏你的东西,不一定是恶意的 . 例如 . 你的off-the-shell拒绝服务 .

    Object.defineProperty(document, "title", {
      get: function() { while(true); }
    });
    // or
    Object.defineProperty(document, "title", {
      get: function() { throw new Error("get off my lawn!"); }
    });
    

相关问题