Injecting javaScript into webview

Posted on by By Nikhilesh, in Java, Javascript | 0

Injecting javaScript into webview

We all know webview is used to show html content within your application.Some time we need to inject javascript into webview through native functionality of android. In this tutorial I am enabling a javascript function using android button.You Can Download Code from below.

Follow these steps.

  1. Create a new android project.
  2. I have added a webview , edittext and button in layout file of that activity. Webview is used to display
    that html file , edittext is used to get some input from user and button is used to submit text to webview.
  3. I am using loadData to put html content into webview. When you click on the button It will generate one string which
    contain javascript code then you just need to call loadUrl method with that string which you can show in the below code.


public class MainActivity extends ActionBarActivity {
EditText editText;
WebView webView; 
   protected void onCreate(Bundle savedInstanceState) {
	webView = (WebView) findViewById(;
	webView.setWebChromeClient(new WebChromeClient());
	webView.setWebViewClient(new WebViewClient());
        // Load Html Data having one function to get current date 
	webView.loadData("" +
		"" +
		"" + //this is function for getting current date 
		"function displayDate() {" +
		"var d = new Date();" +
		"document.getElementById('demo').innerHTML = 'Date: ' + d.getDate() + '-' + d.getMonth() + '-' + d.getFullYear();" +
		"}" +
		"" +
		"" +
		"" +

Hello, I am

” + ”

” + “” + “”,”text/html”,”UTF-8″); Button button = (Button) findViewById(; // user can enter here some text editText = (EditText) findViewById(; // button is used to inject javascript into webview and call an existing javascript funtion i.e. dispalyData() button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String name = editText.getText().toString(); String javascript= “javascript: document.getElementById(‘name’).innerHTML = ‘”+name+”‘; displayDate();”; webView.loadUrl(javascript); } }); } }

Here is screenshot


Best Open Source Business Intelligence Software Helical Insight is Here


A Business Intelligence Framework

0 0 votes
Article Rating
Notify of
Inline Feedbacks
View all comments