Search code examples
javascriptgoogle-chrome-extensionnavigatorcontent-script

Chrome extension reset overridden function


The problem:

A chrome extension I am working on needs a location spoofer. It works, however I cannot 'unset' it.

What I have so far:

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.

Unexpected behaviour:

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)

Screen shot of error

My questions!

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!


Solution

  • Ok, this was a misunderstanding as @wOxxOm pointed out. Please refer to their response. Content scripts do not affect or truly 'override' api functions.