skip to Main Content

I have only 2 routes

/

and

/about

when I am on URL

localhost:8080 -> it renders my home page
localhost:8080/about -> it renders about page 

If user open home page and click on about button and go to about page , not if user will click back button of browser I want just alert "user click on browsers button"

I have tried many internet solution but none of that works
tried this but doest not worked .

$(window).on('popstate', function(event) {
  alert("You are going to back page. Can work that?");
});

2

Answers


  1. you can use the url comparison.

    $(document).ready(function () {
        // Store the initial URL when the page loads
        var initialUrl = window.location.href;
    
        // Listen for beforeunload event
        $(window).on('beforeunload', function () {
            // Compare the current URL with the initial URL
            if (window.location.href !== initialUrl) {
                // Display alert if the user is navigating away
                return 'You are going to a different page. Are you sure you want to leave?';
            }
        });
    });
    Login or Signup to reply.
  2. popstate is designed for a SPA, IOW: your SPA on page routing will do a pushstate.. You won’t get a popstate from a none SPA app.

    Link -> https://developer.mozilla.org/en-US/docs/Web/API/PopStateEvent

    Note: A popstate event is dispatched to the window every time the active history entry changes between two history entries for the same document.

    Notice the bit that says -> same document, IOW: if your navigating to about without using pushstate, then it’s not the same document.

    A SPA works like this ->

    1. pushstate using new URL
    2. load the DOM contents for new URL.

    Back button pressed

    1. popstate fired, load contents of new URL

    So you can use jQuery to do this, often what users do is intercept the a tag, use preventDefault and do 1,2 above.

    Note: beforeunload could be used, but be aware its synchronous and very bad UX, especially using alert. So if you can get push/popstate working you will find you can create much better UX for the user. eg. like been able to use the new HTML Dialog element -> https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialog

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search