Last updated: Mar 7, 2024
Reading time·3 min
To detect the browser back button event in JavaScript:
window.addEventListener()
method to add a beforeunload
event
listener.beforeunload
event is triggered when the window, the document and its
resources are about to be unloaded.Here is the HTML for the example.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <h2>bobbyhadz.com</h2> <script src="index.js"></script> </body> </html>
And here is the related index.js
file.
window.addEventListener('beforeunload', () => { console.log('User clicked back button'); });
We used the addEventListener() method to add a listener for the beforeunload event.
The beforeunload
event is triggered when the window, the document and its
resources are about to be unloaded.
The document is still visible at the point the event is triggered.
popstate
event to detect the Browser Back button eventYou can also use the popstate
event to detect the browser back button event.
Here is the HTML for the example.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <style> body { margin: 100px; } </style> </head> <body> <h2>bobbyhadz.com</h2> <button id="btn">Set background color</button> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
const button = document.getElementById('btn'); button.addEventListener('click', () => { document.body.style.backgroundColor = 'lightgreen'; window.history.pushState({}, null, null); }); window.addEventListener('popstate', () => { console.log('User clicked back button'); document.body.style.backgroundColor = 'white'; });
window
object.The popstate
event is triggered when the active history entry changes while
the user navigates the session history.
The event changes the current history entry to that of the last page the user visited.
However, if history.pushState()
has been used to add a history entry to the
history stack, that history entry is used.
We used the history.pushState()
method in the click
event listener, so when
the user clicks on the back button, we log a message to the console and reset
the background color instead of navigating to the last page the user visited.
hashchange
event to detect the Browser Back button eventYou can also use the hashchange
event to detect the browser back button even
when the fragment identifier #
of the URL changes.
Here is the HTML for the example.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <h2>bobbyhadz.com</h2> <script src="index.js"></script> </body> </html>
And here is the related JavaScript file.
addEventListener('hashchange', event => { console.log('Fragment identifier or URL changed'); });
The
hashchange
event is triggered when the fragment identifier (the hash #
) of the URL has
changed.
The fragment identifier is the part of the URL that starts with a #
symbol.
You can learn more about the related topics by checking out the following tutorials: