Skip to content

我用webview加载微信公众号链接,按照下面的方式去实现,最后链接都加载不了,是哪里写的有问题吗 #8

Description

@zhoufanGithub
 mWebView!!.webViewClient = object : WebViewClient() {
        override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
            view.loadUrl(url)
            return true
        }

        override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? {
            return super.shouldInterceptRequest(view, request)
        }

        override fun shouldInterceptRequest(view: WebView, url: String): WebResourceResponse? {
            if (url.startsWith("https://mp.weixin.qq.com/s")) {
                val res = replaceCss(url, view.context)
                val input: InputStream = ByteArrayInputStream(res.toByteArray())
                return WebResourceResponse("text/html", "utf-8", input)
            }
            return super.shouldInterceptRequest(view, url)
        }


    }
}

private val rex = "(<style>)([\\S ]*)(</style>)"
private fun replaceCss(url: String, context: Context): String {
    val pattern = Pattern.compile(rex)
    val m = pattern.matcher(url)
    if (m.find()) {
        try {
            val css = getString(context.assets.open("weixin/weixin.css"))
            val sb = StringBuilder()
            sb.append(m.group(1))
            sb.append(css)
            sb.append(m.group(3))
            return url.replace(rex.toRegex(), sb.toString())
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }
    return url
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions