我会开始说我是一个 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();
}
});
});
最佳答案
Firefox 使用 Promise 对象,而不是回调。在 Promise 上,您可以使用成功和失败处理程序调用“then”。像这样:
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 开发,则必须使用回调。或者您可以使用“chrome”。而不是“浏览器”。如果您想使用回调而不是 Promises。
关于javascript - Firefox WebExtension 选项页面 - 如何从 storage.local 保存/恢复首选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46046095/