我正在开发浏览器扩展/附加组件。我们让它在 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