shrouk mansour
shrouk mansour

Reputation: 401

Check if user is leaving the page js

I tried onbeforeunload event but it's not working when leaving the page it's only working when I reload but every thing works fine on edge. I think Chrome have changed somethings in configuration. Is there a way to fix that or another method?

onbeforeunload = function(){
    return("bye");
}

AND is there a way I can check if user is closing the page or redirecting to another url with out firing on reloading or can I not do that?

Upvotes: 0

Views: 1336

Answers (2)

BernhardWebstudio
BernhardWebstudio

Reputation: 1135

Even when using JQuery, a framework with the objective cross browser compatibility, they say:

The exact handling of the unload event has varied from version to version of browsers. For example, some versions of Firefox trigger the event when a link is followed, but not when the window is closed. In practical usage, behavior should be tested on all supported browsers and contrasted with the similar beforeunload event.

Source

So you have to accept an inconsistent behaviour.

Upvotes: 3

Nick Parsons
Nick Parsons

Reputation: 50674

You could try doing this:

window.onbeforeunload = function(e) {
  return "Bye";
}

As you need to attach the event to the window

Upvotes: 1

Related Questions