为新用户填充 localStorage 一次

Populate localStorage once for a new user

正在开发 Chrome 允许用户保留使用 localStorage 的列表的扩展。

到目前为止工作:用户可以在他们的列表中输入内容,它会存储在 localStorage 中,用户可以从列表中删除内容,它会从 localStorage 中消失。

试图弄清楚:我怎样才能从用户列表中的一些示例项目开始?

function startStorage (){
localStorage.setItem('list', 'your first list item');}
startStorage();

上述代码的问题:每次用户刷新页面时,它都会重新填充起始项。有没有办法只填充一次?截至目前,每次重新加载时都会触发函数,以便他们再次获得起始项。

如有任何想法,我们将不胜感激。

您可以使用 getItem

检查此本地存储项目是否已存在
function startStorage (){
  if(!localStorage.getItem('list')){
  localStorage.setItem('list', 'your first list item')
   }
}
startStorage();