Swift WKWebView的swift调用js

20 篇文章 0 订阅
7 篇文章 0 订阅

不多说,直接上代码:

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值