美文网首页
WKWebView 注入js代码

WKWebView 注入js代码

作者: CocoaH | 来源:发表于2020-01-17 14:42 被阅读0次

    在WKWebView中注入js代码,从而实现改变js事件实现方法。
    比如,在H5页面中有一个打印按钮,iOS 端没有打印功能,这时就要提示用户不能使用此功能

    主要代码

    // printFrame js打印事件
    - (void)createWebView {
        // js配置
        WKUserContentController *userContentController = [[WKUserContentController alloc] init];
        // WKWebView的配置
        WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
        configuration.userContentController = userContentController;
        // 显示WKWebView
        self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, self.hideNavigationBar?kStatusH:0, ScreenWidth, self.hideNavigationBar?ScreenHeight-kStatusH:ScreenHeight-NavitionbarHeight) configuration:configuration];
        self.webView.UIDelegate = self; // 设置WKUIDelegate代理
        self.webView.navigationDelegate = self;
        [self.view addSubview:self.webView];
        configuration.userContentController = userContentController;
      [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"printLog"];//js打印事件
      //注入js的代码,就相当于重写了js的printLog方法,在printLog方法中去调用原生方法
    // function 后面的方法名跟js代码中的方法名要一致
        NSString *printContent = @"function printLog() {
     //此处的printLog 可自己定义但是要跟上面的addScriptMessageHandler 的name保持一致
    window.webkit.messageHandlers.printLog.postMessage(null);}
    ";
        WKUserScript *userScript = [[WKUserScript alloc] initWithSource:printContent injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
        [self.webView.configuration.userContentController addUserScript:userScript];
    }
    
    //js调用打印方法时就会调用此方法
    - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
        NSLog(@"%@",message);
        NSLog(@"%@",message.body);
        NSLog(@"%@",message.name);
        if ([@"printLog" isEqualToString:message.name]) {
            [self printLog:@"jjj"];
        }
    }
    
    - (void) printLog:(NSString *)hhh {
      //重新实现js方法
    }
    

    相关文章

      网友评论

          本文标题:WKWebView 注入js代码

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