WKWebview 捕获点击事件

1.js注入:

let userContent = WKUserContentController()
userContent.add(self, name: "quitCourse")
let jsContent = " function quit() {  window.webkit.messageHandlers.quitCourse.postMessage(null);}(function(){   var btn = document.getElementById('quit_course');btn.addEventListener('click',quit,false);}());"
userContent.addUserScript(WKUserScript(source: jsContent, injectionTime: .atDocumentEnd, forMainFrameOnly: true))
        
let confiration = WKWebViewConfiguration()
confiration.userContentController = userContent
        
webView = WKWebView(frame:CGRect(x: 0, y: 20, width: view.bounds.size.width, height: courseView.bounds.size.height), configuration: confiration)
webView.navigationDelegate = self;
webView.uiDelegate = self;

2.原生捕获事件:

extension  YKIPCourseViewController:WKScriptMessageHandler{
  
    public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage){
        if message.name == "quitCourse" {
            self.back(nil)
        }
    }

}

注意:由于我的项目中,网页进行了一次跳转,所以js注入主动添加事件监听无效,因此只有叫前端开发人员主动调用:window.webkit.messageHandlers.quitCourse.postMessage(null);

你可能感兴趣的:(IOS)