TypeError when accessing post attributes inside addPostMenuButton extension

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 my manifest.json. While document_idle reduces 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?


Hi again @ThisSlopIsInsane !

The usual approach is to use a MutationObserver rather than relying on setTimeout() or assuming that document_idle means the site’s framework has finished mounting.

document_idle determines when the browser injects your content script relative to document loading; it doesn’t guarantee that a React, Vue, or Ember application has rendered a particular component or finished fetching its data.

For your example, I’d use a MutationObserver to watch for the target element, with an initial check in case it already exists:

function injectCustomButton() {
  const targetMenu = document.querySelector(".action-bar");

  if (!targetMenu) {
    return false;
  }

  // Prevent duplicate injection.
  if (targetMenu.querySelector(".custom-ext-action")) {
    return true;
  }

  const btn = document.createElement("button");
  btn.className = "custom-ext-action";
  btn.textContent = "Extension Action";

  targetMenu.appendChild(btn);
  return true;
}

function initialize() {
  if (injectCustomButton()) {
    return;
  }

  const observer = new MutationObserver(() => {
    if (injectCustomButton()) {
      observer.disconnect();
    }
  });

  observer.observe(document.documentElement, {
    childList: true,
    subtree: true
  });
}

initialize();

A few things to keep in mind:

Handle SPA navigation: The site may replace the target element during client-side navigation. If that happens, you’ll need to detect navigation or observe the relevant DOM changes and reinject when appropriate.

Wait for data separately: A DOM element existing doesn’t necessarily mean the application’s internal data is ready. If you depend on a specific data property, use a documented application event or API where possible, or implement a bounded readiness check with appropriate cleanup.

Avoid permanent observers: Disconnect observers when they’re no longer needed, and scope them to the smallest practical DOM subtree to reduce unnecessary work.

Check the manifest match pattern: "https://*://*" is invalid. Use "https://*/*" for all HTTPS sites, or preferably restrict matches to the specific website you’re targeting.

One final distinction: if the target data is held entirely inside a framework’s internal state rather than exposed through the DOM, a MutationObserver alone won’t solve that problem. The correct solution depends on how the site exposes that state.

For a content script that only needs to insert a button when a particular element appears, though, a MutationObserver plus an idempotent injection function is a solid starting point.

I hope your extension is coming along well!
Regards, AC1DST4R
Self Employed Developer / Unofficial MDN Support

Thank you @AC1DST4R , I appreciate it