-
Notifications
You must be signed in to change notification settings - Fork 0
/
SmartJSWebViewProxy.m
805 lines (688 loc) · 33.6 KB
/
SmartJSWebViewProxy.m
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
//
// SmartJSWebViewProxy.m
// SmartJSWebView
//
// Created by pcjbird on 2017/12/16.
// Copyright © 2017年 Zero Status. All rights reserved.
//
#import "SmartJSWebViewProxy.h"
#import <objc/runtime.h>
#import "SmartJSWebView.h"
#import "SmartJSWebViewDefine.h"
#import "SmartJSDataFunction.h"
#define completeRPCURLPath @"/smartjswebviewprogressproxy/complete"
static const float SmartJSWebViewProgressInitialValue = 0.7f;
static const float SmartJSWebViewProgressInteractiveValue = 0.9f;
static const float SmartJSWebViewProgressFinalProgressValue = 0.9f;
@interface SmartJSWebViewProxy()
{
int _loadingCount;
int _maxLoadCount;
NSURL *_currentURL;
BOOL _interactive;
float _progress;
}
@end
@implementation SmartJSWebViewProxy
@synthesize realDelegate;
@synthesize javascriptInterfaces;
@synthesize progressDelegate;
- (id)init
{
self = [super init];
if (self) {
[self initVariables];
}
return self;
}
-(void)initVariables
{
_maxLoadCount = _loadingCount = 0;
_interactive = NO;
}
- (void)startProgress
{
if (_progress < SmartJSWebViewProgressInitialValue) {
[self setProgress:SmartJSWebViewProgressInitialValue];
}
}
- (void)incrementProgress
{
float progress = _progress;
float maxProgress = _interactive ? SmartJSWebViewProgressFinalProgressValue : SmartJSWebViewProgressInteractiveValue;
float remainPercent = (float)_loadingCount/_maxLoadCount;
float increment = (maxProgress-progress) * remainPercent;
progress += increment;
progress = fminf(progress, maxProgress);
[self setProgress:progress];
}
- (void)completeProgress
{
[self setProgress:1.f];
}
- (void)setProgress:(float)progress
{
if (progress > _progress || progress == 0)
{
_progress = progress;
if (self.progressDelegate)
{
[self.progressDelegate setProgress:progress animated:YES];
}
}
}
- (void)reset
{
_maxLoadCount = _loadingCount = 0;
_interactive = NO;
[self setProgress:0.f];
}
- (BOOL)checkIfRPCURL:(NSURLRequest *)request
{
if ([request.URL.path isEqualToString:completeRPCURLPath]) {
[self completeProgress];
return YES;
}
return NO;
}
- (void) addJavascriptInterfaces:(NSObject*) interface WithName:(NSString*) name{
if (! self.javascriptInterfaces){
self.javascriptInterfaces = [[NSMutableDictionary alloc] init];
}
[self.javascriptInterfaces setValue:interface forKey:name];
}
- (void) injectUserScript:(WKWebView*)webView
{
NSString * functionjs = [NSString stringWithContentsOfFile:[SDK_BUNDLE pathForResource:@"function-inject" ofType:@"js"] encoding:NSUTF8StringEncoding error:nil];
WKUserScript *functionScript = [[WKUserScript alloc] initWithSource:functionjs injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:true];
[webView.configuration.userContentController addUserScript:functionScript];
NSString * deferredjs = [NSString stringWithContentsOfFile:[SDK_BUNDLE pathForResource:@"deferredjs-inject" ofType:@"js"] encoding:NSUTF8StringEncoding error:nil];
WKUserScript *deferredScript = [[WKUserScript alloc] initWithSource:deferredjs injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:true];
[webView.configuration.userContentController addUserScript:deferredScript];
NSString * smartjs = [NSString stringWithContentsOfFile:[SDK_BUNDLE pathForResource:@"smartjs-inject" ofType:@"js"] encoding:NSUTF8StringEncoding error:nil];
WKUserScript *userScript = [[WKUserScript alloc] initWithSource:smartjs injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:true];
[webView.configuration.userContentController addUserScript:userScript];
}
#pragma mark - SmartJSContextDelegate
-(void)webView:(UIWebView *)webView didCreateJavaScriptContext:(JSContext *)ctx
{
if (! self.javascriptInterfaces){
self.javascriptInterfaces = [[NSMutableDictionary alloc] init];
}
//inject the basic functions first
NSString * functionjs = [NSString stringWithContentsOfFile:[SDK_BUNDLE pathForResource:@"function-inject" ofType:@"js"] encoding:NSUTF8StringEncoding error:nil];
NSString * deferredjs = [NSString stringWithContentsOfFile:[SDK_BUNDLE pathForResource:@"deferredjs-inject" ofType:@"js"] encoding:NSUTF8StringEncoding error:nil];
NSString * smartjs = [NSString stringWithContentsOfFile:[SDK_BUNDLE pathForResource:@"smartjs-inject" ofType:@"js"] encoding:NSUTF8StringEncoding error:nil];
[webView stringByEvaluatingJavaScriptFromString:functionjs];
[webView stringByEvaluatingJavaScriptFromString:deferredjs];
[webView stringByEvaluatingJavaScriptFromString:smartjs];
NSMutableString* injection = [[NSMutableString alloc] init];
//inject the javascript interface
for(id key in self.javascriptInterfaces) {
NSObject* interface = [self.javascriptInterfaces objectForKey:key];
[injection appendString:@"SmartJS.inject(\""];
[injection appendString:key];
[injection appendString:@"\", ["];
[injection appendString:@"\""];
[injection appendString:@"createSecretId"];
[injection appendString:@"\""];
[injection appendString:@", "];
unsigned int mc = 0;
Class cls = object_getClass(interface);
Method * mlist = class_copyMethodList(cls, &mc);
for (int i = 0; i < mc; i++){
[injection appendString:@"\""];
[injection appendString:[NSString stringWithUTF8String:sel_getName(method_getName(mlist[i]))]];
[injection appendString:@"\""];
if (i != mc - 1){
[injection appendString:@", "];
}
}
free(mlist);
[injection appendString:@"]);"];
}
//inject the function interface
[webView stringByEvaluatingJavaScriptFromString:injection];
}
#pragma mark - 判断域名是否在白名单中
-(BOOL) isHost:(NSString*)host inWhitelist:(NSArray<NSString*>*)whitelist
{
__block BOOL result = NO;
if([host isKindOfClass:[NSString class]] && [whitelist isKindOfClass:[NSArray<NSString*> class]])
{
[whitelist enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
if([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0f)
{
if([host containsString:obj])
{
result = YES;
*stop = YES;
}
}
else
{
NSRange range = [host rangeOfString:obj];
if(range.location != NSNotFound && range.length > 0)
{
result = YES;
*stop = YES;
}
}
}];
}
return result;
}
#pragma mark - UIWebViewDelegate
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
if(self.realDelegate && [self.realDelegate respondsToSelector:@selector(webView:didFailLoadWithError:)])
{
[self.realDelegate webView:webView didFailLoadWithError:error];
}
_loadingCount--;
[self incrementProgress];
NSString *readyState = [webView stringByEvaluatingJavaScriptFromString:@"document.readyState"];
BOOL interactive = [readyState isEqualToString:@"interactive"];
if (interactive) {
_interactive = YES;
NSString *waitForCompleteJS = [NSString stringWithFormat:@"window.addEventListener('load',function() { var iframe = document.createElement('iframe'); iframe.style.display = 'none'; iframe.src = '%@://%@%@'; document.body.appendChild(iframe); }, false);", webView.request.mainDocumentURL.scheme, webView.request.mainDocumentURL.host, completeRPCURLPath];
[webView stringByEvaluatingJavaScriptFromString:waitForCompleteJS];
}
BOOL isNotRedirect = _currentURL && [_currentURL isEqual:webView.request.mainDocumentURL];
BOOL complete = [readyState isEqualToString:@"complete"];
if ((complete && isNotRedirect) || error) {
[self completeProgress];
}
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
if(self.realDelegate && [self.realDelegate respondsToSelector:@selector(webViewDidFinishLoad:)])
{
[self.realDelegate webViewDidFinishLoad:webView];
}
_loadingCount--;
[self incrementProgress];
NSString *readyState = [webView stringByEvaluatingJavaScriptFromString:@"document.readyState"];
BOOL interactive = [readyState isEqualToString:@"interactive"];
if (interactive) {
_interactive = interactive;
NSString *waitForCompleteJS = [NSString stringWithFormat:@"window.addEventListener('load',function() { var iframe = document.createElement('iframe'); iframe.style.display = 'none'; iframe.src = '%@://%@%@'; document.body.appendChild(iframe); }, false);",
webView.request.mainDocumentURL.scheme,
webView.request.mainDocumentURL.host,
completeRPCURLPath];
[webView stringByEvaluatingJavaScriptFromString:waitForCompleteJS];
}
BOOL isNotRedirect = _currentURL && [_currentURL isEqual:webView.request.mainDocumentURL];
BOOL complete = [readyState isEqualToString:@"complete"];
if (complete && isNotRedirect) {
[self completeProgress];
}
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
if ([self checkIfRPCURL:request]) {
return NO;
}
BOOL isFragmentJump = NO;
if (request.URL.fragment) {
NSString *nonFragmentURL = [request.URL.absoluteString stringByReplacingOccurrencesOfString:[@"#" stringByAppendingString:request.URL.fragment] withString:@""];
isFragmentJump = [nonFragmentURL isEqualToString:webView.request.URL.absoluteString];
}
BOOL isTopLevelNavigation = [request.mainDocumentURL isEqual:request.URL];
BOOL isHTTP = [request.URL.scheme isEqualToString:@"http"] || [request.URL.scheme isEqualToString:@"https"];
if (!isFragmentJump && isHTTP && isTopLevelNavigation) {
_currentURL = request.URL;
[self reset];
}
NSString *requestString = [[request URL] absoluteString];
if ([requestString hasPrefix:@"smart-js:"]) {
BOOL isSafe = YES;
if(self.securityProxy && [self.securityProxy conformsToProtocol:@protocol(SmartJSWebSecurityProxy)])
{
BOOL useWhiteList = [self.securityProxy shouldSmartJSWebViewUseSecurityWhitelist:(SmartJSWebView*)[webView superview]];
if(useWhiteList)
{
NSArray<NSString*> *whitelist = nil;
if([self.securityProxy respondsToSelector:@selector(securityWhitelistForWebView:)])
{
whitelist = [self.securityProxy securityWhitelistForWebView:(SmartJSWebView*)[webView superview]];
}
if(![whitelist isKindOfClass:[NSArray<NSString *> class]])
{
whitelist = [NSArray<NSString *> array];
}
NSString *host = request.mainDocumentURL.host;
if([host isKindOfClass:[NSString class]])
{
if(![self isHost:host inWhitelist:whitelist])
{
isSafe = NO;
}
}
}
}
if(!isSafe)
{
#if DEBUG
NSLog(@"域名%@不在白名单中,无法通过 JavaScript 与 Native App 交互。", request.mainDocumentURL.host);
#endif
return NO;
}
/*
A sample URL structure:
smart-js:MyJSTest:test
smart-js:MyJSTest:testWithParam%3A:haha
*/
NSArray *components = [requestString componentsSeparatedByString:@":"];
//NSLog(@"req: %@", requestString);
NSString* obj = (NSString*)[components objectAtIndex:1];
NSString* method = [(NSString*)[components objectAtIndex:2]
stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSObject* interface = [javascriptInterfaces objectForKey:obj];
if (!interface) return NO;
if([method isEqualToString:@"createSecretId"])
{
if([[webView superview] isKindOfClass:[SmartJSWebView class]])
{
NSString *secretId = ((SmartJSWebView*)[webView superview]).secretId;
[(SmartJSWebView*)[webView superview] evaluateJavaScript:[NSString stringWithFormat:@"SmartJS.retValue=\"%@\";", secretId] completionHandler:nil];
}
return NO;
}
// execute the interfacing method
SEL selector = NSSelectorFromString(method);
NSMethodSignature* sig = [[interface class] instanceMethodSignatureForSelector:selector];
if (!sig) return NO;
NSInvocation* invoker = [NSInvocation invocationWithMethodSignature:sig];
invoker.selector = selector;
invoker.target = interface;
NSMutableArray* args = [[NSMutableArray alloc] init];
if ([components count] > 3){
NSString *argsAsString = [(NSString*)[components objectAtIndex:3]
stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSArray* formattedArgs = [argsAsString componentsSeparatedByString:@":"];
for (int i = 0, j = 0, l = (int)[formattedArgs count]; i < l; i+=2, j++){
NSString* type = ((NSString*) [formattedArgs objectAtIndex:i]);
NSString* argStr = ((NSString*) [formattedArgs objectAtIndex:i + 1]);
if ([@"f" isEqualToString:type]){
SmartJSDataFunction* func = [[SmartJSDataFunction alloc] initWithSmartWebView:(SmartJSWebView *)[webView superview]];
func.funcID = argStr;
[args addObject:func];
[invoker setArgument:&func atIndex:(j + 2)];
}else if ([@"s" isEqualToString:type]){
NSString* arg = [argStr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[args addObject:arg];
[invoker setArgument:&arg atIndex:(j + 2)];
}
}
}
[invoker invoke];
//return the value by using javascript
if ([sig methodReturnLength] > 0){
const char* returnType = sig.methodReturnType;
if(!strcmp(returnType, @encode(id)))
{
void* _retValue;
[invoker getReturnValue:&_retValue];
id retValue = (__bridge id)_retValue;
if (retValue == NULL || retValue== nil)
{
[webView stringByEvaluatingJavaScriptFromString:@"SmartJS.retValue=null;"];
}
else
{
if ([retValue isKindOfClass:[NSString class]])
{
retValue = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL,(CFStringRef) retValue, NULL, (CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8));
[webView stringByEvaluatingJavaScriptFromString:[@"" stringByAppendingFormat:@"SmartJS.retValue=\"%@\";", retValue]];
}
else
{
[webView stringByEvaluatingJavaScriptFromString:[@"" stringByAppendingFormat:@"SmartJS.retValue=\"%@\";", retValue]];
}
}
return NO;
}
NSUInteger length = [sig methodReturnLength];
//根据长度申请内存
void *_retValue = (void *)malloc(length);
[invoker getReturnValue:_retValue];
if(!strcmp(returnType, @encode(BOOL)))
{
BOOL result = *((BOOL*)_retValue);
[webView stringByEvaluatingJavaScriptFromString:[@"" stringByAppendingFormat:@"SmartJS.retValue=%@;", result ? @"true" : @"false"]];
}
else if(!strcmp(returnType, @encode(int)))
{
int result = *((int*)_retValue);
[webView stringByEvaluatingJavaScriptFromString:[@"" stringByAppendingFormat:@"SmartJS.retValue=%d;", result]];
}
else if(!strcmp(returnType, @encode(float)))
{
float result = *((float*)_retValue);
[webView stringByEvaluatingJavaScriptFromString:[@"" stringByAppendingFormat:@"SmartJS.retValue=%f;", result]];
}
else
{
[webView stringByEvaluatingJavaScriptFromString:@"SmartJS.retValue=\"notsupport\";"];
}
}
return NO;
}
if (! self.realDelegate){
return YES;
}
else
{
if([self.realDelegate respondsToSelector:@selector(webView:shouldStartLoadWithRequest:navigationType:)])
{
return [self.realDelegate webView:webView shouldStartLoadWithRequest:request navigationType:navigationType];
}
return YES;
}
}
- (void)webViewDidStartLoad:(UIWebView *)webView{
[self.realDelegate webViewDidStartLoad:webView];
_loadingCount++;
_maxLoadCount = fmax(_loadingCount, _maxLoadCount);
[self startProgress];
}
#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
//所传过来的参数message.body,只支持NSNumber, NSString, NSDate, NSArray, NSDictionary, and NSNull类型
if ([message.name isEqualToString:@"SmartJS"])
{
BOOL isSafe = YES;
if(self.securityProxy && [self.securityProxy conformsToProtocol:@protocol(SmartJSWebSecurityProxy)])
{
BOOL useWhiteList = [self.securityProxy shouldSmartJSWebViewUseSecurityWhitelist:(SmartJSWebView*)[message.webView superview]];
if(useWhiteList)
{
NSArray<NSString*> *whitelist = nil;
if([self.securityProxy respondsToSelector:@selector(securityWhitelistForWebView:)])
{
whitelist = [self.securityProxy securityWhitelistForWebView:(SmartJSWebView*)[message.webView superview]];
}
if(![whitelist isKindOfClass:[NSArray<NSString *> class]])
{
whitelist = [NSArray<NSString *> array];
}
NSString *host = message.webView.URL.host;
if([host isKindOfClass:[NSString class]])
{
if(![self isHost:host inWhitelist:whitelist])
{
isSafe = NO;
}
}
}
}
if(!isSafe)
{
#if DEBUG
NSLog(@"域名%@不在白名单中,无法通过 JavaScript 与 Native App 交互。", message.webView.URL.host);
#endif
return;
}
NSDictionary *body = message.body;
if([body isKindOfClass:[NSDictionary class]])
{
NSString* callbackID = [body objectForKey:@"callbackID"];
NSString* obj = [body objectForKey:@"className"];
if(![obj isKindOfClass:[NSString class]]) return;
NSString* encodedfun = [body objectForKey:@"functionName"];
if(![encodedfun isKindOfClass:[NSString class]]) return;
NSString* method = [encodedfun stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSObject* interface = [self.javascriptInterfaces objectForKey:obj];
if (![interface isKindOfClass:[NSObject class]]) return;
if([method isEqualToString:@"createSecretId"])
{
if([[message.webView superview] isKindOfClass:[SmartJSWebView class]])
{
NSString *secretId = ((SmartJSWebView*)[message.webView superview]).secretId;
[(SmartJSWebView*)[message.webView superview] evaluateJavaScript:[NSString stringWithFormat:@"SmartJS.retValue=%@;", secretId] completionHandler:nil];
}
return;
}
// execute the interfacing method
SEL selector = NSSelectorFromString(method);
NSMethodSignature* sig = [[interface class] instanceMethodSignatureForSelector:selector];
if (![sig isKindOfClass:[NSMethodSignature class]]) return;
NSInvocation* invoker = [NSInvocation invocationWithMethodSignature:sig];
invoker.selector = selector;
invoker.target = interface;
NSMutableArray* args = [[NSMutableArray alloc] init];
NSString *argStr = [body objectForKey:@"argument"];
if([argStr isKindOfClass:[NSString class]] && [argStr length] > 0)
{
NSString *argsAsString = [[argStr substringFromIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSArray* formattedArgs = [argsAsString componentsSeparatedByString:@":"];
for (int i = 0, j = 0, l = (int)[formattedArgs count]; i < l; i+=2, j++)
{
NSString* type = ((NSString*) [formattedArgs objectAtIndex:i]);
NSString* argStr = ((NSString*) [formattedArgs objectAtIndex:i + 1]);
if ([@"f" isEqualToString:type])
{
SmartJSDataFunction* func = [[SmartJSDataFunction alloc] initWithSmartWebView:(SmartJSWebView *)[message.webView superview]];
func.funcID = argStr;
[args addObject:func];
[invoker setArgument:&func atIndex:(j + 2)];
}
else if ([@"s" isEqualToString:type])
{
NSString* arg = [argStr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[args addObject:arg];
[invoker setArgument:&arg atIndex:(j + 2)];
}
}
}
[invoker invoke];
//return the value by using javascript
if ([sig methodReturnLength] > 0){
const char* returnType = sig.methodReturnType;
if(!strcmp(returnType, @encode(id)))
{
void* _retValue;
[invoker getReturnValue:&_retValue];
id retValue = (__bridge id)_retValue;
if (retValue == NULL || retValue== nil)
{
[message.webView evaluateJavaScript:[NSString stringWithFormat:@"SmartJS.asyncCallback(\"%@\", \"success\", [null]);", callbackID] completionHandler:nil];
}
else
{
if ([retValue isKindOfClass:[NSString class]])
{
retValue = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL,(CFStringRef) retValue, NULL, (CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8));
[message.webView evaluateJavaScript:[@"" stringByAppendingFormat:@"SmartJS.asyncCallback(\"%@\", \"success\",[\"%@\"]);", callbackID,retValue] completionHandler:^(id _Nullable result, NSError * _Nullable error) {
}];
}
else
{
[message.webView evaluateJavaScript:[@"" stringByAppendingFormat:@"SmartJS.asyncCallback(\"%@\", \"success\",[\"%@\"]);", callbackID,retValue] completionHandler:nil];
}
}
return;
}
NSUInteger length = [sig methodReturnLength];
//根据长度申请内存
void *_retValue = (void *)malloc(length);
[invoker getReturnValue:_retValue];
if(!strcmp(returnType, @encode(BOOL)))
{
BOOL result = *((BOOL*)_retValue);
[message.webView evaluateJavaScript:[@"" stringByAppendingFormat:@"SmartJS.asyncCallback(\"%@\", \"success\",[\"%@\"]);", callbackID, result ? @"true" : @"false"] completionHandler:nil];
}
else if(!strcmp(returnType, @encode(int)))
{
int result = *((int*)_retValue);
[message.webView evaluateJavaScript:[@"" stringByAppendingFormat:@"SmartJS.asyncCallback(\"%@\", \"success\", [%d]);", callbackID, result] completionHandler:nil];
}
else if(!strcmp(returnType, @encode(float)))
{
float result = *((float*)_retValue);
[message.webView evaluateJavaScript:[@"" stringByAppendingFormat:@"SmartJS.asyncCallback(\"%@\", \"success\", [%f]);", callbackID, result] completionHandler:nil];
}
else
{
[message.webView evaluateJavaScript:@"SmartJS.asyncCallback(\"%@\", \"success\", [\"notsupport\"]);" completionHandler:nil];
}
}
}
}
/*
*/
}
#pragma mark - KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
if ([keyPath isEqualToString:@"estimatedProgress"])
{
WKWebView *webView = object;
if([webView isKindOfClass:[WKWebView class]])
{
[self setProgress:webView.estimatedProgress];
}
}
}
#pragma mark - WKNavigationDelegate
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
if(self.realDelegate && [self.realDelegate respondsToSelector:@selector(webView:decidePolicyForNavigationAction:decisionHandler:)])
{
[self.realDelegate webView:webView decidePolicyForNavigationAction:navigationAction decisionHandler:decisionHandler];
return;
}
decisionHandler(WKNavigationActionPolicyAllow);
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
if(self.realDelegate && [self.realDelegate respondsToSelector:@selector(webView:decidePolicyForNavigationResponse:decisionHandler:)])
{
[self.realDelegate webView:webView decidePolicyForNavigationResponse:navigationResponse decisionHandler:decisionHandler];
return;
}
decisionHandler(WKNavigationResponsePolicyAllow);
}
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation {
if(self.realDelegate && [self.realDelegate respondsToSelector:@selector(webView:didStartProvisionalNavigation:)])
{
[self.realDelegate webView:webView didStartProvisionalNavigation:navigation];
return;
}
}
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(null_unspecified WKNavigation *)navigation {
if(self.realDelegate && [self.realDelegate respondsToSelector:@selector(webView:didReceiveServerRedirectForProvisionalNavigation:)])
{
[self.realDelegate webView:webView didReceiveServerRedirectForProvisionalNavigation:navigation];
}
}
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
if(self.realDelegate && [self.realDelegate respondsToSelector:@selector(webView:didFailProvisionalNavigation:withError:)])
{
[self.realDelegate webView:webView didFailProvisionalNavigation:navigation withError:error];
}
}
- (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation {
if(self.realDelegate && [self.realDelegate respondsToSelector:@selector(webView:didCommitNavigation:)])
{
[self.realDelegate webView:webView didCommitNavigation:navigation];
}
}
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
if (! self.javascriptInterfaces){
self.javascriptInterfaces = [[NSMutableDictionary alloc] init];
}
NSMutableString* injection = [[NSMutableString alloc] init];
//inject the javascript interface
for(id key in self.javascriptInterfaces) {
NSObject* interface = [self.javascriptInterfaces objectForKey:key];
[injection appendString:@"SmartJS.inject(\""];
[injection appendString:key];
[injection appendString:@"\", ["];
unsigned int mc = 0;
Class cls = object_getClass(interface);
Method * mlist = class_copyMethodList(cls, &mc);
for (int i = 0; i < mc; i++){
[injection appendString:@"\""];
[injection appendString:[NSString stringWithUTF8String:sel_getName(method_getName(mlist[i]))]];
[injection appendString:@"\""];
if (i != mc - 1){
[injection appendString:@", "];
}
}
free(mlist);
[injection appendString:@"]);"];
}
//inject the function interface
[webView evaluateJavaScript:injection completionHandler:^(id _Nullable result, NSError * _Nullable error) {
}];
if(self.realDelegate && [self.realDelegate respondsToSelector:@selector(webView:didFinishNavigation:)])
{
[self.realDelegate webView:webView didFinishNavigation:navigation];
}
}
- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
if(self.realDelegate &&[self.realDelegate respondsToSelector:@selector(webView:didFailNavigation:withError:)])
{
[self.realDelegate webView:webView didFailNavigation:navigation withError:error];
}
}
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *__nullable credential))completionHandler {
if(self.realDelegate && [self.realDelegate respondsToSelector:@selector(webView:didReceiveAuthenticationChallenge:completionHandler:)])
{
[self.realDelegate webView:webView didReceiveAuthenticationChallenge:challenge completionHandler:completionHandler];
return;
}
completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
}
- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView {
if(self.realDelegate && [self.realDelegate respondsToSelector:@selector(webViewWebContentProcessDidTerminate:)])
{
if([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0)
{
if (@available(iOS 9.0, *)) {
[self.realDelegate webViewWebContentProcessDidTerminate:webView];
} else {
// Fallback on earlier versions
}
}
}
}
#pragma mark - WKUIDelegate
- (void)webViewDidClose:(WKWebView *)webView {
if(self.realDelegate && [self.realDelegate respondsToSelector:@selector(webViewDidClose:)])
{
if([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0)
{
if (@available(iOS 9.0, *)) {
[self.realDelegate webViewDidClose:webView];
} else {
// Fallback on earlier versions
}
}
}
}
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
NSLog(@"JS Alert Pannel Message:%@.", message);
if(self.realDelegate && [self.realDelegate respondsToSelector:@selector(webView:runJavaScriptAlertPanelWithMessage:initiatedByFrame:completionHandler:)])
{
[self.realDelegate webView:webView runJavaScriptAlertPanelWithMessage:message initiatedByFrame:frame completionHandler:completionHandler];
return;
}
completionHandler();
}
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler
{
NSLog(@"JS Confirm Pannel Message:%@.", message);
if(self.realDelegate && [self.realDelegate respondsToSelector:@selector(webView:runJavaScriptConfirmPanelWithMessage:initiatedByFrame:completionHandler:)])
{
[self.realDelegate webView:webView runJavaScriptConfirmPanelWithMessage:message initiatedByFrame:frame completionHandler:completionHandler];
return;
}
completionHandler(YES);
}
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler {
NSLog(@"JS TextInput Pannel Prompt:%@, defaultText:%@.", prompt, defaultText);
if(self.realDelegate && [self.realDelegate respondsToSelector:@selector(webView:runJavaScriptTextInputPanelWithPrompt:defaultText:initiatedByFrame:completionHandler:)])
{
[self.realDelegate webView:webView runJavaScriptTextInputPanelWithPrompt:prompt defaultText:defaultText initiatedByFrame:frame completionHandler:completionHandler];
return;
}
completionHandler(@"");
}
@end