Android webview detect specific page change - android

I have an android webview app with user authentication, the app allows users to register their devices by collecting the device's android id. When a user runs the mobile app, it will check if the mobile device is registered then validates the login details associated with the registered device. All works as designed with no issue.
My problem is that when the PHP session expires, users will be directed to the login page. If the user closes the app and re-open it, it will log the user without having to re-enter the login details. PHP session time-out can not be changed due to company policy.
I would like to know if I could detect the login page URL change and send the device android id with the login page URL similar to the app startup process. So, when the PHP session expires, users will be automatically logged back in without having to re-enter their login credentials.
Here is the current code I am using, some irrelevant codes have been removed to reduce the code lines. This is my first android app, and I have very limited experience when it comes to mobile programming and I have been searching for the last couple of day without any luck. Help and directions are highly appreciated.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
boolean isConnct = false;
// code here to check internet connection
// end of internet connection code
if (isConnct){
// internet is ok
final WebView webView = (WebView)findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
findViewById(R.id.imageLoading1).setVisibility(ImageView.GONE);
findViewById(R.id.webView).setVisibility(webView.VISIBLE);
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl){
// show error message
}
});
// using setWebChromeClient to enable javascript
webView.setWebChromeClient(new WebChromeClient() {
#Override
public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
// js confirm code
}
#Override
public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
// js alert code
}
});
// enable javascript and other settings
String url = "https://www.domainname/login/" + android.provider.Settings.Secure.getString(getContentResolver(), Secure.ANDROID_ID);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setAllowFileAccess(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setUseWideViewPort(true);
webSettings.setBuiltInZoomControls(true);
webSettings.setDisplayZoomControls(false);
webSettings.setSupportZoom(true);
webSettings.setDefaultTextEncodingName("utf-8");
webView.loadUrl(url);
} else {
// show error message
}
}

try override shouldOverrideUrlLoading method in WebViewClient, check your login URL and start your auto-login from there
another approach is checking cookies expiration time, you may use CookieManager.getInstance() for this

This is what I ended up doing, and it seems working as expected, when PHP session expires, registered devices will be redirected to the index page with new session without having to re-enter user credentials.
If there is a logout button then you need to consider adding different procedure for the logout to allow users to logout and re-direct to login page.
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
//hide loading image
findViewById(R.id.imageLoading1).setVisibility(ImageView.GONE);
//show webview
findViewById(R.id.webView).setVisibility(webView.VISIBLE);
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl){
// show error message
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contentEquals("https://www.domainme/login")){
String url2 = "https://www.domainme/login/" + android.provider.Settings.Secure.getString(getContentResolver(), Secure.ANDROID_ID);
webView.loadUrl(url2);
return true;
}else {
return false;
}
}
// code truncated
}

Related

Javascript on Android WebView not working

I have some issues with Android WebView and Javascript.
Some of customers of app said that WebView on app is not showing anything.
As I checked - its probably not showing javascript at all (whole webpage is loaded in javascript by react).
That my code:
public void setupWebView(WebView accessWebView) {
accessWebView.setWebViewClient(new WebViewClient() {
#SuppressWarnings("deprecation")
#Override
public boolean shouldOverrideUrlLoading(WebView webView, String url) {
handleRedirect(accessWebView);
return true;
}
});
accessWebView.getSettings().setJavaScriptEnabled(true);
accessWebView.getSettings().setDomStorageEnabled(true);
accessWebView.loadUrl(URL);
(I have to use WebViewClient, not WebChromeClient, because of the redirect handling)
Is there anything possible to change so the javascript will load on EVERY device with Android +5.0?
Is it possible that updating WebView on device will help some users?
You need to use setWebChromeClient to enable javascript in your WebView. But don't worry, you can use both setWebChromeClient and setWebViewClient in the same time. Just like in official docs:
// Let's display the progress in the activity title bar, like the
// browser app does.
getWindow().requestFeature(Window.FEATURE_PROGRESS);
webview.getSettings().setJavaScriptEnabled(true);
final Activity activity = this;
webview.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
// Activities and WebViews measure progress with different scales.
// The progress meter will automatically disappear when we reach 100%
activity.setProgress(progress * 1000);
}
});
webview.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
}
});
webview.loadUrl("https://developer.android.com/");
https://developer.android.com/reference/android/webkit/WebView.html

Webview doesn't show a specific website

