如何对 Webview 中加载的网页进行替换
How to make a replacement over the webs loaded in a Webview
我正在使用网络视图实现一个应用程序。对于在 webview 中加载的 urls,我需要对 url 中加载的 html 代码执行替换。
我怎样才能有效地做到这一点?
说明:我需要从源码中替换一个特定的脚本脚本:
例如:我想
<html>
<script> SCRIPT A</script>
<p>Hello World</p>
</html>
我想向用户显示其他
<html>
<script> SCRIPT B</script>
<p>Hello World</p>
</html>
谢谢
您必须覆盖 WebViewClient
的 shouldInterceptRequest
。请参阅文档 here.
一般形式是这样的(未经测试):
webview.setWebViewClient(new WebViewClient() {
@Override
public WebResourceResponse shouldInterceptRequest (final WebView view, String url) {
if (you_want_to_intercept) {
/*return custom WebresourceResponse here*/
} else {
/*call superclass*/
return super.shouldInterceptRequest(view, url);
}
}
}
希望对您有所帮助,如果没有请告诉我。
您可以使用 http 请求以字符串形式获取 HTML 页面,然后使用类似 jsoup to find and replace the script, and use WebView.loadDataWithBaseURL 的内容将 HTML 内容加载到 WebView 中。
我正在使用网络视图实现一个应用程序。对于在 webview 中加载的 urls,我需要对 url 中加载的 html 代码执行替换。
我怎样才能有效地做到这一点?
说明:我需要从源码中替换一个特定的脚本脚本:
例如:我想
<html>
<script> SCRIPT A</script>
<p>Hello World</p>
</html>
我想向用户显示其他
<html>
<script> SCRIPT B</script>
<p>Hello World</p>
</html>
谢谢
您必须覆盖 WebViewClient
的 shouldInterceptRequest
。请参阅文档 here.
一般形式是这样的(未经测试):
webview.setWebViewClient(new WebViewClient() {
@Override
public WebResourceResponse shouldInterceptRequest (final WebView view, String url) {
if (you_want_to_intercept) {
/*return custom WebresourceResponse here*/
} else {
/*call superclass*/
return super.shouldInterceptRequest(view, url);
}
}
}
希望对您有所帮助,如果没有请告诉我。
您可以使用 http 请求以字符串形式获取 HTML 页面,然后使用类似 jsoup to find and replace the script, and use WebView.loadDataWithBaseURL 的内容将 HTML 内容加载到 WebView 中。