summaryrefslogtreecommitdiff
path: root/plugin_loader/static/library.js
blob: 2ec6ce89c4fb682ca7ec97cb2880d7bdb86d08c8 (plain)
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
class PluginEventTarget extends EventTarget { }
method_call_ev_target = new PluginEventTarget();

window.addEventListener("message", function(evt) {
    let ev = new Event(evt.data.call_id);
    ev.data = evt.data.result;
    method_call_ev_target.dispatchEvent(ev);
}, false);

async function call_server_method(method_name, arg_object={}) {
    let id = `${new Date().getTime()}`;
    console.debug(JSON.stringify({
        "id": id,
        "method": method_name,
        "args": arg_object
    }));
    return new Promise((resolve, reject) => {
        method_call_ev_target.addEventListener(`${id}`, function (event) {
            if (event.data.success) resolve(event.data.result);
            else reject(event.data.result);
        });
    });
}

async function fetch_nocors(url, request={}) {
    let args = { method: "POST", headers: {}, body: "" };
    request = {...args, ...request};
    request.url = url;
    request.data = request.body;
    delete request.body; //maintain api-compatibility with fetch
    return await call_server_method("http_request", request);
}

async function call_plugin_method(method_name, arg_object={}) {
    if (plugin_name == undefined) 
        throw new Error("Plugin methods can only be called from inside plugins (duh)");
    return await call_server_method("plugin_method", {
        'plugin_name': plugin_name,
        'method_name': method_name,
        'args': arg_object
    });
}

async function execute_in_tab(tab, run_async, code) {
    return await call_server_method("execute_in_tab", {
        'tab': tab,
        'run_async': run_async,
        'code': code
    });
}