Swift WKWebView的swift调用js

前端之家收集整理的这篇文章主要介绍了Swift WKWebView的swift调用js前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

不多说,直接上代码

import UIKit
import WebKit
class SwiftCallJSController: UIViewController {

    var context = JSContext()
    var webView = WKWebView()
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        //webView
        webView.frame = view.frame
        let config = WKWebViewConfiguration()
        
        //偏好设置
        config.preferences = WKPreferences()
        //字体
        config.preferences.minimumFontSize = 10
        //设置js跳转
        config.preferences.javaScriptEnabled = true
        //不自动打开窗口
        config.preferences.javaScriptCanOpenWindowsAutomatically = false
        //web内容处理池
        config.processPool = WKProcessPool()
        //js和webview内容交互
        config.userContentController = WKUserContentController()
        //注入js对象名称为appmodel,当js通过appmodel来调用
        //可以在wkscriptMessagehandler的代理中接收到
        config.userContentController.add(self,name: "AppModel")
        
        //webView
        webView = WKWebView(frame: view.bounds,configuration: config)
        view.addSubview(webView)
        let url = Bundle.main.url(forResource: "JSCallOC",withExtension: "html")
        webView.load(URLRequest(url:url!))
        
        //swift操作js的按钮
        let button = UIButton.init()
        button.frame = CGRect(x:100,y:100,width:100,height:100)
        button.backgroundColor = .red
        button.addTarget(self,action: #selector(doButton),for: .touchDown)
        view.addSubview(button)
    }
    
    func doButton() {
        webView.evaluateJavaScript("log(10)") { (str,error) in
            if error != nil {
                print("\(error)")
            } else {
                print(str ?? "")
            }
        }
    }
    
    func loadJsFile(name: String) -> String {
        let path = Bundle.main.path(forResource: name,ofType: "js")
        let jsScript = try! String(contentsOfFile: path!,encoding: String.Encoding.utf8)
        return jsScript
    }
}

extension SwiftCallJSController: WKScriptMessageHandler {
    func userContentController(_ userContentController: WKUserContentController,didReceive message: WKScriptMessage) {
        print(message.body)
    }
}

在html里面要添加的的代码显示swift传过去的参数:
function log(n) {
        document.getElementById("result").innerText = n;
    }

这样就实现了swift给js传参数和调用

如果转载请注明转于:AirZilong的博客

原文链接:https://www.f2er.com/swift/321983.html

猜你在找的Swift相关文章