Gale
Gale

Reputation: 399

Stopping window.location.replace from redirecting

I have an html code that I can't change but can load .js file into it.

Can I add some java script code to stop window.location.replace from working?

Upvotes: 4

Views: 6435

Answers (2)

Oriol
Oriol

Reputation: 288120

You can't redefine location.replace because it's not a configurable property.

However, you can try replacing the entire location object with a similar object (e.g. a proxy) but with your custom replace.

The problem is that window.replace isn't configurable neither, but you can shadow it in an inner scope:

(function() {
  function customReplace() { /* ... */ }
  var location = new Proxy(Object.create(window.location), {
    get: function(target, property, receiver) {
      if(property === 'replace') return customReplace;
      return window.location[property];
    },
    set: function(target, property, value, receiver) {
      return window.location[property] = value;
      return true;
    },
  });
  location.replace('http://example.com'); // Nothing happens
  location.host; // Still works
  location.host = 'example.com'; // Still works
})();

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1074335

To do this, you'd have to either replace the replace function on location, replace location entirely, or replace window entirely (which wouldn't be a guarantee, since you can also access it as this at global scope in loose mode, and via a couple of other aliases).

Neither appears to be possible, not even with Object.defineProperty.

Benjamin mentioned the history API, but I don't see anything in the history API that allows you to cancel a navigation initiated by location.replace.

So I don't think you can do this.

(CW because this was a community effort.)

Upvotes: 5

Related Questions