Home >Web Front-end >JS Tutorial >How Can We Reliably Detect Browser Back Button Presses and Differentiate Them from In-Page Back Button Actions?
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.
The above is the detailed content of How Can We Reliably Detect Browser Back Button Presses and Differentiate Them from In-Page Back Button Actions?. For more information, please follow other related articles on the PHP Chinese website!