首页 > 解决方案 > localStorage is null, but only from one function and not another

问题描述

I have a PHP page that loads two JS files at the end. In the first file I have this...

// global variables
var refineSearchStorage = {};

// function calls
window.addEventListener("load", function() {
  refineSearchStorage.get();
});

refineSearchStorage = {
  data : null, // empty storage
  get : function() {
    refineSearchStorage.data = localStorage.getItem("refineSearchStorage");
    if(refineSearchStorage.data === null) { 
      refineSearchStorage.data = { refineKeywords: '' };
      refineSearchStorage.save();
    }
    else { 
      refineSearchStorage.data = JSON.parse(refineSearchStorage.data); 
    }
  },
  add : function(x) {
    refineSearchStorage.data.refineKeywords = x;
    refineSearchStorage.save();
  },
  save : function() {
    localStorage.setItem("refineSearchStorage", JSON.stringify(refineSearchStorage.data));
  }
};

Inline javascript calls Function 1 from the middle of the page. It is created by PHP after a search result...

<script>
  window.addEventListener('load', function () {
    searchActions('{$keywords_human}');
  });
</script>

Function 1 appears in the 2nd JS page and the result is Uncaught TypeError: Cannot set property 'refineKeywords' of null... instead of adding to the localStorage.

function searchActions(x) {
  refineSearchStorage.add(x);
}

Function 2 below is called with the click of a button and adds to a localStorage variable without issue. It is also located on the 2nd JS page...

function keywordAdd(y) {
  var existingParams = refineSearchStorage.data.refineKeywords;
  var param = y.toLowerCase();
  var newParams;
  newParams = (existingParams + ' ' + param).trim();
  refineSearchStorage.add(newParams);
}

Function 1 used to work, but I did something to break it when I split the functions on to different pages. What did I do?

标签: javascriptlocal-storage

解决方案


这是因为

window.addEventListener('load', function () {
    searchActions('{$keywords_human}');
  });

之前被调用

window.addEventListener("load", function() {
  refineSearchStorage.get();
});

推荐阅读