Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I override the location.assign or location.replace functions in JavaScript?

Tags:

javascript

I'm trying to override the location.assign function, so that I can ensure that the URLs set by it will always be absolute. But I can't seem to get it to work: when I use Xmlhttprequest.open as follows, it works fine:

var oldOpen;
oldOpen = XMLHttpRequest.prototype.open;

// override the native open()
XMLHttpRequest.prototype.open = function(){

    //Prepend our proxyURL
    arguments[1] = prependURL+arguments[1];

    // call the native open()
    oldOpen.apply(this, arguments);
}

But for location.assign this technique does not work. This is what I'm trying:

var old;
old = window.location.assign.prototype.constructor;

window.location.assign.prototype.constructor = function(){
    console.log('dd');
    console.log(arguments);
            alert('ff');
}

old.apply(this,arguments);

When I run this (I'm doing my testing in Chrome), the result is Uncaught TypeError: Illegal invocation. How can I override location.assign to get my desired behavior?

like image 503
sunebrodersen Avatar asked Dec 28 '22 06:12

sunebrodersen


1 Answers

The assign method can't be modified per spec. See The Location Interface in the WHATWG HTML Living Standard.

You'll notice an [Unforgeable] extended attribute defined for the Location interface. That's defined in WebIDL: "it indicates that the attribute or operation will be reflected as an ECMAScript property in a way that means its behavior cannot be modified". See [Unforgeable] in the W3C WebIDL editor's draft.

I found this thread after trying to modify the replace method, which is defined on the same [Unforgeable] interface, to no avail.

like image 161
Patrick Dark Avatar answered May 01 '23 16:05

Patrick Dark