0

I'm having a weird issue trying to implement the Chrome keyboard shortcuts API in a Chrome extension I'm developing. Put shortly, I have to press the designated keyboard shortcut 2 times to change the stored value.

Here's my keyboard shortcut listener:

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} );
    });
});

And my toggle_value() function:

function toggle_value(value) {
    if(value == 0) {
        return 1;
    } else if(value == 1) {
        return 0;
    }   
}

My keyboard shortcut listener receives a command as set in the manifest, gets the corresponding value of the same key name from the Chrome synced storage database, toggles the value then it sets it back to the Chrome synced storage using the same key name.

As stated earlier, the value of the command key is only really toggled after pressing the keyboard shortcut 2 consecutive times. I spent hours debugging this with no luck, please help me.

Achraf Almouloudi
  • 756
  • 10
  • 27
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – wOxxOm Apr 29 '18 at 15:28
  • Chrome API is [asynchronous](https://developer.chrome.com/extensions/overview#sync), see the linked topic for solutions. – wOxxOm Apr 29 '18 at 15:29
  • @wOxxOm I wouldn't exactly call this a duplicate but the question you linked does indeed address the issue I have in my code. – Achraf Almouloudi Apr 29 '18 at 22:32
  • That's what a duplicate is here. It doesn't have to be an exact copy as long as the answer applies. – wOxxOm Apr 30 '18 at 05:14

1 Answers1

1

Problem. The functions you are using are asynchronous, but your code is running synchronously. Your code should work if nested.

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} );
        });
    });
});

Suggestion. You should look into Promises to handle asynchronous code more elegantly.

EyuelDK
  • 3,029
  • 2
  • 19
  • 27
  • Very interesting, I know how asynchronous JavaScript works but I'm new to the Chrome API and I didn't expect it to be such. I totally understand the solution and it works, thank you. – Achraf Almouloudi Apr 29 '18 at 22:32