Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

170
Visualizações
Listener keeps executing in false if statement

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?

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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
}
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda