Firefox WebExtension选项页面 - 如何从storage.local保存/恢复首选项?

时间:2017-09-05 02:14:10

标签: javascript firefox firefox-addon firefox-webextensions

我开始说我是一个JavaScript新手(我更像是一个Bash人)...

我尝试创建Firefox WebExtension以禁用Ctrl + Q快捷键,并在按下Ctrl + Q时播放声音。我还想让用户从选项菜单中的一小部分声音中进行选择。到目前为止,所有这些都在起作用

我遇到的唯一障碍是,当用户更改声音并点击“保存”时,新的声音不会在Ctrl + Q上播放,直到重新加载扩展名为止。< / p>

做一些谷歌搜索,我认为问题与storage API is asynchronous的事实有关。根据我的收集,我需要使用回调来设置声音选项。这不是我在下面做的吗?该选项在options.js中设置,然后background.js播放声音。

我很感激任何帮助。

options.js

// Saves options to browser.storage
function save_options() {
  browser.storage.local.set({
    favoriteSound: document.getElementById('CtrlQSound').value,
    }, function() {
      // Update status to let user know options were saved.
      var status = document.getElementById('status');
      status.textContent = 'Options saved.';
      setTimeout(function() {
        status.textContent = '';
    }, 750);
  });
};

// Restores select box state using the preferences stored in browser.storage
function restore_options() {
  // Use default value sound = 'Sound0'
  browser.storage.local.get({
    favoriteSound: 'Sound0',
  }, function(items) {
    document.getElementById('CtrlQSound').value = items.favoriteSound;
  });
};

document.addEventListener('DOMContentLoaded', restore_options);
document.getElementById('save').addEventListener('click', save_options);

background.js

browser.storage.local.get("favoriteSound", function(result) {
  browser.commands.onCommand.addListener(function(SoundToggle) {
    if (result.favoriteSound == "Sound0"){
      new Audio("Sound0.ogg").play();
    }
    else if (result.favoriteSound == "Sound1"){
      new Audio("Sound1.ogg").play();
    }
    else if (result.favoriteSound == "Sound2"){
      new Audio("Sound2.ogg").play();
    }
  });
});

1 个答案:

答案 0 :(得分:1)

Firefox使用Promise对象,而不是回调。在承诺上,你可以打电话给&#34;然后&#34;有成功和失败的处理程序。像这样:

browser.storage.local.set({
    favoriteSound: document.getElementById('CtrlQSound').value
}).then(onSuccess, onError);

function onSuccess() {
    // Saving into storage.local succeeded

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

function onError() {
    // Saving into storage local failed.
    // You might want to use a notification to display this error / warning to the user.
});

如果您正在为Chrome开发,则必须使用回调。或者你可以使用&#34; chrome。&#34;而不是&#34;浏览器。&#34;如果你想使用回调而不是Promises。