我创建了一个 chrome 插件来对页面中的数据进行一些分析,为此我需要从插件中调用一些 API,并且我想提供一些自定义用户代理来从服务器中识别它,不能使用任何其他键在标头中,它将增加工作量,因为它已经为其他一些应用程序提供了 API 我尝试了 3 种方法,我得到的只是一些错误消息和默认的 chrome 用户代理,如果我将密钥名称从用户代理更改为任何其他名称它工作正常,但我只想在用户代理密钥中发送它
var xhr = new XMLHttpRequest();
xhr.open('GET', url, false, "username", "pass");
xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');
xhr.setRequestHeader('User-Agent', 'plugin');
console.log(url)
xhr.onreadystatechange = function () {
if (xhr.readyState != 4) return;
if (xhr.status != 200 && xhr.status != 304) {
setMessageBlock('10008', "Sorry. Error occurred while fetch product URL. Please try again later", "error")
messageblock();
return;
}
response = JSON.parse(xhr.responseText);
}
xhr.send();
return response;
这给出了一些错误,例如
Refused to set unsafe header "User-Agent"
然后我也试过了
fetch(url, {
method: "GET",
headers: {"Content-type": "application/json;charset=UTF-8", "user-agent": "plugin"}
})
.then(response => {
console.log(response.text())
// handle the response
})
.catch(error => {
// handle the error
});
这没有给出任何错误,而是发送默认用户代理
通过更改 background.js 尝试了另一种方法
chrome.webRequest.onBeforeSendHeaders.addListener(
console.log("befire dadad")
function(info) {
// Replace the User-Agent header
var headers = info.requestHeaders;
headers.forEach(function(header, i) {
if (header.name.toLowerCase() == 'user-agent') {
header.value = 'catalog_plugin';
console.log('change')
}
});
return {requestHeaders: headers};
},
// Request filter
{
// Modify the headers for these pages
urls: [ "<all_urls>" ],
// In the main window and frames
types: ["main_frame", "sub_frame"]
},
["blocking", "requestHeaders"]
);
这也没有按预期工作。
请任何人建议我解决这个问题