简体   繁体   English

在 Android Studio 中更改 webView 内容

[英]Changing webView content in Android Studio

I want to take a pages source code, find specific text and replace it with different text.我想获取页面源代码,找到特定文本并将其替换为不同的文本。 Then I want to display the altered page to the user.然后我想向用户显示更改后的页面。 Is there a way to do this in Android Studio?有没有办法在 Android Studio 中做到这一点?

Something you could do is use a custom WebView and add a new method to load a URL's HTML yourself and modify the returned HMTL.您可以做的是使用自定义 WebView 并添加一个新方法来自己加载 URL 的 HTML 并修改返回的 HMTL。 Here's a Kotlin example using coroutines:这是一个使用协程的 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")
            }
        }

    }

}

Usage:用法:

 val url = "https://example.com"
 webView.loadUrlAndReplace(url) {html->
       html.replace("Original Text","New Text")
 }

Unfortunately you can not.不幸的是你不能。

You have two options, you can get html source code - parse it and try to adjust design in your android app + add functionality by yourself.您有两个选择,您可以获得 html 源代码 - 解析它并尝试在您的 android 应用程序中调整设计 + 自己添加功能。

Or display website as Webview, but it will be completely useless, because you can only view content of the page and there is no way to change text etc.或者将网站显示为Webview,但完全没用,因为您只能查看页面内容而无法更改文本等。

In either way you have to do almost everything by yourself.无论哪种方式,您几乎都必须自己做所有事情。 But having and idea already is a good start anyway, wish you luck!但无论如何,拥有和想法已经是一个好的开始,祝你好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM