localStorage and onload JavaScript

Viewed 465

I tried to make a function that displays an alert on the 1st page load <body onload="alertbox()>", and its working on 2nd page load instead of 1st. What should i use instead of "onload" to make it work only on 1st load?

I'm beginner, sorry if it's a dumb question.

var alertboxStatus = localStorage.getItem("alertbox", alertboxStatus);
localStorage.setItem("alertbox", alertboxStatus)

function alertbox()
{
  if (alertboxStatus == "null" || alertboxStatus == "") 
  {
    alert("Alert!");
    alertboxStatus = "displayed";
    localStorage.setItem("alertbox", alertboxStatus);
  }
};

I also tried this: But it's also working on second page load. Am i doing sth wrong with locationStorage.setItem?

document.addEventListener('DOMContentLoaded', function () 
{
  if (alertboxStatus == "null" || alertboxStatus == "") 
  {
    alert("alert");
    alertboxStatus = "displayed";
    localStorage.setItem("alertbox", alertboxStatus);
  }
}, false);

Changing "null" to null worked

3 Answers

Try this, use null instead of "null"

document.addEventListener('DOMContentLoaded', function () 
{
  if (alertboxStatus == null || alertboxStatus == "") 
  {
    alert("alert");
    alertboxStatus = "displayed";
    localStorage.setItem("alertbox", alertboxStatus);
  }
}, false);

I recommend you check the status before working with it to avoid the issue with null and 'null'. Also it dosn't make a lot of sense to load the status and then save it again, since you don't change it here.

The null issue

'null' == null \\ = false

I think you can simplify it to this

// will always be null or 'displayed'
var alertboxStatus = localStorage.getItem("alertbox");

function alertbox()
{
  if (!alertboxStatus) 
  {
    alert("Alert!");
    alertboxStatus = "displayed";
    localStorage.setItem("alertbox", alertboxStatus);
  }
};

You can retrieve a numeric value in localStorage and assign it to a variable like this:

let nOfPageLoads = +( localStorage.getItem("nLoads") || 1 );

The + converts the retrieved value to a number. If localStorage.nLoads does not exist yet, || 1 sets nOfPageLoads to 1.

So, if the value of nOfPageLoads is 1, you know the page is visited for the first time. Do something if so (alerting or whatever).

After that, increase nOfPageLoads with 1 and set the value of nLoads in localStorage to the new value.

Here is an example of this idea (in Stackblitz, because localStorage is sandboxed in SO-snippets).

Related