仅当Header不包含任何引荐来源时,我才必须从www.example.com重定向到xyz.example.com。我写了这段代码:
chrome.webRequest.onHeadersReceived.addListener(
function(details) {
var match = details.url.match(/^(http|https):\/\/www.example.com\/([\S\s]*)/);
console.log(details);
return {redirectUrl: match[1] + "://xyz.example.com/" + match[2]};
},
{urls: ["*://www.example.com/*"]},
["responseHeaders", "blocking"]
);
但" onHeadersReceived"不包含任何引荐来源信息。所以我不能根据引用者信息进一步编写我的逻辑。有一个API" onBeforeSendHeaders"其中包含引荐来源信息但它无法重定向。您能否提出任何可以提供引荐信息和重定向的解决方案。以下是所有API的链接:Chrome API's link
答案 0 :(得分:1)
正如RobW所指出的那样,可以在onHeadersReceived
阶段重定向请求。
所以,计划:
onBeforeSendHeaders
阶段重定向的请求。onHeadersReceived
活动。所以:
var requestsToRedirect = new Object();
chrome.webRequest.onBeforeSendHeaders.addListener(
function(details) {
for (var i = 0; i < details.requestHeaders.length; i++) {
if (details.requestHeaders[i].name === 'Referer') {
requestsToRedirect[details.requestId] = true;
return;
}
}
},
{urls: ["*://www.example.com/*"]},
["requestHeaders"]
);
chrome.webRequest.onHeadersReceived.addListener(
function(details) {
if(requestsToRedirect[details.requestId]) {
delete requestsToRedirect[details.requestId];
var match = details.url.match(/^(http|https):\/\/www.example.com\/(.*)/);
return {redirectUrl: match[1] + "://xyz.example.com/" + match[2]};
}
},
{urls: ["*://www.example.com/*"]},
["blocking"]
);
chrome.webRequest.onErrorOccurred.addListener(
function(details) {
// Cleanup in case we don't reach onHeadersReceived
delete requestsToRedirect[details.requestId];
},
{urls: ["*://www.example.com/*"]}
);