Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grab HTML from WKWebView using evaluateJavascript and then store it in a variable (using Swift)

I have users logging into a website using a WKWebView after which I want to parse the HTML of the page. I am very much new to Swift/iOS Development (just learning things as I go along). I know the id of the HTML tag I am trying to grab the innerHTML of (the id is "dataGrid") and would like to store the string in a variable called htmlString. I have the following code:

var htmlString = "initial value"
webView.evaluateJavaScript("document.getElementById('dataGrid').innerHTML.toString()", 
    completionHandler: { (html: Any?, error: Error?) in htmlString = html as! String})
print(htmlString)

Evidently this doesn't work - the last print statement just prints "initial value". Just so you know, I am basing my code off of the method described in another StackOverflow post (Get HTML from WKWebview in Swift). In the one, the completion handler has a print statement, which actually works in printing the HTML. However, I don't really understand completion handlers, which makes sense considering I haven't really had much experience with Swift yet, but it also means I don't know how to adapt the code in that post for my own purposes. I would really appreciate it if someone could direct me in the right direction so I can store the HTML of the page as a string in a variable that I can mutate later. Thank you!

like image 987
Shardul Joshi Avatar asked Aug 06 '26 09:08

Shardul Joshi


1 Answers

The value of htmlString is "initial value" because the block is executed after the print statement is getting executed!

If you do print the htmlString inside the block you can see the actual value. You have to do your task inside the completion block. Also the completion block will be executed in the main thread so you need to make sure that you don't block the main thread.

like image 153
Karthick Ramesh Avatar answered Aug 08 '26 00:08

Karthick Ramesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!