我试图理解逻辑。在我看来,onBeforeNavigate
事件应该在我们听到任何请求之前完成。但我发现onBeforeRequest
事件首先发生。这里的示例代码将展示我的意思。
test.js
function Test(url) {
chrome.tabs.create({ url: "" }, function (tab) {
chrome.webNavigation.onBeforeNavigate.addListener(function (details) {
console.log("chrome.webNavigation.onBeforeNavigate hit on " + details.timeStamp);
});
chrome.webRequest.onBeforeRequest.addListener(function (details) {
console.log("chrome.webRequest.onBeforeRequest hit on " + details.timeStamp);
}, {
tabId: tab.id,
urls: ["<all_urls>"]
});
chrome.tabs.update(tab.id, {
url: url
});
});
}
Test("http://www.steam.com"); // Simple url with only two requests
产生的控制台消息:
chrome.webRequest.onBeforeRequest hit on 1437083141916.896
chrome.webNavigation.onBeforeNavigate hit on 1437083141916.906
chrome.webRequest.onBeforeRequest hit on 1437083141940.385
的manifest.json
{
"background": {
"persistent": true,
"scripts": [
"test.js"
]
},
"manifest_version": 2,
"name": "Test",
"permissions": [
"<all_urls>",
"webNavigation",
"webRequest"
],
"version": "1.0"
}
以下是三个details
的视图,按照事件发生的顺序:
// first chrome.webRequest.onBeforeRequest
{
"frameId" : 0,
"method" : "GET",
"parentFrameId" : -1,
"requestId" : "72285",
"tabId" : 1312,
"timeStamp" : 1437083141916.896,
"type" : "main_frame",
"url" : "http://www.steam.com/"
},
// chrome.webNavigation.onBeforeNavigate
{
"frameId" : 0,
"parentFrameId" : -1,
"processId" : 3567,
"tabId" : 1312,
"timeStamp" : 1437083141916.906,
"url" : "http://www.steam.com/"
},
// second chrome.webRequest.onBeforeRequest
{
"frameId" : 0,
"method" : "GET",
"parentFrameId" : -1,
"requestId" : "72286",
"tabId" : 1312,
"timeStamp" : 1437083141940.385,
"type" : "image",
"url" : "http://www.steam.com/images/pipebackwhite.gif"
}
答案 0 :(得分:4)
如果你考虑每个事件何时开始,这应该是有意义的。
OnBeforeRequest在你向服务器发出请求之前就开始了:
Fires when a request is about to occur. This event is sent before any TCP
connection is made and can be used to cancel or redirect requests.
另一方面,onBeforeNavigate在页面导航到下一页之前触发:
Fired when a navigation is about to occur.
如果您考虑浏览器的工作方式,它会向服务器发出请求,如果是典型的GET,则浏览器会根据标头导航到请求的新页面。但是,这会在实际请求中发生,OnBeforeRequest正在运行之前运行任何内容。
所以,你提出请求,api说:
答案 1 :(得分:0)
OnBeforeRequest
并不总是在onBeforeNavigate
之前触发。在要加载的页面立即执行window.location="example.com"
重定向的情况下,首先您将获得onBeforeNavigate
事件,然后才是onBeforeRequest
。
Chrome API文档指出没有定义的顺序:
webRequest API的事件与webNavigation API的事件之间没有定义的顺序。”