Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 15 additions & 41 deletions src/content-script.ts
Original file line number Diff line number Diff line change
@@ -1,53 +1,33 @@
function injectScript(path: string) {
console.log("Injecting script:", path);
const script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", path);

script.onload = () => console.log("Script loaded successfully:", path);

script.onerror = (error) => console.error("Script failed to load:", path, error);

// Try head first, then body, then documentElement as fallback
const target = document.head || document.body || document.documentElement;
if (target) {
target.appendChild(script);
console.log("Script element appended to:", target.tagName, "- src:", script.src);
} else {
console.error("No target element found for script injection");
}
target.appendChild(script);
}

function injectCSS(path: string) {
console.log("Injecting CSS:", path);
const css = document.createElement("link");
css.setAttribute("rel", "stylesheet");
css.setAttribute("type", "text/css");
css.setAttribute("href", path);

css.onload = () => console.log("CSS loaded successfully:", path);

css.onerror = (error) => console.error("CSS failed to load:", path, error);

const target = document.head || document.documentElement;
if (target) {
target.appendChild(css);
console.log("CSS element appended to:", target.tagName, "- href:", css.href);
} else {
console.error("No target element found for CSS injection");
}
}

function ensureInjection() {
console.log("Content script: Starting injection process");

const scriptUrl = chrome.runtime.getURL("build/injected.js");
const cssUrl = chrome.runtime.getURL("build/injected.css");

console.log("Content script: Resolved URLs", { scriptUrl, cssUrl });


injectScript(scriptUrl);
injectCSS(cssUrl);

console.log("Content script: Injection attempted");
}

// Wait for DOM to be ready before injecting
Expand All @@ -61,7 +41,6 @@ let resolvers: { [k: number]: any } = {};
let injectedScriptReady = false;

document.addEventListener('serenade-injected-script-ready', () => {
console.log("Injected script is ready!");
injectedScriptReady = true;
});

Expand All @@ -74,18 +53,18 @@ document.addEventListener(`serenade-injected-script-command-response`, (e: any)

async function waitForInjectedScript(timeout = 10000): Promise<void> {
if (injectedScriptReady) return;

return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
reject(new Error('Injected script ready timeout'));
}, timeout);

const handler = () => {
clearTimeout(timer);
document.removeEventListener('serenade-injected-script-ready', handler);
resolve();
};

document.addEventListener('serenade-injected-script-ready', handler);
});
}
Expand All @@ -99,20 +78,20 @@ async function sendMessageToInjectedScript(data: any): Promise<any> {

return new Promise((resolve) => {
const id = Math.random();

const timeout = setTimeout(() => {
if (resolvers[id]) {
delete resolvers[id];
resolve({ error: 'Injected script timeout' });
}
}, 5000);

const originalResolve = resolve;
resolvers[id] = (responseData: any) => {
clearTimeout(timeout);
originalResolve(responseData);
};

document.dispatchEvent(
new CustomEvent('serenade-injected-script-command-request', {
detail: { id, data },
Expand All @@ -122,18 +101,13 @@ async function sendMessageToInjectedScript(data: any): Promise<any> {
}

chrome.runtime.onMessage.addListener((request, _sender, sendResponse) => {
console.log("Content script received message:", request.type);

if (request.type === "injected-script-command-request") {
// Return a promise to handle async operations properly in MV3
(async () => {
try {
console.log("Forwarding to injected script:", request.data);
const response = await sendMessageToInjectedScript(request.data);
console.log("Injected script responded:", response);
sendResponse(response);
} catch (error) {
console.warn("Failed to send message to injected script:", error);
sendResponse({ error: "Injected script communication failed" });
}
})();
Expand All @@ -144,14 +118,14 @@ chrome.runtime.onMessage.addListener((request, _sender, sendResponse) => {
document.addEventListener("DOMContentLoaded", async () => {
try {
const settings = await chrome.storage.sync.get(["alwaysShowClickables"]);

// Wait a bit more for injected script to fully initialize
await new Promise(resolve => setTimeout(resolve, 1000));

await sendMessageToInjectedScript({
type: "clearOverlays",
});

await sendMessageToInjectedScript({
type: "updateSettings",
...settings,
Expand Down
1 change: 0 additions & 1 deletion src/editors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -341,7 +341,6 @@ class NativeInput extends Editor {

private undoStack(): { source: string; cursor: number }[] {
const editor = document.activeElement as Element;
console.log(editor);
if (!this.undoStacks.has(editor)) {
this.undoStacks.set(editor, []);
}
Expand Down
6 changes: 0 additions & 6 deletions src/injected.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,13 @@
import InjectedCommandHandler from "./injected-command-handler";

console.log("Serenade injected script loading...");

const handler = new InjectedCommandHandler();

document.addEventListener(`serenade-injected-script-command-request`, async (e: any) => {
console.log("Injected script received command:", e.detail.data);
const command = e.detail.data;
let handlerResponse = null;

if (command.type in (handler as any)) {
console.log("Executing command:", command.type);
handlerResponse = await (handler as any)[command.type](command);
console.log("Command response:", handlerResponse);
} else {
console.warn("Unknown command type:", command.type);
}
Expand All @@ -27,7 +22,6 @@ document.addEventListener(`serenade-injected-script-command-request`, async (e:
);
});

console.log("Injected script ready, dispatching ready event");
document.dispatchEvent(new CustomEvent('serenade-injected-script-ready'));


6 changes: 1 addition & 5 deletions src/ipc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,15 +96,11 @@ export default class IPC {
tab.url?.startsWith("moz-extension://") ||
tab.url?.startsWith("edge://") ||
tab.url?.startsWith("about:")) {
console.warn('Cannot execute scripts on internal browser pages');
return null;
}

try {
console.log("IPC sending message to content script:", message);
const result = await chrome.tabs.sendMessage(tab.id, message);
console.log("Content script responded:", result);
return result;
return await chrome.tabs.sendMessage(tab.id, message);
} catch (error) {
if (chrome.runtime.lastError) {
console.warn(`Content script message failed: ${chrome.runtime.lastError.message}`);
Expand Down