Last active
July 20, 2022 03:36
-
-
Save minibugdev/cfc6d526eefb4097b1c3c5867560306a to your computer and use it in GitHub Desktop.
Android WebAppInterface
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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