using javascript in android webview - javascript

I'm trying to start an activity from a javascript interface in my webview.
The example shows a toast. How could i call a class instead of a toast?
public class JavaScriptInterface {
Context mContext;
/** Instantiate the interface and set the context */
JavaScriptInterface(Context c) {
mContext = c;
}
/** Show a toast from the web page */
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
this for the html page.
<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />
<script type="text/javascript">
function showAndroidToast(toast) {
Android.showToast(toast);
}

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...

You also need to add the #android.webkit.JavascriptInterface annotation on top of your changeActivity method in your android code, should you run on Android 4.2 or higher.
See this link for more.

Related

Android Callback function from Java to Webview Javascript

I am trying to implement a simple callback to call a function from Java to WebView. I successfully called the function from Javascript to Java but couldn't get any success for the otherway around.
Here's my MainActivity.java
public class MainActivity extends AppCompatActivity {
WebView view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
view= new WebView(this);
setContentView(view);
view.loadUrl("file:///android_res/raw/meter.html");
view.getSettings().setJavaScriptEnabled(true);
view.addJavascriptInterface(new WebAppInterface(this), "Android");
}
public class WebAppInterface {
Context mContext;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
/** Show a toast from the web page */
#JavascriptInterface
public void register(String callback) {
Log.e("work","log printing"); // <--- coming here
view.loadUrl("javascript:callbacker('hola moma');");
}
/** Show a toast from the web page */
#JavascriptInterface
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
}
And here's my meter.html file
<script type="text/javascript">
function showAndroidToast(toast) {
Android.register("callbacker");
}
function callbacker(data){
Android.showToast(data);
}
</script>
</head>
<body>
<p>Display a gauge:</p>
<meter value="2" min="0" max="10">2 out of 10</meter><br>
<meter value="0.6">60%</meter>
<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />
<p><strong>Note:</strong> The <meter> tag is not supported in Internet Explorer, Edge 12, Safari 5 and earlier versions.</p>
</body>
Now When I run the application the Log in the register function of MainActivity.java is printed. But the next line is which is just a call to the callback function is not called. What could be the problem ?

JavaScript displays error while calling android native code

I am using following code.
Android Code
myBrowser.getSettings().setJavaScriptEnabled(true);
myBrowser.loadUrl("file:///android_asset/mypage.html");
myBrowser.setWebViewClient(new WebViewClient());
myBrowser.addJavascriptInterface(new MyJavaScriptInterface(MainActivity.this), "MyJavaScriptInterface");
public class MyJavaScriptInterface {
MainActivity mContext;
MyJavaScriptInterface(MainActivity c) {
mContext = c;
}
public void showToast(String toast)throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException{
Log.e("inside","showtoast of myjavascript interface");
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
JavaScript Code
<input type="button" value="Open Dialog" onClick="checkWindow()"/>
<script language="javascript">
function checkWindow(){
console.log("andriod obj"+window.MyJavaScriptInterface);
if(window.MyJavaScriptInterface){
console.log("andriod in methd"+window.MyJavaScriptInterface);
window.MyJavaScriptInterface.showToast('Hii...');
}
}
</script>
When I click on open dialog button, I get error as "Uncaught TypeError: window.MyJavaScriptInterface.showToast is not a function",
Please tell me what am I missing

JavaScript Not Woking inside Cordova Webview

I am trying to open android activity on html button click. This is not happening properly. I was using JavaScript for that.which is not working. My javascript is not getting called.
public class WebViewActivity extends CordovaActivity{
JavaScriptInterface JSInterface;
#SuppressLint("SetJavaScriptEnabled")
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.init();
setContentView(R.layout.webview);
WebView wV = (WebView)appView.getEngine().getView();
wV = (WebView) findViewById(R.id.webView1);
wV.addJavascriptInterface(new JavaScriptInterface(this), "JSInterface");
System.out.println("Opening webview");
wV.loadUrl("file:///android_asset/index.html" ); }
public class JavaScriptInterface {
Context mContext;
/** Instantiate the interface and set the context */
JavaScriptInterface(Context c) {
mContext = c;
}
public void changeActivity()
{
Log.d("In webviewActivity", "Inside change activity");
Intent i = new Intent(WebViewActivity.this, Google.class);
startActivity(i);
Log.d("After Intent", "Opening google class");
finish();
}
}
}
This is my html file from where my javascript calls inner class method
index.html
<!DOCTYPE html>
<html>
<body>
<head>
<script>
function myFunction() {
alert("Hiii");
JSInterface.changeActivity();
}
</script>
</head>
<button onclick="myFunction()">Try it</button>
</body>
</html>

call java function from javascript over android webview target version 15

I have use this code:
JavaScriptInterface jsInterface = new JavaScriptInterface(this);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(jsInterface, "JSInterface");
class
JavaScriptInterface:
public class JavaScriptInterface {
private Activity activity;
public JavaScriptInterface(Activity activiy) {
this.activity = activiy;
}
public void startVideo(String videoAddress){
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(videoAddress), "video/3gpp");
activity.startActivity(intent);
}
}
and js:
<a href='' onclick="window.JSInterface.startVideo('Environment.getExternalStorageDirectory()+File.separator+"Application"+File.separator+test.3gp');" >play
</a>
but i am not able to locate the file.
any one have working code for target version below 15.
please post..
thanks in advance.

How to call JavaScript in Android 4.2

I have already found many examples about how to call JavaScript from android. But it's not working for me. My target SDK is 17(android 4.2). This is how I am loading my html page from my activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
myWebView = (WebView)findViewById(R.id.mapwebview1);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
JavaScriptHandler jScriptHandler = new JavaScriptHandler(this);
WebChromeClient myWebChromeClient = new WebChromeClient();
myWebView.setWebChromeClient(myWebChromeClient);
myWebView.addJavascriptInterface(jScriptHandler, "MyHandler");
myWebView.loadUrl("file:///android_asset/mywebpage.html");
myWebView.loadUrl("javascript:myFunc()");
}
Here is the code for my JavaScriptHandler:
public class JavaScriptHandler {
//TabFragmentMap mapFragment;
Context context;
//Fragment fragment;
public JavaScriptHandler (Context c){
this.context = c;
}
}
Here is the code for my html:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>PhoneGap</title>
</head>
<body onload="myFunc()">
<h1 id="test1">Hello World</h1>
<input type="button" value="Say hello" onClick="moveMyself()" />
<div id="myDiv"></div>
<script type="text/javascript">
function myFunc()
{
document.getElementById('test1').innerHTML = 'Good Morning';
}
</script>
</body>
</html>
Try this:
final WebView webview = (WebView)findViewById(R.id.browser);
/* JavaScript must be enabled if you want it to work, obviously */
webview.getSettings().setJavaScriptEnabled(true);
/* WebViewClient must be set BEFORE calling loadUrl! */
webview.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url)
{
webview.loadUrl("javascript:(function() { " +
"document.getElementsByTagName('body')[0].style.color = 'red'; " +
"})()");
}
});
webview.loadUrl("http://code.google.com/android");
It was actually the same thing that Tamilarasi has given me. If somebody wants to call an existing JavaScript function from the html, do the following:
myWebView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url){
myWebView.loadUrl("javascript:myFunc()");
}
});
myWebView.loadUrl("file:///android_asset/myHtml.html");
Try this links i hope this will be help to u:
http://android-er.blogspot.in/2011/10/call-javascript-inside-webview-from.html
Android 4.2.1, WebView and javascript interface breaks
Javascript interface not working with android 4.2

Categories