Chrome扩展程序:如何在本地存储数据?

时间:2016-01-10 23:43:59

标签: javascript jquery google-chrome

我尝试做基本的列表chrome扩展。 当我从textarea附加值时,它会在扩展名上显示,但如果我关闭扩展名然后单击它,则附加值不存在。 我怎么存储它?

when i open the extension

after adding

i closed extension and then clicked

// chrome.tabs.getSelected(null, function(tab){

$("#button").click(function() {
  var userList = $('#textarea').val();
  localStorage.setItem('userlist', 'userlist');
  $('#textarea').val('');
  $('#list').append('<p>' + localStorage.getItem('userlist', 'userlist'));
});

// });
#textarea {
  display: inline-block;
  min-width: 200px;
  resize: none;
  outline: none;
}
#button {
  border: none;
  color: #fff;
  background: #333;
  height: 24px;
  width: 50px;
  display: inline-block;
  vertical-align: 7px;
}
#list {
  border: 1px solid #333;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea rows="1" id="textarea"></textarea>
<button id="button">Add</button>
<div id="list"></div>

2 个答案:

答案 0 :(得分:1)

您是否尝试过localStorage

localStorage.setItem('myCat', 'Tom');

答案 1 :(得分:0)

是。答案是localStorage

基本上你可以像这样使用&gt; localStorage.setItem('myCat','Tom');

下面你可以看到我是如何使用它的。

// just created  a list variable where i append my values.
// and then set the list to localStorage.
// then just wrote if statement to check if we have something on local storage already saved.

//all codes here

// chrome.tabs.getSelected(null, function(tab){

$("#button").click(function() {
  var userList = $('#textarea').val();
  $('#textarea').val('');
  $('#list').append('<p>' + userList);

  var list = $("#list").html();
  localStorage.setItem('list', list);
  return false;

});

if (localStorage.getItem('list')) {
  $('#list').html(localStorage.getItem('list'));
}

// });
#textarea {
  display: inline-block;
  min-width: 200px;
  resize: none;
  outline: none;
}
#button {
  border: none;
  color: #fff;
  background: #333;
  height: 24px;
  width: 50px;
  display: inline-block;
  vertical-align: 7px;
}
#list {
  border: 1px solid #333;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea rows="1" id="textarea"></textarea>
<button id="button">Add</button>
<div id="list"></div>