WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

Injecting JavaScript into a local web page (Solved)

Forums > iOS

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!)
            }
        }
    }
}

1      

Save 50% in my Black Friday sale.

SAVE 50% To celebrate WWDC22, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.