How to manage state in a chrome extension in this scenario

28 Views Asked by At

I have an extension, which actively listens for keydowns and I have to keep in memory what the user has typed. So far I had just one file in which there were globally accessible variables and now I want to refactor the code into smaller files, but I am not sure keeping the variables globally accessible throughout all of the files is a smart idea.

I tried to use chrome.storage.local for this purpose. I created this simple file in which there would be wrapper functions for setting and getting data.

function set(key, value) {
    chrome.storage.local.set({ [key]: value });
}

/**
 * @return {Promise}
 */
function get(key) {
    return chrome.storage.local.get([key]);
}

But due to the asynchronous nature of the storage I run into issues, example, now because I want to get this variable from state and I have to await, inside handleNavigation event.preventDefault is not working.

function handleKeyDown(event) {

    let { isSearching } = await get('isSearching');
    if (isSearching) {
        return handleNavigation(event);
    }
    ...
function handleNavigation(event) {
    event.preventDefault();
    event.stopPropagation();
    ...

Am I missing something as to how to make state management work in this case or does the code itself need to be adjusted somehow?

0

There are 0 best solutions below