1

I have a strange JavaScript problem using window.location.href, which apparently only affects Firefox (I'm using 3.6).

Normally window.location.href would not be read-only, and this works perfectly in Firefox:

window.location.href = "http://google.com/";

However, when I call a function in response to an onunload event (<body onunload="testThis();">), this doesn't work as expected:

function testThis() {
    alert ("1: " + window.location.href);
    window.location.href = "http://google.com/";
    alert ("2: " + window.location.href);
    return false;
}

In both cases, the alert displays the current location of the page in Firefox, without making the change. There are no JavaScript errors, and the onunload event successfully calls the function, so the problem appears to be editing or replacing the value of window.location.href.

I've tried using window.location, document.location.href, even tried changing window.location.search. Is it possible that an event, specifically an onunload event, causes window.location.href to become read-only?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Fugue
  • 416
  • 6
  • 20

2 Answers2

5

Yes, to prevent malicious webpages from blocking the user from leaving.

Gipsy King
  • 1,549
  • 9
  • 15
  • 2
    And I for one am very grateful for that :-) – Pointy Mar 01 '10 at 17:19
  • Is the same true of onbeforeunload? – Robusto Mar 01 '10 at 17:33
  • I think so. I also think that you can return a string which is then displayed in a confirm dialog (let's the user confirm the navigate-away or cancel/stay). – Gipsy King Mar 01 '10 at 17:37
  • There can be many reasons to prevent a user from using the back button, like preventing users from resubmitting forms (sloppy programming) or like clients armed with a little knowledge insisting that their intranet users not be able to return to previous pages once they start a test or a survey. I'll leave it up to your collective imagination which one applies here... Is there any documentation available on which events prevent window properties from being edited? And on which browsers are affected? – Fugue Mar 02 '10 at 07:49
  • https://developer.mozilla.org/en/DOM/window.onbeforeunload ``There is no public specification. onbeforeunload was introduced by Microsoft IE 4 and has subsequently been copied by other browsers. ´´ – Gipsy King Mar 02 '10 at 16:13
0

For the record, firefox seems to use document.location in lieu of document.location.href.

Alkanshel
  • 4,198
  • 1
  • 35
  • 54