Pass JavaScript Value from Webview to Activity?Android - javascript

I followed this to Print in android (Thermal Printer)
This is My web-view Over there On-click It will Load My Android Activity Which is Out of Web-view...
For that I have Given this... to Open new activity from web-view..
public class Main_web extends AppCompatActivity {
private WebView webView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_m);
webView = (WebView) findViewById(R.id.webm);
WebSettings set = webView.getSettings();
set.setJavaScriptEnabled(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
final ProgressDialog progressBar = ProgressDialog.show(Main_web.this, "Please Wait", "Loading...");
webView.addJavascriptInterface(new WebAppInterface(this), "NewFUN");
webView.requestFocusFromTouch();
webView.setWebViewClient(new WebViewClient()
{
public void onPageFinished(WebView view, String url) {
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
});
webView.setWebChromeClient(new WebChromeClient());
String url = "www.google.com/m_app_eta.php";
//String url = "file:///android_asset/tex.html";
try {
if (URLUtil.isValidUrl(url)) {
webView.loadUrl(url);
} else {
//do something
}
} catch (Exception e) {
//do something
}
}
//Class to be injected in Web page
public class WebAppInterface {
Context mContext;
WebAppInterface(Context c) {
mContext = c;
}
#JavascriptInterface
public void Print() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("Alert");
alertDialog.setMessage("Are you sure you want to leave to next screen?");
alertDialog.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent chnIntent = new Intent(Main_web.this, Print_activity.class);
startActivity(chnIntent);
}
});
alertDialog.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
}
}
Now My printer Activity is working Fine So here I want to pass a Value On click Button Which Opens Printer... But can Any one suggest me How to Receive same value in android Activity not in web-view...
All I need is In my web-view when I click on the Button its loading Android Activity Along with that I want to Pass A string value to new Activity
Why Should I pass Value means In that I have a Url so I can Print with that URL
Here JS value is different form current URL
Update
I followed this But its Inside the Web-view I want same at Outside the web-view...
Means When I click on the web-view Its opening android activity with the same its should pass a value to my activity not the web-view
Update 1
I followed #Sujal Mandal answer But I dont Know How to use that Value In next activity Can any one suggest me... on this kind... in next activity It may in System.out.println or text-view or any other string So I can use can Any one suggest How to Use the JavaScript Value in other activity outside the web-view..

HTML JS CODE
<script type="text/javascript">
function Pa(value) {
//value is the param received from onClick
NewFUN.Print(value); //call the android method with value param
}
</script>
<center>
<h3>Sample HTML</h3>
<div id="content">Click on Button To thermal print</div>
<div>
<input type="button" onClick="Pa('26997')" /><br/>
</div>
</center>
& change your android code to be like this
#JavascriptInterface
public void Print(final String stringFromWebView) {
//use stringFromWebView
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("Alert");
alertDialog.setMessage("Are you sure you want to leave to next screen?");
alertDialog.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent chnIntent = new Intent(Main_web.this, Print_activity.class);
chnIntent.putExtra("STRING_DATA", stringFromWebView);
startActivity(chnIntent);
}
});
alertDialog.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
In next activity receive the web JS response by using
String data = getIntent().getStringExtra("STRING_DATA");
at oncreate

Related

How to set up fix url in android javascript?

i have an android app which takes URL from users. i want to fix it to one specific URL regardless what user enters. How can i edit code below to set app url as https://www.example.com
public class TakeUrl extends Activity {
EditText urlET;
Button submitBtn;
Locale myLocale;
String langCode = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.take_url_activity);
urlET = findViewById(R.id.et_domain_takeUrl);
submitBtn = findViewById(R.id.btn_submit_takeUrl);
submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String appDomain = urlET.getText().toString();
getDataFromApi(appDomain);
Utility.setSharedPreference(getApplicationContext(), Constants.appDomain, appDomain);
});
}

Get value from DIV element

I want to pass a HTML element value to an Android application. I
I tried retrieving the value using the code below:
document.getElementById(\"summary\").value --> giving null value
document.getElementById(\"summary\").innerHtml --> giving null value
document.getElementById(\"summary\").textContent --> giving null value
I'm trying to implement javascript MutationObserver. So whenever there is a change in the content, I can immediately pass the value to the android java code.
Can anyone help me?
I used the following code:
myWebView = (WebView)this.findViewById(R.id.myWebView);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.loadUrl("https://helloworld.com/details");
myWebView.addJavascriptInterface(new JavaScriptInterface(this, myWebView), "MyHandler");
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
myWebView.setWebContentsDebuggingEnabled(true);
}
myWebView.evaluateJavascript("(function(){return document.getElementById(\"summary\").textContent})();",
new ValueCallback<String>() {
#Override
public void onReceiveValue(String html) {
Log.e("HTML Content",html);
}
});
This is my HTML code:
<div class="well" id="summary" *ngIf="viewModel != null">
<div class="SuccessSummary">{{viewModel.successSummary}}</div>
</div>
Try this
myWebView.evaluateJavascript("(function(){return
document.getElementById('summary').innerHTML})();",
new ValueCallback<String>() {
#Override
public void onReceiveValue(String html) {
Log.e("HTML Content",html);
}
});

