选项页

为了让用户设定你的扩展功能,你可能需要提供一个选项页。如果你提供了选项页,在扩展管理页面 chrome://extensions 上会提供一个链接。点击选项链接就可以打开你的选项页。

第一步:在manifest中定义你的选项页

{
  "name": "My extension",
  ...
  "options_page": "options.html",
  ...
}

第二步:编写你的选项页

下面是个选项页的范例:

// Save this script as `options.js`

// Saves options to localStorage.
function save_options() {
  var select = document.getElementById("color");
  var color = select.children[select.selectedIndex].value;
  localStorage["favorite_color"] = color;

  // Update status to let user know options were saved.
  var status = document.getElementById("status");
  status.innerHTML = "Options Saved.";
  setTimeout(function() {
    status.innerHTML = "";
  }, 750);
}

// Restores select box state to saved value from localStorage.
function restore_options() {
  var favorite = localStorage["favorite_color"];
  if (!favorite) {
    return;
  }
  var select = document.getElementById("color");
  for (var i = 0; i < select.children.length; i++) {
    var child = select.children[i];
    if (child.value == favorite) {
      child.selected = "true";
      break;
    }
  }
}
document.addEventListener('DOMContentLoaded', restore_options);
document.querySelector('#save').addEventListener('click', save_options);
<html>
<head><title>My Test Extension Options</title></head>

<body>

Favorite Color:
<select id="color">
  <option value="red">red</option>
  <option value="green">green</option>
  <option value="blue">blue</option>
  <option value="yellow">yellow</option>
</select>

<br>
<div id="status"></div>
<button id="save">Save</button>
</body>

<script src="options.js"></script>

</html>

注意事项