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);

我的Github地址:https://github.com/klbest1/MyIOSDemo,记得点赞额

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值