Determining whether the user has pressed the browser back button poses a challenge. Many propose using the window.onhashchange function, but it also responds to in-page back buttons, adversely affecting the user experience.
For single-page applications utilizing hash navigation, it's crucial to control the behavior of in-page back buttons. To do so, employ an array (window.location.lasthash) to store previous hashes as the user navigates the interface.
Conventional methods like window.onbeforeunload and window.onmousedown proved ineffective for distinguishing browser back button clicks. Instead, a flag variable toggled by the document's onmouseover (when mouse hovers over the document) and onmouseleave (when mouse exits the document) was devised.
Modify window.onhashchange to incorporate this logic:
window.onhashchange = function() { if (window.innerDocClick) { // In-page mechanism triggered the hash change } else { if (window.location.hash != '#undefined') { // Browser back button clicked goBack(); } } }
To prevent backspace from triggering the back button event, implement the following script:
$(function(){ var rx = /INPUT|SELECT|TEXTAREA/i; $(document).bind("keydown keypress", function(e){ if( e.which == 8 ){ // 8 == backspace if(!rx.test(e.target.tagName) || e.target.disabled || e.target.readOnly ){ e.preventDefault(); } } }); });
In summary, by utilizing the document's hover events, one can effectively differentiate between browser back button clicks and in-page back button usage, allowing for precise control of back button functionality.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3