How to call JavaScript in Android 4.2 - javascript

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

Related

Webview cannot load javascript at onPageFinished

I want my webview insert sort of javascript after a page has been loaded. However, the javascript I added has never been executed:( what can I do on this?
mWebView = findViewById(R.id.webview);
mWebView.getSettings().setDomStorageEnabled(true);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished (WebView view, String url) {
super.onPageFinished(view, url);
Log.d("WebClient", "onPageFinished");
view.loadUrl("javascript:(function(){"+
"aTagElements=document.getElementsByTagName('a');" +
"randromElement=aTagElements[Math.floor(Math.random() * aTagElements.length)];"+
"clickEvent=document.createEvent('HTMLEvents');"+
"clickEvent.initEvent('click',true,true);"+
"randromElement.dispatchEvent(clickEvent);" +
"alert('event dispatched.');"+ //<---not called
"})()");
}
});
Even if I comment out all the scripts except the alert line, still nothing happens.
You will have to use like this on application side
mWebView .addJavascriptInterface(new WebAppInterface(this), "Android");
and will have to implement method on php side where actually this method will be trigger
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 showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
on PHP Side implement like this
<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />
<script type="text/javascript">
function showAndroidToast(toast) {
Android.showToast(toast);
}
</script>
For a complete reference, you can go through on this link
Whenever you will click the button on webView then you will get a message
Try using evaluvateJavascript, loadUrl will work only in old version.
webview.evaluateJavascript("(function() { "javascript:(function(){"+
"aTagElements=document.getElementsByTagName('a');" +
"randromElement=aTagElements[Math.floor(Math.random() * aTagElements.length)];"+
"clickEvent=document.createEvent('HTMLEvents');"+
"clickEvent.initEvent('click',true,true);"+
"randromElement.dispatchEvent(clickEvent);" +
"alert('event dispatched.');";
EvaluvateJavascript
You are mixing views. So change
super.onPageFinished(view, url);
To
super.onPageFinished(mWebView, url);
Try the below solution may it works for you.
WebSettings webSettings = webView.getSettings();
webSettings.setDefaultTextEncodingName("utf-8");
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setLoadWithOverviewMode(true);

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 ?

Android call Javascript from Java not working

I've read many posts but I can't get my Android app call a Javascript function. This is what I have
public class BorrameActivity extends AppCompatActivity {
private static BorrameActivity.MyJavaScriptInterface myJavaScriptInterface;
private static WebView webView;
public class MyJavaScriptInterface {
Context mContext;
MyJavaScriptInterface(Context c) {
mContext = c;
}
#android.webkit.JavascriptInterface
public void doEchoTest(String echo){
Log.e("printer", echo);
Toast toast = Toast.makeText(mContext, echo, Toast.LENGTH_SHORT);
toast.show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_borrame);
myJavaScriptInterface = new BorrameActivity.MyJavaScriptInterface(this);
webView = (WebView) findViewById(R.id.mybrowserAuthorise);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(myJavaScriptInterface, "JSInterface");
webView.loadUrl("file:///android_asset/loginProtocol.html");
//webView.loadUrl("javascript:JSInterface.doEchoTest('test')"); // THIS WORKS!!
webView.loadUrl("javascript:testEcho()"); // THIS DOES NOT WORK
}
}
This works when I execute
webView.loadUrl("javascript:JSInterface.doEchoTest('test')");
But it doesn't work when the Javascript function is in loginProtocol.html:
webView.loadUrl("javascript:testEcho()");
Where
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width; user-scalable=0;" />
<title></title>
</head>
<body style="visibility:visible">
<!-- Used for debugging -->
<h1>HELLO</h1>
<script>
function testEcho(){
JSInterface.doEchoTest('This does not get printed in Android Log');
}
</script>
</body>
</html>
and
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.sedicii.app.sedicii.BorrameActivity">
<WebView
android:id="#+id/mybrowserAuthorise"
android:layout_width="353dp"
android:layout_height="442dp"/>
</LinearLayout>
The WebView seems to be loading correctly (I can see the HELLO from loginProtocol.html on the Android screen).
What am I missing?
SOLUTION
I have to wait until the HTML page is loaded. Thanks #KosWarm
webView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
webView.loadUrl("javascript:testEcho()");
}
});
I think you just need to give parameter to your loadUrl method:
webView.loadUrl("javascript:testEcho('Hello World!')");
and your javascript function must look like:
function testEcho(testHello){
window.JSInterface.doEchoTest(testHello);
}
You execute the method loadUrl twice
At the second execution, the first page is closed, so its script can not be executed
The following page code works
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width; user-scalable=0;" />
<title></title>
</head>
<body style="visibility:visible">
<!-- Used for debugging -->
<h1>HELLO</h1>
<script>
function testEcho(){
JSInterface.doEchoTest('This does not get printed in Android Log');
}
testEcho() //added this line
</script>
</body>
</html>
Update
from this place Calling Javascript method from within webview in Android
rewrite Activity onCrete method as
myJavaScriptInterface = new MyJavaScriptInterface(this);
webView = (WebView) findViewById(R.id.mybrowserAuthorise);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(myJavaScriptInterface, "JSInterface");
webView.loadUrl("file:///android_asset/loginProtocol.html");
webView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
webView.loadUrl("javascript:testEcho()");
}
});

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>

using javascript in android webview

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.

Categories