1

I need my swift class to interact with the html and javascript in a wkwebview that it references, in particular, feed it a variable.

I thought I would start simply by trying to get the webview to retrieve something using getElementByID following the code here. However, it is not working.

Here is code:

HTML file
<div id="username">@twostraws</div>


Swift File

let webView = WKWebView()

    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        if let url = Bundle.main.url(forResource: "myHTML", withExtension: "html") {
            webView.loadFileURL(url, allowingReadAccessTo: url.deletingLastPathComponent())
           
        }
       webView.evaluateJavaScript("document.getElementById('username').innerText") { (result, error) in
            if let result = result {
                print("what is in div",result)
            }
            else {
               print("didn't find it")
                
            }
       
        
    }
   
    override func loadView() {
        
        self.view = webView
    }

The webview is loading, however nothing is getting retrieved by evaluateJavascript.

Edit:

This is error message:

A JavaScript exception occurred" UserInfo={WKJavaScriptExceptionLineNumber=1, WKJavaScriptExceptionMessage=TypeError: null is not an object (evaluating 'document.getElementById('username').innerText'), WKJavaScriptExceptionColumnNumber=32, WKJavaScriptExceptionSourceURL=about:blank, NSLocalizedDescription=A JavaScript exception occurred})

Thanks for any suggestions.

user6631314
  • 1,751
  • 1
  • 13
  • 44

0 Answers0