I am using webview in my application to show canvas. On my webview there is click here button. I want to open new activity on click of this 'click here' button on webview. I dont know how to handle this click event.Need help as soon as possible.
Following is my webview class code:
public class TableWebView extends Activity {
private SharedPreferences sharedPreferences;
private String customer_id,hotel_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_table_web_view);
WebView wvtable= (WebView)findViewById(R.id.webViewTable);
wvtable.setWebViewClient(new MyViewClient());
WebSettings webSettings = wvtable.getSettings();
webSettings.setJavaScriptEnabled(true);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
customer_id = sharedPreferences.getString("cust_id", "0");//if no customerid found automatically 0 will be used
hotel_id=sharedPreferences.getString("hotel_master_id","0");
wvtable.loadUrl("http://192.168.100.169/zoilo_admin/public/index.php/show-hotel-view?hotel_id="+hotel_id+"&customer_id="+customer_id+"&date_time="+ Util.selected_date_time);
}
And here is how it looks after opening that url in webview:
Binding JavaScript code to Android code
When developing a web application that's designed specifically for the WebView in your Android application, you can create interfaces between your JavaScript code and client-side Android code. For example, your JavaScript code can call a method in your Android code to start activity.
To bind a new interface between your JavaScript and Android code, call addJavascriptInterface(), passing it a class instance to bind to your JavaScript and an interface name that your JavaScript can call to access the class.
Caution: If you've set your targetSdkVersion to 17 or higher, you must add the #JavascriptInterface annotation to any method that you want available to your JavaScript (the method must also be public). If you do not provide the annotation, the method is not accessible by your web page when running on Android 4.2 or higher.
public class TableWebView extends Activity {
private SharedPreferences sharedPreferences;
private String customer_id,hotel_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_table_web_view);
WebView wvtable= (WebView)findViewById(R.id.webViewTable);
wvtable.setWebViewClient(new MyViewClient());
wvtable.addJavascriptInterface(new WebAppInterface(this), "Android");
WebSettings webSettings = wvtable.getSettings();
webSettings.setJavaScriptEnabled(true);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
customer_id = sharedPreferences.getString("cust_id", "0");//if no customerid found automatically 0 will be used
hotel_id=sharedPreferences.getString("hotel_master_id","0");
wvtable.loadUrl("http://192.168.100.169/zoilo_admin/public/index.php/show-hotel-view?hotel_id="+hotel_id+"&customer_id="+customer_id+"&date_time="+ Util.selected_date_time);
}
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 startNewActivity() {
//startActivity(new Intent(this, youactivityname.class));
}
}
This creates an interface called Android for JavaScript running in the WebView. At this point, your web application has access to the WebAppInterface class. For example, here's some HTML and JavaScript that call your "startNewActivity" method of your class using the new interface when the user clicks a button:
<input type="button" value="Click Here" onClick="showActivity()" />
<script type="text/javascript">
function showActivity() {
Android.startNewActivity();
}
</script>
Related
I'm displaying a webpage in my Android app using a WebView, this webpage triggers a window message event and gives some data through that event. I need to access the data from the message event.
To achieve this, I'm adding the JavaScript event listener by using evaluateJavascript() method and trying to call a Java function from the JavaScript using addJavascriptInterface().
My Code so far:
public class MyActivity extends AppCompatActivity {
#Override
#SuppressLint("SetJavaScriptEnabled")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView webView = new WebView(this);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.addJavascriptInterface(new JsObject(this), "Android");
webView.evaluateJavascript("window.addEventListener('message', (e) => {Android.logData('Test String')})", null);
webView.loadUrl("https://example.com/mypage");
setContentView(webView);
}
private class JsObject {
Context context;
JsObject(Context context) {
this.context = context;
}
#JavascriptInterface
public void logData(String s) {
Log.v("EEE", s);
}
}
}
But the event handler is not getting called. I'm not sure whether this is the right approach. Please help. TIA.
Switch the order of your loadUrl and evaluateJavascript calls. The loadUrl is resetting that state. Note: this may require changing the code on the page to avoid a race condition triggering the message.
From the evaluateJavascript docs:
global variables and functions defined before calling loadUrl(java.lang.String) will not exist in the loaded page
let's say that i have google page loaded in webview, then i searched for something,
So the page changed, and there's a text in this page that i want to get it in my android app, in textView by using the code below
webview.loadUrl("javascript:api.getSessionID(document.querySelector(bla bla bla)");
class JSInterface {
#JavascriptInterface
public void getSessionID(String id) {
Toast.makeText(context,id, Toast.LENGTH_LONG).show();
}
How can i inject this js in the shown page in webview, not in the page that loaded first in webview which is google search page
Google just an example, i'm trying to save a session id in sharedPreferences when a user loggin in the account, which is the second page
Note: i have all the necessary codes in my full code in order to inject js and get string from it
Note2: if i reloaded the page, i will sign out
Appreciate any help !
your WebView first of all, we must tell the WebView to enable the JavaScript execution:
webview.getSettings().setJavaScriptEnabled(true);
Then we must set the WebViewClient in order to receive the onPageFinished event.
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
super.onPag`enter code here`eFinished(view, url);
webView.loadUrl(
"javascript:(function() { " +
"var element = document.getElementById('hplogo');"
+ "element.parentNode.removeChild(element);" +
"})()");
}
});
To acheive this you can evaluate javascript as,
webview.evaluateJavascript("Your JS here which will return session id",
html1 -> Log.i("HTML", html1));//session id will be printed
Also, make sure you have enabled java script to run in webview webView.getSettings().setJavaScriptEnabled(true);
EDIT
Second approach,
If you want to implement an interface which will give callback do change in your webpage as,
if (typeof YourListener != 'undefined')//check if yourlistner is undefined
yourListener.onTextChange('theReturnValue');
});
In above code the interface is called from webpage same as we do in android. Just apply JS at 'theReturnValue' here you need to retun required value from webpage.
And then add to webview that interface as,
webview.addJavascriptInterface(new WebAppInterface(getActivity(), webview), "YourListener");
also, add interface as,
public class WebAppInterface {
Context mContext;
WebView mView;
/**
* Instantiate the interface and set the context
*/
WebAppInterface(Context c, WebView w) {
mContext = c;
mView = w;
}
/**
* Show a toast from the web page
*/
#JavascriptInterface
public void onTextChange(String html) {
//you will get the callback text here
}
}
How can I call a native function from cordova/phonegap webview for example for showing an ad.
EDIT: OK I FUNALLY GOT IT and I'm gonna write some steps for all of you who don't know how to do that (just to spare 2 days of your lifetime :D)
A) if you have just cordova/phonegap and and wish to call from js do this:
1) Replace the following code with your existing DroidGap Activity.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.init(); // Calling this is necessary to make this work
appView.addJavascriptInterface(this, "MainActivity");
/* "this" points the to the object of the current activity. "MainActivity" is used to refer "this" object in JavaScript as in Step 3. */
super.loadUrl("file:///android_asset/www/index.html");
}
2) Add the custom function in current (this) activity as following.
#JavascriptInterface
public void customFunctionCalled() {
Log.e("Custom Function Called", "Custom Function Called");
}
3) Now call this function from your HTML/JavaScript code as following.
window.MainActivity.customFunctionCalled();
B.1) if you have cordova/phonegap implemented in a webview and wish to call from js do this:
(and want to call normal function)
1) Add this to the main java file:
JavaScriptInterface jsInterface = new JavaScriptInterface(this);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(jsInterface, "JSInterface");
2) Declare the class JavaScriptInterface:
public class JavaScriptInterface {
private Activity activity;
public JavaScriptInterface(Activity activiy) {
this.activity = activiy;
}
#JavascriptInterface
public void showLog(){
Log.v("blah", "blah blah");
}
}
3) Call it from js with `window.JSInterface.showLog();
B.2) if you have cordova/phonegap implemented in a webview and wish to call from js (and want to call UI function, like a toast) do this:
1) Add this to the main java file:
JavaScriptInterface jsInterface = new JavaScriptInterface(this);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(jsInterface, "JSInterface");
2) Declare the class JavaScriptInterface:
public class JavaScriptInterface {
private Activity activity;
public JavaScriptInterface(Activity activiy) {
this.activity = activiy;
}
#JavascriptInterface
public void myFunction()
{
activity.runOnUiThread(new Runnable() {
public void run() {
//Code that interact with UI
showToast();
}
});
}
}
3) Add the toast function underneath:
public void showToast(){
Toast.makeText(getApplicationContext(), "this is my Toast message!!! =)",
Toast.LENGTH_LONG).show();
}
4) Call it with `window.JSInterface.myFunction();
As you see if you need a function that uses the UI you need to wrap your function into activity.runOnUiThread so that it can get called from js.
*If you want to call from java a jquery method do this:
Java:
cordova_webview.loadUrl("javascript:window.functionn()");
Javascript:
window.function = punish;
Have a nice day!
In the .java file
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
super.init(); // Calling this is necessary to make this work
appView.addJavascriptInterface(this, "MainActivity");
super.loadUrl(Config.getStartUrl());
}
In the javascript
window.MainActivity.customFunctionCalled();
This will only work on TargetSDK<17 . An androidManifest.xml targetSDK need to be set < 17. And for TargetSDK >=17 , I guess you'll need to create some custom plugin. I use this process lowering my target SDK for now.
I have one query. Can I pass Value from my html page to My Activity file.
html file located in assets/www folder and Activity file located in src/package_name
You need to use JavaScriptInterface. In your web view add this Interface.
Make JavaScriptInterface class like (Here you can use any name for your class)
public class JavaScriptInterface {
Context mContext;
/** Instantiate the interface and set the context */
JavaScriptInterface(Context context) {
mContext = context;
}
/** Get passed value from the web page here */
public void showMyValue(String passedValue) {
android.util.Log.i("TAG", "I Got this value:" + passedValue);
}
}
Add this interface in your webview like
WebView webView = (WebView) findViewById(R.id.webview);
webView.addJavascriptInterface(new JavaScriptInterface(this), "Android");
Now in your webpage, call this method to pass your value and do something need full with that value
<input type="button" value="ClickMe" onClick="passValueToAndroid('Hello Android!')" />
<script type="text/javascript">
function passValueToAndroid(yourPassingValue) {
Android.showMyValue(yourPassingValue);
}
</script>
Yes you can pass any variable from html to activity.
You need to create JavaScript Interface to interact between html to activity,
Refer this link for implementation detail
http://developer.android.com/guide/webapps/webview.html
I have User registration page in Phonegap www folder.I want to validate email id and phone number using native android functions.How do I do that?
We have to write JS interface to execute java code from javascript.
Write following code in your onCreate method:
public class MainActivity extends DroidGap {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.loadUrl("file:///android_asset/www/index.html");
WebView webView = (WebView) findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.addJavascriptInterface(new Object()
{
public void performClick(String emailAdress, String phoneNo)
{
// Validate email address and Phone number here
}
},"MyAndroid");
}
}
To call JS interface in phonegap app, write javascript function:
<script>
document.getElementById("validateButton").addEventListener('touchstart',touchPagePressed);// you can use 'onclick' also
function touchPagePressed()
{
// MyAndroid interface will execute java's performClick method
MyAndroid.performClick($("#emailId").val(),$("#phoneNo").val());
}
</script>