Undefined when Calling the javascript function - javascript

I'm able to pass data from my android to javascript. But the problem is when I call the function setValue() it become Undefined but when its on load it pass the right value. Here is my Codes below.
Here is my Java Class Codes
public class PaymentActivity extends Activity {
String amount1;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.payment);
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
amount1 = extras.getString("amount1");
}
WebView web = (WebView) findViewById(R.id.web1);
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl("javascript:window.onload = function(){setValue(\""+ amount1 +"\");};");
web.loadUrl("file:///android_asset/www/index.html");
}
}
and here is my Web Page Codes
<!DOCTYPE html>
<html>
<head>
</head>
<body>
Whats your Name?
<input id="name" value="" />
<input id="pass" value="" />
<button onclick = "setValue()">Submit</button>
<script type="text/javascript">
function setValue(amount1){
myValue = amount1;
document.getElementById("pass").value = myValue;
}
</script>
</body>
</html>

You can not call a java script function directly from activity on load. You need to use handler and thread and a hidden button
public class AskUsActivity extends Activity{
private Button scriptButton;
private WebView webView;
private Handler handler;;
MyJavaScriptInterface myJavaScriptInterface;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ask_us);
webView = (WebView)findViewById(R.id.askUs_webView);
scriptButton=(Button)findViewById(R.id.scriptButton);
loadData();
myJavaScriptInterface = new MyJavaScriptInterface(this);
webView.loadUrl("file:///android_asset/AskUs.htm");
webView.addJavascriptInterface(myJavaScriptInterface, "AndroidFunction");
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient());
handler=new Handler(){
#Override
public void handleMessage(Message msg) {
System.out.println("inside handler");
scriptButton.performClick();
}
};
scriptButton.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
webView.loadUrl("javascript:setcontactInfo('1|*|nikhil|||');");
}
});
// String selectedImagePath="1|*|nikhil|||";
// webView.loadUrl("javascript:setInternational()");
// new Thread(){
// #Override
// public void run() {
// System.out.println("inside thread.................Start.......");
// webView.loadUrl("javascript:setcontactInfo('1|*|nikhil|||');");
// System.out.println("inside thread.................end.......");
// }
// }.start();
}
#Override
protected void onResume() {
super.onResume();
try {
Thread.sleep(400);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(){
public void run() {
System.out.println("inside thread................");
handler.sendEmptyMessage(0);
};
}.start();
}
private void loadData(){
try {
String destPath = "/data/data/" + getPackageName()+ "/databases/kellypipe.sqlite";
File f = new File(destPath);
if(!f.exists()){
Log.v("<<< TAG >>>","File Not Exist");
InputStream in = getAssets().open("kellypipe.sqlite");
OutputStream out = new FileOutputStream(destPath);
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
Log.v("<<< TAG >>>","ioexeption");
e.printStackTrace();
}
DBManager dbManager = new DBManager(this);
Log.v("<<< TAG >>>","Database is there with version: "+dbManager.getReadableDatabase().getVersion());
// String sql = "select * from CasingMetric";
String sql= "SELECT ID,listname,name,address,contact,email from contactInfo order by ID";
SQLiteDatabase db = dbManager.getReadableDatabase();
Cursor cursor = db.rawQuery(sql, null);
Log.v("<<< TAG >>>","Query Result:"+cursor);
cursor.moveToFirst();
int i=cursor.getColumnIndex("listname");
int j=cursor.getColumnIndex("name");
int x=0;
while(!cursor.isAfterLast()){
x++;
System.out.println("Listname : "+cursor.getString(i)+ " Name: "+cursor.getString(j)+" :: X is : "+x);
cursor.moveToNext();
}
cursor.close();
db.close();
dbManager.close();
}
public class MyJavaScriptInterface {
Context mContext;
MyJavaScriptInterface(Context c) {
mContext = c;
}
public void showToast(String toast){
//Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
webView.loadUrl("javascript:callFromActivity()");
}
public void openAndroidDialog(){
AlertDialog.Builder myDialog = new AlertDialog.Builder(AskUsActivity.this);
myDialog.setTitle("DANGER!");
myDialog.setMessage("You can do what you want!");
myDialog.setPositiveButton("ON", null);
myDialog.show();
}
}
}

Related

Android webView - javascript code is not getting called

I try to load this javascript in my webview:
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen);
website = "https://www.blizz-z.de";
myWebView = findViewById(R.id.blizzView);
WebSettings settings = blizzView.getSettings();
settings.setJavaScriptEnabled(true);
myWebView.setWebViewClient(new WebViewClient() {
#Override
// Notify the host application that a page has finished loading.
public void onPageFinished(WebView view, String url)
{
myWebView.loadUrl(
"javascript:(function() {" +
"setInterval(function() {" +
+ "jQuery('#myInput').css('background', '#'+(Math.random()*0xFFFFFF<<0).toString(16));"
+ "}, 1000);"
+ "});"
);
}
}
...
}
But it is not getting executed. If I execute the script in my desktop browser, then it works. It changes the background color of my search bar on my website just for test purposes.
Is setInterval not supported in webView?
Update:
I tried it with the function js from #mohkamfer's answer:
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen);
website = "https://www.blizz-z.de";
blizzView = findViewById(R.id.blizzView);
WebSettings settings = blizzView.getSettings();
settings.setJavaScriptEnabled(true);
myWebView.setWebViewClient(new WebViewClient() {
#Override
// Notify the host application that a page has finished loading.
public void onPageFinished(WebView view, String url)
{
js(myWebView, "(function() {" +
"setInterval(function() {" +
+ "jQuery('#myInput').css('background', '#'+(Math.random()*0xFFFFFF<<0).toString(16));"
+ "}, 1000);"
+ "});"
);
}
}
...
}
public void js(WebView view, String code)
{
String javascriptCode = "javascript:" + code;
if (Build.VERSION.SDK_INT >= 19) {
view.evaluateJavascript(javascriptCode, new ValueCallback<String>() {
#Override
public void onReceiveValue(String response) {
Log.i("debug_log", response);
}
});
} else {
view.loadUrl(javascriptCode);
}
}
But it makes no difference.
Are you deploying on API 19 or higher? If so you'll have to use WebView#evalulateJavascript instead of WebView#loadUrl
I always use this method to simplify and quicken things a bit
public void js(String code) {
if (Build.VERSION.SDK_INT >= 19) {
this.evaluateJavascript(code, new ValueCallback<String>() {
#Override
public void onReceiveValue(String response) {
}
});
} else {
this.loadUrl("javascript:" + code);
}
}
I figured it out... I just had to call the code with jQuery(document).ready(function() {. The code was executed but did not changed anything because it was executed before the DOM was ready...
Solution:
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen);
website = "https://www.blizz-z.de";
myWebView = findViewById(R.id.blizzView);
WebSettings settings = blizzView.getSettings();
settings.setJavaScriptEnabled(true);
myWebView.setWebViewClient(new WebViewClient() {
#Override
// Notify the host application that a page has finished loading.
public void onPageFinished(WebView view, String url)
{
js(myWebView, "jQuery(document).ready(function() {" +
"setInterval(function() {" +
+ "jQuery('#myInput').css('background', '#'+(Math.random()*0xFFFFFF<<0).toString(16));"
+ "}, 1000);"
+ "});"
);
}
}
...
}
public void js(WebView view, String code)
{
String javascriptCode = "javascript:" + code;
if (Build.VERSION.SDK_INT >= 19) {
view.evaluateJavascript(javascriptCode, new ValueCallback<String>() {
#Override
public void onReceiveValue(String response) {
Log.i("debug_log", response);
}
});
} else {
view.loadUrl(javascriptCode);
}
}
Credits to #mohkamfer for contributing the js function.

Fill in a form OK, but validation does not take the fields content

On the following page :
https://teleservices.ac-nancy-metz.fr/login/ct_logon_vk.jsp
And with the following lines, the login field and password field are filled in, but when I validate, manually or programmtically, the fields seemed not to be filled in
webView = (WebView) findViewById(R.id.travail_activity_webview);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setDomStorageEnabled(true);
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String urlNewString) {
if (!loadingFinished) {
redirect = true;
}
loadingFinished = false;
view.loadUrl(urlNewString);
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
loadingFinished = false;
}
#Override
public void onPageFinished(WebView view, String url) {
Log.e("Page finished", "url : " +url);
if(!redirect){
loadingFinished = true;
}
if(loadingFinished && !redirect){
if (!connected) {
completionIdentifiants();
connected=true;
} else if (!portailled){
accesPortail();
portailled=true;
}
} else{
redirect = false;
}
}
});
private void accesPortail() {
webView.loadUrl("https://teleservices.ac-nancy-metz.fr/login/ct_logon_vk.jsp");
}
public void completionIdentifiants() {
webView.loadUrl("javascript:var x = document.getElementById('user').value = 'mylogin';");
webView.loadUrl("javascript:var y = document.getElementById('password').value = 'mypass';");
webView.loadUrl("javascript:var z = window.document.getElementById('myform').submit();");
webView.loadUrl("javascript:alert('Test')");
}
The field are visually filled in, but the value is not taken after submitting.
Their content is just erased...
I tried a lot of combinations, without success.
It is about your shouldOverrideUrlLoading method, please take a look at this Android documenation: link and search for shouldOverrideUrlLoading section, you need to return false in this method.

How to pass Android post request response to javascript function?

I created a webview on android studio and want to place the android post request response inside textarea on webiview . The post request is working correctly and i receive data from server but my Javascript function inside webview never get called to populate the textarea. Could an expert look at my code and show me how to fix it.Thanks in advance.
public class MainActivity extends AppCompatActivity {
private WebView mWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView= (WebView) findViewById(R.id.activity_main_webview);
mWebView.loadUrl("file:///android_asset/index.html");
mWebView.getSettings().setJavaScriptEnabled(true);
// Force links to open in the WebViewinstead of in a browser
mWebView.setWebViewClient(new WebViewClient());
}
#Override
protected void onResume()
{
super.onResume();
new PostClass().execute();
}
private class PostClass extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
final TextView outputView = (TextView) findViewById(R.id.postOutput);
try {
StrictMode.setThreadPolicy(new Builder().permitAll().build());
HttpURLConnection myURLConnection = (HttpURLConnection) new URL("http://myownapi.com/api").openConnection();
myURLConnection.setReadTimeout(60000);
myURLConnection.setConnectTimeout(60000);
myURLConnection.setRequestMethod("POST");
myURLConnection.setUseCaches(false);
myURLConnection.setDoInput(true);
myURLConnection.setDoOutput(true);
myURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
myURLConnection.setRequestProperty("Content-Language", "en-US");
myURLConnection.setRequestProperty("API_KEY", "12345_ABC_MNO_12345678_123ABC");
myURLConnection.setRequestProperty("Connection", "Keep-Alive");
myURLConnection.addRequestProperty("Content-length", "");
OutputStream os = myURLConnection.getOutputStream();
os.close();
myURLConnection.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(myURLConnection.getInputStream()));
StringBuffer sb = new StringBuffer();
System.out.println(sb);
String line;
while ((line = in.readLine()) != null) {
sb.append(line);
}
in.close();
outputView.setText(sb.toString());
//outputView.setText("finished");
mWebView.loadUrl("javascript:MyFunction(" + sb.toString() + ")");
//mWebView.loadUrl("javascript:MyFunction()");
} catch (Exception e) {
}
return null;
}
}
}
html code inside webview:
<html>
<head>
<script>
function MyFunction(myVar)
{
//var myVar = 'test data';
var myTextArea = document.getElementById('myArea');
myTextArea.innerHTML += myVar;
};
</script>
</head>
<body>
<br>
<br>
<textarea id="myArea" rows="30" cols="40"></textarea>
</body>
Hello there you are missing quotes in
mWebView.loadUrl("javascript:MyFunction(" + sb.toString() + ")");
Right now you what you call is this
MyFunction(string)
instead this should be
MyFunction('string')
So instead of passing a string you are trying to pass the variable like an object.
mWebView.loadUrl("javascript:MyFunction('" + sb.toString() + "')");

Unable to run show image preview on android webview?

Firstly this may sound like a duplicate question but i was unable to get any solutions via previous posted questions.I have a jsp page through which i am selecting images from PC and showing preview of that image which is working fine on chrome browser of my android phone also.But when i run it on WEBVIEW document.getElementById.click() function not working so i am unable to get image preview.
This is my JSP page:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
<script>
function img_prvw(id1,id2)/*******************show preview of image*******************/
{
var oFiles = document.getElementById(id1).files;
var valid_extensions = /(.jpg|.jpeg|.png)$/i;
if(!(valid_extensions.test(document.getElementById(id1).files[0].name)))
{
document.getElementById('er').innerHTML="Select jpg or png image";
}
else
{
var reader = new FileReader();
reader.readAsDataURL(oFiles[0]);
reader.onload=
function (e) {
document.getElementById(id2).src=e.target.result;
};
}
}
</script>
</head>
<body>
<input type="file" style="display: none;" id="advrts_img" name="advrts_img" onchange="img_prvw('advrts_img','advrts_img_prvw')">
<img src="images/img_place.png" id="advrts_img_prvw" alt="" class="cursor margin_top10" style="width:100px;height:100px" onClick="document.getElementById('advrts_img').click()">
</body>
</html>
This is my android WebView code:
package com.example.sample_webview;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
WebView web;
private ValueCallback<Uri> mUploadMessage;
private final static int FILECHOOSER_RESULTCODE = 1;
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == mUploadMessage)
return;
Uri result = intent == null || resultCode != RESULT_OK ? null
: intent.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
web = (WebView) findViewById(R.id.wView);
web = new WebView(this);
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl("http://minkme.org/minkmeuser/image_preview1.jsp");
web.setWebViewClient(new myWebClient());
web.setWebChromeClient(new WebChromeClient() {
// The undocumented magic method override
// Eclipse will swear at you if you try to put #Override here
// For Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
MainActivity.this.startActivityForResult(
Intent.createChooser(i, "File Chooser"),
FILECHOOSER_RESULTCODE);
}
// For Android 3.0+
public void openFileChooser(ValueCallback uploadMsg,
String acceptType) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
MainActivity.this.startActivityForResult(
Intent.createChooser(i, "File Browser"),
FILECHOOSER_RESULTCODE);
}
// For Android 4.1
public void openFileChooser(ValueCallback<Uri> uploadMsg,
String acceptType, String capture) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
MainActivity.this.startActivityForResult(
Intent.createChooser(i, "File Chooser"),
MainActivity.FILECHOOSER_RESULTCODE);
}
});
setContentView(web);
}
public class myWebClient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
}
}
// flipscreen not loading again
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
// To handle "Back" key press event for WebView to go back to previous
// screen.
/*
* #Override public boolean onKeyDown(int keyCode, KeyEvent event) { if
* ((keyCode == KeyEvent.KEYCODE_BACK) && web.canGoBack()) { web.goBack();
* return true; } return super.onKeyDown(keyCode, event); }
*/
}
I just want to browse images from android phone using input type="file".
in short : look over here to your input file Input file in a webview
After some time and some test, i have found that document.getElementById.click work perfectly well. i have test with the following change
test.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script src="jquery-1.11.1.min.js"> </script>
<script>
function img_prvw(id1,id2)/*******************show preview of image*******************/
{
console.log("Call of img_prvw");
var oFiles = document.getElementById(id1).files;
var valid_extensions = /(.jpg|.jpeg|.png)$/i;
if(!(valid_extensions.test(document.getElementById(id1).files[0].name)))
{
document.getElementById('er').innerHTML="Select jpg or png image";
}
else
{
var reader = new FileReader();
reader.readAsDataURL(oFiles[0]);
reader.onload=
function (e) {
document.getElementById(id2).src=e.target.result;
};
}
}
function onAdvrtsImgPrvwClick() {
console.log('Clickevent');
document.getElementById('advrts_img').click();
}
</script>
</head>
<body>
<input type="file" style="display: none;" id="advrts_img" name="advrts_img" onclick="console.log('click on input');" onchange="img_prvw('advrts_img','advrts_img_prvw')">
<img src="images/img_place.png" id="advrts_img_prvw" alt="" class="cursor margin_top10" style="width:100px;height:100px" onClick="onAdvrtsImgPrvwClick()">
</body>
</html>
MainActivity.java
public class MainActivity extends Activity {
private WebView mWebview;
static final String TAG = "MainActivity";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebview = (WebView) findViewById(R.id.webView1);
mWebview.getSettings().setJavaScriptEnabled(true); // enable javascript
final Activity activity = this;
mWebview.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
Toast.makeText(activity, description, Toast.LENGTH_SHORT)
.show();
}
});
mWebview.setWebChromeClient(new WebChromeClient() {
#Override
public boolean onConsoleMessage(ConsoleMessage cm)
{
String msg = cm.message() + " -- From line " + cm.lineNumber() + " of " + cm.sourceId();
switch (cm.messageLevel()) {
case ERROR:
Log.e(TAG, msg);
break;
case LOG:
case TIP:
Log.i(TAG, msg);
break;
case WARNING:
Log.w(TAG, msg);
break;
case DEBUG:
default:
Log.d(TAG, msg);
break;
}
return true;
}
});
mWebview.loadUrl("file:///android_asset/test.html");
//setContentView(mWebview);
}
}
And it's appear that the console show the message 'click on input', so it have been correctly call, but it's the on change that is not called properly.

calling a javascript function from android

I'm trying to call a javascript function from java android code. i tried to look at all previous questions concerning this but nothing seems to be working. are there any suggestions? thanks!
javascript code:
<html>
<head>
<script language="javascript">
function doSomething() {
alert('hey!!!!!!!');
}
</script>
</head>
<body>
ilana
</body>
</html>
java code (from an activity on create)
final WebView webview=(WebView)findViewById(R.id.myWebView);
webview.getSettings().setJavaScriptEnabled(true);
webview.addJavascriptInterface(new JavaScriptInterface(this), "Android");
webview.loadUrl("file:///android_asset/www/index.html");
webview.setWebChromeClient(new WebChromeClient());
webview.loadUrl("javascript:doSomething()");
my updated (but still not working) code is:
javascript:
<html>
<head>
<script type="text/javascript">
function doSomething(){
alert("hello");
}
</script>
</head>
<body>
hello hello hello!
</body>
</html>
java:
final WebView webview=(WebView)findViewById(R.id.myWebView);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("file:///android_asset/www/index.html");
webview.setWebChromeClient(new WebChromeClient());
webview.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
view.loadUrl("javascript:doSomething()");
}
});
I think you have to wait the end of loading page
try that
webview.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
view.loadUrl("javascript:doSomething()");
}
});
where is Main.this change for your activity this
webview.setWebChromeClient(new WebChromeClient(){
#Override
public boolean onJsAlert(WebView view, String url, String message, final JsResult result){
new AlertDialog.Builder(Main.this)
.setTitle("Alert")
.setMessage(message)
.setPositiveButton("OK",
new AlertDialog.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
result.confirm();
}
})
.setCancelable(false)
.create()
.show();
return true;
}
});
# comments #
my onCreate
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webview = (WebView)findViewById(R.id.webView1);
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
Log.d("", "!!!! here 1 !!!!");
view.loadUrl("javascript:doSomething()");
}
});
webview.setWebChromeClient(new WebChromeClient(){
#Override
public boolean onJsAlert(WebView view, String url, String message, final JsResult result){
Log.d("", "!!!! here 2 !!!!");
new AlertDialog.Builder(Main.this)
.setTitle("Alert")
.setMessage(message)
.setPositiveButton("OK",
new AlertDialog.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
result.confirm();
}
})
.setCancelable(false)
.create()
.show();
return true;
}
});
webview.loadUrl("file:///android_asset/index.html");
You have used language="javascript", the correct attribute is type="text/javascript"

Categories