UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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

3      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.