最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Associate a custom user agent to a specific Google Chrome pagetab - Stack Overflow

programmeradmin1浏览0评论

I'm developing a Google Chrome extension and I'd like to set up a specific user agent to a tab/page, or to a popup (iframe shown as a "bubble popup"), without affecting other pages or tabs.

Is it possible?

I'm developing a Google Chrome extension and I'd like to set up a specific user agent to a tab/page, or to a popup (iframe shown as a "bubble popup"), without affecting other pages or tabs.

Is it possible?

Share Improve this question edited Dec 25, 2012 at 15:17 Rob W 349k87 gold badges807 silver badges682 bronze badges asked Apr 26, 2012 at 13:53 auinoauino 1,6565 gold badges23 silver badges44 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 19

The webRequest API can be used to modify the User Agent header.
Note: The Network tab at the Developer tools show the old headers. I've verified that the headers are set correctly, using netcat (nc -l 127.0.0.1 -p 6789).

In the example below, the code activates on all tabs. Adjust the request filter to meet your requirements. Add tabId to limit the functionality to this filter, with the tabId of your tabs (obtainable through various APIs, chrome.tabs in particular).

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

  • chrome.webRequest.onbeforeSendHeaders event
  • The Request filter
发布评论

评论列表(0)

  1. 暂无评论