【发布时间】:2017-09-05 02:14:10
【问题描述】:
我先说我是 JavaScript 新手(我更喜欢 Bash 人)...
我正在尝试创建一个 Firefox WebExtension 来禁用 Ctrl+Q 快捷方式并在按下 Ctrl+Q 时播放声音。我还想让用户从选项菜单中的一小部分声音中进行选择。到目前为止,所有这些都在工作。
我遇到的唯一问题是当用户更改声音并单击“保存”时,在重新加载扩展程序之前不会在 Ctrl+Q 上播放新声音。
做一些谷歌搜索,我认为问题与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();
}
});
});
【问题讨论】:
-
您正在使用
browser.*命名空间,它期望为异步函数返回 Promise,而不是使用回调。如果要使用回调,则需要使用chrome.*命名空间。因此,基本上将所有 API 调用从browser.storage.local.set()更改为chrome.storage.local.set()。这样做通常会导致您的扩展程序在 Firefox 和 Chrome 上都能正常运行。
标签: javascript firefox firefox-addon firefox-addon-webextensions