-1

Below are two files. One to do a localStorage and two to retrieve the variable first_name. I get a null result when I try to retrieve the variable first_name value of "Peter". I have tried windows.localStorage to no avail. The URL called by the first file opens but no retrieval.

File 1

<script>
    localStorage.setItem("first_name", "Peter");
    window.open(URL);
</script>

File 2 - URL

<script>
    first_name="";
    localStorage.getItem("first_name");
    console.log("fn",first_name); 
</script>
dabl99
  • 1
  • 1

4 Answers4

2

You don't set localStorage.getItem("first_name"); to a variable. Instead, your code should look like this:

var first_name = localStorage.getItem("first_name");
console.log("fn",first_name); 
Rojo
  • 1,941
  • 1
  • 7
  • 24
0

Generally speaking, those are the right calls to localStorage (aside from not actually storing the output of getItem, as another answer has pointed out).

However, if "URL" is in a different domain or subdomain than the page where the first script runs, they won't share the same localStorage! Reference this question: In HTML5, is the localStorage object isolated per page/domain?

If this is in fact the case, you have a somewhat complicated problem on your hands. Depending on your needs and framework, you might find some useful ideas in one of these questions:

Ben Arvey
  • 34
  • 5
0

Try this:

window.localStorage.setItem("first_name", "Peter");
var first_name = window.localStorage.getItem("first_name");
console.log(first_name);
Aaron Plocharczyk
  • 2,403
  • 2
  • 3
  • 13
  • No other code being used apart from the javascript code in the header section. And as far as I know there is no restriction on writing to my domain as I write files to it all the time like the two small files E1 and E2. I fancy I could use local storage some years ago in a different program and perhaps on a different computer. – dabl99 Dec 13 '19 at 05:38
  • You ever figure out what the deal was with this? – Aaron Plocharczyk Jan 04 '20 at 18:37
0

I have checked that windows.localStorage.setitem is storing the value "Peter" in the variable first_name. However the second file when called gives a null result for first_name.

2nd file is

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   </head>

   <script>
        if(!localStorage.getItem('first_name')) 
            {
                 prompt(" first_name there");
            }
        else
            {
                 prompt("first_name not there");
            }
        var second_name = localStorage.getItem("first_name");
        console.log("fn",second_name); 
    </script>
</html>
dabl99
  • 1
  • 1