简体   繁体   中英

Firefox extension how to get extension storage value

I created a temporary Firefox add-on which opens a new tab when an icon is clicked. I used the example provided in this link:

https://github.com/mdn/webextensions-examples/tree/master/open-my-page-button

This works fine but the new tab opens to a fixed URL. So added a preferences page using the code provided in this link:

https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Implement_a_settings_page

Now I'm able to save a URL in the preference page of the extension and the saved URL can be verified in the Extension Storage, here is an image showing it:

浏览器控制台图片

function openPage() {
    browser.tabs.create({
        url: "https://www.google.com"
    });
}

browser.browserAction.onClicked.addListener(openPage);

function onError(error) {
    console.log(`Error: ${error}`);
}

function onGot(item) {
    let preference_url = "https://www.google.com";
    if (item.preference_url) {
        preference_url = item.preference_url;
    }
    browser.storage.local.set({ type : preference_url });
}

let getting = browser.storage.sync.get("preference_url");
getting.then(onGot, onError);

On the third line I have url: "https://www.google.com" but I would like to use the value in the extension storage.

Since you have the onGot(item) function working. You should give your preference_url a name to be traced from.

As you can see, when you inspect the [ Extension Storage ] . The preference_url is stored in a key named as type .

So, you should give it a name like preferred_URL or other name for easy tracking.

function onGot(item) {
    let preference_url = "https://www.google.com";
    if (item.preference_url) {
        preference_url = item.preference_url;
    }
    browser.storage.local.set({ "preferred_URL" : preference_url });
}

Alright, it seems like a bit of work is needed before we can access the value of preferred_URL .

function openPage() {
  // <...>.storage.local.get is an async function,
  // we need wrap our function below it
  browser.storage.local.get(['preferred_URL'], function(result) {
    console.log(result);
    browser.tabs.create({
      // The key in result.key means the name of the "key" holding the value.
      "url": result.preferred_URL
    })
  });
}

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