Using Javascript bridge in android

Im just trying to communicate my java app with the content on the webview .
In detail , may be just showing a toast on button click ?
After searching on google and doing some research , ended up with the following code .
P.S : - Im using Android Studio , is there any external library i need to compile inorder to get things done ? or something else ?
Following is my WebviewActivity code:-
public class WebviewActivity extends AppCompatActivity {
private static final String TAG = "Main";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview);
//WebView Object
WebView browser;
browser=(WebView)findViewById(R.id.webView);
//Enable Javascript
browser.getSettings().setJavaScriptEnabled(true);
//Inject WebAppInterface methods into Web page by having Interface 'Android'
browser.addJavascriptInterface(new WebAppInterface(this), "Android");
browser.loadUrl("http://www.somewebsite.com/app/form.html");
}
//Class to be injected in Web page
public class WebAppInterface {
Context mContext;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
/**
* Show Toast Message
* #param toast
*/
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
/**
* Show Dialog
* #param dialogMsg
*/
public void showDialog(String dialogMsg){
AlertDialog alertDialog = new AlertDialog.Builder(mContext).create();
// Setting Dialog Title
alertDialog.setTitle("JS triggered Dialog");
// Setting Dialog Message
alertDialog.setMessage(dialogMsg);
// Setting alert dialog icon
//alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(mContext, "Dialog dismissed!", Toast.LENGTH_SHORT).show();
}
});
// Showing Alert Message
alertDialog.show();
}
/**
* Intent - Move to next screen
*/
public void moveToNextScreen(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("Alert");
// Setting Dialog Message
alertDialog.setMessage("Are you sure you want to leave to next screen?");
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//Move to Next screen
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Cancel Dialog
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
}
}
form.html:-
<html>
<head>
<style>
body{
background-color: #FA5858;
color:#fff;
}
input{
background-color: #F7D358;
width: 300px;
padding:10px;
color: #000;
}
div#content{
padding:20px;
background-color: #F7D358;
color: #000;
}
</style>
<script type="text/javascript">
function showAndroidToast(toastmsg) {
Android.showToast(toastmsg);
}
function showAndroidDialog(dialogmsg) {
Android.showDialog(dialogmsg);
}
function moveToScreenTwo() {
Android.moveToNextScreen();
}
</script>
</head>
<body>
<center>
<h3>Binding JavaScript code to Android code</h3>
<div id="content">
//some content here
</div>
<div>
Here are few examples:
</div>
<div>
<input type="button" value="Make Toast" onClick="showAndroidToast('Toast made by Javascript')" /><br/>
<input type="button" value="Trigger Dialog" onClick="showAndroidDialog('This dialog is triggered by Javascript ')" /><br/>
<input type="button" value="Take me to Next Screen" onClick="moveToScreenTwo()" />
</div>
</center>
</body>
</html>
I have this above code , but it is not working in android-studio , tried all posiblities so finally posted my question here .
My study for this :-
https://developer.android.com/guide/webapps/webview.html
https://developer.android.com/reference/android/webkit/WebView.html
http://stackoverflow.com/questions/4325639/android-calling-javascript-functions-in-webview
Your methods inside WebAppInterface class are missing the #JavascriptInterface annotation.
Your WebAppInterface class should be like this,
public class WebAppInterface {
Context mContext;
WebAppInterface(Context c) {
mContext = c;
}
#JavascriptInterface
public void showToast(String toast) {
}
#JavascriptInterface
public void showDialog(String dialogMsg){
}
#JavascriptInterface
public void moveToNextScreen(){
}
}
Edit
Don't forget to limit your app to API17+ when loading web content into the WebView, otherwise your App will be vulnerable to attacks. Read #Robert's comment below.
Thanks , this helped me. I made a working example:
here the zip for download:
http://www.mediafire.com/file/xyirbqdf73op7zs/file
https://www.b4x.com/android/forum/threads/webviewextras-send-data-from-webview-to-b4x-from-b4x-to-webview-addjavascriptinterface-callsub.121471/

For JavaFX's WebEngine, how do I get notified of javascript errors?

I'm trying to run some SVG that contains Javascript in JavaFX's WebView. I know some of the scripts I'm trying to run have errors and am trying to figure out how to print them to the console so I can debug them. I've tried the following, but the WebErrorEvent is never called:
WebEngine webEngine = browser.getEngine();
webEngine.setOnError(new EventHandler<WebErrorEvent>()
{
#Override
public void handle(WebErrorEvent event)
{
System.err.println(event);
}
});
Is this the right way to get javascript error feedback from this control?
setOnError listener only works for error while loading a given document.
One way to solve this is to call a Java method when console.log is called. You can do this by.
Your FX application
WebEngine engine = mainWebView.getEngine();
engine.load("http://whereever.com");
engine.getLoadWorker().stateProperty().addListener(new ChangeListener<Worker.State>() {
#Override
public void changed(ObservableValue<? extends Worker.State> observable, Worker.State oldValue, Worker.State newValue) {
JSObject window = (JSObject) engine.executeScript("window");
window.setMember("java", new Bridge());
engine.executeScript("console.log = function(message) { java.log(message); }"); // Now where ever console.log is called in your html you will get a log in Java console
}
});
Your Bridge class
public class Bridge {
public void exit() {
Platform.exit();
}
public void log(String text) {
System.out.println(text);
}
}
Your html
<h1>Text Page</h1>
<button onclick="java.log('This is log')">Log</button>
<button onclick="console.log('This produces the same result as above')">Console.log</button>
<button onclick="java.exit()">Exit</button>
Hope this is of some help.

