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);
}
});
Related
I am trying to toggle showing/hiding a html element from within a C# function.
Things I've tried based on previously answered questions:
calling the html element's id via the code behind
Calling a J-query function from the code behind using Page.ClientScript.RegisterStartupScript.
Same as above but using: ScriptManager.RegisterStartupScript(this.GetType(), this.GetType(), "script", "HideMonthSelector();", true);
C# function:
Namespace NamespaceName.Geotext
{
public class ClassName
{
private void FunctionName(int objectUid, int ddsUid, string month, string year, bool toggle)
{
Default CodeBehind = new Default();
CodeBehind.HideMonthSelector();
}
}
}
Code Behind
Namespace NamespaceName
{
public partial class Default : System.Web.UI.Page
{
public string VersionNumber = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
protected void Page_Load(object sender, EventArgs e)
{
Page.Header.DataBind();
HtmlHead head = Page.Header;
foreach (Control child in head.Controls)
{
if (child is HtmlLink)
{
((HtmlLink)child).Href += "?" + VersionNumber;
}
}
}
public void HideMonthSelector()
{
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "script", "HideMonthSelector();", true);
}
}
}
Default.aspx:
<li runat="server" id="selectMonth" class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown" href="#">
<i class="fa fa-calendar" aria-hidden="true"></i> Select Month
</a>
<ul class="dropdown-menu" id ="navDropCalendar"></ul>
</li>
<script>function HideMonthSelector() { $("#selectMonth").hide();}</script>
<script>function ShowMonthSelector() { $("#selectMonth").show();}</script>
EDIT: based on the comments, it appears that the issue is that I am creating an instance of the default.aspx.cs page and then calling a method in that instance. Apparently this means that the html id element is not initialised and remains null. What other alternative is there?
I am able to run Default.HideMonthSelector() if I change the HideMonthSelector function to a static field, but then the code within that function errors (object reference required for the non-static field)
The problem lies in your javascript code
<script>function HideMonthSelector() { $("#monthSelector").hide();}</script>
<script>function ShowMonthSelector() { $("#monthSelector").show();}</script>
I can't find the any html element with id monthSelector. That's why your code isn't working.
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
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/
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.
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..