Created
October 9, 2018 11:09
-
-
Save Tadaboody/c6b9a9d933d1106cbce9a07ee97ee441 to your computer and use it in GitHub Desktop.
Wrapper for a webview that handles JSONs, invoking a callback when encountering them
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
class JsonWebView(private val webView: WebView) { | |
private val BASEURL: String = BackendRemote.SERVER_ADDRESS | |
val TAG = JsonWebView::class.java.name | |
@SuppressLint("SetJavaScriptEnabled") | |
fun loadURL(url:URL,cb: (JSONObject) -> Unit) { | |
webView.settings.apply { | |
javaScriptEnabled = true | |
domStorageEnabled = true | |
webView.loadUrl(url.toString()) | |
} | |
// Creates a js interface method, callabale from the webview | |
webView.addJavascriptInterface( | |
object { | |
@JavascriptInterface | |
fun parseJSON(html: String) { | |
Log.d(TAG, "Injected $html") | |
try { | |
val obj = JSONObject(html) | |
Log.d(TAG, "valid json obj from $html : $obj") | |
cb(obj["api_key"] as String) | |
} catch (ex: JSONException) { | |
Log.d(TAG,"Invalid json") | |
} | |
} | |
}, | |
"JSONHandler" // interface name for url calling | |
) | |
webView.webViewClient = object : WebViewClient() { | |
private val TAG = "${OAuthHandler::TAG}::WEBVIEW" | |
override fun onPageFinished(view: WebView?, url: String?) { | |
Log.d(TAG,"PAGE FINISHED") | |
//Call the js interface | |
view?.loadUrl("javascript:window.JSONHandler.parseJSON(document.body.innerText);") | |
super.onPageFinished(view, url) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment