简体   繁体   中英

Browser go back to previous page function, how to reload a document if go back?

Here is my problem with browser-build-in go back function.

Say I have two pages: Page1 and Page2.

What Page1 does is that it downloads a .json file then prints .json file's data on the webpage.

Page2 allows user to insert new data to that .json file.

If, user hit page1 then go to page2 to insert new data, then hit the go back button. The .json file will not updated. Thus the just-inserted-data wouldn't show.

But I need new data updated.

Any idea to solve this problem?

If caching is your issue then you might want to consider this buggy, hoary old chestnut. Add these to your <head> section, but be wary as its effectiveness varies between browsers/versions. See link to w3.org for in-depth details.

<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />

https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9

I presume you use javascript and the onload event to download the .json file and to display its content. The problem there is that the onload event isn't triggerd when you use the back button. You could try to use the window.onpopstate event instead of onload. The onpopstate event is also invoked when the back button is used to navigate to a webpage.

function init() {
   //load .json ...
}   
window.onpopstate = init;

It could be that the json data is being cached, so even if you request it again upon arriving on "Page1", you may be reading a cached version of it. That is, if you have successfully avoided the page itself from being cached, the data could still be cached.

A simple though hacky way to overcome that type of issue, is to alter the URL of the json data every time it is being loaded. Eg add a timestamp or some other, ideally unique, portion to the URL:

myjson.json?timestamp=xxx

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