Reading HTML content from a UIWebView
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:
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:
Sniping specific elements
To home in on specific elements by id
, type:
Pouring HTML directly into UIWebView
Fancy loading your own HTML content into UIWebView
? Use loadHTMLString:baseURL:
:
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:
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).
Was this article helpful?