A chrome extension I am working on needs a location spoofer. It works, however I cannot 'unset' it.
Let's examine the relevant code. This is a part of a content script.
let cachedGeoLocFunc = navigator.geolocation.getCurrentPosition
let geoSpoofCode = conf => `
(function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition = function(success) { return success(${conf}); }
} else {
console.error('Geolocation is not supported in this browser');
}
})()
`
browser.runtime
.sendMessage({ type: 'request-spoofed-coords' })
.then(curCoords => {
//json from state, contains current spoofed locale
if (curCoords) {
let script = document.createElement('script')
script.textContent = geoSpoofCode(curCoords)
document.documentElement.appendChild(script)
script.remove()
} else {
//revert to default behavior
let unSetScript = document.createElement('script')
unSetScript.textContent = `
(function() {
navigator.geolocation.getCurrentPosition = ${cachedGeoLocFunc};
})()`
document.documentElement.appendChild(unSetScript)
unSetScript.remove()
}
})
As you can see, I am overriding the chrome native function and providing my own value. This works fine for spoofing a location.
Conceptually I imagined this would work. I am caching the native chrome function so I can later reset it (see the else). In practice I get this error when this content script gets injected into a page.
Uncaught SyntaxError: Unexpected identifier
And it breaks here (as per the chrome inspector)
So, it just injects [ native code ] instead of the actual function (at-least that is what it looks like).
Does anyone know how I can un-override this function. Is there an elegant way to do this?
How does caching in chrome work, is there ever a way to view this native code
Anyways help would be appreciated. Hope you all have a great day!
Ok, this was a misunderstanding as @wOxxOm pointed out. Please refer to their response. Content scripts do not affect or truly 'override' api functions.