如何在页面代码运行firefox扩展之前注入导航器对象

时间:2017-10-28 05:28:39

标签: javascript firefox firefox-addon firefox-addon-sdk selenium-firefoxdriver

我想在加载页面内容之前在浏览器的所有选项卡/窗口上向导航器对象注入一个元素。例如:

window.navigator.myCustomObject = "this is my data";

我找到了一个例子,但是这段代码不支持bootstrapped扩展如何对引导扩展做同样的事情?

bootstrap.js:

function startup(data, reason) {

// some magic here

}

我尝试在启动功能中复制此代码无效。我想窗口。对象没有在这里定义,我没有找到如何做到这一点:( firefox-webdriver插件的示例代码:

// This will configure a FirefoxDriver and DomMessenger for each
// _browser window_ (not chrome window). Multiple tabs in the same window will
// share a FirefoxDriver and DomMessenger instance.
window.addEventListener('load', function(e) {
  // http://w3c.github.io/webdriver/webdriver-spec.html#security-and-privacy
  var appcontent = document.getElementById('appcontent');
  if (appcontent) {
    appcontent.addEventListener('DOMContentLoaded', function(e) {
      var doc = e.originalTarget || e.target;
      var isSvg = doc.documentElement.nodeName == 'svg';
      var script = isSvg ?
          doc.createElementNS('http://www.w3.org/2000/svg', 'script') :
          doc.createElement('script');
      script.setAttribute('type', 'text/javascript');
      script.textContent = '(' + function() {
        Object.defineProperty(window.navigator, 'webdriver', {
          value: true,
          configurable: false,
          enumerable: true,
          writable: false
        });
      } + ')()';
      doc.documentElement.appendChild(script);
      doc.documentElement.removeChild(script);
    });
  }
});

编辑:我找到了Addon-SDK的解决方案:

const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
let myObserver =
    {
        QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver, Ci.nsISupportsWeakReference]),
        observe: function(subject, topic, data)
        {
            if (topic === "content-document-global-created" && subject instanceof Ci.nsIDOMWindow /*&& subject.location.hostname === "example.com"*/)
            {
                XPCNativeWrapper.unwrap(subject).navigator.webdriver = true;
                XPCNativeWrapper.unwrap(subject).navigator.oglum = function() { return "babacim"; };
            }
        }
    };
let observerService = Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService);
observerService.addObserver(myObserver, "content-document-global-created", true);

0 个答案:

没有答案