java - 在 Android Studio 中更改 webView 内容
问题描述
我想获取页面源代码,查找特定文本并将其替换为不同的文本。然后我想向用户显示更改后的页面。有没有办法在 Android Studio 中做到这一点?
解决方案
您可以做的是使用自定义 WebView 并添加一个新方法来自己加载 URL 的 HTML 并修改返回的 HMTL。这是一个使用协程的 Kotlin 示例:
class OverrideWebView : WebView {
constructor(context: Context?) : super(context)
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
private val okHttpClient = OkHttpClient()
fun loadUrlAndReplace(url: String, replace: (String) -> String) {
val request = Request.Builder()
.url(url)
.build()
GlobalScope.launch {
okHttpClient.newCall(request).execute().body()?.string()?.let { html ->
GlobalScope.launch(Dispatchers.Main) {
val newHtml = replace(html)
loadData(newHtml, "text/html", "UTF-8");
}
} ?: kotlin.run {
Log.e("ERROR", "Error loading $url")
}
}
}
}
用法:
val url = "https://example.com"
webView.loadUrlAndReplace(url) {html->
html.replace("Original Text","New Text")
}
推荐阅读
- tensorflow - 如何在keras中保存vgg模型
- ios - 在协议见证相关问题上崩溃
- java - 单击按钮时如何更改 Firestore 查询?
- javascript - dash.js 多次重新加载同一段
- r - 通过查找另一个数据框在 R 中创建一个新列
- ruby - Ruby:评估顺序取决于空格和看似多余的括号,为什么?
- reactjs - react-intl 包中 defineMessages 的打字稿
- android - 我如何为大用户群的 android 应用程序登录服务器?
- android - 通知父小部件在异步子小部件中加载数据时发生错误
- c# - 如何解决 BlazorServer 默认项目解决方案中的命名空间错误(VisualStudio 代码)