Android WebView 获取网页 iframe 内容方法详解
Android WebView 获取网页 iframe 内容方法详解
在 Android 开发中,我们经常需要使用 WebView 来加载网页,有时需要获取网页中 iframe 的内容。本文将详细介绍如何使用 WebView 的 loadUrl 方法加载网页,并在 onPageFinished 方法中使用 JavaScriptInterface 获取 frame 中的内容。
实现步骤
-
创建 WebViewClient 子类并重写 onPageFinished 方法。
public class MyWebViewClient extends WebViewClient { @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); view.loadUrl("javascript:window.android.getContent(document.getElementsByTagName('iframe')[0].contentWindow.document.documentElement.outerHTML);"); } }
-
创建 JavaScriptInterface 类并实现 getContent 方法。
public class MyJavaScriptInterface { private Context mContext; public MyJavaScriptInterface(Context context) { mContext = context; } @JavascriptInterface public void getContent(String content) { // 将 frame 中的内容发送到父页面 ((Activity) mContext).runOnUiThread(new Runnable() { @Override public void run() { webView.loadUrl("javascript:window.parent.postMessage('"+ content +"', '*');"); } }); } }
-
在 WebView 中设置 JavaScriptInterface。
webView.addJavascriptInterface(new MyJavaScriptInterface(this), "android");
-
在父页面中监听 message 事件。
window.addEventListener('message', function(event) { var content = event.data; // 处理 frame 中的内容 });
代码说明
- 在 onPageFinished 方法中,我们使用
loadUrl
方法执行 JavaScript 代码,该代码调用window.android.getContent
函数,并传入 iframe 的内容。 MyJavaScriptInterface
类中的getContent
方法接受 iframe 的内容,并使用postMessage
方法将其发送到父页面。- 父页面使用
addEventListener
方法监听message
事件,并在事件处理程序中获取 iframe 的内容。
注意事项
- 在 Android 4.2 及以上版本中,需要使用
@JavascriptInterface
注解声明 JavaScriptInterface 方法,才能在 JavaScript 中访问。 postMessage
方法用于跨域通信,它允许 iframe 将消息发送到父页面。- 需要注意的是,如果 iframe 的内容是动态生成的,则需要在 iframe 内容加载完成后再执行
getContent
方法,以确保获取到最新的内容。
总结
本文详细介绍了如何在 Android WebView 中使用 JavaScriptInterface 获取网页 iframe 中的内容,并提供了示例代码和注意事项。希望本文能帮助您更好地理解和使用 WebView。
原文地址: http://www.cveoy.top/t/topic/mu4V 著作权归作者所有。请勿转载和采集!