Home > Back-end >  Listener keeps executing in false if statement
Listener keeps executing in false if statement

Time:12-27

I am writing a Chrome extension which has a content script that executes certain actions on seclectionchange event, but it is desired for these actions to execute only when the user has enabled them in the extensions settings.

Here is my code:

const readOption = async(key) => {
  return new Promise((resolve, reject) => {
    chrome.storage.sync.get([key], function(result) {
      if (result[key] === undefined) {
        reject();
      } else {
        resolve(result[key]);
      }
    });
  });
};

async function myAsyncFunction() {
  let checkVariable = await readOption('mykey');

  if (checkVariable === true) {

    document.addEventListener('selectionchange', function(e) {
      // Doing stuff
    }, false);
  }
}

myAsyncFunction();

chrome.storage.onChanged.addListener((changes, area) => {
  if (area === 'sync' && changes.mykey) {
    myAsyncFunction();
  }
});

And here is the problem. When I change the variable from true to false as I can see by setting breakpoints the if (checkVariable === true) gets executed triggered by the onChanged listener and then its body gets skipped, because the variable is false.

But after that the selectionchange executes as if it is not in the if statement. I have to reload the page to prevent its execution.

How do I solve this issue? I thought of removing the selectionchange listener in the onchanged listener only when the mykey is set to false, but how can I do it?

CodePudding user response:

When you register an event listener without specifying {once: true}, it will be active forever in this page until you unregister it explicitly using removeEventListener with the same function reference. To ensure sameness you can simply move the function to the outer scope where it'll be persistent:

async function myAsyncFunction() {
  let checkVariable = await readOption('mykey');
  let onoff = `${checkVariable ? 'add' : 'remove'}EventListener`;
  document[onoff]('selectionchange', onSelChange);
}

function onSelChange(e) {
  // Doing stuff
}
  • Related