欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

WebView与H5交互

程序员文章站 2022-03-11 08:17:40
val settings = rm_webview.settingssettings.javaScriptEnabled = truesettings.domStorageEnabled = truesettings.javaScriptCanOpenWindowsAutomatically = truesettings.cacheMode = WebSettings.LOAD_DEFAULTsettings.setAppCacheEnabled(true)settings.setSuppor....
val settings = rm_webview.settings
settings.javaScriptEnabled = true
settings.domStorageEnabled = true
settings.javaScriptCanOpenWindowsAutomatically = true
settings.cacheMode = WebSettings.LOAD_DEFAULT
settings.setAppCacheEnabled(true)
settings.setSupportZoom(true)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
}
settings.useWideViewPort = true
settings.loadWithOverviewMode = true
rm_webview.loadUrl(load_url + h5_url)

rm_webview.webViewClient = object : WebViewClient() {
    override fun onReceivedSslError(
        view: WebView?,
        handler: SslErrorHandler?,
        error: SslError?
    ) {
        handler?.cancel()
    }

    override fun onPageFinished(view: WebView?, url: String?) {
        super.onPageFinished(view, url)

        val userData = UserDataUtlis().getUserData()

        if (userData != null) {


            if (type == 2) {
                initData(
                    "{}"
                )
            }
        }

    }

}
rm_webview.webChromeClient = object : WebChromeClient() {
    override fun onReceivedTitle(view: WebView?, title: String?) {
        super.onReceivedTitle(view, title)
        if (title != null) {
            app_title_tv.text = title
        }
    }
}
rm_webview.addJavascriptInterface(jsObject, "androidObject")


@Suppress("NewApi")
private fun initData(jsonData: String) {
    if (Build.VERSION.SDK_INT < 18) {
        rm_webview.loadUrl("javascript:initData($jsonData)\"")
    } else {
        rm_webview.evaluateJavascript("javascript:initData($jsonData)") {
        }
    }
}



/**
 * 返回上一级页面 
 */
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
    if (keyCode == KeyEvent.KEYCODE_BACK && rm_webview.canGoBack()) {
        rm_webview.goBack()
        return true
    }
    return super.onKeyDown(keyCode, event)
}

fun goUpPage(keyCode: Int) {
    object : Thread() {
        override fun run() {
            try {
                val inst = Instrumentation()
                inst.sendKeyDownUpSync(keyCode)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }.start()
}

 

//调我们的的方法

inner class JsObject {
    @JavascriptInterface
    fun openConcat() {
        //打开通讯录
        startNumber(this@H5Activity, 1)
    }

    @JavascriptInterface
    fun finishView() {
        finish()
    }


}

本文地址:https://blog.csdn.net/weixin_41194750/article/details/107177731