I’m looking for the most straight-forward way to get the FULL html from a page. After page load and after JS will finish work.
Speed is not important. Optimization is not important. Locking of main thread is not important.
Only the result is important: get the full HTML code of the page. Synchronously.
I’m tried to get html with WKWebView:
class InternetLoader {
private let webView = WKWebView(frame: .zero)
private let script = """
window.onload = function() {
document.body.innerHTML;
};
"""
private var resultHtml: String? = nil
func getHTML(from url: URL) -> String {
webView.load(URLRequest(url: url))
let semaphore = DispatchSemaphore(value: 0)
webView.evaluateJavaScript(script) { (result, error) in
if let error = error {
print("Error executing JavaScript: (error.localizedDescription)")
} else if let htmlContent = result as? String {
self.resultHtml = htmlContent
}
semaphore.signal()
}
semaphore.wait()
return resultHtml!
}
}
Usage:
let il = InternetLoader()
let html = il.getHTML(from: URL(string: "/questions"))
But it endlessly stuck.
what I’m doing wrong?
11