Skip to content Skip to sidebar Skip to footer

How To Capture Browser's Event By Javascript

i want to know is there any way we can know browser's events.. like : clicking on BACK button, FORWARD button, REFRESH button by javascript.

Solution 1:

These specific browser events are not available as it would be vulnerable to severe privacy violations. Privacy is something browser vendors hold sacred and a key selling (proverbial) point. All browsers allow you to know is when a user enters or leaves your page for which Kamui pointed out the technical details.

Within the same site, it's possible to achieve some browser event tracking using cookies and javascript. For example track wether users click on a hyperlink and label it as a forward event and when a user leaves the page without clicking on a hyperlink it could be one of:

  • browser url input
  • back action
  • javascript location.href replace

The location.href replace can be tracked as well when you have full control over all javascript, just use a helper method with tracking code instead of directly chaning location.href.

That leaves browser url input and the back action. With cookies and request headers (getting the referrer) it is possible to get close to finding out the forward and back events, though not 100%, but pragmatically, 99% sure is good enough.

Figuring out the refresh event is easy with request headers (referrer), if the current url matches the referrrer, it's a refresh event.

Now I offer no code or definite solution, but I outlined what you could do to track back, forward and refresh events within a single domain context. It won't be a quick and easy way to implement it and as far as I know, there's no framework in existance that reliably tracks browser events or even comes close to what I described above.

A more common/lazy technique to achieve something similar is to create a single page app, for which there are many frameworks available. Just google single page app framework, but thats a pretty heavy solution with other implications that I won't go into now.

Solution 2:

You can not capture (for example run some piece of code when user presses Back button) them, however, you can direct your pages in history by using:

More about JS History object.

Solution 3:

As @sarfraz says you cannot capture the back and forward button clicks but you could call

window.onbeforeunload = function(){alert("you just tried to leave the page");};

which should be triggered when either the back/forward/refresh buttons are clicked to perform an action, unfortunately you can't tell if they are going back or forward. Please note don't alert a message it's really annoying when trying to exit a page.

EDIT you can also do this in jQuery if you have it

 $(window).unload( function () { alert("Bye now!"); } );

Post a Comment for "How To Capture Browser's Event By Javascript"