运行 JavaScript 在当前页面上一次从 Firefox 加载 Android 附加组件

Running JavaScript on current page once loaded from a Firefox for Android add-on

我想 运行 JavaScript 在浏览器中加载的每个页面上。 JavaScript 应该只在页面加载后 运行 并且需要访问 DOM.

中的所有元素

我能够在 Scratchpad 中成功执行以下 JavaScript,尽管在将其移植到我的 bootstrap.js 时遇到问题。

// Use the current content window as the execution context.
// To make properties defined by scripts executing on the page
// available to your sandbox script, use content.wrappedJSObject
// instead.
let context = content;

// Create the Sandbox
let sandbox = Components.utils.Sandbox(context, {
    // Make properties of the context object available via the
    // script's global scope
    sandboxPrototype: context,
    // Wrap objects retrieved from the sandbox in XPCNativeWrappers.
    // This is the default action.
    wantXrays: true
});

// The script that will be executed:
let script = "document.body.style.background = 'red'; alert('test')";

// Evaluate the script:
Components.utils.evalInSandbox(script, sandbox,
                               // The JavaScript version
                               "1.8",
                               // The apparent script filename:
                               "zz-9://plural/zed/alpha",
                               // The apparent script starting line number:
                               42);

任何人都可以解释一下上面的代码究竟需要放在 bootstrap.js 中的什么地方吗?

你需要用它制作一个框架脚本,这是一个完整的例子,你将在 DOM 中执行的脚本应该进入 contentscript.js 文件:https://github.com/Noitidart/modtools

如果你使用 addon-sdk,它会为你处理这个,我不想这样做,但这就是我上面链接的 repo 这样做的原因。