Chrome 插件无法在 Api 调用中使用自定义用户代理

问题描述

我创建了一个 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"]
);

这也没有按预期工作。

请任何人建议我解决这个问题

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)