Displaying specific div from a website into webview in android
What is Android WebView
Android webview is an android UI component that allows you the developer to deliver web content as part of your activity layout. Unlike browsers such as chrome webview lack advanced features of a fully developed web browser.
In this tutorial series we are going to explore some features of webview and challenges you are most likely to experience when working with a webview. We are going to offer solutions that solve some troubles you may have come across when using webview.
Some of these challenges I have encountered and have found ways to navigate through them. We are going to take on each challenge as a topic. Let us get started.
Setting Up WebView Client
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_stats)
webView.settings.javaScriptEnabled = true
webView.webViewClient = MyBrowser(mainUrl)
webView.loadUrl(mainURL)
}
How to Disable Navigation to other pages in Android WebView.
At what time will you face such a scenario? Assuming you wanted to present to your users just a single page from an external website and this page has other internal links a user can navigate to, in this case you do not want your users to navigate to any other website except the one you loaded initially into the webview.
In this case we will be required to compare the initial URL and any other URL your user may be trying to navigate to. In case your user tries to navigate to that URL our webView will do nothing.
Below is the solution to prevent user navigation to other urls except the first initial URL.
private class MyBrowser(var mainURL: String) : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView, url: String?): Boolean {
if (url == mainURL) {
view.loadUrl(url)
}
return true
}
}
Any way to hide elements in a webview - Hiding Element by ID.
You may not want to display particular sections of a html in your website. To achieve this you must have a basic understanding of JavaScript and CSS. To achieve this you will be required to manipulate the DOM(Document Object Model) of the site you are trying to load to your webview.
Assuming you do not want to display an element with the id “game” We are going to override the onpageFinished
function and inject a JavaScript code to hide the element with id “game”
private class MyBrowser(var mainURL: String) : WebViewClient() {
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
view.loadUrl("javascript:(function() { document.getElementById('game').style.display='none';})()"
}
}
Android webview how to hide webview error page
Maybe you do not want to display the default error page of a webview. One reason is you may not want to disclose the url your web page is loading data from. The most effective way to achieve this would be to hide your webview when the webview has raised an error and replace the view with another view showing your custom error.
Webview errors are catched on the “onReceivedError
” function of the webview client; we will have to override this method to hide the webview when an error is raised.
private class MyBrowser(var context:Context,var webview: Webview) : WebViewClient() {
private var isError = false
override fun onReceivedError(
view: WebView?,
request: WebResourceRequest?,
error: WebResourceError
) {
super.onReceivedError(view, request, error)
if (error.errorCode == -2) {
isError = true
}
Toast.makeText(
context,
"Your Internet Connection May not be active Or " + error.description,
Toast.LENGTH_LONG
).show()
}
}
Error code -2 shows that an error has occurred and we need to hide the webview and notify the user.
Displaying specific div from a website into webview in android
To view a specific div from a website you will be required to install jsoup dependency as follows.
implementation 'org.jsoup:jsoup:1.13.1'
We are going to load the html of a whole web page and display only the part we are interested with on the webview.
val doc: Document = Jsoup.connect(url).get()
val element: javax.lang.model.util.Elements = doc.select("div#yourdivid")
webView.loadData(ele.toString(), "text/html", "utf-8"
This is all you are required to do.
You may get an exemption when you try to run the above code as is. Loading url content is a network operation not permitted in android with the default policy. You can consider running the script in a coroutine as follows.
GlobalScope.launch {
val doc: Document = withContext(Dispatchers.IO){Jsoup.connect(url).get()}
val element: javax.lang.model.util.Elements = doc.select("div#yourdivid")
webView.loadData(ele.toString(), "text/html", "utf-8")
}
Thank You for reading up to this point. I hope you found this helpful . Cheers!