mirror of
https://github.com/wavetermdev/waveterm.git
synced 2024-12-22 16:48:23 +01:00
64 lines
2.0 KiB
TypeScript
64 lines
2.0 KiB
TypeScript
|
// Copyright 2024, Command Line Inc.
|
||
|
// SPDX-License-Identifier: Apache-2.0
|
||
|
|
||
|
import { BrowserWindow, ipcMain, webContents, WebContents } from "electron";
|
||
|
|
||
|
export async function getWebContentsByBlockId(
|
||
|
win: BrowserWindow,
|
||
|
tabId: string,
|
||
|
blockId: string
|
||
|
): Promise<WebContents> {
|
||
|
const prtn = new Promise<WebContents>((resolve, reject) => {
|
||
|
const randId = Math.floor(Math.random() * 1000000000).toString();
|
||
|
const respCh = `getWebContentsByBlockId-${randId}`;
|
||
|
win.webContents.send("webcontentsid-from-blockid", blockId, respCh);
|
||
|
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;
|
||
|
}
|
||
|
try {
|
||
|
const escapedSelector = escapeSelector(selector);
|
||
|
const queryMethod = opts?.all ? "querySelectorAll" : "querySelector";
|
||
|
const prop = opts?.inner ? "innerHTML" : "outerHTML";
|
||
|
const execExpr = `
|
||
|
Array.from(document.${queryMethod}("${escapedSelector}") || []).map(el => el.${prop});
|
||
|
`;
|
||
|
|
||
|
const results = await wc.executeJavaScript(execExpr);
|
||
|
return results;
|
||
|
} catch (e) {
|
||
|
console.error("webGetSelector error", e);
|
||
|
return null;
|
||
|
}
|
||
|
}
|