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:
What I've tried:
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);
}
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?