嘿,试图在特定时间从 page1 重定向到 page2(在选项卡内,而不是打开新的)。
list .json:
{
"name": "Google",
"description": "Test",
"version": "1.0",
"manifest_version": 2,
"background": {"scripts":["script.js"]},
"permissions": [
"alarms",
"webRequest",
"*://www.google.com/*",
"webRequestBlocking"
]
}
脚本.js:
var host = "https://www.facebook.com/"
chrome.alarms.onAlarm.addListener(function(alarm){
return {redirectUrl: host}
})
chrome.webRequest.onBeforeRequest.addListener(
function(details) {
return chrome.alarms.create("redirect", {when: Date.now() + 5000})
},{
urls: [
"*://www.google.com/*"
],
types: ["main_frame", "sub_frame", "stylesheet", "script", "image", "object", "xmlhttprequest", "other"]
["blocking"]
)
重定向代码取自 This Question , 使用计时器的代码取自 This Question
编辑:感谢下面 Xan 的回答
list .json
{
"name": "Google",
"description": "Test",
"version": "1.0",
"manifest_version": 2,
"content_scripts": [{
"matches": ["*://www.google.com/*"],
"js": ["script.js"]
}]
}
script.js(用 Date.now() 修改 setTimeout 以获得正确的等待时间)
setTimeout(function() {
window.location = "https://www.facebook.com/"
}, 5000)
最佳答案
那是行不通的,而且这也不是您想要的。
chrome.webRequest.onBeforeRequest
指的是在发送网络请求之前决定什么。
首先,它会暂停网络请求以等待决定。因此,它不允许异步发生重定向 - 您必须现在而不是 5 秒内做出决定。
其次,您似乎希望页面加载,但在 5 秒后被重定向到其他地方 - 不要让“加载”持续 5 秒。然后 webRequest
是错误的地方。
你想要的是一个content script ,一段 JS 代码,加载后将在选项卡的上下文中执行。
我将 list 字段留给读者作为练习,这段代码将起作用:
// Content script
setTimeout(function() {
window.location = "https://example.com/";
}, 5000);
关于javascript - Chrome 扩展 : Redirect at specific time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32845101/