Is it possible to hook a non-configurable property like window.location.hostname, in JavaScript?

39 Views Asked by At

I would like to know if there is a way to hook a non-configurable property, like window.location.hostname.

By this, I mean if it's possible to get an event/do something when a non-configurable property is accessed?

For example, it is currently possible to be notified and to do something when the window.navigator.userAgent property is called:

(function() {
    var userAgent = window.navigator.userAgent;
    Object.defineProperty(window.navigator, "userAgent", {
        get: function() {
            console.log("hello from useragent");
            return userAgent;
        }
    });
})(); 

However, in my case, I need to do the same thing when the window.location.hostname property is accessed, but I can't find anything that allows me to do this.

Thank you very much for your help,

Bests!

1

There are 1 best solutions below

1
PassThru On

You can save the domain in a global variable and then take advantage of your existing onload event to check each time for change, like this...

var Saved_Domain=''; // global

//----------------------------

window.addEventListener('load',function(){

 
 if((Saved_Domain!=='')&&(window.location.hostname!==Saved_Domain)){

  // The domain changed so do something here

  Saved_Domain=window.location.hostname; // save it again  

 }

     
 // other after-load tasks continue running here
     
  

},false); 

Actually scratch that...

If window.location.hostname has changed then a new document has loaded into the window... in which case you can't keep track of a domain change from the same document!

Or are you in control of the window/frame but haven't mentioned it?