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
Calculate Age from Birth Date Using Nsdatecomponents in Swift
How to Convert a Decimal Number to Binary in Swift
Delete Folder With Contents from Firebase Storage
How to Remove the Left and Right Padding of a List in Swiftui
Separating Multiple If Conditions With Commas in Swift
Deinit Method Is Never Called - Swift Playground
What Happened to the Uiview() Constructor in Swift 3.0
Uitextview With Hyperlink Text
How to Import a Swift File from Another Swift File
Swift Function Object Wrapper in Apple/Swift
Fatal Error: Swapping a Location With Itself Is Not Supported With Swift 2.0
How Add Tabs Programmatically in Uitabbarcontroller With Swift
How to Avoid Force Unwrapping a Variable
The Use of Swift 3 @Objc Inference in Swift 4 Mode Is Deprecated