[英]Chrome extension keyboard shortcut takes 2 presses to change value
嘗試在我正在開發的Chrome擴展程序中實現Chrome鍵盤快捷鍵 API時遇到一個奇怪的問題。 簡短地說,我必須按兩次指定的鍵盤快捷鍵才能更改存儲的值。
這是我的鍵盤快捷鍵監聽器:
chrome.commands.onCommand.addListener(function(command) {
chrome.storage.sync.get([command], function(result) {
toggle = result[command];
});
toggle = toggle_value(toggle)
chrome.storage.sync.set({[command]: toggle }, function() {
console.log( {[command]: toggle} );
});
});
還有我的toggle_value()
函數:
function toggle_value(value) {
if(value == 0) {
return 1;
} else if(value == 1) {
return 0;
}
}
我的鍵盤快捷鍵偵聽器接收清單中設置的command
,從Chrome同步存儲數據庫中獲取相同鍵名的對應值,切換該值,然后使用相同的鍵名將其設置回Chrome同步存儲。
如前所述,僅連續兩次按下鍵盤快捷鍵后,才能真正切換command
鍵的值。 我花了幾個小時調試它,但是沒有運氣,請幫助我。
問題。 您使用的功能是異步的,但是您的代碼正在同步運行。 如果嵌套,您的代碼應該可以工作。
chrome.commands.onCommand.addListener(function(command) {
chrome.storage.sync.get([command], function(result) {
toggle = result[command];
toggle = toggle_value(toggle);
chrome.storage.sync.set({[command]: toggle }, function() {
console.log( {[command]: toggle} );
});
});
});
建議。 您應該研究Promises
以更優雅地處理異步代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.