Is there a way to make the user's back button on their browser, call a javascript function instead of going back a page?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
由
翻译强力驱动
问题:
回答1:
You can't override the behaviour that if a user follows a link to your page, clicking Back will take them off it again.
But you can make JavaScript actions on your page add entries into the history as though they were clicks to new pages, and control what happens with Back and Forward in the context of those clicks.
There are JavaScript libraries to help with this, with Really Simple History being a popular example.
回答2:
yes, you can. Use this js:
(function(window, location) { history.replaceState(null, document.title, location.pathname+"#!/stealingyourhistory"); history.pushState(null, document.title, location.pathname); window.addEventListener("popstate", function() { if(location.hash === "#!/stealingyourhistory") { history.replaceState(null, document.title, location.pathname); setTimeout(function(){ location.replace("http://www.programadoresweb.net/"); },0); } }, false); }(window, location));
That will redirect your back button to the location.replace you specify
回答3:
I think this will do the trick. you can write your custom code to execute on browser back button click inside onpopstate function. This works in HTML5.
window.onpopstate = function() { alert("clicked back button"); }; history.pushState({}, '');