作为我的第一个扩展,我尝试使用 chrome.webRequest
API 重新加载网页,当该网页不可用时,网络服务器会将请求重定向到另一个 URL。如果发现重定向(发生onBeforeRedirect
事件),我的扩展将继续尝试原始请求(tabs.reload
)。
一切正常,除了我无法让它在多个选项卡上运行。该扩展程序可以创建一个选项卡并继续重新加载,但是当我单击扩展程序图标打开另一个选项卡或单击其他非事件选项卡时,background.js 停止运行。
如何修改它以在多个选项卡上运行(例如,同时运行 5 个选项卡)而不停止?
这是background.js:
chrome.browserAction.onClicked.addListener(function(activeTab) {
var newURL = "https://myurl";
chrome.tabs.create({ url: newURL });
});
chrome.webRequest.onBeforeRedirect.addListener(function (details) {
console.log("Redirect -> Reload");
chrome.tabs.reload();
}, {
urls: ["http://*/*", "https://*/*"]
}, ["responseHeaders"]);
chrome.webRequest.onResponseStarted.addListener(function (details) {
console.log("Response Started");
console.log(details.url);
console.log(details.statusLine);
if (details.url === "https://myurl" && details.statusCode === 200 ) {
console.log("Finally");
}
}, {
urls: ["http://*/*", "https://*/*"]
}, ["responseHeaders"]);
manifest.json:
{
"name": "My Tool",
"description": "My Tool",
"version": "1",
"manifest_version": 2,
"browser_action": {
"default_icon": "icon.png"
},
"background": {
"scripts": ["background.js"]
},
"permissions":[
"https://myurl",
"http://redirectedurl",
"webRequest",
"webRequestBlocking",
"tabs"
]
}
最佳答案
虽然我没有测试您的代码,但它无法在当前窗口的事件选项卡以外的任何其他位置上工作的原因之一是您没有将参数传递给 chrome.tabs.reload()
。如果没有参数,它默认重新加载当前窗口中的事件选项卡,无论哪个选项卡实际触发了 chrome.webRequest.onBeforeRedirect
事件。要重新加载实际触发 webRequest.onBeforeRedirect
事件的选项卡,您需要将带有选项卡 ID 的参数传递给 chrome.tabs.reload()
,例如像:
chrome.tabs.reload(details.tabId);
关于javascript - 让 chrome.tabs.reload() 重新加载事件选项卡以外的选项卡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41837512/