乐闻世界logo
搜索文章和话题

How to get html content from a webview?

1个答案

1

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:

java
webView.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:

swift
wkWebView.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:

csharp
string 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.

2024年6月29日 12:07 回复

你的答案