【发布时间】:2016-07-25 21:22:59
【问题描述】:
我正在开发浏览器扩展/插件。我们让它在 Chrome 中运行,所以我正在尝试让它在 Firefox 中运行。
我的插件已加载到 Firefox Developer Edition 49.0a2 (2016-07-25)。
我的扩展涉及一个 content_script 设置为run_at: document_start,所以它可以在其他页面脚本运行之前注入一个脚本标签,这样它就可以使一个对象对网站全局可用。
这在 Chrome 中似乎运行良好,但在 Firefox 中已被证明有点竞争条件,大多数时间其他页面资源首先加载。
是否有一种策略来加载内容脚本,使其可以在任何其他页面脚本运行之前注入和加载脚本?
当我添加日志时,我可以很好地隔离正在发生的事情。在此示例内容脚本中:
// inject in-page script
console.log('STEP 1, this always happens first')
var scriptTag = document.createElement('script')
scriptTag.src = chrome.extension.getURL('scripts/inpage.js')
scriptTag.onload = function () { this.parentNode.removeChild(this) }
var container = document.head || document.documentElement
// append as first child
container.insertBefore(scriptTag, container.children[0])
现在如果文件scripts/inpage.js 只是运行一个日志,比如
console.log('STEP 2, this should always run second')
我访问了一个带有这样脚本的页面:
console.log('Step 3, the page itself, should run last')
在实践中,第 2 步和第 3 步以不确定的顺序运行。
非常感谢!
如果你敢自己尝试的话,我在一个特殊分支的公共存储库中有 Firefox 兼容版本的脚本:https://github.com/MetaMask/metamask-plugin/tree/FirefoxCompatibility
【问题讨论】:
-
这是我在当前页面中添加脚本标记的行。当我使用日志执行此操作时,我确实看到此代码在页面脚本之前运行,但注入的脚本本身并不总是在页面脚本之前运行。 github.com/MetaMask/metamask-plugin/blob/FirefoxCompatibility/…
标签: firefox-addon content-script firefox-addon-webextensions