![](/img/trans.png)
[英]Modify document html before load with Chrome extension, using document_start
[英]Chrome extension - get variable value before “document_start”
我写了一个chrome扩展来伪造User-Agent字符串。 替换标头已完成,但是我无法在JavaScript中伪造User-Agent字符串。
众所周知,要在客户端检测用户代理,我们可以阅读navigator.userAgent
和window.navigator.userAgent
,并且要禁用它,我在content_scripts中使用以下代码:
var new_ua = 'Hell Yeah!'; if (typeof new_ua === 'string' && new_ua !== '') { var d = document.documentElement, injection_code = '(' + function(useragent) { if (typeof window === 'object' && typeof window.navigator === 'object') { navigator = Object.create(window.navigator); Object.defineProperties(navigator, { userAgent: {get: function() {return useragent;}}, appVersion: {get: function() {return useragent;}} }); Object.defineProperty(window, 'navigator', { value: navigator, configurable: false, enumerable: false, writable: false }); } } + ')("' + new_ua.replace(/([\\"\\'])/g, '\\\\$1') + '");'; d.setAttribute('onreset', injection_code); d.dispatchEvent(new CustomEvent('reset')); d.removeAttribute('onreset'); Object.defineProperties(navigator, { userAgent: {get: function() {return new_ua;}}, appVersion: {get: function() {return new_ua;}} }); }
manifest.json
:
"content_scripts": [{
"all_frames": true,
"js": ["/js/inject/content.js"],
"matches": ["*://*/*"],
"run_at": "document_start"
}],
"minimum_chrome_version": "49.0",
"permissions": [
"webRequest", "webRequestBlocking", "*://*/*", "storage", "tabs"
]
一切正常:
测试页代码:
<html> <body> headers = <?php echo $_SERVER['HTTP_USER_AGENT']; ?><br /> <script> document.write('navigator.userAgent = ' + navigator.userAgent + '<br />'); document.write('window.navigator.userAgent = ' + window.navigator.userAgent + '<br />'); </script> <iframe style="display: none"></iframe> </body> </html>
为了从扩展程序设置中获取伪造的用户代理,我们可以使用chrome.runtime.sendMessage
方法,可以。 但是,如果我们使用:
chrome.runtime.sendMessage({action: 'useragent.get'}, function(new_ua){
// code from first snippet is here
});
伪造不起作用! 为什么? 因为我们在页面onLoad事件之后执行代码。 因此,我们必须从后台脚本中获取实际的用户代理,而无需使用chrome.runtime.sendMessage
和任何其他异步方法。
但是如何?
对不起,我的英语
消息在Javascript引擎的下一个事件任务中传递,而您的小页面和简单页面完全在活动事件任务中解析。
可能的解决方法:
localStorage
:您的扩展程序将在首次访问该页面时设置一个值,然后您的内容脚本将能够及时读取它。 当然,这是不可靠的,有些人在重新启动浏览器后将其浏览器设置为清除localStorage。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.