injectContentScript function application exported

Last updated: 2026-03-05T10:53:28.864Z

Metrics

LOC: 17 Complexity: 4 Params: 1

Signature

injectContentScript(tabId: number): : Promise<boolean>

Summary

Inject a content script into a tab. Used to re-inject after cross-origin navigations that destroy the previous content-script context. Chrome re-injects the manifest-declared content script automatically when the page loads. This function polls until the content script is responsive (via PING) or the timeout is reached.

Source Code

export async function injectContentScript(tabId: number): Promise<boolean> {
  const maxAttempts = 6;
  const retryDelayMs = 250;

  for (let i = 0; i < maxAttempts; i++) {
    await sleep(retryDelayMs);
    try {
      const response = await chrome.tabs.sendMessage(tabId, { type: "PING" });
      if (response?.pong) return true;
    } catch {
      // content script not yet ready — retry
    }
  }

  log.warn(`Content script did not respond in tab ${tabId} after polling`);
  return false;
}

Dependencies (Outgoing)

graph LR injectContentScript["injectContentScript"] sleep["sleep"] injectContentScript -->|calls| sleep style injectContentScript fill:#dbeafe,stroke:#2563eb,stroke-width:2px click injectContentScript "8371aca98c2d1d41.html" click sleep "25404f77365ed229.html"
TargetType
sleep calls

Impact (Incoming)

graph LR injectContentScript["injectContentScript"] OrchestratorCallbacks["OrchestratorCallbacks"] sendStepToContentScript["sendStepToContentScript"] executeNavigateStep["executeNavigateStep"] runLoop["runLoop"] OrchestratorCallbacks -->|uses| injectContentScript sendStepToContentScript -->|calls| injectContentScript executeNavigateStep -->|calls| injectContentScript runLoop -->|calls| injectContentScript style injectContentScript fill:#dbeafe,stroke:#2563eb,stroke-width:2px click injectContentScript "8371aca98c2d1d41.html" click OrchestratorCallbacks "984a6b93df2ea9af.html" click sendStepToContentScript "98a94012c260f4a2.html" click executeNavigateStep "b662d9614e361217.html" click runLoop "c94a70bb97b4ccad.html"