Javascript : Change the function of the browser's back button

匿名 (未验证) 提交于 2019-12-03 02:29:01

问题:

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({}, '');


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!