Get HTML from Wkwebview in Swift

Get HTML from WKWebview in Swift

If you wait until the page has loaded you can use:

webView.evaluateJavaScript("document.documentElement.outerHTML.toString()", 
completionHandler: { (html: Any?, error: Error?) in
print(html)
})

You could also inject some javascript that returns you back the HTML.

let script = WKUserScript(source: javascriptString, injectionTime: injectionTime, forMainFrameOnly: true)
userContentController.addUserScript(script)
self.webView.configuration.userContentController.addScriptMessageHandler(self, name: "didGetHTML")



func userContentController(userContentController: WKUserContentController,
didReceiveScriptMessage message: WKScriptMessage) {

if message.name == "didGetHTML" {
if let html = message.body as? String {
print(html)
}
}
}

The javascript you could inject looks something like:

webkit.messageHandlers.didGetHTML.postMessage(document.documentElement.outerHTML.toString());

Get HTML by evaluating JavaScript in a WKWebView

The issue was the webpage wasn't fully loaded! I was calling my function in ViewDidAppear but after I added a button and called the javascript when I pressed the button, I got the HTML I was looking for.

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

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.

Get html content from webView in Swift?

You can get the inner text of the div by:

func webViewDidFinishLoad(_ webView: UIWebView) {

guard let text = webView.stringByEvaluatingJavaScript(from: "document.getElementById(\"displayMsg\").innerText") else {
return
}

print(text) // Thanh toán thành công
}


Related Topics



Leave a reply



Submit