I'm trying to do a webview based application for this website to show it in a mobile application.
when I put any different site the application work great, but in this specific site never show the second page when I clicked in the button to go to the desk page. However, I put a Log statement in the onPageFinished method and log that the page is loaded completely.
My Code Here
final WebView myWebView = (WebView) rootView.findViewById(R.id.webview);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.setWebViewClient(new WebViewClient() {
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(getActivity(), "Oh no! " + description, Toast.LENGTH_SHORT).show();
}
#Override
public void onPageFinished(WebView view, String url) {
Log.d("WEBSITE", "Page Loaded.");
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.d("WEBSITE", url);
myWebView.loadUrl(url);
return false;
}
});
myWebView.loadUrl("https://demo.frappecloud.com/");
I believe the problem is with your shouldOverrideUrlLoading. If you check the documentation you will see that :
This method is not called for requests using the POST "method"
When you are submitting the Form, you are making a POST request, which is basically ignored.
Here is the link: WebViewClient
Also check this reference where it says how you could load a URL with POST data: LOAD A POST REQUEST INTO A WEBVIEW IN ANDROID
Consider checking this thread: Android - how to intercept a form POST

Android WebView Facebook Login (popup/redirection issues)

how is everyone?
I am working on a simple mobile application utilizing WebView. My website utilizes a layout giving it the appearance of a native app. I also allow users to login with their facebook account into my website. Here are my scenarios
** WORKS ** From PC/Chrome: Can access the mobile site URL, login with facebook which opens the pop-up dialog to either A.) Login, or B.) if user is FB logged in, prompt user to accept
** WORKS ** From Phone/Chrome: Can access the mobile site URL, login with facebook which opens a new tab with A.) Login, or B.) if user is FB logged in, prompt user to accept
** PROBLEM! ** From Phone/APK: Loads website in WebView, click login with facebook, opens facebook login page in the webview, but once I enter details and attempt to login, nothing happens. If I go to my home screen and reopen the app, it logs me in using the details I previously submitted
So basically what I am saying is that in the APP, once I leave my website URL and go to facebook's website to enter facebook details to login with it and press login -- it doesn't redirect back to my website for some reason. I've been plucking my hairs trying to find a solution to this, I've also searched extensively on here and other places but have not been able to find a workable solution, I'm sure many other people may be experiencing similar issues with facebook or other services
Here is my code (was originally much more simple, however I am now utilizing what I found in another topic covering this issue, however it still does not work -- I'd also like to mention that with this portion of code that I found, when TARGET_URL is loaded from a phone, the phone will redirect it to the mobile version of the website, which, since it's how the code functions, causes it to open up in a browser instead of my WebView)
I'm totally confused =/
public class MainActivity extends Activity {
/* URL saved to be loaded after fb login */
private static final String target_url="http://www.moneygirlsmusic.tv/app/index.php?do=/mobile/";
private static final String target_url_prefix="www.moneygirlsmusic.tv/app/index.php?do=/mobile/";
private Context mContext;
private WebView mWebview;
private WebView mWebviewPop;
private FrameLayout mContainer;
private long mLastBackPressTime = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// final View controlsView =
// findViewById(R.id.fullscreen_content_controls);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
mWebview = (WebView) findViewById(R.id.webview);
//mWebviewPop = (WebView) findViewById(R.id.webviewPop);
mContainer = (FrameLayout) findViewById(R.id.webview_frame);
WebSettings webSettings = mWebview.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAppCacheEnabled(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setSupportMultipleWindows(true);
mWebview.setWebViewClient(new UriWebViewClient());
mWebview.setWebChromeClient(new UriChromeClient());
mWebview.loadUrl(target_url);
mContext=this.getApplicationContext();
}
private class UriWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
String host = Uri.parse(url).getHost();
Log.d("shouldOverrideUrlLoading", url);
if (host.equals(target_url_prefix))
{
// This is my web site, so do not override; let my WebView load
// the page
if(mWebviewPop!=null)
{
mWebviewPop.setVisibility(View.GONE);
mContainer.removeView(mWebviewPop);
mWebviewPop=null;
}
return false;
}
if(host.equals("m.facebook.com") || host.equals("www.facebook.com"))
{
return false;
}
// Otherwise, the link is not for a page on my site, so launch
// another Activity that handles URLs
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
#Override
public void onReceivedSslError(WebView view, SslErrorHandler handler,
SslError error) {
Log.d("onReceivedSslError", "onReceivedSslError");
//super.onReceivedSslError(view, handler, error);
}
}
class UriChromeClient extends WebChromeClient {
#Override
public boolean onCreateWindow(WebView view, boolean isDialog,
boolean isUserGesture, Message resultMsg) {
mWebviewPop = new WebView(mContext);
mWebviewPop.setVerticalScrollBarEnabled(false);
mWebviewPop.setHorizontalScrollBarEnabled(false);
mWebviewPop.setWebViewClient(new UriWebViewClient());
mWebviewPop.getSettings().setJavaScriptEnabled(true);
mWebviewPop.getSettings().setSavePassword(false);
mWebviewPop.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
mContainer.addView(mWebviewPop);
WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
transport.setWebView(mWebviewPop);
resultMsg.sendToTarget();
return true;
}
#Override
public void onCloseWindow(WebView window) {
Log.d("onCloseWindow", "called");
}
}
I forgot to include my previous resources used to try to figure this out
Making facebook login work with an Android Webview
Making facebook login work with an Android Webview
Android WebView for Facebook Like Button
Android WebView for Facebook Like Button
In android 6 running in some mobiles you should add this to your java code to redirect . otherwise it doesn't redirect and nothing happens .
webview.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
});

