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的博客 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- xcode – NSURLConnection sendAsynchronousRequest:queue
- ruby-on-rails – 将文本插入现有文件
- 存储过程 – BLToolkit Oracle SP支持
- oracle11g – Oracle解释计划:基数返回一个庞大的数字,但查
- cocos2d-x接入GooglePlay IAB(In-app Billing)和iOS IAP(In
- Swift 3(SpriteKit):停止永久循环的SKAction有一个延迟
- c# – 如何删除Visual Studio 2017 15.8版中的水平白线?
- ruby – 命名Class.new
- xml解析-sax范例
- iphone – 如何编译armv6,armv7和i386的静态库(胖)