1 |
|
-module(chrme_runtime). |
2 |
|
-export([evaluate/2, call_function_on/4, add_binding/2, remove_binding/2, |
3 |
|
register_exception_thrown_handler/2, unregister_exception_thrown_handler/2]). |
4 |
|
|
5 |
|
%% Evaluate a JavaScript expression in the page |
6 |
|
evaluate(Name, Expr0) -> |
7 |
6 |
Expr = chrme_util:to_binary(Expr0), |
8 |
6 |
case chrme_cdp:call(Name, <<"Runtime.evaluate">>, #{expression => Expr}) of |
9 |
|
{ok, Resp} -> |
10 |
6 |
Result = maps:get(<<"result">>, Resp), |
11 |
6 |
{ok, Result}; |
12 |
|
Err -> |
13 |
:-( |
Err |
14 |
|
end. |
15 |
|
|
16 |
|
%% Call a function on a remote object |
17 |
|
call_function_on(Name, ObjectId, FuncDecl0, Args) -> |
18 |
:-( |
FuncDecl = chrme_util:to_binary(FuncDecl0), |
19 |
:-( |
Params = #{objectId => ObjectId, functionDeclaration => FuncDecl, arguments => Args}, |
20 |
:-( |
case chrme_cdp:call(Name, <<"Runtime.callFunctionOn">>, Params) of |
21 |
|
{ok, Resp} -> |
22 |
:-( |
Result = maps:get(<<"result">>, Resp), |
23 |
:-( |
{ok, Result}; |
24 |
|
Err -> |
25 |
:-( |
Err |
26 |
|
end. |
27 |
|
|
28 |
|
%% Add a binding in the runtime |
29 |
|
add_binding(Name, BindingName0) -> |
30 |
:-( |
NameBin = chrme_util:to_binary(BindingName0), |
31 |
:-( |
chrme_cdp:call(Name, <<"Runtime.addBinding">>, #{name => NameBin}). |
32 |
|
|
33 |
|
%% Remove a binding |
34 |
|
remove_binding(Name, BindingName0) -> |
35 |
:-( |
NameBin = chrme_util:to_binary(BindingName0), |
36 |
:-( |
chrme_cdp:call(Name, <<"Runtime.removeBinding">>, #{name => NameBin}). |
37 |
|
|
38 |
|
%% Subscribe to exceptionThrown events |
39 |
|
-spec register_exception_thrown_handler(Name :: chrme_session:name(), Fun :: fun((map()) -> any())) -> reference(). |
40 |
|
register_exception_thrown_handler(Name, Fun) -> |
41 |
:-( |
Ref = make_ref(), |
42 |
:-( |
CallbackName = {chrme_runtime, register_exception_thrown_handler, Name, Ref}, |
43 |
:-( |
CallbackFun = fun |
44 |
:-( |
(stop) -> false; |
45 |
|
(Msg = #{<<"method">> := <<"Runtime.exceptionThrown">>, <<"params">> := Params}) -> |
46 |
:-( |
Fun(Params), |
47 |
:-( |
true; |
48 |
:-( |
(_) -> false |
49 |
|
end, |
50 |
:-( |
chrme_ws_apic:add_callback(Name, {CallbackName, CallbackFun}), |
51 |
:-( |
Ref. |
52 |
|
|
53 |
|
%% Unsubscribe from exceptionThrown events |
54 |
|
-spec unregister_exception_thrown_handler(Name :: chrme_session:name(), Ref :: reference()) -> ok. |
55 |
|
unregister_exception_thrown_handler(Name, Ref) -> |
56 |
:-( |
CallbackName = {chrme_runtime, register_exception_thrown_handler, Name, Ref}, |
57 |
:-( |
chrme_ws_apic:remove_callback(Name, CallbackName), |
58 |
:-( |
ok. |