0

I created one chrome plugin for doing some analysis on the data in the page, for that i need to call some API's from the plugin and i want to give some custom user-agent for that to identify it from server, cant use any other keys in header it will increase the workload as it's already available API for some other applications I Tried 3 methods and all i am getting is some error message and default chrome user-agent, if i change the key name from user-agent to any other name its working fine, but i want to send it in user-agent key only

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;

this is givng some error like

Refused to set unsafe header "User-Agent"

Then i Tried this as well

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
    });

this is not giving any error but sending default user-agent

Tried one more method by changing 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"]
);

this also not working as expected.

Please any one suggest me a solution for this

SAJIKUMAR j s
  • 27
  • 1
  • 4

0 Answers0