-
Notifications
You must be signed in to change notification settings - Fork 41
/
WebView_mac.js
825 lines (792 loc) · 36.8 KB
/
WebView_mac.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
module.exports = (function() {
if(global.__TINT.WebView) {
return global.__TINT.WebView;
}
var $ = process.bridge.objc;
var util = require('Utilities');
var Container = require('Container');
var core = require('_core');
function createWebViewPolicyHandler() {
var result = function() {
/* self, cmd, webview, action, request, frame, listener */
var request = arguments[4];
var listener = arguments[6];
try {
var presult = this.fireEvent('policy',[request('URL')('absoluteURL')('description')('UTF8String')]);
presult = typeof(presult) === 'undefined' ? true : presult;
listener(presult ? 'use' : 'ignore');
} catch (e) {
console.log(e.message);
console.log(e.stack);
process.exit(1);
}
};
return result;
}
function createWKWebViewPolicyHandler(pass,fail) {
var result = function() {
/* self, cmd, webview, navigation, decisionHandler */
var navigation = arguments[3];
var decisionHandler = arguments[4];
try {
var presult = this.fireEvent('policy', [navigation('request')('URL')('absoluteURL')('description')('UTF8String')]);
presult = typeof(presult) === 'undefined' ? true : presult;
var d = decisionHandler.reinterpret(32);
var block = new core.__block_literal_1(d);
var bfunc = core.createUnwrapperFunction(block.invoke,['v',['?','I']]);
bfunc(block.ref(), presult ? pass : fail);
} catch (e) {
console.log(e.message);
console.log(e.stack);
process.exit(1);
}
};
return result;
}
function createWebViewBridge() {
if(!$.tintWebKitResponseDelegate) {
process.bridge.objc.delegates = process.bridge.objc.delegates || {};
// This class implements a set of javascript -> objective-c functions on the object window.TintMessages
// within each webview. This allows communication to-from webkit and our hosting JS instance. Only serializable
// strings can be passed back-forth. For now, only post message is used.
var tintWebKitResponseDelegate = $.NSObject.extend('tintWebKitResponseDelegate');
tintWebKitResponseDelegate.addMethod('initWithJavascriptObject:', ['@',[tintWebKitResponseDelegate, $.selector, '@']],
util.errorwrap(function() {
/* self, cmd, id */
var self = arguments[0];
var id = arguments[2];
self.callback = process.bridge.objc.delegates[id.toString()];
process.bridge.objc.delegates[id.toString()] = null;
return self;
}));
tintWebKitResponseDelegate.addClassMethod('webScriptNameForSelector:','@@::',
util.errorwrap(function() { return $("postMessage"); }));
tintWebKitResponseDelegate.addClassMethod('isSelectorExcludedFromWebScript:','B@::',
util.errorwrap(function() {
/* self,_cmd,sel */
var sel = arguments[2];
return sel === "postMessage" ? $.NO : $.YES;
}));
/**
* @event message
* @memberof WebView
* @description Fires when the top frame HTML document has executed window.postMessageToHost(). The message is a string
* passed into the callback provided as the first argument.
*/
tintWebKitResponseDelegate.addMethod('postMessage','v@:@',
util.errorwrap(function() {
/* self, cmd, message */
var self = arguments[0];
var message = arguments[2];
var args;
try {
args = JSON.parse(message.toString());
} catch (e) {
args = message.toString();
}
if(args.type === "console") {
self.callback.fireEvent('console',[args.subtype, args.args]);
} else {
self.callback.fireEvent('message',[args.message]);
}
}));
tintWebKitResponseDelegate.register();
}
return $.tintWebKitResponseDelegate;
}
function fireError() {
/* self, cmd, webview, navigationOrError, error */
var navigationOrError = arguments[3];
var error = arguments[4];
try {
if(this.useWKWebView) {
this.fireEvent('error',[error('localizedDescription')('UTF8String')]);
} else {
this.fireEvent('error',[navigationOrError('localizedDescription')('UTF8String')]);
}
} catch (e) {
console.log(e.message);
console.log(e.stack);
process.exit(1);
}
}
function fireLoad() {
/* self, _cmd, frameOrWebview, navigation */
try {
if(!this.useWKWebView) {
// Create the comm delegate and assign it to window.TintMessages, then override window.postMessageToHost.
var frameWinObj = this.nativeView('windowScriptObject');
if(frameWinObj) {
frameWinObj('setValue',this.private.commDelegate,'forKey',$('TintMessages'));
this.execute("window.postMessageToHost = function(e) { try { window.TintMessages.postMessage(JSON.stringify({type:'message',message:e})); } catch (e) {} }");
this.execute("console = console || {};");
this.execute("console.log = function() { try { window.TintMessages.postMessage(JSON.stringify({type:'console',subtype:'log',args:arguments})); } catch(e) {} };");
this.execute("console.warn = function() { try { window.TintMessages.postMessage(JSON.stringify({type:'console',subtype:'warn',args:arguments})); } catch(e) {} };");
this.execute("console.error = function() { try { window.TintMessages.postMessage(JSON.stringify({type:'console',subtype:'error',args:arguments})); } catch(e) {} };");
this.execute("console.info = function() { try { window.TintMessages.postMessage(JSON.stringify({type:'console',subtype:'info',args:arguments})); } catch(e) {} };");
}
}
var loc = this.location;
if(this.private.previousUrl !== loc) {
this.fireEvent('location-change', [this.private.previousUrl,loc]);
this.private.previousUrl = loc;
}
this.fireEvent('load');
} catch(e) {
console.error(e.message);
console.error(e.stack);
process.exit(1);
}
}
function fireNewWindow() {
/* self,_cmd,webview,config,navAction,features */
var config = arguments[3];
try {
var newWebview = new WebView({}, this.useWKWebView ? {configuration:config} : {});
return (this.fireEvent('new-window', [newWebview])) === false ? null : newWebview.nativeView;
} catch (e) {
console.log(e.message);
console.log(e.stack);
process.exit(1);
}
}
/**
* @class WebView
* @description The WebView allows HTML content to be embedded in an application as a normal control. It uses WebKit on OSX
* and the latest version of IE installed when on Windows (forcing IE9 or above).
* @extends Container
*/
/**
* @new
* @memberof WebView
* @description Creates a new webview control.
* @example
* require('Common');
* var win = new Window();
* win.visible = true;
* var webView = new WebView();
* win.appendChild(webView);
* webView.left=webView.top=webView.right=webView.bottom=0;
* webView.location = "https://www.google.com";
* @screenshot-window {win}
*/
// TODO: Add progress event
function WebView(properties, options, inherited) {
var firstLoad = true;
this.useWKWebView = ((process.bridge.objc.WKWebView && WebView.useNewWKWebView) ? true : false);
options = options || {};
options.delegates = options.delegates || [];
options.nonStandardEvents = true;
options.doNotInitialize = true;
// TODO: auth
// TODO: alert
// TODO: confirm
// TODO: input
// TODO: download
// TODO: resize
// TOOD: close (new?)
this.nativeViewClass = this.nativeClass = this.nativeClass || this.useWKWebView ? $.WKWebView : $.WebView;
if(this.useWKWebView) {
// WKWebView actions
options.delegates = options.delegates.concat([
/**
* @event loading
* @memberof WebView
* @description Fires when a new request for a HTML document at the top frame is committed, this means the
* new URL has passed security requirement checks, but has yet to begin making a network request
* or render any parts of the page.
*/
['webView:didCommitNavigation:', 'v@:@@', function() {
/* self, cmd, webview, navigation */
if(firstLoad) {
firstLoad = false;
} else {
this.fireEvent('unload');
}
this.fireEvent('loading');
}.bind(this)],
/**
* @event error
* @memberof WebView
* @description Fires when an unrecoverable error occurs, such as being unable to retrieve the requested page for the top frame,
* or when a security error has occured. The callback function is passed the translated description of
* the error message that occured.
*/
['webView:didFailNavigation:withError:', 'v@:@@@', fireError.bind(this)],
['webView:didFailProvisionalNavigation:withError:', 'v@:@@@', fireError.bind(this)],
/**
* @event location-change
* @memberof WebView
* @description Fires when a change in location occurs (E.g., a new URL has been requested). This differs from a
* load (or loading) event in-that it does not fire if the current page is reloaded and the URL or
* location has not changed. The event handler is passed two arguments, the first is the old URL,
* and the second is the new URL.
*/
/**
* @event load
* @memberof WebView
* @description Fires when a new request for a HTML document at the top frame has loaded and the document object
* model is ready.
*/
['webView:didFinishNavigation:', 'v@:@@', fireLoad.bind(this)],
/*
['webView:didReceiveAuthenticationChallenge:completionHandler:', ['v',['@',':','@','@','?']], function(self, cmd, webview, challenge, completionHandler) {
try {
var credentials = this.fireEvent('auth');
if(credentials && credentials.username && credentials.password) {
var creds = $.NSURLCredential('credentialWithUser',$(credentials.username),'password',$(credentials.password),'persistence', $.NSURLCredentialPersistenceForSession);
var d = completionHandler.reinterpret(32);
var block = new core.__block_literal_1(d);
var bfunc = core.createUnwrapperFunction(block.invoke,['v',['?','I','@']]);
bfunc(block.ref(), $.NSURLSessionAuthChallengeUseCredential, creds);
}
} catch (e) {
console.log(e.message);
console.log(e.stack);
process.exit(1);
}
}.bind(this)],
*/
/**
* @event redirect
* @memberof WebView
* @description Fires when a redirect from a server request occurs.
*/
['webView:didReceiveServerRedirectForProvisionalNavigation:', 'v@:@@', function() { /*self, cmd, webview, navigation*/ this.fireEvent('redirect'); }.bind(this)],
/**
* @event request
* @memberof WebView
* @description Fires when a new request for a HTML document at the top frame has occured, but before loaded or load has occured.
*/
['webView:didStartProvisionalNavigation:', 'v@:@@', function() { /*self, cmd, webview, navigation*/ this.fireEvent('request'); }.bind(this)],
/**
* @event policy
* @memberof WebView
* @description Fires the callback for the event to ask if the page about to be loaded should be blocked.
* The URL for the target resource or navigation is passed in to the event callback. If false (and only strictly false)
* is returned by the event handler the request is blocked. If any other value is returned (including undefined or null)
* the resource is allowed to load and continue. This event is useful if you want to screen URL's being loaded and
* deny navigation and resource requests based on the URL (e.g., such as a net nanny or for security reasons).
* @noscreenshot
* @example
* require('Common');
* var win = new Window();
* var webView = new WebView();
* win.appendChild(webView);
* webView.left=webView.right=webView.top=webView.bottom=0;
* win.visible = true;
* webView.addEventListener('policy', function(url) {
* if(url === "https://www.google.com") {
* console.log('blocking requests to google!');
* return false;
* }
* });
* webView.location = "https://www.google.com";
*/
['webView:decidePolicyForNavigationAction:decisionHandler:', ['v',['@',':','@','@','?']],
createWKWebViewPolicyHandler($.WKNavigationActionPolicyAllow, $.WKNavigationActionPolicyCancel).bind(this)],
//['webView:decidePolicyForNavigationResponse:decisionHandler:', ['v',['@',':','@','@','?']],
// createWKWebViewPolicyHandler($.WKNavigationResponsePolicyAllow, $.WKNavigationResponsePolicyCancel).bind(this)],
/**
* @event new-window
* @memberof WebView
* @description When a new window is requested, this event is fired. The event handler
* is passed a new WebView that can be used for a new window (or alternatively)
* a new tab. It is the responsibility of the event handler to attach the
* web view to a window, tab (or other GUI item). If the event handler chooses
* not to open the web site in a new window, the webview can simply be discarded.
* @note The WebView is the TARGET in which the new window request will load the
* page, no further action is taken on the web view (e.g., loading content) until
* the event handler successfully returns.
* @noscreenshot
* @example
* require('Common');
* var win = new Window();
* var webView = new WebView();
* win.appendChild(webView);
* webView.left=webView.right=webView.top=webView.bottom=0;
* win.visible = true;
* webView.location = "https://www.google.com";
* webView.addEventListener('new-window', function(newWebView) {
* // Create a new window for the "new-window" event. Alternatively we could
* // create a new tab or simply add another webview to the current window.
* // the webview does not necessarily need to be onscreen. The webview can be
* // held offscreen until the load event occurs to check its url and then dispose
* // or attach it to a visible UI window/panel/etc.
* var newWin = new Window();
* newWin.appendChild(newWebView);
* newWebView.left=newWebView.right=newWebView.top=newWebView.bottom=0;
* newWin.visible = true;
* // Note we could alternatively do nothing with the web view preventing any
* // and all new web views from loading.
* });
*/
// TODO: TEST ME.
['webView:createWebViewWithConfiguration:forNavigationAction:windowFeatures:', ['@',['@',':','@','@','@','@']], fireNewWindow.bind(this)],
['userContentController:didReceiveScriptMessage:', 'v@:@@', function() {
/* self, cmd, control, message */
var message = arguments[3];
var name = message('name')('description')('UTF8String').toString();
if(name === "TintConsole") {
try {
var args = JSON.parse(message('body')('description')('UTF8String').toString());
this.fireEvent('console',[args.type, args.args]);
} catch (e) {}
} else {
this.fireEvent('message',[message('body')('description')('UTF8String').toString()]);
}
}.bind(this)]
/* TODO
['webView:runJavaScriptAlertPanelWithMessage:initiatedByFrame:completionHandler:',['v',['@',':','@','@','@','@']], function() {
var result = this.fireEvent('alert');
}.bind(this)],
// TODO
['webView:runJavaScriptConfirmPanelWithMessage:initiatedByFrame:completionHandler:',['v',['@',':','@','@','@','@']], function() {
var result = this.fireEvent('confirm');
}.bind(this)],
// TODO
['webView:runJavaScriptTextInputPanelWithPrompt:defaultText:initiatedByFrame:completionHandler:',['v',['@',':','@','@','@','@']], function() {
var result = this.fireEvent('text-input');
}.bind(this)] */
]);
Container.call(this, properties, options, inherited || true);
if(options.configuration) {
this.native = this.nativeView = this.nativeViewClass('alloc')('initWithFrame',$.NSMakeRect(0,0,500,480), 'configuration', options.configuration);
} else {
this.native = this.nativeView = this.nativeViewClass('alloc')('initWithFrame',$.NSMakeRect(0,0,500,480));
}
this.native('setNavigationDelegate', this.native);
this.nativeView('configuration')('userContentController')('removeScriptMessageHandlerForName',$('TintMessages'));
this.nativeView('configuration')('userContentController')('addScriptMessageHandler',this.nativeView,'name',$('TintMessages'));
this.nativeView('configuration')('userContentController')('removeScriptMessageHandlerForName',$('TintConsole'));
this.nativeView('configuration')('userContentController')('addScriptMessageHandler',this.nativeView,'name',$('TintConsole'));
var script = $.WKUserScript('alloc')('initWithSource',
$("window.postMessageToHost = function(e) { window.webkit.messageHandlers.TintMessages.postMessage(e); }"),
'injectionTime',$.WKUserScriptInjectionTimeAtDocumentStart,
'forMainFrameOnly', $.YES);
this.nativeView('configuration')('userContentController')('addUserScript', script);
/**
* @event console
* @memberof WebView
* @description Fires when a new console messages appears, the first argument is the type of console
* message (info, log, warn, error) as a string, the second parameter is an array of all the arguments
* the console object was ran with. This only fires for console.warn(), console.log(), console.error() and
* console.info(), it does not fire for console.assert, console.dir, or console.group.
* @noscreenshot
* @example
* require('Common');
* var win = new Window();
* win.visible = true;
* var webView = new WebView();
* win.appendChild(webView);
* webView.left=webView.top=webView.right=webView.bottom=0;
* webView.location = "https://www.google.com";
* // redirect all console output to our actual console..
* webView.addEventListener('console', function (type, args) {
* if(type === 'log') console.log(args);
* else if(type === 'error') console.error(args);
* else if(type === 'info') console.info(args);
* else if(type === 'warn') console.warn(args);
* });
*/
var consoleScript = $.WKUserScript('alloc')('initWithSource',
$("console = console || {};" +
"console.log = function() { try { window.webkit.messageHandlers.TintConsole.postMessage(JSON.stringify({type:'log',args:arguments})); } catch(e) {} };" +
"console.warn = function() { try { window.webkit.messageHandlers.TintConsole.postMessage(JSON.stringify({type:'warn',args:arguments})); } catch(e) {} };" +
"console.error = function() { try { window.webkit.messageHandlers.TintConsole.postMessage(JSON.stringify({type:'error',args:arguments})); } catch(e) {} };" +
"console.info = function() { try { window.webkit.messageHandlers.TintConsole.postMessage(JSON.stringify({type:'info',args:arguments})); } catch(e) {} };"),
'injectionTime',$.WKUserScriptInjectionTimeAtDocumentStart,
'forMainFrameOnly', $.YES);
this.nativeView('configuration')('userContentController')('addUserScript', consoleScript);
} else {
options.delegates = options.delegates.concat([
// DEPRECATED IN OSX YOSEMITE, NOT AVAILABLE ON WINDOWS
// @event cancel
// @memberof WebView
// @description Fires when a navigation or resource load request was cancelled programmatically or for security reasons.
['webView:didCancelClientRedirectForFrame:','v@:@@', function() { /*self,_cmd,frame*/ this.fireEvent('cancel'); }.bind(this)],
/**
* @event unload
* @memberof WebView
* @description Fires when a page in the top frame is unloaded.
*/
['webView:didClearWindowObject:forFrame:','v@:@@@', function() { /*self,_cmd,win,frame*/ this.fireEvent('unload'); }.bind(this)],
['webView:didFailLoadWithError:forFrame:','v@:@@', fireError.bind(this)],
['webView:didFailProvisionalLoadWithError:forFrame:','v@:@@', fireError.bind(this)],
['webView:didReceiveServerRedirectForProvisionalLoadForFrame:','v@:@@', function() { /*self, _cmd, title, frame*/ this.fireEvent('redirect'); }.bind(this)],
// DEPRECATED IN OSX YOSEMITE, NOT AVAILABLE ON WINDOWS
// @event title
// @memberof WebView
// @description Fires when the title of the HTML document loaded is available.
['webView:didReceiveTitle:forFrame:', 'v@:@@@', function() { /*self, _cmd, title, frame*/ this.fireEvent('title'); }.bind(this)],
// DEPRECATED IN OSX YOSEMITE, NOT AVAILABLE ON WINDOWS
// @event icon
// @memberof WebView
// @description Fires when the icon of the HTML document loaded is available.
//
['webView:didReceiveIcon:forFrame:', 'v@:@@@', function() { /* self, _cmd, icon, frame */ this.fireEvent('icon'); }.bind(this)],
['webView:didStartProvisionalLoadForFrame:', 'v@:@@', function() { /*self, _cmd, frame*/ this.fireEvent('loading'); }.bind(this)],
['webView:didFinishLoadForFrame:', 'v@:@@', fireLoad.bind(this)],
['webView:didCommitLoadForFrame:', 'v@:@@', function() { /*self, _cmd, frame*/ this.fireEvent('request'); }.bind(this)],
// DEPRECATED IN OSX YOSEMITE, Not entirely sure how useful this is anyways. Most window.close events are ignored
// by browsers anyways.
// @event close
// @memberof WebView
// @description Fires when a request to close the frame has occured (e.g., window.close in HTML javascript)
['webView:willCloseFrame:', 'v@:@@', function() { /*self, _cmd, frame*/ this.fireEvent('close'); }.bind(this)],
//['webView:didChangeLocationWithinPageForFrame:', 'v@:@@', function(self, _cmd, notif) { }.bind(this)],
['webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:', 'v@:@@d@@', function() { this.fireEvent('redirect'); }.bind(this)],
['webView:createWebViewWithRequest:', '@@:@@', fireNewWindow.bind(this)],
['webView:decidePolicyForNavigationAction:request:frame:decisionListener:','v@:@@@@@', createWebViewPolicyHandler().bind(this)]
]);
Container.call(this, properties, options, inherited);
this.native = this.nativeView = this.nativeViewClass('alloc')('initWithFrame',$.NSMakeRect(0,0,500,480),'frameName',$('main'),'groupName',$('main'));
var tintWebKitResponseDelegate = createWebViewBridge();
var id = (Math.random()*100000).toString();
process.bridge.objc.delegates[id] = this;
this.private.commDelegate = tintWebKitResponseDelegate('alloc')('initWithJavascriptObject',$(id));
this.private.commDelegate.fireEvent = this.fireEvent;
this.nativeView('setShouldUpdateWhileOffscreen',$.YES);
this.nativeView('setFrameLoadDelegate', this.nativeView);
this.nativeView('setPolicyDelegate', this.nativeView);
this.nativeView('setShouldCloseWithWindow',$.YES);
}
this.nativeView('setUIDelegate', this.nativeView);
this.nativeView('setTranslatesAutoresizingMaskIntoConstraints',$.NO);
util.setProperties(this, properties, inherited);
}
WebView.useNewWKWebView = true;
WebView.prototype = Object.create(Container.prototype);
WebView.prototype.constructor = Container;
/**
* @method back
* @memberof WebView
* @description Moves to the previously rendered page. If no previously rendered page is available this takes no action.
* @noscreenshot
* var win = new Window();
* win.visible = true;
* var webView = new WebView();
* win.appendChild(webView);
* webView.left=webView.top=webView.right=webView.bottom=0;
* webView.location = "https://www.google.com";
* setTimeout(function() { webView.location = "https://www.bing.com"; }, 1000);
* setTimeout(function() { webView.back() }, 2000);
*/
WebView.prototype.back = function() { this.nativeView('goBack',this.nativeView); };
/**
* @method forward
* @memberof WebView
* @description Moves to the history forward to the next rendered page. If no "next" rendered page is available this takes no action.
* @noscreenshot
* @example
* require('Common');
* var win = new Window();
* win.visible = true;
* var webView = new WebView();
* win.appendChild(webView);
* webView.left=webView.top=webView.right=webView.bottom=0;
* webView.location = "https://www.google.com";
* setTimeout(function() { webView.location = "https://www.bing.com"; }, 1000);
* setTimeout(function() { webView.location = "https://www.reddit.com"; }, 2000);
* setTimeout(function() { webView.location = "https://www.slashdot.org"; }, 3000);
* setTimeout(function() { webView.back(); }, 4000);
* setTimeout(function() { webView.back(); }, 5000);
* setTimeout(function() { console.log(webView.location); }, 6000);
*/
WebView.prototype.forward = function() { this.nativeView('goForward',this.nativeView); };
/**
* @method reload
* @memberof WebView
* @description Reloads the current page.
* @noscreenshot
* @example
* require('Common');
* var win = new Window();
* win.visible = true;
* var webView = new WebView();
* win.appendChild(webView);
* webView.left=webView.top=webView.right=webView.bottom=0;
* webView.location = "https://www.google.com";
* setTimeout(function() { webView.reload(); }, 1000);
*/
WebView.prototype.reload = function() { this.nativeView('reload',this.nativeView); };
/**
* @method stop
* @memberof WebView
* @description Stops loading the current page, if nothing is currently loading this takes no action.
* @noscreenshot
* @example
* require('Common');
* var win = new Window();
* win.visible = true;
* var webView = new WebView();
* win.appendChild(webView);
* webView.left=webView.top=webView.right=webView.bottom=0;
* webView.location = "https://www.google.com";
* setTimeout(function() { webView.stop(); }, 1000);
*/
WebView.prototype.stop = function() { this.loading = false; };
/**
* @method boundsOfElement
* @memberof WebView
* @param {string} selector A css selector (e.g., the same as querySelector) to find on the page. (#someid or .someclass)
* @param {function} callback The function which is called when the execution finishes. The result is an object with
* width, height, x, and y properties that are passed as the first argument.
* @description Returns an object with a x, y, width and height relative to the web view for any css query selector
* passed in for the first argument, the second argument is the callback to receive the result (as its first argument).
* This is mainly useful as a means for unit testing web pages and checking for elements positions.
* @noscreenshot
* @example
* require('Common');
* var win = new Window();
* win.visible = true;
* var webView = new WebView();
* win.appendChild(webView);
* webView.left=webView.top=webView.right=webView.bottom=0;
* webView.location = "somewebpage.html";
* webView.addEventListener('load', function() {
* webView.boundsOfElement('.someclass', function(rect) {
* console.log('.someclass was ' + rect.width + ' wide ' + rect.height + ' tall.');
* });
* });
*/
WebView.prototype.boundsOfElement = function(e, cb) {
this.execute("(function() { var rect = document.querySelector('"+e+"').getBoundingClientRect();\n" +
"return '{\"width\":'+rect.width+',\"height\":'+rect.height+',\"y\":'+rect.top+',\"x\":'+rect.bottom+'}'; })();",
function(r) { if(cb) { cb(JSON.parse(r)); } });
};
/**
* @method postMessage
* @param {string} message The string or message to pass.
* @memberof WebView
* @description Posts an HTML "Message" event to the top frame (and window) of the HTML page. The HTML page can listen to window message events
* to receive these messages. Strings are only allowed to be passed, complex objects may be serialized via JSON to transfer them back and forth.
* See the event 'message' to listen for messages sent from the HTML page back to Tint.
*/
WebView.prototype.postMessage = function(e) {
var msg = "var msg=document.createEvent('MessageEvent');\n";
msg += "msg.initMessageEvent('message',true,true,'"+e.toString().replace(/\\/g, "\\\\").replace(/'/g,"\\'").replace(/\n/g,'\\n')+"');\n";
msg += "window.dispatchEvent(msg);\n";
if(this.useWKWebView) {
this.execute(msg);
} else {
this.nativeView('stringByEvaluatingJavaScriptFromString',$(msg));
}
};
/**
* @method execute
* @param {string} javascript Executes the javascript (passed in as a string) in the window context of the top frame of the page.
* @param {function} callback The function which is called when the execution finishes. The result is passed as the first argument.
* @memberof WebView
* @description This will execute the passed in javascript in the window context of the top frame of the currently loaded page. The result is
* passed back when the callback is ran.
*/
WebView.prototype.execute = function(jscode, cb) {
this.callbacks = [];
if(this.useWKWebView) {
var callback = null;
if(cb) {
callback = $(function(obj, result) {
if(cb) {
if(result === null) {
cb(null);
} else {
if(this.callbacks.indexOf(callback) > -1) {
this.callbacks.splice(callback, 1);
}
cb(result('description')('UTF8String').toString());
}
}
}.bind(this), ['v',['@','@']]);
this.callbacks.push(callback);
}
this.nativeView('evaluateJavaScript', $(jscode.toString()), 'completionHandler', callback);
} else {
var result = this.nativeView('stringByEvaluatingJavaScriptFromString',$(jscode.toString()))('UTF8String').toString();
if(cb) {
cb(result);
}
}
};
// DEPRECATED IN OSX YOSEMITE, UNSUPPORTED ON WINDOWS
//
// @member icon
// @type {string}
// @memberof WebView
// @description Gets the URL of the icon resource for the HTML page. Note if this is not available an error will occur.
// Listen to the 'icon' event to know when an icon is available and its safe to access.
//
util.def(WebView.prototype, 'icon',
function() {
if(!this.useWKWebView) {
var ico = this.nativeView('mainFrameIcon');
return ico ? util.makeURIFromNSImage(ico) : null;
}
return null;
}
);
/**
* @member progress
* @type {number}
* @memberof WebView
* @description Gets the progress of loading all resources (if the page is currently loading). Note this will return
* -1 when the progress is indeterminate (e.g., the page is not loading or the progress could not be determined).
* The number returned is between 0 and 1, e.g., 0.5 represents 50% loaded.
* @noscreenshot
* @example
* require('Common');
* var win = new Window();
* win.visible = true;
* var webView = new WebView();
* win.appendChild(webView);
* webView.left=webView.top=webView.right=webView.bottom=0;
* webView.location = "https://www.google.com";
* setInterval(function() { console.log(webView.progress); }, 10);
*/
util.def(WebView.prototype, 'progress',
function() { return this.nativeView('estimatedProgress'); }
);
/**
* @member location
* @type {string}
* @memberof WebView
* @description Gets or sets the URL location of the HTML document rendered in the WebView.
* @example
* require('Common');
* var win = new Window();
* win.visible = true;
* var webView = new WebView();
* win.appendChild(webView);
* webView.left=webView.top=webView.right=webView.bottom=0;
* webView.location = "https://www.google.com";
* @screenshot-window {win}
*/
util.def(WebView.prototype, 'location',
function() {
if(this.useWKWebView) {
var url = this.nativeView('URL');
return url === null ? null : url('absoluteURL')('description')('UTF8String');
} else {
var mainUrl = this.nativeView('mainFrameURL');
return mainUrl === null ? null : mainUrl('UTF8String');
}
},
function(url) {
if(this.useWKWebView) {
if(url.indexOf("app:") > -1) {
// TODO: Get app schema supported by WKWebView, see bugreport and open RDAR on this.
// potentially use private class WKCustomProtocol?..
url = url.replace("app://",encodeURI("file://"+process.cwd()+"/"));
}
this.nativeView('loadRequest', $.NSURLRequest('requestWithURL',$.NSURL('URLWithString',$(url))));
} else {
this.nativeView('setMainFrameURL',$(url));
}
}
);
/**
* @member useragent
* @type {string}
* @memberof WebView
* @description Gets or sets the user agent string used.
* @noscreenshot
* @example
* require('Common');
* var win = new Window();
* win.visible = true;
* var webView = new WebView();
* win.appendChild(webView);
* webView.left=webView.top=webView.right=webView.bottom=0;
* webView.location = "https://www.google.com";
* setTimeout(function() { console.log(webView.useragent); }, 2000);
*/
util.def(WebView.prototype, "useragent",
function() {
if(this.useWKWebView) {
var userAgentWk = this.nativeView('_customUserAgent');
return userAgentWk.toString();
} else {
var userAgent = this.nativeView('customUserAgent');
if(!userAgent) {
userAgent = this.nativeView('userAgentForURL', this.nativeView('mainFrameURL'));
}
return userAgent.toString();
}
},
function(e) {
if(this.useWKWebView) {
this.nativeView('_setCustomUserAgent', $(e));
} else {
this.nativeView('setCustomUserAgent',$(e));
}
}
);
/**
* @member loading
* @type {boolean}
* @memberof WebView
* @description Gets or sets whether the page is loading. If set to true (when false) it reloads the current page, when
* set to false (when true) it stops loading the current page.
*/
util.def(WebView.prototype, 'loading',
function() {
if(this.useWKWebView) {
return this.nativeView('loading');
} else {
return this.nativeView('isLoading');
}
},
function(e) {
if(!e && this.useWKWebView) {
this.nativeView('stopLoading');
} else if (!e) {
this.nativeView('stopLoading',$.YES);
}
}
);
//TODO: Unsupported on Windows.
util.def(WebView.prototype, 'transparent',
function() {
if(this.useWKWebView) {
return this.nativeView('_drawsTransparentBackground') ? true : false;
} else {
return this.nativeView('drawsBackground') ? false : true;
}
},
function(e) {
if(this.useWKWebView) {
this.nativeView('_setDrawsTransparentBackground', e ? $.YES : $.NO );
} else {
this.nativeView('setDrawsBackground', !e ? $.YES : $.NO );
}
}
);
/**
* @member title
* @type {string}
* @memberof WebView
* @description Gets the title of the HTML document loaded in the webview. If nothing is loaded or is in the process of loading
* this will throw an error. LIsten to the 'title' event to know when the title of the HTML docuemnt is available.
* @noscreenshot
* @example
* require('Common');
* var win = new Window();
* win.visible = true;
* var webView = new WebView();
* win.appendChild(webView);
* webView.left=webView.top=webView.right=webView.bottom=0;
* webView.location = "https://www.google.com";
* setTimeout(function() { console.log(webView.title); }, 4000);
*/
util.def(WebView.prototype, 'title',
function() {
if(this.useWKWebView) {
return this.nativeView('title')('UTF8String');
} else {
return this.nativeView('mainFrameTitle')('UTF8String');
}
}
);
global.__TINT.WebView = WebView;
return WebView;
})();