Android WebView Bind Javascript Tutorial

Javascript is very useful in web development, it is a very popular programming language should be learn from every developers. Many of us will ask does javascipt able to bind with the android webview. Good news for us, you can create the interface in the javascript and get the interface to perform some action in the android application. For example, you can create a button in the html, add a interface to the button event. Then you can use the html button to navigate another activity. In this tutorial, I will tell you how to use android webview bind javascript so you can use it in every project.

Creating a new Project

1. Open Android Studio IDE in your computer.
2. Create a new project and Edit the Application name to “JavaScriptWebViewExample”.
(Optional) You can edit the company domain or select the suitable location for current project tutorial. Then click next button to proceed.
3. Select Minimum SDK (API 15:Android 4.0.3 (IceCreamSandwich). I choose the API 15 because many android devices currently are support more than API 15. Click Next button.
4. Choose “Empty Project” and Click Next button
5. Lastly, press finish button.

Add a new assets folder

By create a new assets folder, right click “app” module > new > Folder > assets folder, then it will create an assets folder for you. The below picture is the sample steps to create assets folder.

webviewjavascript2-a

Create a html file

After that, create a html file by right click the assets folder > new > file. Name the html file as “sample.html”. Then follow the source code below to add buttons in the html file and create the javascript interface.

Create a Second Activity

After create the html file, go to create a new activity in your project, so later you will use the html button navigate to this activity.

Edit activity_main.xml layout

Besides, view your activity_main.xml and add a webview inside the relative layout like the source code below.

Edit MainActivity.java class

Open your mainactivity class and edit to the source code below. The second parameter “InterfaceName” in the addJavascriptInterface should be same as the html file else you will get error.

Run you Project

In conclusion, the webview is successfully bind with the javascript and now you can perform some action in your android project so you can see the effect.

(Android WebView bind Javascript)

Source Code

(Visited 771 times, 1 visits today)
Advertisements

Yong Loon Ng

Ng Yong Loon, better known as Kristofer is a software engineer and computer scientist who doubles up as an entrepreneur.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *