Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ulixee
GitHub Repository: ulixee/secret-agent
Path: blob/main/plugins/execute-js/lib/ClientPlugin.ts
2579 views
1
import { ISendToCoreFn } from '@secret-agent/interfaces/IClientPlugin';
2
import ClientPlugin from '@secret-agent/plugin-utils/lib/ClientPlugin';
3
import type { Agent, Tab, FrameEnvironment } from 'secret-agent';
4
import { IExecuteJsArgs } from './IExecuteJsArgs';
5
6
const { name: pluginId } = require('../package.json');
7
8
export default class ExecuteJsClientPlugin extends ClientPlugin {
9
public static id = pluginId;
10
public static coreDependencyIds = [pluginId];
11
12
public onAgent(agent: Agent, sendToCore: ISendToCoreFn) {
13
agent.executeJs = this.executeJs.bind(this, sendToCore);
14
}
15
16
public onTab(agent: Agent, tab: Tab, sendToCore: ISendToCoreFn) {
17
tab.executeJs = this.executeJs.bind(this, sendToCore);
18
}
19
20
public onFrameEnvironment(
21
agent: Agent,
22
frameEnvironment: FrameEnvironment,
23
sendToCore: ISendToCoreFn,
24
) {
25
frameEnvironment.executeJs = this.executeJs.bind(this, sendToCore);
26
}
27
28
// PRIVATE
29
30
private executeJs<T extends any[]>(
31
sendToCore: ISendToCoreFn,
32
fn: string | ((...args: T) => any),
33
...args: T
34
): Promise<any> {
35
let fnName = '';
36
let fnSerialized = fn as string;
37
if (typeof fn !== 'string') {
38
fnName = fn.name;
39
fnSerialized = `(${fn.toString()})(${JSON.stringify(args).slice(1, -1)});`;
40
}
41
return sendToCore(pluginId, <IExecuteJsArgs>{
42
fnName,
43
fnSerialized,
44
args,
45
isolateFromWebPageEnvironment: false,
46
});
47
}
48
}
49
50