你需要使用内容脚本将该代码插入到页面上下文中 https://stackoverflow.com/a/9517879.
1a.注入内容脚本
它可以通过编程方式从您的扩展页面注入到 iframe 中。
清单.json
"permissions": ["webNavigation"]
索引.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.声明内容脚本
请注意,以前的方法理论上可能允许某些 iframe 的内联脚本在其<head>
先跑。在这种情况下,您必须向 iframe 添加一个虚拟 URL 参数src
(例如https://example.org/page/page?foobar
)并使用声明性匹配 https://developer.chrome.com/extensions/content_scripts#declaratively在manifest.json中:
"content_scripts": [{
"matches": ["*://example.org/*?foobar*"],
"all_frames": true,
"run_at": "document_start",
"js": ["content.js"]
}],
2.添加页面脚本
要立即运行我们的代码,让我们通过 textContent 运行它。我们没有为页面代码使用单独的文件,因为这会将其放入队列中,可以在当前挂起的页面脚本之后运行。
内容.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();