js 与WKWebView 交互

实现delegate WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler

js调起oc的方法

注入要和js交互的方法

    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    WKUserContentController *userContentController = [[WKUserContentController alloc] init];
    [userContentController addScriptMessageHandler:self name:@"splitGotoWebPage"];
    [userContentController addScriptMessageHandler:self name:@"splitShareDialog"];
复制代码

设置代理

    _webView.UIDelegate = self;
    _webView.navigationDelegate = self;
复制代码

实现代理方法 (js 调起 oc)

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    MALog(@"%@",message.name);
    MALog(@"%@",message.body);
    NSString *method = [NSString stringWithFormat:@"%@:",message.name];
    SEL selector = NSSelectorFromString(method);
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
    if ([self respondsToSelector:selector]) {
        [self performSelector:selector withObject:message.body];
    }
#pragma clang diagnostic pop
}
复制代码

js 要如何做

window.webkit.messageHandlers.<name>.postMessage(<messageBody>) for all
复制代码
  • name 为[userContentController addScriptMessageHandler:self name:@"splitShareDialog"];中的name
  • postMessage(_nonull), 如果方法的返回参数为空 不能调起oc的方法
oc 调起js

声明方法

//一个参数时
NSString *jsStr = [NSString stringWithFormat:@"function(%@)",@"abc"]; 
// 多个参数传递的是时候
NSString *jsStr = [NSString stringWithFormat:@"function('%@','%@')",@"abc",@"123"]; 
复制代码
  • 如何调用
//oc 调用js
  [self.webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable reponse, NSError * _Nullable error) {
        MALog(@"%@",error);
    }];
复制代码
  • function 要和js的中的方法名是一致的
  • webview 如何禁止缩放
//web页面进制缩放
    NSString *js = @" $('meta[name=description]').remove(); $('head').append( '<meta name=\"viewport\" content=\"width=device-width, initial-scale=1,user-scalable=no\">' );";
    WKUserScript *script = [[WKUserScript alloc] initWithSource:js injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:NO];
    [userContentController addUserScript:script];
复制代码

转载于:https://juejin.im/post/5c9881c4518825341467edbc

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值