Authored by 孟顺

新增wkwebview注入js 方法 并修改 uiwebview 注入方式的注入条件

review by 枪兵
... ... @@ -7,6 +7,7 @@
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <WebKit/WebKit.h>
@interface YHInjectJsCordovaManager : NSObject
... ... @@ -14,4 +15,6 @@
- (void)cycleInject:(UIWebView*)webView;
- (void)cycleInjectWKWebView:(WKWebView *)webView;
@end
... ...
... ... @@ -42,12 +42,19 @@
self.jsCordova = [NSString stringWithContentsOfFile:jsPath encoding:NSUTF8StringEncoding error:NULL];
}
[webView stringByEvaluatingJavaScriptFromString:self.jsCordova];
//用cordova.version判断cordova是否注入成功
NSString* jsCordovaVersion = [NSString stringWithFormat:
@"cordova.version"];
NSString* jsCordovaVersion = [NSString stringWithFormat:@"cordova.version"];
NSString* res = [webView stringByEvaluatingJavaScriptFromString:jsCordovaVersion];
if (res != nil && res.length > 0) {
return TRUE;
}
NSLog(@"injectJavascript uiwebview");
//注入cordova js 代码
[webView stringByEvaluatingJavaScriptFromString:self.jsCordova];
//再次判定是否已经注入
res = [webView stringByEvaluatingJavaScriptFromString:jsCordovaVersion];
if (res != nil && res.length > 0) {
return TRUE;
... ... @@ -68,7 +75,6 @@
if (!bSuc) {
__weak typeof(self) weakSelf = self;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[weakSelf cycleInject:webView];
});
... ... @@ -77,4 +83,52 @@
}
- (void)cycleInjectWKWebView:(WKWebView *)webView
{
__weak typeof(self) weakSelf = self;
[self injectJavascript:@"cordova" wkWebView:webView completion:^(BOOL isSuccessed) {
if (!isSuccessed) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[weakSelf cycleInjectWKWebView:webView];
});
}
}];
}
- (void)injectJavascript:(NSString *)resource wkWebView:(WKWebView*)webView completion:(void(^)(BOOL isSuccessed))completionBlock{
if(!self.jsCordova) {
NSString *jsPath = [[NSBundle mainBundle] pathForResource:resource ofType:@"js"];
self.jsCordova = [NSString stringWithContentsOfFile:jsPath encoding:NSUTF8StringEncoding error:NULL];
}
__weak typeof(self) weakSelf = self;
[self testWKWebViewInjectResult:webView completionBlock:^(BOOL successed) {
if (!successed) {
NSLog(@"injectJavascript wkwebview");
[webView evaluateJavaScript:weakSelf.jsCordova completionHandler:^(id obj, NSError* error) {
if (completionBlock) {
completionBlock(error ? NO : YES);
}
}];
}
}];
}
//检验wk注入的结果
- (void)testWKWebViewInjectResult:(WKWebView*)webView completionBlock:(void(^)(BOOL successed))block
{
[webView evaluateJavaScript:@"cordova.version" completionHandler:^(id obj, NSError* error) {
BOOL isSuccess = NO;
if ([obj isKindOfClass:NSString.class]
&& ((NSString *)obj).length > 0) {
isSuccess = YES;
}
if (block) {
block(isSuccess);
}
}];
}
@end
... ...