chrome有2套可以拦截URL的API:
我写了一个有输出的content script. 从console中看到content script在这种情况下也没有被调用
webRequest和webNavigation
试验中:
http://developer.chrome.com/extensions/declarativeWebRequest.html
据说速度更快,而且可以
RedirectToEmptyDocument [但是在试验阶段]
两者关系:
There is no defined ordering between events of the webRequest API and the events of the webNavigation API. It is possible that webRequest events are still received for frames that already started a new navigation, or that a navigation only proceeds after the network resources are already fully loaded.
In general, the webNavigation events are closely related to the navigation state that is displayed in the UI, while the webRequest events correspond to the state of the network stack which is generally opaque to the user.
webNavigation只会发出事件。不能拦截。
webRequest可以拦截请求并改变内容。
http://developer.chrome.com/extensions/webRequest.html#type-RequestFilter
BlockingResponse
( object )
Returns value for event handlers that have the 'blocking' extraInfoSpec applied. Allows the event handler to modify network requests.
用cancel方式拦截会导致页面无法继续
chrome.webRequest.onBeforeRequest.addListener(
function(info) {
console.log("onBeforeRequest:"+info.type );
return {cancel:true};
},
// filters
{
urls: [
"<all_urls>"
],
types: ["main_frame"]
},
// extraInfoSpec
["blocking"]
);
我写了一个有输出的content script. 从console中看到content script在这种情况下也没有被调用
If the optional
opt_extraInfoSpec
array contains the string
'blocking'
(only allowed for specific events), the callback function is handled synchronously. That means that the request is blocked until the callback function returns. In this case, the callback can return a
BlockingResponse
that determines the further life cycle of the request. Depending on the context, this response allows cancelling or redirecting a request (
onBeforeRequest
), cancelling a request or modifying headers (
onBeforeSendHeaders
,
onHeadersReceived
), or providing authentication credentials (
onAuthRequired
).
所以能够cancel请求的有2处:onBeforeRequest和onBeforeSendHeaders