Adding an options page to a Chrome extension

This article can be read in about 5 minutes.
PR

The purpose 

Some Chrome extensions, when their icon is clicked, display an “Options” menu item that opens the options page.

This article adds options to the extension as described above.

For the basics of creating Chrome extensions, please refer to the following page.

PR

Implementation

Modify manifest

The following settings will be added to the manifest file. 

    "permissions": ["storage"],
    "options_page": "options.html",

The Storage permission allows saving and loading settings.

Create option page

Create the HTML displayed when a menu option is clicked. (It will be created on the same page as the manifest.)

This time, create a page with a single checkbox.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>オプション</title>
</head>
<body>
  <h1>オプション</h1>
  <div>
    <label for="onoff">on/off:</label>
    <input type="checkbox" id="onoff"  />
  </div>
  <div id="msg"></div>
  <script src="option.js"></script>
</body>
</html>

Next, we will create the option.js file, which is referenced by the HTML above. (Create this on the same page as the manifest.)

I got an error when I wrote code between the <script></script> tags in HTML.

The error disappeared and the code executed successfully when I loaded an external .js file.

The JavaScript is as follows

chrome.storage.sync.get(null, (options) => { ////load setting
    let onoff = false;
    if (options.my_plugin== undefined || options.my_plugin.onoff == undefined) {
      onoff = true;////デフォルトはTrue
    } else {
      onoff = options.my_plugin.onoff////got value from setting
    }
    document.getElementById("onoff").checked = onoff;/////update GUI
    document.getElementById('onoff').addEventListener('change', function() {////this is called by update GUI
      let options = {
        my_plugin: {onoff: document.getElementById("onoff").checked}////create object to save
      }
      chrome.storage.sync.set(options);  ////save setting
    })
  });

Loading settings from other scripts in the extension

Other JavaScript files used by the extension (such as sample.js in the example below) can also load the saved settings.

load by

chrome.storage.sync.get()

get setting by

options.my_plugin.onoff

PR

Result

We added an options page to the Chrome extension, enabling the extension to access its settings.

PR

Reference

拡張機能マニフェストで API アクセス許可を宣言する - Microsoft Edge Developer documentation
マニフェストで API のアクセス許可を宣言する方法について説明します。
とほほのChrome拡張機能開発入門 - とほほのWWW入門

comment

Copied title and URL