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的博客

你可能感兴趣的:(iOS,HTML5,Swift)