Hi everyone! I'm a little stumped on why this isn't working for me. I've been following Paul's Ultimate Guide to WKWebKit and can't seem to get the injection and readback of JavaScript to work. Below is what I currently have. Let me know if you can suggest what I can do different to make this work. Much appreciated!
ViewController.swift
import UIKit
import WebKit
class ViewController: UIViewController {
let webView = WKWebView()
override func viewDidLoad() {
super.viewDidLoad()
self.view = webView
if let url = Bundle.main.url(forResource: "index", withExtension: "html") {
webView.loadFileURL(url, allowingReadAccessTo: url.deletingLastPathComponent())
webView.evaluateJavaScript("document.getElementById('username').innerText") { (result, error) in
if let result = result {
print(result)
}
}
webView.addObserver(self, forKeyPath: #keyPath(WKWebView.title), options: .new, context: nil)
}
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "title" {
if let title = webView.title {
print(title)
}
}
}
}
index.html
<html>
<head>
<title>Hello World!</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div id="username">This is a test!</div>
</body>
</html>
Solution
So I kind of feel a little silly, but after posting this question, I solved my problem. I failed to see that JavaScript evaluation needed to be performed through a function. Below is my solution:
import UIKit
import WebKit
class ViewController: UIViewController {
let webView = WKWebView()
override func viewDidLoad() {
super.viewDidLoad()
self.view = webView
if let url = Bundle.main.url(forResource: "index", withExtension: "html") {
webView.loadFileURL(url, allowingReadAccessTo: url.deletingLastPathComponent())
webView.addObserver(self, forKeyPath: #keyPath(WKWebView.title), options: .new, context: nil)
}
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "title" {
if let title = webView.title {
print(title)
}
}
// document.getElementById('username').innerText
webView.evaluateJavaScript("document.getElementById('demo').innerHTML = obj.name + ', ' + obj.age;") { (result, error) in
if error == nil {
print(result!)
}
}
}
}