How can we overwrite navigator.getBattery()?

断了今生、忘了曾经 提交于 2021-02-19 09:07:20

问题


We are writing a chrome extension that returns a random battery level when the battery level is checked by a site running client-side code for fingerprinting reasons. Sample code that can be used by a site can be seen below.

navigator.getBattery().then(function(battery) {
    console.log(battery.level);
});

We are unable to find documentation regarding how the navigator.getBattery() method can be overwritten to accomplish the goal. The incomplete content-script.js can be seen below.

var navigatorBatteryPrivacy = '(' + function() {
    'use strict';
    var navigator = window.navigator;
    var modifiedNavigator;
    if (Navigator.prototype) {


        modifiedNavigator = Navigator.prototype;

    } else {

        modifiedNavigator = Object.create(navigator);
        Object.defineProperty(window, 'navigator', {
            value: modifiedNavigator,
            configurable: false,
            enumerable: false,
            writable: false
        });
    }


    modifiedNavigator.getBattery = function modifiedGetBattery() {
        return Promise.resolve(new BatteryManager());
    };




} + ')();';

var s = document.createElement('script');
s.textContent = navigatorBatteryPrivacy;
document.documentElement.appendChild(s);
s.remove();

We appreciate the cooperation of the community members.


回答1:


Use a content script that injects a script at document_start with the following code -

Object.defineProperty(navigator, "getBattery", {
    value: () => {/*your custom logic goes here*/}
});

Add the following to manifest json.

"content_scripts": [{
    "run_at": "document_start",
    "js": ["contentscript.js"]
}]



回答2:


Rather than creating a new navigator object, you can simply replace navigator.getBattery.

var navigatorBatteryPrivacy = "(" + function() {
    navigator.getBattery = function modifiedGetBattery() {
        return Promise.resolve(new BatteryManager());
    };
} + ")();";


来源:https://stackoverflow.com/questions/52455681/how-can-we-overwrite-navigator-getbattery

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