我正在尝试解决我的 chrome 扩展程序中最近出现的问题。我正在使用以下代码并且它有效,直到后来的某个时刻,现在它不起作用......
我的扩展程序会覆盖新的标签页,并且它还附带一个已加载的内置页面 通过“chrome-extension:”url 从扩展文件夹本身。
每当有更新可用时,我都会向我的内容脚本发送一条消息,该脚本将通过 window.open 重新加载当前的“扩展”页面,然后重新加载自身,但是在新版本的 Edge 中,例如浏览器只是退出,因为重新加载会导致新的 about:blank 页面被视为从扩展本身打开。
解决这个问题的一种方法是将用户发送到某个互联网网页,显示正在发生更新,如果可能的话我想避免这种情况......问题是如果我的扩展程序的页面是唯一打开的页面并且重新加载发生,浏览器关闭。
想知道是否有人有其他解决方案......
背景:
chrome.runtime.onUpdateAvailable.addListener(function(details)
{
chrome.tabs.query({currentWindow:true, active:true}, function(tabs)
{
// here I check to make sure my extension's page is open,- code hidden.
chrome.tabs.sendMessage(tabs[0].id, {restart:"page"});
});
});
从内容脚本来看:
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse)
{
if (message.restart)
{
var clonePage = window.open("about:blank");
clonePage.document.open();
clonePage.document.write(document.documentElement.outerHTML);
clonePage.document.close();
chrome.runtime.reload();
}
});
编辑:
我认为这是 Edge 中的一个错误,因为它在 Opera 浏览器中仍然可以正常工作,并且当重新加载发生时,扩展程序打开的新选项卡 about:blank page 不会关闭,就像在 Edge 中一样......
您可以暂时将自己的选项卡重定向到虚拟 URL,然后在更新后返回。
注意,由于
'chrome://newtab/'
是Chrome/Chromium特有的,跨浏览器的方法是在newtab页面的html中指定一个favicon,然后检查它。
// newtab.html
<link rel="icon" href="favicon.png">
................
//后台脚本
chrome.runtime.onUpdateAvailable.addListener(async () => {
const tabs = await chrome.tabs.query({});
const fav = chrome.runtime.getURL('/favicon.png');
const tabIds = tabs.map(t => t.favIconUrl === fav && t.id).filter(Boolean);
const jobs = tabIds.map(id => chrome.tabs.update(id, {url: 'data:,'}));
jobs.push(chrome.storage.local.set({tabIds}));
await Promise.all(jobs);
chrome.runtime.reload();
});
chrome.runtime.onInstalled.addListener(async ({reason}) => {
if (reason === 'update') {
const {tabIds} = await chrome.storage.local.get('tabIds');
chrome.storage.local.remove('tabIds');
tabIds?.forEach(id => chrome.tabs.goBack(id));
}
});