-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathWebViewNativeApi.cs
254 lines (234 loc) · 11.3 KB
/
WebViewNativeApi.cs
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
using System.Reflection;
using System.Text.Json;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
namespace WebViewNativeApi
{
public class NativeBridge
{
private const string DEFAULT_SCHEME = "native://";
private const string INTERFACE_JS = "window['createNativeBridgeProxy'] = " +
"(name, methods, properties, scheme = '" + DEFAULT_SCHEME + "') =>" +
"{" +
" let apiCalls = new Map();" +
"" +
" function createRequest(target, success, reject, argumentsList) {" +
" let uuid = crypto.randomUUID();" +
" while(apiCalls.has(uuid)) { uuid = crypto.randomUUID(); };" +
" apiCalls.set(uuid, { 'success': success, 'reject': reject, 'arguments': argumentsList });" +
" location.href = scheme + name + '/' + target + '/' + uuid + '/';" +
" }" +
"" +
" return new Proxy({" +
" getArguments : (token) => {" +
" return apiCalls.get(token).arguments;" +
" }," +
" returnValue : (token, value) => {" +
" let ret = value;" +
" try { ret = JSON.parse(ret); } catch(e) { };" +
" let callback = apiCalls.get(token).success;" +
" if (callback && typeof callback === 'function')" +
" callback(ret);" +
" apiCalls.delete(token);" +
" }," +
" rejectCall : (token, error) => {" +
" let callback = apiCalls.get(token).reject;" +
" if (callback && typeof callback === 'function')" +
" callback(error);" +
" apiCalls.delete(token);" +
" }" +
" }," +
" {" +
" get: (target, prop, receiver) => {" +
" if (methods.includes(prop)) {" +
" return new Proxy(() => {}, {" +
" apply: (target, thisArg, argumentsList) => {" +
" return new Promise((success, reject) => {" +
" createRequest(prop, success, reject, argumentsList);" +
" });" +
" }" +
" });" +
" }" +
" if (!properties.includes(prop)) {" +
" return Reflect.get(target, prop, receiver);" +
" }" +
" return new Promise((success, reject) => {" +
" createRequest(prop, success, reject, []);" +
" });" +
" }," +
" set: (target, prop, value) => {" +
" return new Promise((success, reject) => {" +
" createRequest(prop, success, reject, [value]);" +
" });" +
" }" +
" });" +
"};";
private readonly WebView _webView = null;
private readonly Dictionary<(string, string), Object> _targets = new();
private bool _isInit = false;
private (string, string, string, Object) _query = ("", "", "", null);
public NativeBridge(WebView wv)
{
_webView = wv;
_webView.Navigated += OnWebViewInit;
_webView.Navigating += OnWebViewNavigatin;
}
public void AddTarget(string name, Object obj, string sheme = DEFAULT_SCHEME)
{
if (obj == null)
return;
_targets.Add((name, sheme), obj);
if (_isInit)
AddTargetToWebView(name, obj, sheme);
}
private void OnWebViewInit(object sender, WebNavigatedEventArgs e)
{
if (!_isInit)
{
RunJS(INTERFACE_JS);
foreach (KeyValuePair<(string, string), Object> entry in _targets)
AddTargetToWebView(entry.Key.Item1, entry.Value, entry.Key.Item2);
_isInit = true;
}
}
private void OnWebViewNavigatin(object sender, WebNavigatingEventArgs e)
{
if (!_isInit)
return;
foreach (KeyValuePair<(string, string), Object> entry in _targets)
{
string startStr = entry.Key.Item2 + entry.Key.Item1;
if (!e.Url.StartsWith(startStr))
continue;
string request = e.Url[(e.Url.IndexOf(startStr) + startStr.Length)..].ToLower();
request = request.Trim(new Char[] { '/', '\\' });
string[] requestArgs = request.Split('/');
if (requestArgs.Length < 2)
return;
e.Cancel = true;
string prop = requestArgs[0];
string token = requestArgs[1];
Type type = entry.Value.GetType();
if (type.GetMember(prop) == null)
{
RunJS("window." + entry.Key.Item1 + ".rejectCall('" + token + "', 'Member not found!');");
return;
}
_query = (entry.Key.Item1, token, prop, entry.Value);
Task.Run(() =>
{
RunCommand(_query.Item1, _query.Item2, _query.Item3, _query.Item4);
_query = ("", "", "", null);
});
return;
}
}
private void AddTargetToWebView(string name, Object obj, string sheme)
{
Type type = obj.GetType();
List<string> methods = new List<string>();
List<string> properties = new List<string>();
foreach (MethodInfo method in type.GetMethods())
methods.Add(method.Name);
foreach (PropertyInfo p in type.GetProperties())
properties.Add(p.Name);
RunJS("window." + name + " = window.createNativeBridgeProxy('" + name + "', " + JsonSerializer.Serialize(methods) + ", " +
JsonSerializer.Serialize(properties) + ", '" + sheme + "');");
}
private static bool IsAsyncMethod(MethodInfo method)
{
Type attType = typeof(AsyncStateMachineAttribute);
var attrib = (AsyncStateMachineAttribute)method.GetCustomAttribute(attType);
return (attrib != null);
}
private async void RunCommand(string name, string token, string prop, Object obj)
{
try
{
Type type = obj.GetType();
string readArguments = await RunJS("window." + name + ".getArguments('" + token + "');");
JsonElement[] jsonObjects = JsonSerializer.Deserialize<JsonElement[]>(Regex.Unescape(readArguments));
MethodInfo method = type.GetMethod(prop);
if (method != null)
{
var parameters = method.GetParameters();
Object[] arguments = new Object[parameters.Length];
foreach (ParameterInfo arg in parameters)
{
if (jsonObjects.Length <= arg.Position)
{
arguments[arg.Position] = arg.DefaultValue;
}
else
{
JsonElement jsonObject = jsonObjects[arg.Position];
arguments[arg.Position] = jsonObject.Deserialize(arg.ParameterType);
}
}
Object result = method.Invoke(obj, arguments);
string serializedRet = "null";
if (result != null)
{
if (IsAsyncMethod(method))
{
Task task = (Task)result;
await task.ConfigureAwait(false);
result = (object)((dynamic)task).Result;
}
serializedRet = JsonSerializer.Serialize(result);
}
await RunJS("window." + name + ".returnValue('" + token + "', " + serializedRet + ");");
}
else
{
PropertyInfo propety = type.GetProperty(prop);
if (propety != null)
{
if (jsonObjects != null && jsonObjects.Length > 0)
propety.SetValue(obj, jsonObjects[0].Deserialize(propety.PropertyType));
string result = JsonSerializer.Serialize(propety.GetValue(obj, null));
await RunJS("window." + name + ".returnValue('" + token + "', " + result + ");");
}
else
{
await RunJS("window." + name + ".rejectCall('" + token + "', 'Member not found!');");
}
}
}
catch(Exception e)
{
string error = e.Message + " (" + e.GetHashCode().ToString() + ")";
error = error.Replace("\\n", " ");
error = error.Replace("\n", " ");
error = error.Replace("\"", """);
await RunJS("window." + name + ".rejectCall('" + token + "', '" + error + "');");
}
}
public async Task sendEvent(string type, Dictionary<string, string> detail = null, bool optBubbles = false, bool optCancelable = false, bool optComposed = false)
{
List<string> opts = new List<string>();
if (optBubbles)
opts.Add("bubbles: true");
if (optCancelable)
opts.Add("cancelable: true");
if (optComposed)
opts.Add("composed: true");
if (detail != null)
opts.Add("detail: " + JsonSerializer.Serialize(detail));
string optsStr = (opts.Count > 0 ? ", { " + String.Join(", ", opts) + " }" : "");
await RunJS("const nativeEvent = new CustomEvent('" + type + "'" + optsStr + "); document.dispatchEvent(nativeEvent);");
}
public Task<string> RunJS(string code)
{
return _webView.Dispatcher.DispatchAsync(() =>
{
string resultCode = code;
if (resultCode.Contains("\\n") || resultCode.Contains('\n'))
resultCode = "console.error('Called js from native api contain new line symbols!')";
else
resultCode = "try { " + resultCode + " } catch(e) { console.error(e); }";
return _webView.EvaluateJavaScriptAsync(resultCode);
});
}
}
}