waveterm/emain/emain-web.ts

66 lines
2.2 KiB
TypeScript
Raw Permalink Normal View History

2024-09-10 21:50:55 +02:00
// Copyright 2024, Command Line Inc.
// SPDX-License-Identifier: Apache-2.0
2024-10-17 23:34:02 +02:00
import { ipcMain, webContents, WebContents } from "electron";
2024-12-02 19:56:56 +01:00
import { WaveBrowserWindow } from "./emain-window";
2024-09-10 21:50:55 +02:00
2024-10-17 23:34:02 +02:00
export function getWebContentsByBlockId(ww: WaveBrowserWindow, tabId: string, blockId: string): Promise<WebContents> {
2024-09-10 21:50:55 +02:00
const prtn = new Promise<WebContents>((resolve, reject) => {
const randId = Math.floor(Math.random() * 1000000000).toString();
const respCh = `getWebContentsByBlockId-${randId}`;
2024-10-17 23:34:02 +02:00
ww?.activeTabView?.webContents.send("webcontentsid-from-blockid", blockId, respCh);
2024-09-10 21:50:55 +02:00
ipcMain.once(respCh, (event, webContentsId) => {
if (webContentsId == null) {
resolve(null);
return;
}
const wc = webContents.fromId(parseInt(webContentsId));
resolve(wc);
});
setTimeout(() => {
reject(new Error("timeout waiting for response"));
}, 2000);
});
return prtn;
}
function escapeSelector(selector: string): string {
return selector
.replace(/\\/g, "\\\\")
.replace(/"/g, '\\"')
.replace(/'/g, "\\'")
.replace(/\n/g, "\\n")
.replace(/\r/g, "\\r")
.replace(/\t/g, "\\t");
}
export type WebGetOpts = {
all?: boolean;
inner?: boolean;
};
export async function webGetSelector(wc: WebContents, selector: string, opts?: WebGetOpts): Promise<string[]> {
if (!wc || !selector) {
return null;
}
2024-09-18 08:10:09 +02:00
const escapedSelector = escapeSelector(selector);
const queryMethod = opts?.all ? "querySelectorAll" : "querySelector";
const prop = opts?.inner ? "innerHTML" : "outerHTML";
const execExpr = `
(() => {
const toArr = x => (x instanceof NodeList) ? Array.from(x) : (x ? [x] : []);
try {
const result = document.${queryMethod}("${escapedSelector}");
const value = toArr(result).map(el => el.${prop});
return { value };
} catch (error) {
return { error: error.message };
}
})()`;
const results = await wc.executeJavaScript(execExpr);
if (results.error) {
throw new Error(results.error);
2024-09-10 21:50:55 +02:00
}
2024-09-18 08:10:09 +02:00
return results.value;
2024-09-10 21:50:55 +02:00
}