Advertisement
728x90
The beforeunload event is triggered when the window, the document and its resources are about to be unloaded. This event is helpful to warn users about losing the current data and detect back button event.
javascript
1window.addEventListener("beforeunload", () => {
2 console.log("Clicked browser back button");
3 });You can also use popstate event to detect the browser back button.
Note: The history entry has been activated using history.pushState method.
javascript
1window.addEventListener("popstate", () => {
2 console.log("Clicked browser back button");
3 box.style.backgroundColor = "white";
4 });
5
6const box = document.getElementById("div");
7
8box.addEventListener("click", () => {
9 box.style.backgroundColor = "blue";
10 window.history.pushState({}, null, null);
11});In the preceeding code, When the box element clicked, its background color appears in blue color and changed to while color upon clicking the browser back button using popstate event handler. The state property of popstate contains the copy of history entry's state object.
Advertisement
Responsive Ad
🎯 Practice NowRelated Challenge
JavaScript Coding Exercise 39
Test your knowledge with this interactive coding challenge.
Start CodingAdvertisement
728x90
381of476