How does js listen for the click event of the return button

the recent project requires that when users enter a page, they should distinguish between a forward jump or a click on the return button to return to the current page.
this reminds me of the event that listens to the user clicking the back button.
HTML5 has a history management method that includes history.pushState () methods and popstate events. You need to use the history.pushState () method to add the status of the current page to the browser"s browsing history. The popstate event is triggered when the user clicks the back or back buttons to access the saved historical state.
but: is not compatible with Safari browsers!
find a compatible listener for the click event of the browser"s back button, or determine that the current page is from the returned method.

May.12,2022

get the URL of the last browsing history: document.referrer;

you can add the parameter "isForward=asdfas" after url to determine whether to jump forward or not.
when jumping forward, a random string is generated and saved to localstorage and appended to url. When the page is loaded, the two strings are compared to see if they are consistent. After the
page is loaded, you need to change the string saved in the localstorage.
if it is not a forward jump, the two strings will be inconsistent.


https://github.com/luokuning/...


    var detectBack = {

        initialize: function() {
            //hashchange
            window.addEventListener('hashchange', function() {

                //tag
                this.history.replaceState('hasHash', '', '');

            }, false);

            window.addEventListener('popstate', function(e) {

                if (e.state) {
                    //, dosomething
                    //url
                    this.location.reload();
                }
            }, false);
        }
    }

    detectBack.initialize();

add a status value when clicking the forward or return button, and identify the status value by adding a hash value -sharpforward or-sharpback at the end of url.
for example, when I click the back button to jump to this page, this page uses location.hash to get the hash value. And then judge it.


this method has another drawback: it adds one more history record. As a result, when I don't want the current page to generate history, I use the replace () method to jump to the page after the jump, and then click back to return to the previous page. In fact, what I want is a higher level.

Menu