Trevor
Trevor

Reputation: 2457

Overwriting a function on window

My understanding was that if you overwrote a function on the window object it would be forever overwritten during that session.

However, I recently tried overwriting window.navigator.geolocation.watchPosition but found that other source's watchPosition function where unchanged.

Here's a list of sources

  1. Main website bundle
  2. Extension on website
  3. Snippet inside of google chrome dev tools

These all had different readings on the window.navigator.geolocation.watchPosition despite being inside of the same window.

Example code

window.navigator.geolocation.watchPosition = function(success, error, options){
            success({ coords: { 
              latitude: 15.0, 
              longitude: 15.0,
          }, timestamp: Date.now() }); 
        }

All three sources will list different lat/lon if you change the variables for them.

Can somebody explain to me if it's possible to overwrite functions on the window object for all other sources? Or am I already doing this right and possibly messing up somewhere else?

Any help is greatly appreciated.

Upvotes: 0

Views: 811

Answers (1)

Patrick Evans
Patrick Evans

Reputation: 42736

Content scripts have their own isolated environment. Meaning they do not share functions, variables etc. This means changing an object in the content script isnt going to be observable to the actual page. This is why there are differences from your script from your extension and code included in the on the page and in the console. Note though you can change the dev tools console to work in the extension environment, simply select it from the drop down menu in the tab.

Both content script and page do however have access to the same page DOM. So either can add/remove elements to the page. This allows a content script to add a script to the page which runs in the same environment as the regular scripts on the page.

//inside content script
let s=document.createElement('script')
s.textContent = 'your code here';
//or use getURL() to get a usable url to set
//src to
s.src = chrome.extension.getURL('scriptforpage.js')
document.head.appendChild(s)

Upvotes: 2

Related Questions