微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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 举报,一经查实,本站将立刻删除。