inject CSS to a site with webview in android

前端 未结 4 1787
小鲜肉
小鲜肉 2020-11-28 09:02

For example I want to change the background-color of www.google.comto red. I have used webview, and my style.cssfile is i

4条回答
  •  情书的邮戳
    2020-11-28 09:56

    For Kotlin Users

    import this

    import android.util.Base64
    

    and this is onPageFinished code

     override fun onPageFinished(view: WebView?, url: String?) {
                    injectCSS()
    }
    

    and this is the code to call

    private fun injectCSS() {
                try {
                    val inputStream = assets.open("style.css")
                    val buffer = ByteArray(inputStream.available())
                    inputStream.read(buffer)
                    inputStream.close()
                    val encoded = Base64.encodeToString(buffer , Base64.NO_WRAP)
                    webframe.loadUrl(
                        "javascript:(function() {" +
                                "var parent = document.getElementsByTagName('head').item(0);" +
                                "var style = document.createElement('style');" +
                                "style.type = 'text/css';" +
                                // Tell the browser to BASE64-decode the string into your script !!!
                                "style.innerHTML = window.atob('" + encoded + "');" +
                                "parent.appendChild(style)" +
                                "})()"
                    )
                } catch (e: Exception) {
                    e.printStackTrace()
                }
    
            }
    

提交回复
热议问题