Chrome 扩展更新流程

Chrome extension update flow

我从 chrome 扩展开发开始,有几个关于扩展 install/update 流程和开发期间测试的问题:

  1. 扩展更新后后台脚本发生了什么,chrome 执行后台脚本重新加载吗?
  2. 扩展更新后内容脚本是否与后台脚本分离?
  3. 如果后台脚本中有一个 onInstalled 事件处理程序,当 chrome 更新扩展时该事件处理程序会发生什么(这个事件处理程序是否已分离,更新完成后,新的处理程序将被附加并执行,或者执行了一些其他流程)?
  4. 有没有办法在开发过程中模拟更新过程,以便调试更新过程中发生的事件,例如在某些本地服务器上托管扩展并从那里更新?
  5. 在哪里可以搜索有关此类主题和类似主题的文档,铬源代码是正确的地方还是至少是起点?

谢谢!

  1. What happens with the background script after extension update, does Chrome perform background script reload?

该行为取决于您是否注册了 chrome.runtime.onUpdateAvailable event 处理程序以及您的扩展程序是否具有持久的后台页面或事件页面。

  • 如果你有一个持久的后台页面:
    • 如果您处理此事件并调用 chrome.runtime.reload(),扩展将被卸载并在再次加载之前进行更新。
    • 如果您处理此事件而不调用 chrome.runtime.reload(),则更新将仅在下一次重新加载扩展时应用 - 可能是下一次完整的浏览器重新启动。
    • 如果您根本不处理此事件,将立即卸载扩展以进行更新。
  • 如果您有一个非持久性事件页面:
    • 如果您处理此事件并调用 chrome.runtime.reload(),扩展将在再次加载之前更新。
    • 如果您不调用 chrome.runtime.reload(),或者根本不处理事件,Chrome 将在事件页面下次卸载时更新扩展。

无论出于何种原因卸载后台页面后,都无法以编程方式阻止更新。

  1. Are content scripts detached from background script after extension update?

是的,它并不漂亮。它们在使用 Chrome 时进入 "orphaned" 状态 API 给出不一致的错误(有些什么都不做,有些触发异常),但仍然是 运行 — 例如,任何 DOM 事件侦听器仍会触发。

因此,如果您希望内容脚本立即再次运行,您的工作是:

  • 在现有选项卡中以编程方式注入脚本,而不假设它之前没有执行:必要时先清理。
  • 确保孤立副本停止执行:通过在旧副本中注意到它是孤立的,或者通过从新副本广播 DOM 事件。

关于 WebExtensions 的重要说明: Firefox 与 Chrome 不同,总是 在加载到匹配清单的页面时重新注入内容脚本条目。请务必考虑到这一点。

有几个问题涵盖了这个;例如:

  • Sending message from a background script to a content script, then to a injected script (See addendum to the answer)
  • How to properly handle chrome extension updates from content scripts
  • Chrome extension content script re-injection after upgrade or install
  1. If there's an onInstalled event handler in background script, what happens with that event handler when chrome updates extension (is this event handler detached, and when update finishes, the new handler is attached and then executed or some other flow is exercised)?

由于更新只能在后台页面卸载时发生,所以没有复杂的逻辑;它会在 details.reason == "update" 之后第一次加载扩展时简单地触发。确保在脚本加载时同步注册处理程序(例如在顶层代码中),否则您可能会错过事件 — 通常这只涉及事件页面,但我怀疑它在这里也很重要。

  1. Is there a way to simulate update process during development in order to debug events that happen during the update process, for example to host extension on some local server and update from there?

遗憾的是,据我所知这不再可能,除非您可以使用 Enterprise Policy install。您最好的选择是在 CWS 中有一个发布为 Private 的扩展。

在某种程度上,在对解压缩的扩展进行一些更改后按 "Reload" 可以模拟更新期间发生的情况 - onInstalled 事件除外。

  1. Where to search for documentation on topics like this and similar, is the chromium source code the right place or at least the starting point?

嗯.. 详细问题Chromium代码当然是权威来源。您也应该搜索 Whosebug,因为这里已经积累了相当多的知识。最后,官方文档提供了很多信息,即使不是很明显 - 例如 chrome.runtime API docs