Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get HTML from WKWebview in Swift

I log into a website using WKWebView and now i would like to parse the html of the website. How can I access the websites html in swift? I know how it works for a UIWebView but not for WKWebView.

Thanks for your help!

like image 738
MotoxX Avatar asked Jan 12 '16 19:01

MotoxX


People also ask

What is WKWebView in Swift?

A WKWebView object is a platform-native view that you use to incorporate web content seamlessly into your app's UI. A web view supports a full web-browsing experience, and presents HTML, CSS, and JavaScript content alongside your app's native views.

How do I load a URL in WKWebView swift 5?

Loading local content WKWebView can load any HTML stored in your app bundle using its loadFileURL() method. You should provide this with a URL to some HTML file that you know is in your bundle, along with another URL that stores any other files you want to allow the web view to read. That url.


1 Answers

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()); 
like image 145
Onato Avatar answered Oct 05 '22 10:10

Onato