简体   繁体   中英

Save and restore settings on Chrome

I have 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) {
    });
}

How save: CheckBox status, value in Edit and RadioGroup ItemIndex?

How restore: CheckBox (Checked := True), Edit (Text := 'bla-bla') and RadioGroup (ItemIndex := 1)?

Thanks!

The "checked" property of both checkboxes and radio buttons will let you see if they are selected:

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

You can also use this to programmatically set them, eg

document.getElementById(id).checked = true

For text boxes, their current value is in the value property:

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

and likewise can be set:

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

Solved

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM