美文网首页swift
WKWebView---WKScriptMessageHandl

WKWebView---WKScriptMessageHandl

作者: 初灬终 | 来源:发表于2018-12-07 22:34 被阅读7次

    - (void)addScriptMessageHandler:(id <WKScriptMessageHandler>)scriptMessageHandler name:(NSString *)name;

    //WKWebView initial
    WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:_webView];
    NSString *path = [[NSBundle mainBundle] pathForResource:@"WebView" ofType:@"html"];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]];
    [webView loadRequest:request];
    
    //- (void)addScriptMessageHandler:(id <WKScriptMessageHandler>)scriptMessageHandler name:(NSString *)name;
    //name表示添加的js方法名
    [webView.configuration.userContentController addScriptMessageHandler:self name:@"openCamera"];
    [webView.configuration.userContentController addScriptMessageHandler:self name:@"playVideo"];
    

    window.webkit.messageHandlers.注册的方法名.postMessage(parameters);

    <!DOCTYPE html>
    <html>
    <head>
        <title>webView</title>
        <style>
            button {
                font-size: 30px;
                width: 250px;
                height: 50px;
                display: block;
                margin-top: 5px;
            }
        </style>
        <script type="text/javascript">
            function useCamera() {
                window.webkit.messageHandlers.openCamera.postMessage(null);
            }
            function useVideo(vedio) {
                var obj = {"name":"God", "Author":"Jhon Trank"};
                window.webkit.messageHandlers.playVideo.postMessage(obj);
            }
        </script>
    </head>
    <body>
        <button onclick="openCamera()" id="openCameraButton">openCamera</button>
        <button onclick="playVideo()" id="playVideoButton">playVideo</button>
    </body>
    </html>
    

    WKScriptMessageHandler这个协议的代理方法

    js通过messageHandlers调用方法,传递参数。在这个代理里,都可以获取到。

    - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
        if ([message.name isEqualToString:@"openCamera"]) {
            NSLog(@"%@ -- %@", message.name, message.body);//openCamera -- <null>
        }else if([message.name isEqualToString:@"playVideo"]) {
            NSLog(@"%@ -- %@", message.name, message.body);//playVideo -- {Author = "Jhon Trank";name = God;}
        }
    }
    

    相关文章

      网友评论

        本文标题:WKWebView---WKScriptMessageHandl

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