To retrieve HTML content from WebView, several methods can be used. These methods depend on the platform and development environment you are working with. Here are some common approaches:
Android WebView
On Android, you can use the evaluateJavascript method of WebView to inject JavaScript code and retrieve the HTML content of the current page. Here is an example:
javawebView.evaluateJavascript("(function() { return document.documentElement.outerHTML; })();", new ValueCallback<String>() { @Override public void onReceiveValue(String html) { // Process the retrieved HTML content here Log.d("HTML", html); } });
iOS WKWebView
On iOS, using WKWebView, you can inject JavaScript code via the evaluateJavaScript method to retrieve the HTML of the page. Here is an example:
swiftwkWebView.evaluateJavaScript("document.documentElement.outerHTML.toString()", completionHandler: { (html: Any?, error: Error?) in if error == nil { if let htmlString = html as? String { // Process the retrieved HTML content here print(htmlString) } } })
UWP WebView
In Universal Windows Platform (UWP) applications, you can use the InvokeScriptAsync method to execute JavaScript code and retrieve HTML content. Here is an example:
csharpstring html = await webView.InvokeScriptAsync("eval", new string[] { "document.documentElement.outerHTML;" }); // Process the retrieved HTML content here Debug.WriteLine(html);
Considerations
- Due to security constraints, these methods are typically only applicable to web pages you have loaded directly or those under your control. For cross-origin content, you may encounter restrictions imposed by the Same-Origin Policy.
- Ensure the WebView control has fully loaded the page before executing the HTML retrieval operation; otherwise, you may receive an empty or incomplete result.
- The retrieved HTML represents a snapshot of the page's state at the time of retrieval. If the page changes subsequently (e.g., due to dynamically loaded content via JavaScript), these changes will not be reflected.
In practical development, choose the appropriate method based on your requirements and platform. Additionally, handle JavaScript execution results carefully, including error handling and asynchronous operation management.