在Chrome上保存和恢复设置

时间:2015-03-10 18:54:51

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

我有 的 options.html

<html>
<head>
<meta charset="utf-8">
<title>Options</title>
<script src="js/options.js"></script>
</head>
<body>
<p>
  <input type="checkbox" name="checkbox" id="checkbox">
  <label for="checkbox">Test</label></p>
<p>
  <label for="textfield">Filter:</label>
  <input type="text" name="textfield" id="textfield">
</p>
<p>Select type:</p>
<p>
  <label>
    <input type="radio" name="RadioGroup1" value="True" id="RadioGroup1_0">
  Radio</label>
  <br>
  <label>
    <input type="radio" name="RadioGroup1" value="False" id="RadioGroup1_1">
    Radio</label>
</p>
<p>
<button id="BtnSave">Save</button>
<button id="BtnRestore">Restore</button>
  <br>
</p>
</body>
</html>

options.js

document.addEventListener("DOMContentLoaded", function() {
    document.getElementById("BtnSave").addEventListener("click", ButtonSave);
    document.getElementById("BtnRestore").addEventListener("click", ButtonsRestore);
});

function ButtonSave() {
    var ... = document.getElementById('...').checked;
    chrome.storage.sync.set({...: ...}, function() {
    });
}

function ButtonsRestore() {
    chrome.storage.sync.get(likesColor, function (retVal) {
    });
}

如何保存: CheckBox 状态,修改 RadioGroup 项目索引中的值?

如何恢复: CheckBox (Checked:= True),编辑(文字:='bla-bla')和 RadioGroup (ItemIndex := 1)?

谢谢!

2 个答案:

答案 0 :(得分:1)

复选框和单选按钮的“已选中”属性可让您查看是否已选中它们:

console.log(document.getElementById(id).checked)

您也可以使用它以编程方式设置它们,例如

document.getElementById(id).checked = true

对于文本框,其当前值位于value属性中:

console.log(document.getElementById(id).value)

同样可以设置:

document.getElementById(id).value = "whatever"

答案 1 :(得分:0)

解决

function save_options() {
  var elements = document.getElementsByName('RadioGroup1');
  for (i = 0; i < elements.length; i++) {
    if (elements[i].checked) {
      localStorage.setItem("RadioGroup1", elements[i].value);
      break;
    }
  }
}

function restore_options() {
  var elements = document.getElementsByName('RadioGroup1');
  var num = localStorage.getItem("RadioGroup1");
  elements[num].checked = true;
}