【问题标题】:Custom User Agent with Iframes带有 iframe 的自定义用户代理
【发布时间】:2020-09-03 17:52:36
【问题描述】:

是的,我已阅读Load iframe content with different user agent,但我不明白如何正确实现它/它不起作用

我正在尝试在 chrome 扩展中创建一个带有自定义用户代理的 iframe,这是我当前的代码(来自其他教程/答案)

function setUserAgent(window, userAgent) {
    if (window.navigator.userAgent != userAgent) {
        var userAgentProp = { get: function () { return userAgent; } };
        try {
            Object.defineProperty(window.navigator, 'userAgent', userAgentProp);
        } catch (e) {
            window.navigator = Object.create(navigator, {
                userAgent: userAgentProp
            });
        }
    }
}
window.addEventListener("load", function() {
document.querySelector('iframe').contentWindow, 'Test User Agent';
});
<title>Title</title>
<link rel="icon" href="favicon.ico" type="image/ico" sizes="16x16">
<iframe src="https://www.whatsmyua.info/" frameborder="0" style="overflow:hidden;height:100%;width:100%" height="100%" width="100%"></iframe>
<script src='index.js'>
</script>

由于某些原因,用户代理无法正常工作,如加载的页面所示。​​

【问题讨论】:

  • 我应该怎么匹配?因为我只想更改某些窗口的用户代理,而不是所有选项卡(甚至我的所有扩展窗口),但匹配需要一个 URL

标签: javascript html iframe google-chrome-extension


【解决方案1】:

你需要insert that code into the page context using a content script

1a。注入内容脚本

它可以以编程方式从您的扩展页面注入 iframe。

manifest.json

"permissions": ["webNavigation"]

index.js:

chrome.tabs.getCurrent(tab => {
  chrome.webNavigation.onCommitted.addListener(function onCommitted(info) {
    if (info.tabId === tab.id) {
      chrome.webNavigation.onCommitted.removeListener(onCommitted);
      chrome.tabs.executeScript({
        frameId: info.frameId,
        file: 'content.js',
        runAt: 'document_start',
      });
    }
  }, {
    url: [{urlEquals: document.querySelector('iframe').src}],
  });
});

1b。声明内容脚本

请注意,以前的方法理论上可能允许其&lt;head&gt; 中的一些iframe 内联脚本首先运行。在这种情况下,您必须将虚拟 URL 参数添加到 iframe src(例如 https://example.org/page/page?foobar)并在 manifest.json 中使用 declarative matching

"content_scripts": [{
  "matches": ["*://example.org/*?foobar*"],
  "all_frames": true,
  "run_at": "document_start",
  "js": ["content.js"]
}],

2。添加页面脚本

要立即运行我们的代码,让我们通过 textContent 运行它。我们没有为页面代码使用单独的文件,因为这会将其放入队列中,它可以在当前待处理的页面脚本之后运行。

content.js:

var script = document.createElement('script');
script.textContent = '(' + function() {
  Object.defineProperty(navigator, 'userAgent', {
    get() {
      return 'Test User Agent';
    },
  });
} + ')();';
(document.head||document.documentElement).appendChild(script);
script.remove();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-17
    • 1970-01-01
    • 1970-01-01
    • 2014-05-02
    • 1970-01-01
    • 1970-01-01
    • 2018-01-28
    • 1970-01-01
    相关资源
    最近更新 更多