Skip to content

Instantly share code, notes, and snippets.

@minibugdev
Last active July 20, 2022 03:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save minibugdev/cfc6d526eefb4097b1c3c5867560306a to your computer and use it in GitHub Desktop.
Save minibugdev/cfc6d526eefb4097b1c3c5867560306a to your computer and use it in GitHub Desktop.
Android WebAppInterface
typealias Listener = () -> Unit
class WebViewActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_webview)
setupWebView()
loadWebView("[your-web-url]")
}
private fun setupWebView() {
webView.apply {
addJavascriptInterface(WebAppInterface(onLoginSuccess), "Android")
settings.apply {
javaScriptEnabled = true
domStorageEnabled = true
}
webChromeClient = WebChromeClient()
webViewClient = object : WebViewClient() {
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
view?.loadUrl("javascript:" +
"window.Android.checkContentExist('<html>'" +
" + document.getElementsByTagName('html')[0].innerHTML + " +
"'</html>');")
}
}
}
}
private fun loadWebView(url: String) {
webView.post {
webView.loadUrl(url)
}
}
}
class WebAppInterface(private val listener: Listener?) {
@JavascriptInterface
fun checkContentExist(html: String) {
val frameUrl = Jsoup.parse(html)?.getElementsByTag("frame")?.firstOrNull()?.attr("src")
if (frameUrl?.contains("exptected-string") == true) {
listener?.invoke()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment