Search code examples
javascriptbrowserbackforward

How to capture browser's back/forward button click event or hash change event in javascript?


I want to alert() when browser's back or forward button is clicked or hash is changed in javascript. I have tried this solution and it is working but it is causing problems on other links in webpage and submit each request twice on any link click event.

Is there any solution to capture it without using setInterval() function? So I need to capture hash change or back/forward button click event? I need a simple javascript code/function/property that should work in all modern browsers.

Any solution ?

Thanks


Solution

  • Not a good idea

    Can you rather explain the reasoning behind this? We've all been down this road of preventing backs/forwards and similar and mangling with browser functionality.

    It turns out though it's better to obey to browser and write your application in that way so these things become irrelevant. And it's also true that browsers are locking more and more things to client javascript apps so it's highly likely your app is going to fail after (few) browser upgrades.

    Go with HTML5

    HTML5 History spec may be exactly what you're after. It's the way things should work and be done in regard to Ajax applications and browser0s back/forward functionality. I suggest you check it out. See a working demo that does this rather nicely.