【问题标题】:Local storage is being erased in chrome extension本地存储在 chrome 扩展中被删除
【发布时间】:2015-11-19 14:19:52
【问题描述】:

所以我想保存用户选择的主题,因此我选择弹出窗口来显示它们。 每次我关闭标签页(3 次后)或退出 chrome 时,它​​都会忘记我的选择。

我的选项.html

<html>
<head>
  <script src="options.js"></script>
  <link href='https://fonts.googleapis.com/css?family=Raleway:400,300,200,100' rel='stylesheet' type='text/css'>
</head>
<body>
  <center>
    <label class="paylabel" for="cardtype">Theme:</label>
    <select id="cardtype" name="cards">
      <option value="selectcard">--- Please select ---</option>
      <option value="op1">Theme 1</option>
      <option value="op2">Theme 2</option>
    </select>
  </center>
  <br />
  <br />
  <br />
  <br />
  <h1 style="font-family:Raleway; font-weight:200; float:left">Theme 1</h1>
    <h1 style="font-family:Raleway; font-weight:200; float:Right">Theme 2</h1>
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
  <img src = "screen2.png"; alt="" style="float:left"/>

  <img src = "screen1.png"; alt="" style="float:right"/>
</body>
</html>

Options.js:

time=setInterval(function(){
  var ddl = document.getElementById("cardtype");
  var selectedValue = ddl.options[ddl.selectedIndex].value;
  localStorage["inputText"] = selectedValue;
  var myvar = localStorage["inputText"];
    if (myvar == "op2")
   {
     chrome.browserAction.setPopup({
             popup: 'popup.html'
         });
   }
   else{
     chrome.browserAction.setPopup({
             popup: 'popup2.html'
         });
   }
},1000);

谢谢。

【问题讨论】:

  • 不要使用setInterval。使用正确的方法,如ddl.onchange = function(e) { ....... };
  • 好的,这不起作用我还需要做什么?谢谢
  • 您需要尝试实现它并在出现问题时使用the debugger
  • 我真的很抱歉,但我似乎能弄明白。除非我使用 serInterval,否则我的弹出窗口不会改变。可以帮忙解答一下吗?

标签: javascript google-chrome google-chrome-extension local-storage


【解决方案1】:
  1. &lt;script src="options.js"&gt;&lt;/script&gt; 移动到结束&lt;/body&gt; 标记之前,以便脚本代码只有在整个文档被解析和加载时才会执行。
  2. 使用适当的 on-change 监听器代替 setInterval

var element = document.getElementById("cardtype");

element.value = localStorage.inputText || 'op1';

element.addEventListener("change", function(e) {
    var selectedValue = this.value;
    localStorage.inputText = selectedValue;
    chrome.browserAction.setPopup({
        popup: selectedValue == 'op1' ? 'popup.html' : 'popup2.html'
    });
});

【讨论】:

  • 抱歉,代码似乎对我不起作用。即使我发出警报,它也不会为我运行。
  • 如果我在我的 js 代码中(在事件监听器之后)放置一个警报,我应该能够得到一个弹出警报,对吧?
  • 抱歉您的代码没有将值保存在本地存储中
  • 太好了,它现在正在保存选项,但是当我重新启动 chrome 时,它​​不会检查上一个选项。
  • 谢谢,你真的很亲密。它工作得很好,除非我重新启动 chrome,然后(即使它被保存),它没有显示正确的弹出窗口。
猜你喜欢
  • 1970-01-01
  • 2012-12-06
  • 1970-01-01
  • 2014-06-02
  • 2014-06-03
  • 2012-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多