这两个链接(第一,第二)帮助我解决了我的问题。
html/javascript 代码:
function bar(qq){
document.getElementById('foo').innerHTML = qq;
}
<div id="foo"></div>
我的 ViewController 看起来像这样:
class ViewController: UIViewController, WKNavigationDelegate, WKUIDelegate {
var webView: WKWebView
required init(coder aDecoder: NSCoder) {
self.webView = WKWebView(frame: CGRect.zero)
super.init(coder: aDecoder)!
}
override func loadView() {
super.loadView()
let userContentController = WKUserContentController()
let source = "bar('Hello from swift');"
let userScript = WKUserScript(source: source, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: true)
userContentController.addUserScript(userScript)
let configuration = WKWebViewConfiguration()
configuration.userContentController = userContentController
self.webView = WKWebView(frame: self.view.frame, configuration: configuration)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
view.addSubview(webView)
webView.translatesAutoresizingMaskIntoConstraints = false
let height = NSLayoutConstraint(item: webView, attribute: .height, relatedBy: .equal, toItem: view, attribute: .height, multiplier: 1, constant: 0)
let width = NSLayoutConstraint(item: webView, attribute: .width, relatedBy: .equal, toItem: view, attribute: .width, multiplier: 1, constant: 0)
view.addConstraints([height, width])
let path = Bundle.main.path(forResource: "foldername/index", ofType: "html")!
let url = URL(fileURLWithPath: path)
webView.load(URLRequest(url: url))
webView.allowsBackForwardNavigationGestures = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}