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

160
Visualizações
How to prevent content script from having DOM injection race conditions?

I have a content script which modifies the DOM based on the current url.

My background script listens to chrome.webNavigation.onHistoryStateUpdated and sends a message to the content script with the current url:

chrome.webNavigation.onHistoryStateUpdated.addListener(onNavigation, { url: ... });


async function onNavigation(details) {
        const { url, tabId } = details;
        chrome.tabs.sendMessage(tabId, { id: 'my-msg-id', url });
}

Then, based on the url, the content script injects a certain div to the current page:

chrome.runtime.onMessage.addListener(async (message, sender, sendResponse) => {
    if (message.id === 'my-msg-id' && message.url === '...') {
        await injectDiv();
    }
    ...
});

My problem is that sometimes, the same div gets injected to the DOM twice.

This looks like a race condition that happens:

  1. When the page loads slowly.
  2. When the user navigates quickly between urls or goes back and forth between pages.

What I've tried:

  1. Wrapping the injection logic with a guard like this:
async function injectDiv() {
   if (document.getElementById('my-div-id')) {
       return;
   }
   const myDiv = document.createElement('div');
   myDiv.id = 'my-div-id';
   ... // Some async code that waits until the container is loaded to the DOM using setInterval
   const container = document.querySelector('div.container');
   container.appendChild(myDiv);
}
  1. Using throttle to limit the url triggers sent from the background script to the content script:
const throttledNav = throttle(onNavigation, 2000, { leading: true, trailing: true });
chrome.webNavigation.onHistoryStateUpdated.addListener(throttledNav, { url: ... });

It looks like it helped with most cases but I still get a double (or even a triple) duplicate DOM injection of my div from time to time, which makes my extension look very buggy.

What can I do to fix this?

about 4 years ago · Juan Pablo Isaza
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