Webview javascript code img buton click - javascript

I want to
td id="IOMToolbarActive1_kaydet_b" Auto click
<tr>
<td><img src="../../images/toolimages/seperator.jpg" border="0"></td>
<td id="IOMToolbarActive1_kaydet_b" width="25">
<img src="../../images/toolimages/save.jpg" style="cursor:hand;CURSOR:pointer;" alt="Kaydet" onmouseover="this.src='../../images/toolimages/save_a.jpg'" onmouseout="this.src='../../images/toolimages/save.jpg'" onclick="return AlanKontrolveKayit();" border="0">
</td>
</tr>

If you want auto click the img tag
mWebView = (WebView) findViewById(R.id.web_view);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowUniversalAccessFromFileURLs(true);
mWebView.addJavascriptInterface(new WebAppInterface(this), "Android");
mWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
mWebView.loadUrl( "javascript:window.onload= (function(){ document.getElementById('IOMToolbarActive1_kaydet_b').getElementsByTagName('img')[0].click();})();");
}
});
// ...
If you want to auto click the id="IOMToolbarActive1_kaydet_b" tag, replace
mWebView.loadUrl( "javascript:window.onload= (function(){ document.getElementById('IOMToolbarActive1_kaydet_b').getElementsByTagName('img')[0].click();})();");
with
mWebView.loadUrl( "javascript:window.onload= (function(){ document.getElementById('IOMToolbarActive1_kaydet_b').click();})();");

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);
});
}

Primefaces PickList Limit number of transferred elements

Salam,
I'm triying to implements a Primefaces PickList in my project, and i'm stuck with the max elements i have to transfer from source list to target :
in my case i want to trandfer max of 2 choices from a list of about 12 possible choices.
my selectChoice.xhtml looks like this :
<?xml version="1.0" encoding="UTF-8"?>
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<h1>Liste des cadres</h1>
</h:head>
<h:body>
<ui:composition template="../resources/template.xhtml">
<ui:define name="content">
<h:form>
<p:messages for="update"/>
<p:pickList id="pickList" value="#{etudiantController.pickFiliere}" var="filiere" itemLabel="#{filiere.intitule}" itemValue="#{filiere}" />
</h:form>
</ui:define>
</ui:composition>
</h:body>
</html>
my managed bean is like this :
public List<Filiere> getListFiliere() {
listFiliere = filiereService.findAll();
return listFiliere;
}
public void setListFiliere(List<Filiere> listFiliere) {
this.listFiliere = listFiliere;
}
public DualListModel<Filiere> getPickFiliere() {
if (pickFiliere == null) {
pickFiliere = new DualListModel<Filiere>();
pickFiliere.setSource(getListFiliere());
}
return pickFiliere;
}
public void setPickFiliere(DualListModel<Filiere> pickFiliere) {
this.pickFiliere = pickFiliere;
}
public void onTransfer(TransferEvent event) {
StringBuilder builder = new StringBuilder();
for(Object item : event.getItems()) {
builder.append(((Filiere) item).getIntitule()).append("<br />");
}
FacesMessage msg = new FacesMessage();
msg.setSeverity(FacesMessage.SEVERITY_INFO);
msg.setSummary("Items Transferred");
msg.setDetail(builder.toString());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void onSelect(SelectEvent event) {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Item Selected", event.getObject().toString()));
}
public void onUnselect(UnselectEvent event) {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Item Unselected", event.getObject().toString()));
}
public void onReorder() {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "List Reordered", null));
}
How to tell my PickList to disable transfer of elements after doing 2 transfer.
thanx
///////////////////**********************////////////////////////////////////////
switched to SelectManyCheckbox like melloware has suggested, because it seems more freindley for user to use checkbox, so my xhtml :
<p:selectManyCheckbox id="studentChoices" value="#{etudiantController.choixFLTmp}" layout="responsive" columns="3">
<f:selectItems value="#{filiereController.allFilieres}" var="filiere" itemLabel="#{filiere.intitule}" itemValue="#{filiere}" />
<f:validator validatorId="studentChoicesValidator" />
</p:selectManyCheckbox>
<p:message id="verifyMaxChoices" for="studentChoices"/>
i v created a validator based on balusC answers on this post : How to validate the maximum amount of checked values of a selectManyCheckbox based on the current selection of a selectOneMenu?
my Validator :
#FacesValidator("studentChoicesValidator")
public class StudentChoicesValidator implements Validator {
#Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
List<Filiere> choixFLTmp = (List<Filiere>) value;
if (choixFLTmp.size() > 2) {
throw new ValidatorException(new FacesMessage(
FacesMessage.SEVERITY_ERROR, "Vous ne pouvez cochez plus que deux(2) choix !", null));
}
}
}
For now the message does not apear in my xhtml, and user can do more than 2 check.
How am i supposed to fire the validation(in my mind i always thinked that it fires automatically)
thanx.

Pass JavaScript Value from Webview to Activity?Android

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

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/

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