Change navigator.platform on Chrome, Firefox, or IE to test OS detection code

陌路散爱 提交于 2021-02-09 06:54:51

问题


How can I spoof the value of navigator.platform on Chrome, Firefox, or Internet Explorer (preferably Chrome)? It looks like it used to be possible on Firefox natively but that support was dropped for that.

This is to test some code on a site which runs in a conditional JavaScript check which tests the navigator.platform property. Unfortunately it's not testing userAgent which would be easy to change.

I tried writing a simple chrome extension per the suggestion in the second post on https://groups.google.com/a/chromium.org/forum/#!topic/chromium-discuss/8cCllrVX4kI but it doesn't work (I included the code I tried below). If I do console.log(navigator.platform) in the extension, it prints out "MacIntel" as desired but if I type navigator.platform in the console after page load it says "Win32" (i.e. the actual OS which I'm not wanting it to say).

//navigator_change.js
Object.defineProperty(navigator,"platform", {
  get: function () { return "MacIntel"; },
  set: function (a) {}
 });

//manifest.json
{
    "manifest_version": 2,
    "content_scripts": [ {
        "js":        [ "navigator_change.js" ],
        "matches":   [ "<all_urls>"],
        "run_at":    "document_start"
    } ],
    "converted_from_user_script": true,
    "description":  "Fake navigator.platform",
    "name":         "MacFaker",
    "version":      "1"
}

回答1:


Credit @wOxxOm and https://stackoverflow.com/a/9517879/4811197 - I updated the navigator_change.js code in the question to the following and it works.

var codeToInject = 'Object.defineProperty(navigator,"platform", { \
  get: function () { return "MacIntel"; }, \
  set: function (a) {} \
 });';
var script = document.createElement('script');
script.appendChild(document.createTextNode(codeToInject));
(document.head || document.documentElement).appendChild(script);
script.parentNode.removeChild(script);


来源:https://stackoverflow.com/questions/38808968/change-navigator-platform-on-chrome-firefox-or-ie-to-test-os-detection-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!