Associate a user agent with a specific Google Chrome page / tab.

I am developing a Google Chrome extension, and I would like to configure a specific user agent on a tab / page or pop-up (iframe shown as a "bubble pop-up") without affecting other pages or tabs.

Is it possible?

+5
source share
1 answer

webRequest API can be used to change the User Agent header.
Note. The Network tab in the developer tools displays the old headers. I have verified that the headers are set correctly using netcat ( nc -l 127.0.0.1 -p 6789 ).

In the example below, the code is activated on the all tabs. Adjust the query filter to your requirements. Add tabId to limit the functionality of this filter, from the tabId of your tabs (in particular, using the various APIs, chrome.tabs ).

background.js

 chrome.webRequest.onBeforeSendHeaders.addListener( function(info) { // Replace the User-Agent header var headers = info.requestHeaders; headers.forEach(function(header, i) { if (header.name.toLowerCase() == 'user-agent') { header.value = 'Spoofed UA'; } }); return {requestHeaders: headers}; }, // Request filter { // Modify the headers for these pages urls: [ "http://stackoverflow.com/*", "http://127.0.0.1:6789/*" ], // In the main window and frames types: ["main_frame", "sub_frame"] }, ["blocking", "requestHeaders"] ); 

manifest.json

 { "name": "WebRequest UA test", "version": "1.0", "permissions": ["webRequest", "webRequestBlocking", "http://*/*"], "background": { "scripts": ["background.js"] }, "manifest_version": 2 } 

Documentation

+15
source

Source: https://habr.com/ru/post/918415/


All Articles