简体   繁体   中英

Detect if the user arrived to the current page via the browser back button

I have a site where if a user navigates to a certain page then he gets a dialog notification depending on some condition on the page. The user can navigate to other pages from this page and of course can press the back button on those pages to navigate back to this page.

I'd like to detect if the user arrives via the back button to this page, so the dialog notification is not shown again (because the user has already seen it).

Is there a way to detect this reliably?

MDN list of window events

Your best possibility may be window.onpageshow = function(){};

An event handler property for pageshow events on the window.

window.onpageshow = function(event) {
    if (event.persisted) {
        alert("From back / forward cache.");
    }
};

Input trick is not longer working. Here's the solution I use:

if (window.performance && window.performance.navigation.type === window.performance.navigation.TYPE_BACK_FORWARD) {
    alert('Got here using the browser "Back" or "Forward" button.');
}

The best (although not TREMENDOUSLY reliable) way is to use the Javascript history object. You can look at the history.previous page to see if it's the next in the series. Not a great solution, but maybe the only way to figure it out.

I like use a value in an input field for this:-

<input type="hidden" id="fromHistory" value="" />

<script type="text/javascript">
if (document.getElementById('fromHistory').value == '') {
    document.getElementById('fromHistory').value = 'fromHistory');
    alert('Arrived here normally');
} else {
    console.log('Arrived here from history, e.g. back or forward button');
}
</script>

This works because the browser repopulates the value of the field with the one the javascript puts in there if it navigates back to it from history :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM