Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically disable window.location.reload?

Tags:

javascript

Is there a way to override default behavior of window.location.reload - making it a no-op, for debugging purposes?

like image 478
Jure V. Avatar asked Mar 05 '11 15:03

Jure V.


People also ask

How do I stop Windows reloading my location?

You can use the following code: window. stop();

Is window location reload deprecated?

location. reload is falsely reported as a deprecated function.

What is the difference between location reload () and window location reload ()?

location. reload(true); reloads the page from the server instead of from the cache, window. location. reload(); would do the same thing as location.

Is location reload asynchronous?

Since it's asynchronous, the Javascript continues running (it doesn't wait for the AJAX request to complete in order to continue to run the rest of your code ( window. location. reload() ).


1 Answers

The problem is that for some reason, location.reload effectively is not a writable property in Firefox and Chrome. Here's some crazy way I came up with to override it (and others) in those browsers. It uses the non-standard .__defineGetter__() method, in part to bypass the magic of window.location = "/home.html" from interfering.

var _location = location;
__defineGetter__('location', function() {
    var s = new String(_location);
    for(i in _location) (function(i) {
        s.__defineGetter__(i, function() {
            return typeof _location[i] == 'function' ? function(){} : _location[i];
        });
        s.__defineSetter__(i, function(){});
    })(i);
    return s;
});
__defineSetter__('location', function(){});

The resulting mock object should prevent any function call (including .reload) or assignment (setting .href) from actually taking effect. Alternatively, you can limit your testing to IE, Safari, and Opera, in which .reload is writable.

like image 137
PleaseStand Avatar answered Oct 21 '22 10:10

PleaseStand