0

I have been trying to switch the user agent only for the Chrome extension I am developing. The extension needs to change the user agent so it can scan Dropbox and needs a specific user agent to do so. I have been able to switch the user agent, but either it is for all tabs or for only one website. When I open Dropbox on another tab it is using the other user agent. But I only want the user agent to be switched in the tab of the extension and when I close the extension as it runs in the background.

I have tried this so far:

chrome.webRequest.onBeforeSendHeaders.addListener(function(info) {

        chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {

            // since only one tab should be active and in the current window at once
            // the return variable should only have one entry
            var activeTab = tabs[0];
            var activeTabId = activeTab.id; // or do whatever you need

        });

    // Replace the User-Agent header
        var headers = info.requestHeaders;
        headers.forEach(function(header) {
            if (header.name.toLowerCase() == 'user-agent') { 
                header.value = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1468.0 Safari/537.36';
            }
        });


        hasSetUA = true;
        return {requestHeaders: headers};
    },
    // Request filter
    {
        // Modify the headers for these pages
        urls: [
            "https://dropbox.com/*"
        ],
        tabId: activeTabId

    },
        ["blocking", "requestHeaders"]
    );

Any help would be great. I have added webrequest, webrequestblocking, and tabs to my manifest permissions list.

trevorp
  • 1,161
  • 1
  • 14
  • 19
  • 1. Extensions API callbacks are asynchronous 2. Read about [how asynchronous code works](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call), 3. You can't rely on asynchronous code inside a blocking onBeforeSendHeaders callback so you'll have to use a workaround - for example you can maintain a list of tabs in a global object by using chrome.tabs.onUpdated and other tab-related events. – wOxxOm Jul 09 '18 at 13:15
  • Thanks that does help! but is there a way to only change the user agent in the background of a specific tab/extension? – user10053692 Jul 09 '18 at 13:28
  • You mean another extension? AFAIK extensions can't intercept each other's requests. – wOxxOm Jul 09 '18 at 13:41
  • No in the same extension. I want so when the extension is doing things in the background it uses a specific user agent but only in its operations, not other tabs or pages. – user10053692 Jul 09 '18 at 13:49
  • Did you search for an existing answer? I see [Changing User-Agent in XMLHttpRequest from a Chrome extension](//stackoverflow.com/q/21090733) so you might want to upgrade your "google-fu". – wOxxOm Jul 09 '18 at 14:04

0 Answers0