File size: 1,491 Bytes
fb38ec5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
const LOCAL_API_URL = "http://localhost:3000/v1/events";
const FALLBACK_API_URL = "http://0.0.0.0:3000/v1/events"; // Need to point to 0.0.0.0 in some deploys
let currentApiUrl = LOCAL_API_URL;

async function injectScript(tabId, changeInfo, tab) {
  if (changeInfo.status === "complete" && tab.url) {
    try {
      await chrome.scripting.executeScript({
        target: { tabId },
        files: ["inject.js"],
      });
    } catch (error) {
      console.error("Script injection failed:", error);
    }
  }
}

// Listen for tab updates
chrome.tabs.onUpdated.addListener(injectScript);

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.type !== "SAVE_EVENTS") {
    return false;
  }

  console.log("[Recorder Background] Saving events to", currentApiUrl);

  const sendEvents = async (url) => {
    try {
      const response = await fetch(url, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(message),
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      sendResponse({ success: true });
    } catch (error) {
      if (url === LOCAL_API_URL) {
        // Retry with fallback URL
        currentApiUrl = FALLBACK_API_URL;
        return sendEvents(FALLBACK_API_URL);
      }
      sendResponse({ success: false, error: error.message });
    }
  };

  sendEvents(currentApiUrl);
  return true;
});