I am building a custom browser extension that injects a custom functional button into a specific target website’s UI layout. The extension functions perfectly when navigating through the site dynamically via client-side router links.
However, if a user does a hard browser refresh (Ctrl+R / Cmd+R) or lands on a deep URL directly, my script throws an uncaught error. The target element or the object data I need to extract from the page returns undefined.
It seems like my script is executing before the target website’s asynchronous framework (React/Ember/Vue) has fully mounted the DOM elements or loaded its internal state.
What I’ve Tried:
- Setting
"run_at": "document_end"and"document_idle"in mymanifest.json. Whiledocument_idlereduces the frequency of the error, it still consistently breaks on slow network connections. - Using a basic
setTimeout, which feels hacky and unreliable because network speeds vary. - I suspect I need to implement a more robust lifecycle hook or a MutationObserver, but I am struggling to capture the exact moment the application data layer becomes safe to interact with.
Relevant Extension Code:
manifest.json:
{
"manifest_version": 3,
"name": "Custom UI Enhancer",
"version": "1.0",
"permissions": ["activeTab"],
"content_scripts": [
{
"matches": ["https://*://*"],
"js": ["content.js"],
"run_at": "document_idle"
}
]
}
content.js:
function injectCustomButton() {
// Target container on the host website
const targetMenu = document.querySelector(".action-bar");
// BUG: targetMenu is null on initial hard refresh, throwing the error below
if (!targetMenu) {
console.error("Target menu container not found in DOM.");
return;
}
// Logic to append extension button
const btn = document.createElement("button");
btn.className = "custom-ext-action";
btn.innerText = "Extension Action";
targetMenu.appendChild(btn);
}
// Initial execution
injectCustomButton();
Errors / Logs:
When loading the page directly, the browser developer console outputs:
Uncaught TypeError: Cannot read properties of null (reading 'appendChild')
at injectCustomButton (content.js:14:14)
at content.js:18:1
What is the industry-standard way for content scripts to wait for specific DOM elements or dynamic state properties to exist on modern single-page apps (SPAs) before executing injection logic?