Using JavaScript in Android Webview

using javascript in android webview

You have to first register the JavaScriptInterface on your webview.
JavaScriptInterFace can be a inner class as shown below. This class will have a function that you can call from html page( via javaScript ) and inside this function you can write code to change activity.

Here is the working solution for you:

public class JavascriptInterfaceActivity extends Activity {
/** Called when the activity is first created. */

WebView wv;

JavaScriptInterface JSInterface;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
wv = (WebView)findViewById(R.id.webView1);

wv.getSettings().setJavaScriptEnabled(true);
// register class containing methods to be exposed to JavaScript

JSInterface = new JavaScriptInterface(this);
wv.addJavascriptInterface(JSInterface, "JSInterface");

wv.loadUrl("file:///android_asset/myPage.html");

}

public class JavaScriptInterface {
Context mContext;

/** Instantiate the interface and set the context */
JavaScriptInterface(Context c) {
mContext = c;
}

@android.webkit.JavascriptInterface
public void changeActivity()
{
Intent i = new Intent(JavascriptInterfaceActivity.this, nextActivity.class);
startActivity(i);
finish();
}
}
}

Here is the html page

<html>
<head>
<script type="text/javascript">
function displaymessage()
{
JSInterface.changeActivity();
}
</script>
</head>

<body>
<form>
<input type="button" value="Click me!" onclick="displaymessage()" />
</form>
</body>
</html>

Hope this helps...

Run JavaScript in Android webview

Well I replaced:

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
webview.evaluateJavascript(javascript, null);
} else {
webview.loadUrl("javascript:(function(){" + javascript + "})()");
}

with

webview.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView webview, String url) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
webview.evaluateJavascript(javascript, null);
} else {
webview.loadUrl("javascript:(function(){" + javascript + "})()");
}
}
});

and it just WORKS!

How to load a Javascript in WebView

You can do it like this :

private static class WC extends WebViewClient {
Handler handler1 = null;
WebView webView = null;
byte[] b = null;

public WC(Handler handler, WebView webView) {
this.handler1 = handler;
this.webView = webView;
}

@Override
public void onPageFinished(final WebView view, String url) {
super.onPageFinished(view, url);
new Thread(new Runnable() {
@Override
public void run() {
try {
injectScriptFromNetWork("http://192.168.216.254:4000/test.js");
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();

}

private void injectScriptFromNetWork(String urlStr) throws IOException {

URL url = new URL(urlStr);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
int code = urlConnection.getResponseCode();
if (code == 200) {
InputStream inputStream = urlConnection.getInputStream();
b = new byte[inputStream.available()];
inputStream.read(b);
}

handler1.post(new Runnable() {
@Override
public void run() {
String jsSource = Base64.encodeToString(b, Base64.NO_WRAP);
webView.loadUrl("javascript:(function() {" +
"var parent = document.getElementsByTagName('head').item(0);" +
"var script = document.createElement('script');" +
"script.type = 'text/javascript';" +
"script.innerHTML = window.atob('" + jsSource + "');" +
"parent.appendChild(script)" +
"})()");
}
});
}
}

MainActivity.java code like this:

handler = new Handler(getMainLooper());
webView.setWebViewClient(new WC(handler, webView));
webView.loadUrl("file:///android_asset/index.html");

Forgave me, this is my first time answering questions on stackoverflow.

JavaScript in WebView - Android Studio

allow javascript in your webview:

myWebView.getSettings().setJavaScriptEnabled(true);

Run javascript code in Webview

From kitkat onwards use evaluateJavascript method instead loadUrl to call the javascript functions like below

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
webView.evaluateJavascript("var FunctionOne = function () {"
+ " try{document.getElementsByClassName('test')[0].style.color='red';}catch(e){}"
+ "};", null);
} else {
webView.loadUrl("javascript:"
+ "var FunctionOne = function () {"
+ " try{document.getElementsByClassName('test')[0].style.color='red';}catch(e){}"
+ "};");
}

Enable Javascript for your webview by adding the following line

wb.getSettings().setJavaScriptEnabled(true);

Android - How to use Javascript in an Android WebView?

Based on the Binding JavaScript documentation

Note: The object that is bound to your JavaScript runs in another thread and not in the thread in which it was constructed.

You are starting the activity on non-UI thread. You should run it on UI thread as follows:

@android.webkit.JavascriptInterface
public void changeActivity(){
runOnUiThread(new Runnable() {
@Override
public void run() {
Intent i = new Intent(MainActivity.this, JavascriptInterfaceActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
});

}

Alternatively you can also use Handler.



Related Topics



Leave a reply



Submit