fail to override setter & getter of window.location

2.1k Views Asked by At

I want to change all links assigned to window.location. So I assume location has getter & setter . That's why i cloned it & then i override the real window.location :

  var clonedLocation=Object.assign({},window.location);


            Object.defineProperty( window, 'location', {
              get: function (f) {
                return clonedLocation;
               },
              set:function(o){
                if(typeof o==='string'){
                  o=o+'?id=1';
                }
                clonedLocation=o;
              }
            } );

        };

The expected behavior (if overriding done ) is , when you write :

window.location='/go';

The script should redirect you to /go?id=1 NOT /go.

However the actual behavior is that this script redirects to /go

==> Thus, the window.location setter wasn't overridden ,

How to override the setter of window.location?

2

There are 2 best solutions below

2
lorefnon On

Javascript properties can be defined to have configurable: false indicating that they can not be redefined.

Attempt to redefine such property will result in an error like:

Uncaught TypeError: Cannot redefine property: location

It is to be expected that properties on host objects are not configurable for security reasons.

You can verify this by checking the property descriptor:

Property descriptor for location

0
k1r0s On

you're used to wrap window.location with another static class which could implement hooks (before and after):

take a look into kaop

Aspects.add(
  function op1(){
    console.log("operation one");
    var argument0 = meta.args[0];
    if(typeof argument0==='string'){
        argument0=argument0+'?id=1';
    }
  },
  function op2(){
    console.log("operation two");
  }
)

var DummyLocation = Class({
  set: ["op1", function(newUrl){
    location = newUrl;
  }, "op2"],
  get: [function(){
    return location;
  }]
})

Now you should use:

DummyLocation.set("/go");