Explain Codes LogoExplain Codes Logo

Reading HTML content from a UIWebView

html
uiwebview
html-content
javascript-execution
Nikita BarsukovbyNikita Barsukov·Aug 14, 2024
TLDR

For quick access to page HTML in a UIWebView, utilize the stringByEvaluatingJavaScript(from:) method. Here's how you can execute JavaScript to extract HTML content:

if let htmlString = webView.stringByEvaluatingJavaScript(from: "document.documentElement.innerHTML") { print(htmlString) // printing HTML content more fun than fine print }

Make sure to call this inside the webViewDidFinishLoad delegate function. This simple trick neatly fetches the HTML payload (not to be confused with—payload in the back of your car).

Master UIWebView and HTML content

Playing around with UIWebView and its HTML content can be a fun exercise. Why, you ask? You get to witness how WebKit smoothens the interaction between your Swift code and web content.

Grabbing the HTML of entire page

When you're in the mood to dump a complete HTML snippet<head> and <body>, included, here's what you can do:

if let fullHTMLString = webView.stringByEvaluatingJavaScript(from: "document.documentElement.outerHTML") { print(fullHTMLString) // Look, Ma! I got the whole thing! }

Sniping specific elements

To home in on specific elements by id, type:

if let elementHTML = webView.stringByEvaluatingJavaScript(from: "document.getElementById('yourElementId').innerHTML") { print(elementHTML) // And... bullseye! }

Pouring HTML directly into UIWebView

Fancy loading your own HTML content into UIWebView? Use loadHTMLString:baseURL::

webView.loadHTMLString(yourHTMLString, baseURL: nil) // Watch as your HTML takes the stage

Beware! Executing scripts within loaded content might cause your UIWebView to hang. And you don’t want that, do you?

Keeping your precious HTML safe

Fetching HTML from the web brings about a few challenges. Always ensure you can handle any errors and user-agent variations. Encode and store HTML securely (just like your stash of cookies).

Code smart: Steer clear of pitfalls

Watch your script execution

Flash news! Running unnecessary scripts in loadHTMLString may slow down your UIWebView (kinda like traffic during peak hours). Test the JavaScript execution and optimize!

Cater to user-agent variations

When pulling HTML, it's important to play nice with the web server. You can adjust your user agent to ensure you're served the right content:

if let userAgent = webView.stringByEvaluatingJavaScript(from: "navigator.userAgent") { // Adjust headers or settings to get the VIP treatment from the server }

Never compromise on storage and privacy

HTML content should be stored securely. Make sure your storage and handling methods follow all regulations boldly (not in the fine print).