将自定义用户代理关联到特定的Google Chrome页面/标签 [英] Associate a custom user agent to a specific Google Chrome page/tab

查看:360
本文介绍了将自定义用户代理关联到特定的Google Chrome页面/标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发Google Chrome浏览器扩展程序,并且希望将某个特定的用户代理设置为标签页/页面或弹出窗口(显示为泡泡弹出窗口的iframe),而不会影响其他页面或选项卡。



是否有可能? webRequest API 可用于修改用户代理标题。
注意:Developer工具中的Network标签显示标头。我已验证使用 netcat 正确设置了标题( nc -l 127.0.0.1在下面的示例中,代码会在全部选项卡上激活。

调整请求过滤器以符合您的要求。添加 tabId 以限制此过滤器的功能,并使用选项卡的tabId(可通过各种API获得 chrome.tabs )。

background.js



  chrome.webRequest.onBeforeSendHeaders.addListener(
function(info){
//替换User-Agent头部
var headers = info.requestHeaders;
headers.forEach(function(header,i){
if(header .name.toLowerCase()=='user-agent'){
header.value ='Spoofed UA';
}
});
return {requestHeaders:headers} ;
},
//请求过滤器
{
//修改这些页面的标题
url:[
http:// stackoverflow。 com / *,
http://127.0.0.1:6789/*

//在主风ow和frames
类型:[main_frame,sub_frame]
},
[blocking,requestHeaders]
);



manifest.json



  {
name:WebRequest UA测试,
版本:1.0,
权限:[webRequest,webRequestBlocking,http:// * / *],
background:{
scripts:[background.js]
$,
manifest_version:2
}



h2>


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?

解决方案

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

这篇关于将自定义用户代理关联到特定的Google Chrome页面/标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