美文网首页
WKWebView添加js点击事件

WKWebView添加js点击事件

作者: koreadragon | 来源:发表于2017-02-20 18:06 被阅读1193次

    由于WKWebView可以监听进度,从而实现真实显示进度条进度。所以我在工程中用它取代了UIWebView,下面看下与js交互的按钮点击;

    现在js文件中实现JS执行window.webkit.messageHandlers.方法名.postMessage(<参数>)

    注意导入协议<WKScriptMessageHandler>
    - (WKWebView *)webView {
        if (!_webView) {
            
            WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
            configuration.userContentController = [WKUserContentController new];
            
            WKPreferences *preferences = [WKPreferences new];
            preferences.javaScriptCanOpenWindowsAutomatically = YES;
            preferences.minimumFontSize = 12.0;
            configuration.preferences = preferences;
            
            CGRect frame = CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 64);
            _webView = [[WKWebView alloc] initWithFrame:frame configuration:configuration];
          
            //OC注册供JS调用的方法
            [[_webView configuration].userContentController addScriptMessageHandler:self name:@"onBackHome"];
    
            _webView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
            _webView.backgroundColor = [UIColor clearColor];
            _webView.scrollView.backgroundColor = [UIColor clearColor];
            _webView.scrollView.showsVerticalScrollIndicator = NO;
            _webView.scrollView.showsHorizontalScrollIndicator = NO;
           
            
        }
        return _webView;
    }
    

    然后在使用时直接获取就好了

    //JS调用OC
    - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
    {
        
        
        if ([message.name isEqualToString:@"onBackHome"]) {
            
            [self dismissViewControllerAnimated:YES completion:nil];
            
        }
        
    }
    
    
    

    UIWebView中就更简单了

     JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
        
        //按钮点击
        context[@"backHome"] = ^() {
        
            [self dismissViewControllerAnimated:YES completion:nil];
            
        };
    
    

    相关文章

      网友评论

          本文标题:WKWebView添加js点击事件

          本文链接:https://www.haomeiwen.com/subject/sduewttx.html