问题
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