npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

autooptions

v1.3.3

Published

AutoOptions - Chrome Storage API helper

Downloads

83

Readme

AutoOptions - Chrome Storage API Helper

AutoOptions is a JavaScript/TypeScript library that simplifies the process of saving and managing extension preferences automatically using the Chrome Storage API. It is designed to be used in Chrome extensions to handle user configurations and persist them across sessions. It can handle categories, exceptions, default values and more. Also, it's really fast.

Table of Contents

Installation

You can install AutoOptions using npm:

npm install autooptions

To use AutoOptions in your project, import the AutoOptions module.

<script type="module" src="options.js"></script>
import { AutoOptions } from "../node_modules/autooptions/AutoOptions.mjs";

Usage

background.js

chrome.runtime.onInstalled.addListener((details) => {
    if (details.reason === "install") setDefaultConfig();
    
    // to apply changes made in options using session storage later,  include this here:
    chrome.storage.session.setAccessLevel({accessLevel: "TRUSTED_AND_UNTRUSTED_CONTEXTS"});
});

chrome.runtime.onMessage.addListener((message)=> {
    if (message === "openOptions") setDefaultConfig();
});

function setDefaultConfig() {
    // --- IMPORTANT: ONLY OPEN THE PAGE / POPUP HERE IF YOU USE AUTOOPTIONS IN IT! ---

    // get URL of the options HTML from the manifest file
    const page = chrome.runtime.getManifest().options_page; // full page
    const embedded = chrome.runtime.getManifest().options_ui.page; // embedded
    const popup = chrome.runtime.getManifest().action.default_popup; // popup

    // open and close the tab to create the default config
    createTab(popup);

    // OR use this if you have a welcome message (except for popups)
    chrome.runtime.openOptionsPage();
}

function createTab(tab) {
    chrome.tabs.create({
        url: tab
    });

    // the rest is handled in the JS file of the tab
}

options.js

The init method of AutoOptions returns a Promise. This allows you to perform actions after the initialization is complete. The Promise will resolve if the initialization is successful and reject if there is an error.

AutoOptions.init(options)
  .then(() => {
    // Initialization successful
  })
  .catch((error) => {
    // Error occurred during initialization
  });

The options parameter is an object containing the developer-defined options for AutoOptions.

To reset your inputs to the default configuration, you can use the resetToDefault method:

AutoOptions.resetToDefault();

To see if user just installed your extension, use AutoOptions.isFirstTime:

if (AutoOptions.isFirstTime) {
  // ...
}

script.js

This is an example on how to handle the configuration changes live.


const configName = 'page';
let configuration = {};

  chrome.storage.sync.get([configName]).then(storedConfiguration => {
    if (configName in storedConfiguration) {
      configuration = storedConfiguration[configName];
    } else {
      // fallback if configuration somehow wasn't created on extension install
      chrome.runtime.sendMessage("openOptions");
    };
  });

  // message listener
    chrome.storage.onChanged.addListener((storedConfiguration, storageType) => {
        const newConfig = storedConfiguration[configName].newValue;

        switch (storageType) {
            case 'sync':
                this.configuration = newConfig;
                break;
            case 'session':
                this.onConfigChange(newConfig);
                break;
        }
    });

    onConfigChange(updatedConfig) {
        const { category, setting } = updatedConfig;

        switch (category) {
            case 'ui':
                // your script
                break;
            case 'buttons':
                // your script
                break;
            case 'misc':
                // your script
                break;
            default:
                H.error.throwException(`${category} is an unknown configuration category!`);
                break;
        }
    }

HTML Inputs

AutoOptions automatically handles HTML inputs and validates them.

  • Inputs that should be included must have an ID set.
  • Radio inputs should also have a name set.

Supported input types and properties can be defined using the autooptions-* (or ao-) attribute. It provides a way to customize the behavior of input elements in the configuration process. It allows you to specify additional properties for each input, influencing how the configuration is handled.

  1. autooptions-default: This attribute marks an input element as checked by default, applicable to radio buttons and checkboxes. Use this instead of "checked".

  2. autooptions-value="": If an input requires a default value, you can specify it using this attribute. Use this instead of "value".

  3. autooptions-category="": To group similar inputs under a category, add this attribute to the input.

  4. autooptions-exclude: This attribute can be used to exclude specific inputs from the configuration process, ensuring they are not considered when saving the configuration.

Developer Options

The following developer options can be provided when initializing AutoOptions:

  • configName: Specifies the type of options (accepted values: 'page', 'popup', 'site'). (Required)
  • closeOptionsOnInstall: Specifies whether to close the options page after opening it in a new tab on install to save the configuration for the first time. Should be always true if options is popup, should be false if options page has a welcome message on first install. (Default value: true, Accepted values: true, false)
  • applyChangesInstantly: Specifies whether changes made in options should take effect immediately. (Default value: true, Accepted values: true, false)

License

AutoOptions is licensed under the CC BY 4.0 license. You are free to use, modify, and distribute this library as long as you provide appropriate attribution to the original author (skyfighteer).