0

I have 5 html pages and a JavaScript function DoInitialConfiguration() in a JavaScript File. User can open any of the five html pages and I want that irrespective of which page is opened, I call this function on the first page access. But also want to remember that the function has been called once and not call it in other page load. I only have these 5 html pages and the JavaScript file which has the function. I am owner of the JavaScript file but can do limited change in the html pages (which I don't own) like load the JavaScipt file and call the function DoInitialConfiguration().

Since the JavaScript file will remain in browser cache, is there a way to remember the function has been called once by using any variable in the JS file. It is OK to call DoInitialConfiguration() again if the page is reloaded after clearing browser cache.

how can this functionality be achieved

Scott Weaver
  • 7,192
  • 2
  • 31
  • 43
Sourav
  • 5
  • 2

3 Answers3

3

If your 5 pages are hosted under same site (which probably would be the case), you can use localStorage to add a key to check if your script was called first time or not.

if (localStorage.getItem("firstRun") != null) {
  // second run+ code goes here
} else {
  localStorage.setItem("firstRun", "ohyes");
  // first run code goes here
}
mehulmpt
  • 15,861
  • 12
  • 48
  • 88
0

You can possibly use localStorage for this. Once your code executes set a localStorage variable i.e. localStorage.setItem(<key>, <value>) and in the function check if the localStorage has been set i.e. localStorage.getItem("lastname"). If its set do not execute the code.

Vinit Sarvade
  • 750
  • 6
  • 14
0

It would be good to understand you setup and case study better.

If I understand you correctly, you have 5 separate HTML pages (and you are not running a Single Page Application [SPA]) then what you want to do is impossible through browser and cache memory alone. If you want to remember settings you need to save these using localStorage or cookies (as some of the answers popped up have suggested) but as they are 5 different html pages what does the Js do to make you not want to re-run it on a second page load?

David Brewer
  • 131
  • 5
  • This is a valid comment. You are only a few rep away from commenting. Don't squander rep on downvoted answers that are really comments but wait until you have enough to actually comment – mplungjan Feb 25 '17 at 14:32
  • Ok, now you can convert to comment :) – mplungjan Feb 25 '17 at 14:35