美文网首页
WKWebView与Vue交互

WKWebView与Vue交互

作者: ChenL | 来源:发表于2020-09-24 17:22 被阅读0次

一、iOS 端

1、 初始化

- (void)initWebConfig
{
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0,self.webX+1, kScreenWidth, kScreenHeight-SafeAreaTopHeight-(self.webX+1)) configuration:config];
    self.webView.scrollView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [self.view addSubview:self.webView];
    self.webView.navigationDelegate = self;
    self.webView.UIDelegate = self;// 与webview UI交互代理
}

2、设置delegate

WKScriptMessageHandler
//需要监听来自web端发过来的消息
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    NSLog(@"message.body:-----------%@",message.body);
  //web 给iOS 端传相应的参数 及方法
 if ([message.name isEqualToString:@"goDetail"])
 {
     //需要addScriptMessageHandler 后方可生效
 }

}


//addScriptMessageHandler要和removeScriptMessageHandlerForName配套出现,否则会造成内存泄漏。
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    //web调用iOS
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"goDetail"];//获取web的传的参数

}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];

    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"goDetail"];

}
WKNavigationDelegate
//我这里向web端执行h5GetImageUrl来将我iOS端上传相关的参数交给web端进行
#pragma mark - WKNavigationDelegate (执行js)
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
     [self  runJavaScriptDeal];//首次调用成功后,可以单独调用给web端传值
}

- (void)runJavaScriptDeal
{
  //给web端传参数 
     NSString *jsonStr = [NSString strToJsonStrWithDict:dic];
     NSString *JSResult = [NSString stringWithFormat:@"getWorkJsonParams('%@')",jsonStr];
     //执行一段JS
     [self.webView evaluateJavaScript:JSResult completionHandler:^(id _Nullable object, NSError * _Nullable error) {
        XHLog(@"webObject:%@-%@",object,error);
     }];
}

WKUIDelegate
//alert(),confirm(),prompt() 与 WK 有对应的方法
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler {
}

3、JS代码注入
#define Js @"function %@() { return '%@';}; "
- (void)injectionJsFunToJS
{
    AppDelegate *delegate=(AppDelegate*)[[UIApplication sharedApplication] delegate];
    //js注入
   NSString *Str = [NSString stringWithFormat:Js,@"getToken",delegate.token];
   //创建自定义JS 注意两个参数
   WKUserScript *noneSelectScript = [[WKUserScript alloc] initWithSource:Str                                     injectionTime:WKUserScriptInjectionTimeAtDocumentStart
                                                        forMainFrameOnly:NO];
   // 将自定义JS加入到配置里
   [self.webView.configuration.userContentController addUserScript:noneSelectScript];
}

二、Web 端

window.webkit.messageHandlers.<name>.postMessage(<messageBody>)
window.webkit.messageHandlers. goDetail.postMessage(<messageBody>)
goDetail 是商定的的key,上面是模板,直接copy过去,不会报错
<messageBody> 一定要给东西 至少给 null

1、web端给iOS端传值或发送消息如下:

//传递空
 window.webkit.messageHandlers.goDetail.postMessage(null)
//传递字符串
window.webkit.messageHandlers.goDetail.postMessage("123") 
//传递数组
window.webkit.messageHandlers.goDetail.postMessage(['1', '2','3'])
//传递字典
window.webkit.messageHandlers.goDetail.postMessage({4: { 'windowID': 10004 } })

2、web端接收iOS端的参数

 //需要挂载
       mounted() {
            window.getWorkJsonParams = this.shareResult
         },
      methods: {
           shareResult:function(strings) {
             alert('strings');
          }
       }

3、web端调用 alert(),confirm(),prompt() 给iOS端发送消息

<script type="text/javascript">
        function callJsAlert() {
          alert('Objective-C call js to show alert');
    
          window.webkit.messageHandlers.AppModel.postMessage({body: 'call js alert in js'});
        }

      function callJsConfirm() {
        if (confirm('confirm', 'Objective-C call js to show confirm')) {
          document.getElementById('jsParamFuncSpan').innerHTML
          = 'true';
        } else {
          document.getElementById('jsParamFuncSpan').innerHTML
          = 'false';
        }
  
        // AppModel是我们所注入的对象
        window.webkit.messageHandlers.AppModel.postMessage({body: 'call js confirm in js'});
      }
    function callJsInput() {
        var response = prompt('Hello', 'Please input your name:');
        document.getElementById('jsParamFuncSpan').innerHTML = response;
         // AppModel是我们所注入的对象
        window.webkit.messageHandlers.AppModel.postMessage({body: response});
      }
    </script>

相关文章

网友评论

      本文标题:WKWebView与Vue交互

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