将自定义用户代理关联到特定的 Google Chrome 页面/标签 [英] Associate a custom user agent to a specific Google Chrome page/tab
问题描述
我正在开发 Google Chrome 扩展程序,我想为标签/页面或弹出窗口(显示为气泡弹出窗口"的 iframe)设置特定的用户代理,而不影响其他页面或标签.
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.
有可能吗?
推荐答案
webRequest
API 可用于修改用户代理标头.
注意:开发者工具中的网络标签显示旧标题.我已经使用 netcat (nc -l 127.0.0.1 -p 6789
).
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
).
在下面的示例中,代码在所有标签上激活.调整请求过滤器以满足您的要求.添加 tabId
以限制此过滤器的功能,使用您的选项卡的 tabId(可通过各种 API 获得,chrome.tabs
特别是).
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).
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
}
文档
chrome.webRequest.onbeforeSendHeaders
事件莉>- 请求过滤器
这篇关于将自定义用户代理关联到特定的 Google Chrome 页面/标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!