10

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

4
  • My first guess was window.location.reload = function() {} but this doesn't work, at least on Firefox. Commented Mar 5, 2011 at 15:12
  • Should be possible - see Javascript - override or prevent execution Commented Mar 5, 2011 at 15:12
  • window.location.reload = function() {} works on Firefox 4 Commented Mar 6, 2011 at 7:58
  • @YiJiang Not in my Firefox 4+: [14:27:19.242] Error: Permission denied to shadow native property Commented Oct 31, 2012 at 13:28

3 Answers 3

12

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Won't work in Opera 11.60: "Unhandled Error: __defineGetter__: invalid modification of non-configurable property".
That solution doesn't seem so crazy, but it doesn't seem to work in Chrome 99.
3

you have to call this code in a self-calling-function unless it won't work.

(function(location){
   ...
})(window.location);

1 Comment

This also fails silently in Chrome
0

Works on Chrome, if the idea is to prevent the reload/refresh:

window.addEventListener('beforeunload', function(e) {
   e.preventDefault();
   e.returnValue = ''; // For Chrome
   return '';
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.