如何让Chrome应用程序尽快更新?

17

部署Chrome打包应用并在Chrome Web商店发布更新,使用户可以自动接收应用程序更新。有一些情况下你需要知道运行的应用程序是否是最新版本,以及如何进行更新,例如:

  • 仅保持用户处于最新版本。
  • 检测应用程序与服务器端API之间的不匹配,并要求客户端应用程序更新以使用新的服务器端API。

chrome.runtime.requestUpdateCheck()的文档提供了"throttled""no_update""update_available"的状态,但没有指示如果需要更新到新版本应该怎么做。

4个回答

31

安装监听器 chrome.runtime.onUpdateAvailable,当新的 .crx 文件已下载并准备好安装新版本时触发。然后调用 chrome.runtime.requestUpdateCheck

chrome.runtime.onUpdateAvailable.addListener(function(details) {
  console.log("updating to version " + details.version);
  chrome.runtime.reload();
});

chrome.runtime.requestUpdateCheck(function(status) {
  if (status == "update_available") {
    console.log("update pending...");
  } else if (status == "no_update") {
    console.log("no update found");
  } else if (status == "throttled") {
    console.log("Oops, I'm asking too frequently - I need to back off.");
  }
});

2
“throttled” 的文档在哪里?你怎么知道它的含义是什么? - cprcrack
1
“throttled”状态仅在http://developer.chrome.com/apps/runtime.html#method-requestUpdateCheck中被提及,作为可能的返回值之一。它意味着你请求得太频繁了,而Chrome为了避免过多的网络获取来检查是否有更新,因此会限制你的请求,你需要等待几分钟才能再次请求。如果您还能得到需要等待的时间指示,那将很有用。 - Antony Sargent
3
chrome.runtime.requestUpdateCheck(...) 包装在一个if语句中,以限制它只能每15分钟、30分钟或甚至每小时调用一次,这样做是否值得?我想把它放在popup.html中,但我想这可能是一项昂贵的操作。 - benmccallum
除了知道更新状态之外,requestUpdateCheck 还有任何意义吗? - mallik1055
@AntonySargent,当您需要知道更新可用时,但用户的浏览器尚未下载crx文件时会发生什么? - Pacerier
requestUpdateCheck 强制浏览器检查您的插件是否有更新,而不是依赖现有的自动更新检查。一般来说,这并不推荐使用,但在响应用户发起的操作时应该没问题。另一方面,onUpdateAvailable 尤其有帮助,因为当后台页面正在使用时,扩展程序将不会自动更新(对于使用持久性后台页面的扩展程序来说,这实际上意味着等待浏览器重新启动)。 - Brian

0
根据Google Chrome文档,您需要具备以下要求。
chrome.runtime.onUpdateAvailable.addListener(function(details) {
  chrome.runtime.reload(); // To restart the chrome App instantaneously
});

但是这需要时间才能将JS更改反映到Chrome中,因为background.js加载到后台并且需要被卸载和重新加载

为了解决这个问题,您需要包含以下内容

chrome.runtime.onInstalled.addListener(function(details) {
  chrome.runtime.reload();
});

同样地。

onInstalled 在 Google 扩展首次安装(全新安装)、Google 扩展更新或 Google Chrome 更新时被调用。


0
根据您的应用程序,当检测到更新时,您可能希望使用类似于setTimeout的东西,并稍后调用chrome.runtime.restart()chrome.runtime.restart()

1
restart() 仅适用于 kiosk 模式。https://developer.chrome.com/extensions/runtime#method-restart - Pier

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接