Android WebView - Javascript doesn't fire the call back function

I am new to Android and was trying to setup the Android Webview to load a javascript function and return the result to a callback function.
See the code below
public class AWebViewActivity extends Activity {
/**
* Defines an Interface to call Syntax Highlighting Javascript and return the result
* to a string by calling the call back function.
*/
public class JavaScriptInterface {
Context mContext;
JavaScriptInterface(Context c) {
mContext = c;
}
//add other interface methods to be called from JavaScript
// This annotation is required in Jelly Bean and later:
#JavascriptInterface
public void receiveValueFromJs(String str) {
//do something useful with str
Toast.makeText(mContext, "Received Value from JS: " + str,Toast.LENGTH_LONG).show();
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Try WebView
WebView webView = (WebView) findViewById(R.id.editor_view);
//webView.setWebChromeClient(new WebChromeClient());
webView.getSettings().setJavaScriptEnabled(true);
// RiNxX's suggestion
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url){
view.loadUrl("javascript:getValue()");
}
});
webView.addJavascriptInterface(new JavaScriptInterface(this), "MyAndroid");
webView.loadUrl("file:///mnt/sdcard/a.html");
//SystemClock.sleep(1000);
//webView.loadUrl("javascript:getValue()");
}
}
The HTML file is given below:
<html>
<head>
</head>
<body>
<script type="text/javascript">
function getValue()
{
var val="Amith Raravi";
MyAndroid.receiveValueFromJs(val);
}
</script>
Hey ya
</body>
</html>
I have also added the INTERNET permission as a child of the Manifest element. I went through the other questions posted on StackOverflow and moved the script to Body of the HTML.
After i added the changes suggested by RiNxX, the app closes(it doesnt execute the callback) and i get the below warning in LogCat
JNI WARNING: jarray 0x405414e8 points to non-array object (Ljava/lang/String;)
I/dalvikvm(361): "WebViewCoreThread" prio=5 tid=9 NATIVE
I/dalvikvm(361): | group="main" sCount=0 dsCount=0 obj=0x4051d580 self=0x29a1a8
I/dalvikvm(361): | sysTid=370 nice=0 sched=0/0 cgrp=default handle=2728672
I/dalvikvm(361): | schedstat=( 277421205 460097188 88 )
I/dalvikvm(361): at android.webkit.BrowserFrame.stringByEvaluatingJavaScriptFromString(Native Method)
I/dalvikvm(361): at android.webkit.BrowserFrame.stringByEvaluatingJavaScriptFromString(Native Method)
I/dalvikvm(361): at android.webkit.BrowserFrame.loadUrl(BrowserFrame.java:246)
I/dalvikvm(361): at android.webkit.WebViewCore.loadUrl(WebViewCore.java:1570)
I/dalvikvm(361): at android.webkit.WebViewCore.access$1400(WebViewCore.java:53)
I/dalvikvm(361): at android.webkit.WebViewCore$EventHub$1.handleMessage(WebViewCore.java:956)
I/dalvikvm(361): at android.os.Handler.dispatchMessage(Handler.java:99)
I/dalvikvm(361): at android.os.Looper.loop(Looper.java:123)
I/dalvikvm(361): at android.webkit.WebViewCore$WebCoreThread.run(WebViewCore.java:629)
I/dalvikvm(361): at java.lang.Thread.run(Thread.java:1019)
E/dalvikvm(361): VM aborting
I have been at it for over a day now. Any help would be most welcome:)
Apparently, this has been a long standing bug in the 2.3.3 emulator.
See the below link.
http://groups.google.com/group/android-developers/browse_thread/thread/992ca132e15745ec/da8da866d107e8b3?pli=1
Currently downloading 2.2 and 3.0 emulators.
Thank You for all the help, and the great forum.
I will be back with more questions!
I'm having same issue, but worked fine when I try to load the file from assets:
webView.loadUrl("file:///android_asset/a.html");
Add webview client that calls javascript interface when page is loaded
webview.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
view.loadUrl("javascript:getValue()");
}
webview.loadUrl(SOME_WEBPAGE);
java script Called from android webview
webView.loadUrl("javascript:setDatePickervalue(\""
+ pselSelectedDateProp.getFormatedDate() + "\")");
Java Script Function
<script type="text/javascript" language="JavaScript">
function setDatePickervalue(selecteddate){
document.getElementById("text").innerHTML = selecteddate.toString();
//alert('hello' + selecteddate.toString());
}
</script>
....
i was trying to implement same thing like u did...
its giving me vm aborting exception in emulator...BUT ITS WORKING FINE ON DEVICE..

Categories