Android Webview Facebook Login

In my app, I want to make users be able to login with their Facebook account. After some searches, I am able to figure out this although I don't think this way is the best method. I used a webview in my UI, and a webviewclient to sense url switchings. As I understand, On Android, I must handle all redirections in my webviewclient (Facebook redirections, several redirections happen when user set the his/her email and password). But all I need is to parse my output xml and make a decision according to output result(redirect to my home activiy or failure etc). Here is my code, Please give your suggestions if more suitable method exists.
public class FbLoginActivity extends Activity {
String fbLoginBaseUrl = "{my server url}/facebook/redirector.jsp?";
private ProgressDialog progressBar;
WebView webView;
int count = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fb_login);
fbLoginBaseUrl += "usdId=NoSession:";
fbLoginBaseUrl += Subroutines.getInstance().getDeviceId() + "_L";
webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
progressBar = ProgressDialog.show(FbLoginActivity.this, "", "Page is loading...");
webView.setWebViewClient(new HelloWebViewClient());
webView.loadUrl(fbLoginBaseUrl);
}
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
Log.v(Subroutines.TAG, url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
Log.i(Subroutines.TAG, "Finished loading URL: " +url);
// if login screen loading finishes, cancel the progressdialog..
// twice redirecting happens to this sub url..
String subFace = "m.facebook.com/login.php";
if(url.indexOf(subFace) != -1 && ++count == 2){
if (progressBar.isShowing()) {
progressBar.cancel();
}
}
// Permission redirecting..
String loginSub = "www.facebook.com/connect/uiserver.php?method=permissions.request";
if(url.indexOf(loginSub) != -1){
progressBar = ProgressDialog.show(FbLoginActivity.this, "", "Logging in...");
}
// finally if my server makes a response..
String sub = "{my server url}/facebook/connect.jsp";
if(url.indexOf(sub) != -1){
Log.v(Subroutines.TAG, "my server makes a response..");
// xml parsing stuff..
// use url content to parse
}
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Log.e(Subroutines.TAG, "Error: " + description);
}
}
}
I would get the Facebook SDK and use their functions
In a nutshell you do this:
public Facebook facebook = new Facebook("appID");
Then in on create or wherever:
facebook.authorize(this,String[] YourNeededPermissions, new DialogListener() {
#Override
public void onComplete(Bundle values) {}
#Override
public void onFacebookError(FacebookError error) {}
#Override
public void onError(DialogError e) {}
#Override
public void onCancel() {}
});
You can see this here: http://developers.facebook.com/docs/guides/mobile/#android
I have actually a similar problem in integrating the facebook registration with my own (but I'm not the android developer).
I asked the question here Facebook registration flow from Android
but I didn't know about the webview. That seems a good solution, can I contact you by chat or other means?
EDIT:
Facebook just updated their login procedure:
https://developers.facebook.com/docs/offline-access-deprecation/
as you can see, now the token you get from SSO (or any other client token) is linked only to your application (there is a validation token-app id-app secret).
The endpoint is now
https://graph.facebook.com/oauth/access_token?
client_id=APP_ID&
client_secret=APP_SECRET&
grant_type=fb_exchange_token&
fb_exchange_token=EXISTING_ACCESS_TOKEN
So using the facebook sdk for android the steps are:
1) get the user signed
2) send the token to the server
3) server will validate the token against its app id and app secret
4) add your own security features

Android how to pass google account to webview

I am using webview to show google canlender but want to pass google account programmatic-ally,so the setHttpAuthUsernamePassword() function should be what I need but it doesn't work at all. Here is the code:
WebView webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.setHttpAuthUsernamePassword("www.google.com", "", "email", "password");
webview.setWebViewClient(new WebViewClient() {
#Override
public void onReceivedHttpAuthRequest (WebView view, HttpAuthHandler handler, String host,String realm){
handler.proceed("email","password");
}
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(activity, description, Toast.LENGTH_SHORT).show();
}
});
webview.loadUrl("http://www.google.com/calendar/");
If you have any idea to make this worked, please let me know. I tried to search a lot but don't see any useful.
You're trying to use HTTP authentication (http://en.wikipedia.org/wiki/Basic_access_authentication) which is not supported by most web services. You need to have valid Google cookies, which are set only when you manually sign in with your password.

Categories

Resources