xxkamil72xx
xxkamil72xx

Reputation: 11

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?

Upvotes: 0

Views: 1818

Answers (2)

Benoit TH
Benoit TH

Reputation: 631

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. Here's a Kotlin example using coroutines:

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")
 }

Upvotes: 3

Olehcoding
Olehcoding

Reputation: 122

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.

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.

In either way you have to do almost everything by yourself. But having and idea already is a good start anyway, wish you luck!

Upvotes: 0

Related Questions