Detect if page is load from back button

后端 未结 7 933
无人及你
无人及你 2021-02-06 23:07

Is there any way to detect if current page came from back button?

I want to load data from cookie only if current page came from back button.

7条回答
  •  無奈伤痛
    2021-02-07 00:02

    Note: This is reported to no longer work in the latest versions of Chrome.

    When a user goes back a page, any visible form data is preserved, while any JavaScript variables are reset. I say 'visible' form data, as hidden fields seem not to be preserved, but invisible inputs are.

    You can use this to your advantage in order to detect whether the page was an initial load, or had already been loaded previously such as from a back button click.

    Create a invisible input field (not type 'hidden') with a value of '0', and within a DOM ready loader check to see if the value has been set to '1'; if it has you know the page has already been loaded, such as from a back button; if it is still '0' then the page has initially loaded for the first time, set the value to '1'.

    Note: This is a bit delicate in the way it works, and probably doesn't work in all browsers; I built it with Chrome in mind.

    • The DOM needs to be loaded; not all ready functions work. The one below does, so does the JQuery ready; however (function() { }) in my instance does not.
    • The Input cannot be of type="hidden". Set style="display:none;" on the input instead.

    .

    
    
    

提交回复
热议问题