forked from ionic-team/capacitor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
native-bridge.js
853 lines (845 loc) · 41 KB
/
native-bridge.js
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
/*! Capacitor: https://capacitorjs.com/ - MIT License */
/* Generated File. Do not edit. */
var nativeBridge = (function (exports) {
'use strict';
var ExceptionCode;
(function (ExceptionCode) {
/**
* API is not implemented.
*
* This usually means the API can't be used because it is not implemented for
* the current platform.
*/
ExceptionCode["Unimplemented"] = "UNIMPLEMENTED";
/**
* API is not available.
*
* This means the API can't be used right now because:
* - it is currently missing a prerequisite, such as network connectivity
* - it requires a particular platform or browser version
*/
ExceptionCode["Unavailable"] = "UNAVAILABLE";
})(ExceptionCode || (ExceptionCode = {}));
class CapacitorException extends Error {
constructor(message, code, data) {
super(message);
this.message = message;
this.code = code;
this.data = data;
}
}
// For removing exports for iOS/Android, keep let for reassignment
// eslint-disable-next-line
let dummy = {};
const initBridge = (w) => {
const getPlatformId = (win) => {
var _a, _b;
if (win === null || win === void 0 ? void 0 : win.androidBridge) {
return 'android';
}
else if ((_b = (_a = win === null || win === void 0 ? void 0 : win.webkit) === null || _a === void 0 ? void 0 : _a.messageHandlers) === null || _b === void 0 ? void 0 : _b.bridge) {
return 'ios';
}
else {
return 'web';
}
};
const convertFileSrcServerUrl = (webviewServerUrl, filePath) => {
if (typeof filePath === 'string') {
if (filePath.startsWith('/')) {
return webviewServerUrl + '/_capacitor_file_' + filePath;
}
else if (filePath.startsWith('file://')) {
return (webviewServerUrl + filePath.replace('file://', '/_capacitor_file_'));
}
else if (filePath.startsWith('content://')) {
return (webviewServerUrl +
filePath.replace('content:/', '/_capacitor_content_'));
}
}
return filePath;
};
const initEvents = (win, cap) => {
cap.addListener = (pluginName, eventName, callback) => {
const callbackId = cap.nativeCallback(pluginName, 'addListener', {
eventName: eventName,
}, callback);
return {
remove: async () => {
var _a;
(_a = win === null || win === void 0 ? void 0 : win.console) === null || _a === void 0 ? void 0 : _a.debug('Removing listener', pluginName, eventName);
cap.removeListener(pluginName, callbackId, eventName, callback);
},
};
};
cap.removeListener = (pluginName, callbackId, eventName, callback) => {
cap.nativeCallback(pluginName, 'removeListener', {
callbackId: callbackId,
eventName: eventName,
}, callback);
};
cap.createEvent = (eventName, eventData) => {
const doc = win.document;
if (doc) {
const ev = doc.createEvent('Events');
ev.initEvent(eventName, false, false);
if (eventData && typeof eventData === 'object') {
for (const i in eventData) {
// eslint-disable-next-line no-prototype-builtins
if (eventData.hasOwnProperty(i)) {
ev[i] = eventData[i];
}
}
}
return ev;
}
return null;
};
cap.triggerEvent = (eventName, target, eventData) => {
const doc = win.document;
const cordova = win.cordova;
eventData = eventData || {};
const ev = cap.createEvent(eventName, eventData);
if (ev) {
if (target === 'document') {
if (cordova === null || cordova === void 0 ? void 0 : cordova.fireDocumentEvent) {
cordova.fireDocumentEvent(eventName, eventData);
return true;
}
else if (doc === null || doc === void 0 ? void 0 : doc.dispatchEvent) {
return doc.dispatchEvent(ev);
}
}
else if (target === 'window' && win.dispatchEvent) {
return win.dispatchEvent(ev);
}
else if (doc === null || doc === void 0 ? void 0 : doc.querySelector) {
const targetEl = doc.querySelector(target);
if (targetEl) {
return targetEl.dispatchEvent(ev);
}
}
}
return false;
};
win.Capacitor = cap;
};
const initLegacyHandlers = (win, cap) => {
// define cordova if it's not there already
win.cordova = win.cordova || {};
const doc = win.document;
const nav = win.navigator;
if (nav) {
nav.app = nav.app || {};
nav.app.exitApp = () => {
var _a;
if (!((_a = cap.Plugins) === null || _a === void 0 ? void 0 : _a.App)) {
win.console.warn('App plugin not installed');
}
else {
cap.nativeCallback('App', 'exitApp', {});
}
};
}
if (doc) {
const docAddEventListener = doc.addEventListener;
doc.addEventListener = (...args) => {
var _a;
const eventName = args[0];
const handler = args[1];
if (eventName === 'deviceready' && handler) {
Promise.resolve().then(handler);
}
else if (eventName === 'backbutton' && cap.Plugins.App) {
// Add a dummy listener so Capacitor doesn't do the default
// back button action
if (!((_a = cap.Plugins) === null || _a === void 0 ? void 0 : _a.App)) {
win.console.warn('App plugin not installed');
}
else {
cap.Plugins.App.addListener('backButton', () => {
// ignore
});
}
}
return docAddEventListener.apply(doc, args);
};
}
// deprecated in v3, remove from v4
cap.platform = cap.getPlatform();
cap.isNative = cap.isNativePlatform();
win.Capacitor = cap;
};
const initVendor = (win, cap) => {
const Ionic = (win.Ionic = win.Ionic || {});
const IonicWebView = (Ionic.WebView = Ionic.WebView || {});
const Plugins = cap.Plugins;
IonicWebView.getServerBasePath = (callback) => {
var _a;
(_a = Plugins === null || Plugins === void 0 ? void 0 : Plugins.WebView) === null || _a === void 0 ? void 0 : _a.getServerBasePath().then((result) => {
callback(result.path);
});
};
IonicWebView.setServerBasePath = (path) => {
var _a;
(_a = Plugins === null || Plugins === void 0 ? void 0 : Plugins.WebView) === null || _a === void 0 ? void 0 : _a.setServerBasePath({ path });
};
IonicWebView.persistServerBasePath = () => {
var _a;
(_a = Plugins === null || Plugins === void 0 ? void 0 : Plugins.WebView) === null || _a === void 0 ? void 0 : _a.persistServerBasePath();
};
IonicWebView.convertFileSrc = (url) => cap.convertFileSrc(url);
win.Capacitor = cap;
win.Ionic.WebView = IonicWebView;
};
const initLogger = (win, cap) => {
const BRIDGED_CONSOLE_METHODS = [
'debug',
'error',
'info',
'log',
'trace',
'warn',
];
const createLogFromNative = (c) => (result) => {
if (isFullConsole(c)) {
const success = result.success === true;
const tagStyles = success
? 'font-style: italic; font-weight: lighter; color: gray'
: 'font-style: italic; font-weight: lighter; color: red';
c.groupCollapsed('%cresult %c' +
result.pluginId +
'.' +
result.methodName +
' (#' +
result.callbackId +
')', tagStyles, 'font-style: italic; font-weight: bold; color: #444');
if (result.success === false) {
c.error(result.error);
}
else {
c.dir(result.data);
}
c.groupEnd();
}
else {
if (result.success === false) {
c.error('LOG FROM NATIVE', result.error);
}
else {
c.log('LOG FROM NATIVE', result.data);
}
}
};
const createLogToNative = (c) => (call) => {
if (isFullConsole(c)) {
c.groupCollapsed('%cnative %c' +
call.pluginId +
'.' +
call.methodName +
' (#' +
call.callbackId +
')', 'font-weight: lighter; color: gray', 'font-weight: bold; color: #000');
c.dir(call);
c.groupEnd();
}
else {
c.log('LOG TO NATIVE: ', call);
}
};
const isFullConsole = (c) => {
if (!c) {
return false;
}
return (typeof c.groupCollapsed === 'function' ||
typeof c.groupEnd === 'function' ||
typeof c.dir === 'function');
};
const serializeConsoleMessage = (msg) => {
if (typeof msg === 'object') {
try {
msg = JSON.stringify(msg);
}
catch (e) {
// ignore
}
}
return String(msg);
};
const platform = getPlatformId(win);
if (platform == 'android' || platform == 'ios') {
// patch document.cookie on Android/iOS
win.CapacitorCookiesDescriptor =
Object.getOwnPropertyDescriptor(Document.prototype, 'cookie') ||
Object.getOwnPropertyDescriptor(HTMLDocument.prototype, 'cookie');
let doPatchCookies = false;
// check if capacitor cookies is disabled before patching
if (platform === 'ios') {
// Use prompt to synchronously get capacitor cookies config.
// https://stackoverflow.com/questions/29249132/wkwebview-complex-communication-between-javascript-native-code/49474323#49474323
const payload = {
type: 'CapacitorCookies.isEnabled',
};
const isCookiesEnabled = prompt(JSON.stringify(payload));
if (isCookiesEnabled === 'true') {
doPatchCookies = true;
}
}
else if (typeof win.CapacitorCookiesAndroidInterface !== 'undefined') {
const isCookiesEnabled = win.CapacitorCookiesAndroidInterface.isEnabled();
if (isCookiesEnabled === true) {
doPatchCookies = true;
}
}
if (doPatchCookies) {
Object.defineProperty(document, 'cookie', {
get: function () {
if (platform === 'ios') {
// Use prompt to synchronously get cookies.
// https://stackoverflow.com/questions/29249132/wkwebview-complex-communication-between-javascript-native-code/49474323#49474323
const payload = {
type: 'CapacitorCookies.get',
};
const res = prompt(JSON.stringify(payload));
return res;
}
else if (typeof win.CapacitorCookiesAndroidInterface !== 'undefined') {
return win.CapacitorCookiesAndroidInterface.getCookies();
}
},
set: function (val) {
const cookiePairs = val.split(';');
const domainSection = val.toLowerCase().split('domain=')[1];
const domain = cookiePairs.length > 1 &&
domainSection != null &&
domainSection.length > 0
? domainSection.split(';')[0].trim()
: '';
if (platform === 'ios') {
// Use prompt to synchronously set cookies.
// https://stackoverflow.com/questions/29249132/wkwebview-complex-communication-between-javascript-native-code/49474323#49474323
const payload = {
type: 'CapacitorCookies.set',
action: val,
domain,
};
prompt(JSON.stringify(payload));
}
else if (typeof win.CapacitorCookiesAndroidInterface !== 'undefined') {
win.CapacitorCookiesAndroidInterface.setCookie(domain, val);
}
},
});
}
// patch fetch / XHR on Android/iOS
// store original fetch & XHR functions
win.CapacitorWebFetch = window.fetch;
win.CapacitorWebXMLHttpRequest = {
abort: window.XMLHttpRequest.prototype.abort,
getAllResponseHeaders: window.XMLHttpRequest.prototype.getAllResponseHeaders,
getResponseHeader: window.XMLHttpRequest.prototype.getResponseHeader,
open: window.XMLHttpRequest.prototype.open,
send: window.XMLHttpRequest.prototype.send,
setRequestHeader: window.XMLHttpRequest.prototype.setRequestHeader,
};
let doPatchHttp = false;
// check if capacitor http is disabled before patching
if (platform === 'ios') {
// Use prompt to synchronously get capacitor http config.
// https://stackoverflow.com/questions/29249132/wkwebview-complex-communication-between-javascript-native-code/49474323#49474323
const payload = {
type: 'CapacitorHttp',
};
const isHttpEnabled = prompt(JSON.stringify(payload));
if (isHttpEnabled === 'true') {
doPatchHttp = true;
}
}
else if (typeof win.CapacitorHttpAndroidInterface !== 'undefined') {
const isHttpEnabled = win.CapacitorHttpAndroidInterface.isEnabled();
if (isHttpEnabled === true) {
doPatchHttp = true;
}
}
if (doPatchHttp) {
// fetch patch
window.fetch = async (resource, options) => {
var _a;
if (!(resource.toString().startsWith('http:') ||
resource.toString().startsWith('https:'))) {
return win.CapacitorWebFetch(resource, options);
}
const tag = `CapacitorHttp fetch ${Date.now()} ${resource}`;
console.time(tag);
try {
// intercept request & pass to the bridge
let headers = options === null || options === void 0 ? void 0 : options.headers;
if ((options === null || options === void 0 ? void 0 : options.headers) instanceof Headers) {
headers = Object.fromEntries(options.headers.entries());
}
const nativeResponse = await cap.nativePromise('CapacitorHttp', 'request', {
url: resource,
method: (options === null || options === void 0 ? void 0 : options.method) ? options.method : undefined,
data: (options === null || options === void 0 ? void 0 : options.body) ? options.body : undefined,
headers: headers,
});
nativeResponse.headers = Object.entries(nativeResponse.headers).reduce((acc, [key, value]) => {
acc[key.toLowerCase()] = value;
return acc;
}, {});
let data = ((_a = nativeResponse.headers['content-type']) === null || _a === void 0 ? void 0 : _a.startsWith('application/json'))
? JSON.stringify(nativeResponse.data) : nativeResponse.data;
// use null data for 204 No Content HTTP response
if (nativeResponse.status === 204) {
data = null;
}
// intercept & parse response before returning
const response = new Response(data, {
headers: nativeResponse.headers,
status: nativeResponse.status,
});
/*
* copy url to response, `cordova-plugin-ionic` uses this url from the response
* we need `Object.defineProperty` because url is an inherited getter on the Response
* see: https://stackoverflow.com/a/57382543
* */
Object.defineProperty(response, 'url', {
value: nativeResponse.url,
});
console.timeEnd(tag);
return response;
}
catch (error) {
console.timeEnd(tag);
return Promise.reject(error);
}
};
// XHR event listeners
const addEventListeners = function () {
this.addEventListener('abort', function () {
if (typeof this.onabort === 'function')
this.onabort();
});
this.addEventListener('error', function () {
if (typeof this.onerror === 'function')
this.onerror();
});
this.addEventListener('load', function () {
if (typeof this.onload === 'function')
this.onload();
});
this.addEventListener('loadend', function () {
if (typeof this.onloadend === 'function')
this.onloadend();
});
this.addEventListener('loadstart', function () {
if (typeof this.onloadstart === 'function')
this.onloadstart();
});
this.addEventListener('readystatechange', function () {
if (typeof this.onreadystatechange === 'function')
this.onreadystatechange();
});
this.addEventListener('timeout', function () {
if (typeof this.ontimeout === 'function')
this.ontimeout();
});
};
// XHR patch abort
window.XMLHttpRequest.prototype.abort = function () {
if (this._url == null ||
!(this._url.startsWith('http:') || this._url.startsWith('https:'))) {
return win.CapacitorWebXMLHttpRequest.abort.call(this);
}
this.readyState = 0;
this.dispatchEvent(new Event('abort'));
this.dispatchEvent(new Event('loadend'));
};
// XHR patch open
window.XMLHttpRequest.prototype.open = function (method, url) {
this._url = url;
if (!(url.startsWith('http:') || url.toString().startsWith('https:'))) {
return win.CapacitorWebXMLHttpRequest.open.call(this, method, url);
}
Object.defineProperties(this, {
_headers: {
value: {},
writable: true,
},
_method: {
value: method,
writable: true,
},
readyState: {
get: function () {
var _a;
return (_a = this._readyState) !== null && _a !== void 0 ? _a : 0;
},
set: function (val) {
this._readyState = val;
this.dispatchEvent(new Event('readystatechange'));
},
},
response: {
value: '',
writable: true,
},
responseText: {
value: '',
writable: true,
},
responseURL: {
value: '',
writable: true,
},
status: {
value: 0,
writable: true,
},
});
addEventListeners.call(this);
this.readyState = 1;
};
// XHR patch set request header
window.XMLHttpRequest.prototype.setRequestHeader = function (header, value) {
if (this._url == null ||
!(this._url.startsWith('http:') || this._url.startsWith('https:'))) {
return win.CapacitorWebXMLHttpRequest.setRequestHeader.call(this, header, value);
}
this._headers[header] = value;
};
// XHR patch send
window.XMLHttpRequest.prototype.send = function (body) {
if (this._url == null ||
!(this._url.startsWith('http:') || this._url.startsWith('https:'))) {
return win.CapacitorWebXMLHttpRequest.send.call(this, body);
}
const tag = `CapacitorHttp XMLHttpRequest ${Date.now()} ${this._url}`;
console.time(tag);
try {
this.readyState = 2;
// intercept request & pass to the bridge
cap
.nativePromise('CapacitorHttp', 'request', {
url: this._url,
method: this._method,
data: body !== null ? body : undefined,
headers: this._headers != null && Object.keys(this._headers).length > 0
? this._headers
: undefined,
})
.then((nativeResponse) => {
var _a;
// intercept & parse response before returning
if (this.readyState == 2) {
this.dispatchEvent(new Event('loadstart'));
this._headers = nativeResponse.headers;
this.status = nativeResponse.status;
this.response = nativeResponse.data;
this.responseText = ((_a = nativeResponse.headers['Content-Type']) === null || _a === void 0 ? void 0 : _a.startsWith('application/json'))
? JSON.stringify(nativeResponse.data) : nativeResponse.data;
this.responseURL = nativeResponse.url;
this.readyState = 4;
this.dispatchEvent(new Event('load'));
this.dispatchEvent(new Event('loadend'));
}
console.timeEnd(tag);
})
.catch((error) => {
this.dispatchEvent(new Event('loadstart'));
this.status = error.status;
this._headers = error.headers;
this.response = error.data;
this.responseText = JSON.stringify(error.data);
this.responseURL = error.url;
this.readyState = 4;
this.dispatchEvent(new Event('error'));
this.dispatchEvent(new Event('loadend'));
console.timeEnd(tag);
});
}
catch (error) {
this.dispatchEvent(new Event('loadstart'));
this.status = 500;
this._headers = {};
this.response = error;
this.responseText = error.toString();
this.responseURL = this._url;
this.readyState = 4;
this.dispatchEvent(new Event('error'));
this.dispatchEvent(new Event('loadend'));
console.timeEnd(tag);
}
};
// XHR patch getAllResponseHeaders
window.XMLHttpRequest.prototype.getAllResponseHeaders = function () {
if (this._url == null ||
!(this._url.startsWith('http:') || this._url.startsWith('https:'))) {
return win.CapacitorWebXMLHttpRequest.getAllResponseHeaders.call(this);
}
let returnString = '';
for (const key in this._headers) {
if (key != 'Set-Cookie') {
returnString += key + ': ' + this._headers[key] + '\r\n';
}
}
return returnString;
};
// XHR patch getResponseHeader
window.XMLHttpRequest.prototype.getResponseHeader = function (name) {
if (this._url == null ||
!(this._url.startsWith('http:') || this._url.startsWith('https:'))) {
return win.CapacitorWebXMLHttpRequest.getResponseHeader.call(this, name);
}
return this._headers[name];
};
}
}
// patch window.console on iOS and store original console fns
const isIos = getPlatformId(win) === 'ios';
if (win.console && isIos) {
Object.defineProperties(win.console, BRIDGED_CONSOLE_METHODS.reduce((props, method) => {
const consoleMethod = win.console[method].bind(win.console);
props[method] = {
value: (...args) => {
const msgs = [...args];
cap.toNative('Console', 'log', {
level: method,
message: msgs.map(serializeConsoleMessage).join(' '),
});
return consoleMethod(...args);
},
};
return props;
}, {}));
}
cap.logJs = (msg, level) => {
switch (level) {
case 'error':
win.console.error(msg);
break;
case 'warn':
win.console.warn(msg);
break;
case 'info':
win.console.info(msg);
break;
default:
win.console.log(msg);
}
};
cap.logToNative = createLogToNative(win.console);
cap.logFromNative = createLogFromNative(win.console);
cap.handleError = err => win.console.error(err);
win.Capacitor = cap;
};
function initNativeBridge(win) {
const cap = win.Capacitor || {};
// keep a collection of callbacks for native response data
const callbacks = new Map();
const webviewServerUrl = typeof win.WEBVIEW_SERVER_URL === 'string' ? win.WEBVIEW_SERVER_URL : '';
cap.getServerUrl = () => webviewServerUrl;
cap.convertFileSrc = filePath => convertFileSrcServerUrl(webviewServerUrl, filePath);
// Counter of callback ids, randomized to avoid
// any issues during reloads if a call comes back with
// an existing callback id from an old session
let callbackIdCount = Math.floor(Math.random() * 134217728);
let postToNative = null;
const isNativePlatform = () => true;
const getPlatform = () => getPlatformId(win);
cap.getPlatform = getPlatform;
cap.isPluginAvailable = name => Object.prototype.hasOwnProperty.call(cap.Plugins, name);
cap.isNativePlatform = isNativePlatform;
// create the postToNative() fn if needed
if (getPlatformId(win) === 'android') {
// android platform
postToNative = data => {
var _a;
try {
win.androidBridge.postMessage(JSON.stringify(data));
}
catch (e) {
(_a = win === null || win === void 0 ? void 0 : win.console) === null || _a === void 0 ? void 0 : _a.error(e);
}
};
}
else if (getPlatformId(win) === 'ios') {
// ios platform
postToNative = data => {
var _a;
try {
data.type = data.type ? data.type : 'message';
win.webkit.messageHandlers.bridge.postMessage(data);
}
catch (e) {
(_a = win === null || win === void 0 ? void 0 : win.console) === null || _a === void 0 ? void 0 : _a.error(e);
}
};
}
cap.handleWindowError = (msg, url, lineNo, columnNo, err) => {
const str = msg.toLowerCase();
if (str.indexOf('script error') > -1) ;
else {
const errObj = {
type: 'js.error',
error: {
message: msg,
url: url,
line: lineNo,
col: columnNo,
errorObject: JSON.stringify(err),
},
};
if (err !== null) {
cap.handleError(err);
}
postToNative(errObj);
}
return false;
};
if (cap.DEBUG) {
window.onerror = cap.handleWindowError;
}
initLogger(win, cap);
/**
* Send a plugin method call to the native layer
*/
cap.toNative = (pluginName, methodName, options, storedCallback) => {
var _a, _b;
try {
if (typeof postToNative === 'function') {
let callbackId = '-1';
if (storedCallback &&
(typeof storedCallback.callback === 'function' ||
typeof storedCallback.resolve === 'function')) {
// store the call for later lookup
callbackId = String(++callbackIdCount);
callbacks.set(callbackId, storedCallback);
}
const callData = {
callbackId: callbackId,
pluginId: pluginName,
methodName: methodName,
options: options || {},
};
if (cap.isLoggingEnabled && pluginName !== 'Console') {
cap.logToNative(callData);
}
// post the call data to native
postToNative(callData);
return callbackId;
}
else {
(_a = win === null || win === void 0 ? void 0 : win.console) === null || _a === void 0 ? void 0 : _a.warn(`implementation unavailable for: ${pluginName}`);
}
}
catch (e) {
(_b = win === null || win === void 0 ? void 0 : win.console) === null || _b === void 0 ? void 0 : _b.error(e);
}
return null;
};
if (win === null || win === void 0 ? void 0 : win.androidBridge) {
win.androidBridge.onmessage = function (event) {
returnResult(JSON.parse(event.data));
};
}
/**
* Process a response from the native layer.
*/
cap.fromNative = result => {
returnResult(result);
};
const returnResult = (result) => {
var _a, _b;
if (cap.isLoggingEnabled && result.pluginId !== 'Console') {
cap.logFromNative(result);
}
// get the stored call, if it exists
try {
const storedCall = callbacks.get(result.callbackId);
if (storedCall) {
// looks like we've got a stored call
if (result.error) {
// ensure stacktraces by copying error properties to an Error
result.error = Object.keys(result.error).reduce((err, key) => {
// use any type to avoid importing util and compiling most of .ts files
err[key] = result.error[key];
return err;
}, new cap.Exception(''));
}
if (typeof storedCall.callback === 'function') {
// callback
if (result.success) {
storedCall.callback(result.data);
}
else {
storedCall.callback(null, result.error);
}
}
else if (typeof storedCall.resolve === 'function') {
// promise
if (result.success) {
storedCall.resolve(result.data);
}
else {
storedCall.reject(result.error);
}
// no need to keep this stored callback
// around for a one time resolve promise
callbacks.delete(result.callbackId);
}
}
else if (!result.success && result.error) {
// no stored callback, but if there was an error let's log it
(_a = win === null || win === void 0 ? void 0 : win.console) === null || _a === void 0 ? void 0 : _a.warn(result.error);
}
if (result.save === false) {
callbacks.delete(result.callbackId);
}
}
catch (e) {
(_b = win === null || win === void 0 ? void 0 : win.console) === null || _b === void 0 ? void 0 : _b.error(e);
}
// always delete to prevent memory leaks
// overkill but we're not sure what apps will do with this data
delete result.data;
delete result.error;
};
cap.nativeCallback = (pluginName, methodName, options, callback) => {
if (typeof options === 'function') {
console.warn(`Using a callback as the 'options' parameter of 'nativeCallback()' is deprecated.`);
callback = options;
options = null;
}
return cap.toNative(pluginName, methodName, options, { callback });
};
cap.nativePromise = (pluginName, methodName, options) => {
return new Promise((resolve, reject) => {
cap.toNative(pluginName, methodName, options, {
resolve: resolve,
reject: reject,
});
});
};
cap.withPlugin = (_pluginId, _fn) => dummy;
cap.Exception = CapacitorException;
initEvents(win, cap);
initLegacyHandlers(win, cap);
initVendor(win, cap);
win.Capacitor = cap;
}
initNativeBridge(w);
};
initBridge(typeof globalThis !== 'undefined'
? globalThis
: typeof self !== 'undefined'
? self
: typeof window !== 'undefined'
? window
: typeof global !== 'undefined'
? global
: {});
dummy = initBridge;
Object.defineProperty(exports, '__esModule', { value: true });
return exports;
})({});