ron tornambe
ron tornambe

Reputation: 10780

Why doesn't the jQuery beforeunload fire when page is reloaded?

I have read reams of answers about this subject, but no solutions have worked for me. The jQuery documentation is clear:

The unload event is sent to the window element when the user navigates away from the page. This could mean one of many things. The user could have clicked on a link to leave the page, or typed in a new URL in the address bar. The forward and back buttons will trigger the event. Closing the browser window will cause the event to be triggered. Even a page reload will first create an unload event.

But none of these events seems to trigger the beforeunload event.

JS

$(function () {
    $(window).on('beforeunload', function(){
        console.log("hash=" + location.hash)
    });
    ...

Upvotes: 1

Views: 1327

Answers (2)

Zerquix18
Zerquix18

Reputation: 769

You are not using beforeunload as the law stands. You should not return false, you should return a string with the message. Try with this:

$(window).on('beforeunload', function(e) {
  console.log("hash=" + location.hash);
  var confirmationMessage = 'There is something you must finish';
  (e || window.event).returnValue = confirmationMessage;
  return confirmationMessage;
});

Upvotes: 0

Drown
Drown

Reputation: 5982

The event is fired when the page reloads. The problem is that your code doesn't prevent the refresh from occurring, so it won't have time to print to the console before the refresh.

To test that it indeed works when you refresh the page, try this code :

$(window).on('beforeunload', function(){
    console.log("hash=" + location.hash);
    return false;
});

You'll see the text in the console, and there will be a prompt asking you if you want to reload the page or not.

EDIT

I have implemented @drown's suggestion as follows:

    location.href = location.hostnamme + "/#/" + location.pathname
    console.log("href=" + location.href)

but the log shows ref=http://writers-tryst.com/writers.

What am I missing?

Upvotes: 1

Related Questions