WKWebView和JS的那些事
最近公司需要将 某网站注入JS,从而实现对其中一些视频添加下载按钮的功能。当然我对JS不太懂,JS是由我们Web前端写的,我要实现的就是打开网站的时候注入JS,并根据里面点击按钮的操作作出响应,JS会给我传一些参数。这里记录下我做的事情,给需要的朋友看下。
之后我们会用 http://www.test.com
代替你要注入的网站网址。之后自己写的代码做个替换就好。
注入JS (OC调用JS)
最重要的第一步,就是将JS注入。
- (WKWebView *)myWebView {
if (!_myWebView) {
WKWebViewConfiguration *theConfiguration = [[WKWebViewConfiguration alloc] init];
theConfiguration.userContentController = [[WKUserContentController alloc] init];
[theConfiguration.userContentController addScriptMessageHandler:self name:@"downloader"];
[theConfiguration.userContentController addScriptMessageHandler:self name:@"console"];
if(IOSVersion >= 10.0){
theConfiguration.mediaTypesRequiringUserActionForPlayback = WKAudiovisualMediaTypeNone;
}
theConfiguration.allowsPictureInPictureMediaPlayback = YES;
theConfiguration.preferences.javaScriptEnabled = YES;
theConfiguration.allowsInlineMediaPlayback <