我正在尝试使Javascript-Swift接口与WKWebView一起使用,并且似乎有人在here上使它工作。
但是我无法在Swift中运行它(我是Swift的新手,而Obj-C的新手)。我尝试在ViewController.swift中执行以下代码,并将WKWebView添加到Main.storyboard并进行连接:
import WebKit
class ViewController: NSViewController, WKUIDelegate {
@IBOutlet weak var wkWebView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "http://127.0.0.1:8080")
let request = URLRequest(url: url!)
wkWebView!.configuration.preferences.javaScriptEnabled = true
wkWebView!.load(request)
}
}
extension WKWebView {
open override func invokeUndefinedMethod(fromWebScript name: String!, withArguments arguments: [Any]!) -> Any! {
return "Hello From Swift"
}
}
在HTML方面:
<html>
<body>
<p>Hello World</p>
<input type=text id='i'/>
<input type=button value='Submit' onclick='document.getElementById(\"i\").value = window.external.MY_ObjectiveCFunction();'>
</body>
</html>
但是,当我单击“提交”按钮时,没有任何反应。如果我使用document.getElementById("i") = "hello"
,虽然可以。 @ctrlspace似乎已使其以某种方式工作(请参见上面的链接)。
有什么想法吗?
答案 0 :(得分:1)
您发现有一篇旧文章是为古老的WebView
而写的,而不是为WKWebView
而写的。
使用WKScriptMessageHandler
时,您可以使用WKWebView
在JavaScript和Swift之间进行交互。
ViewController.swift:
import WebKit
class ViewController: NSViewController, WKUIDelegate {
@IBOutlet weak var wkWebView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
let url = Bundle.main.url(forResource: "index", withExtension: "html")! //Simplified for testing
let request = URLRequest(url: url)
wkWebView.configuration.preferences.javaScriptEnabled = true
wkWebView.configuration.userContentController.add(self, name: "mySwiftMessage") //<-
wkWebView.load(request)
}
//...
}
extension ViewController: WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
switch message.name {
case "mySwiftMessage":
if let callbackName = message.body as? String {
message.webView?.evaluateJavaScript("\(callbackName)('Hello From Swift');", completionHandler: nil)
}
default:
break
}
}
}
index.html:
<html>
<body>
<script>
function myCallback(value) {
document.getElementById("i").value = value;
}
</script>
<p>Hello World</p>
<input type=text id='i'/>
<input type=button value='Submit' onclick='window.webkit.messageHandlers.mySwiftMessage.postMessage("myCallback");'>
</body>
</html>
要使WKWebView
在11之前的iOS上运行,您只需以编程方式实例化它:
import WebKit
class ViewController: UIViewController, WKUIDelegate {
var wkWebView: WKWebView! //<- NOT an IBOutlet
override func viewDidLoad() {
super.viewDidLoad()
let webConfig = WKWebViewConfiguration()
webConfig.preferences.javaScriptEnabled = true
webConfig.userContentController.add(self, name: "mySwiftMessage")
wkWebView = WKWebView(frame: self.view.bounds, configuration: webConfig)
view.addSubview(wkWebView)
//You may need to add some constraints...
//And create a better `index.html` for iOS...
let url = Bundle.main.url(forResource: "index", withExtension: "html")!
let request = URLRequest(url: url)
wkWebView.load(request)
}
//...
}