iOS WKWebView响应JS调用

2018-06-19  本文已影响33人  FicowShen



web端按照以下方式调用wkwebview的回调函数:

window.webkit.messageHandlers.<方法名>.postMessage(<参数>);



实例如下:

    function saveImage(url){
        var message = {
            'method' : 'saveImage',
            'args' : {
                'url' : url,
            },
        };
        window.webkit.messageHandlers.saveImage.postMessage(message);
        return url;
    }



iOS端需要注意内存泄露问题!
创建一个代理对象,然后通过弱引用的方式调用self!

class WebVCJSDelegate: NSObject,WKScriptMessageHandler {

    weak var scriptDelegate:WKScriptMessageHandler! = nil
    
    init(scriptDelegate:WKScriptMessageHandler) {
        self.scriptDelegate = scriptDelegate
    }
    
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage){
        
        self.scriptDelegate.userContentController(userContentController, didReceive: message)
    }
}



初始化WKWebView的代码:

        let conf:WKWebViewConfiguration = WKWebViewConfiguration.init()
        let prefer:WKPreferences = WKPreferences.init()
        prefer.javaScriptEnabled = true
        conf.preferences = prefer
        conf.allowsInlineMediaPlayback = true

        let userContentCtrl:WKUserContentController = WKUserContentController.init()
        self.jsDelegate = WebVCJSDelegate.init(scriptDelegate: self) //防止内存泄露
        userContentCtrl.add(jsDelegate, name: "saveImage") //查看图片的JS函数
        conf.userContentController = userContentCtrl
        
        webView = WKWebView.init(frame: CGRect.zero, configuration: conf)



实现WKScriptMessageHandler协议,即可在js调用时执行协议的回调方法:

    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage){
        
        let body = message.body
        print(body)
    }




参考文章:
iOS WKWebView与JS交互

上一篇下一篇

猜你喜欢

热点阅读