有很多选择,其中一个比另一个更复杂。
- The webRequestAPI,特别是onBeforeRequest event。 (更好的是,即将到来的declarativeWebRequest API).
-
内容脚本。注入
location.replace('http://example.com')
在一个页面中。
- The tabsAPI。使用onUpdated event检测页面何时更改其位置,以及chrome.tabs.update更改其 URL。但要避免无限循环!
第一个是最好的,因为它甚至在请求页面之前就被激活。第二个可以在请求完成后、页面呈现之前激活("run_at":"document_start"
) 或渲染后 ("run_at":"document_end"
)。为了完整性,我提到了最后一个选项,但您不应该使用它,因为其他选项更好。
这是一个使用的示例webRequest
API,一个简单的扩展,允许我浏览 Pirate bay 上的页面,即使主要主机已被我的 ISP 关闭(实际的 URL 列表要长得多,但为了示例,我省略了它们)。
See 匹配模式有关 URL 格式的说明。
manifest.json
{
"name": "The Pirate Bay",
"description": "Redirect The Pirate Bay to a different host",
"version": "1.0",
"manifest_version": 2,
"background": {"scripts":["background.js"]},
"permissions": [
"webRequest",
"*://thepiratebay.se/*",
"*://www.thepiratebay.se/*",
"webRequestBlocking"
]
}
background.js
var host = "http://tpb.pirateparty.org.uk";
chrome.webRequest.onBeforeRequest.addListener(
function(details) {
return {redirectUrl: host + details.url.match(/^https?:\/\/[^\/]+([\S\s]*)/)[1]};
},
{
urls: [
"*://piratebay.se/*",
"*://www.piratebay.se/*"
],
types: ["main_frame", "sub_frame", "stylesheet", "script", "image", "object", "xmlhttprequest", "other"]
},
["blocking"]
);