gpt4 book ai didi

google-chrome-extension - 为什么 chrome.webRequest.OnBeforeRequest 在 chrome.webNavigation.onBeforeNavigate 之前触发?

转载 作者:行者123 更新时间:2023-12-02 00:30:44 28 4
gpt4 key购买 nike

我正在尝试理解其中的逻辑。在我看来,onBeforeNavigate 事件应该在我们听到任何请求的任何内容之前完成。但我发现 onBeforeRequest 事件首先触发。下面的示例代码将演示我的意思。

测试.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

list .json

{
"background": {
"persistent": true,
"scripts": [
"test.js"
]
},
"manifest_version": 2,
"name": "Test",
"permissions": [
"<all_urls>",
"webNavigation",
"webRequest"
],
"version": "1.0"
}

以下是三个详细信息的 View ,按事件触发的顺序排列:

// 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"
}

最佳答案

如果您考虑每个事件何时触发,这应该是有意义的。

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,浏览器会根据 header 导航到请求的新页面。然而,这种情况发生在实际请求中,并且 OnBeforeRequest 是在向服务器发出任何内容之前运行的。

所以,你提出一个请求,API 会说:

  • 发出请求后,在做任何事情之前,我应该触发 OnBeforeRequest
  • 好的,我处理了这个请求,它让我导航/重定向,在执行此操作之前,我应该执行 OnBeforeNavigate

关于google-chrome-extension - 为什么 chrome.webRequest.OnBeforeRequest 在 chrome.webNavigation.onBeforeNavigate 之前触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31465837/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com