Reputation: 4778
I am running into an issue with my single page application where users don't have the latest version because they never need to reload the page. Is there any way I can get the date that the page first loaded via javascript? I can store the date I updated the code in the database, and then periodically check that date to see if the user needs to refresh. I just need a date to compare it to.
I was thinking I could use localStorage and just put in a timestamp when the page loads, but if there are multiple tabs open this would create an issue. Also I run into the same issue if I try to store it on the database on the server.
What I am looking to achieve is something similar to google inbox's "There's a new version available, please refresh" message I see at the bottom of that page from time to time.
Any ideas?
Upvotes: 2
Views: 1082
Reputation: 86
Checking timestamps may be a bad idea, depending on your working environment. If your users have a device that has no RTC (think: raspberry pi) you may get unlucky and there may be a chance that their system clock is completely wrong (by hours, days, or even, years) when they open your webpage. You will get false positives this way. For example, if their clock is very far in the past, they'll get prompted to reload, despite having the latest version. This is an extreme case, of course.
If you just need to know if the version is outdated, and you are going to query the server anyway, why not just put a version somewhere in your javascript?
var VERSION="1.0.1"; // gobablly accessible variable
Or in the html itself, and then retrieve it with javascript?
<body class="something" data-version="1.0.1">
If you don't like numbers-and-dots notation, a simple integer is enough:
var VERSION=7; // version 7. Increment for each new release.
Or even the release timestamp:
var VERSION=1470786198;
Then when you periodically ask the server what the newest version is, you compare with what you have. If your version is different, then you prompt the user to reload the page.
Upvotes: 2
Reputation: 34169
Ideally, you need access to the response headers. But I don't believe you can do that. What if you do something simpler. You don't need to play around with localStorage
or cookies. Just simply have a variable that is set to new Date()
when the page is loaded. Something like
<html>
...
<script>
var pageLoadedOn = new Date()
</script>
</html>
And then, later on you can check for pageLoadedOn
which should be equal to when the page was first rendered. This should also work across tabs as each page is rendered separately per tab.
Upvotes: 2