iOS webview js交互总结

iOS webview js交互总结

iOS web控件有两种,一种是UIWebView,一种是WKWebView

UIWebView

UIWebView 拦截函数为自定义函数
UIWebView js交互,如果交互函数只有函数名称,即中间没有.号的话,拦截很容易,如果有.号的话,要拦截,必须使用第三方组件UIWebView+TS_JavaScriptContext,然后在 webViewDidFinishLoad: 里面执行以下函数(demo中的函数是thirdPartyApp. CloseWebView())

self.context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
self.context[@"thirdPartyApp"] = self;

然后再在web控制器页面添加函数就可以完成拦截过程了

- (void)CloseWebView{
}

## WKWebView
WKWebView 拦截的js方法和UIWebView不一样,只能拦截window.webkit.messageHandlers.mydemo.postMessage函数,拦截名称为灰色部分。
WKWebView 有两种方案

方案1:

修改web,然后添加兼容WKWebView的代码,本地修改useragent,添加webConfiguration.applicationNameForUserAgent = @”demo”;后面为添加的区分代码
交互代码为

window.webkit.messageHandlers.mydemo.postMessage('');

方案2:初始化代码如下,添加的js交互代码

拦截核心代码如下

WKUserContentController *userController = [[WKUserContentController alloc]init];
        NSString *javaScriptSource = @"var thirdPartyApp = {};thirdPartyApp.function(){window.webkit.messageHandlers.mydemo.postMessage('');}";
        WKUserScript *userScript = [[WKUserScript alloc] initWithSource:javaScripinjectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:NO];
[userController addUserScript:userScript];
webConfiguration.userContentController = userController;

以下是比较完整的代码部分

WKWebViewConfiguration *webConfiguration = [[WKWebViewConfiguration alloc] init];
WKPreferences *preference = [[WKPreferences alloc]init];
//最小字体大小 当将javaScriptEnabled属性设置为NO时,可以看到明显的效果
preference.minimumFontSize = 0;
//设置是否支持javaScript 默认是支持的
preference.javaScriptEnabled = YES;
// 在iOS上默认为NO,表示是否允许不经过用户交互由javaScript自动打开窗口
preference.javaScriptCanOpenWindowsAutomatically = YES;
webConfiguration.preferences = preference;
webConfiguration.applicationNameForUserAgent = @"demo";
WKUserContentController *userController = [[WKUserContentController alloc]init];
        NSString *javaScriptSource = @"var thirdPartyApp = {};thirdPartyApp.function(){window.webkit.messageHandlers.mydemo.postMessage('');}";
        WKUserScript *userScript = [[WKUserScript alloc] initWithSource:javaScripinjectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:NO];
[userController addUserScript:userScript];
webConfiguration.userContentController = userController;
[userController addScriptMessageHandler:self name:@"mydemo"];
        _webview = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.configuration:webConfiguration];
_webview.UIDelegate = self;
_webview.navigationDelegate = self;
_webview.backgroundColor = [UIColor clearColor];
[self.view addSubview:_webview];
_webview.allowsBackForwardNavigationGestures = YES;
NSURL *url;
url = [NSURL URLWithString:@"https://www.baidu.com"];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
[_webview loadRequest:request];

发表评论

电子邮件地址不会被公开。 必填项已用*标注