Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

165
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!