加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift WKWebView的swift调用js

发布时间:2020-12-14 06:22:59 所属栏目:百科 来源:网络整理
导读:不多说,直接上代码: import UIKitimport WebKitclass SwiftCallJSController: UIViewController { var context = JSContext() var webView = WKWebView() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white //webView web

不多说,直接上代码:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读