首页 > 解决方案 > 在 Android Studio 中更改 webView 内容

问题描述

我想获取页面源代码,查找特定文本并将其替换为不同的文本。然后我想向用户显示更改后的页面。有没有办法在 Android Studio 中做到这一点?

标签: javaandroidhtmlweb

解决方案


您可以做的是使用自定义 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")
 }

推荐阅读