Firebase Auth not working well in android webview - javascript

I'm building a webapp (html, css, js) with Firebase backend. If the site is opened from the browser, everything is working well, if the user is logged in, it redirects the user to another page. However if I'm using the same site from an android app (which is using webview), the redirecting doesn't work. Any idea why?
The code I'm using in android studio:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
setContentView(R.layout.activity_main);
web = findViewById(R.id.webView);
WebSettings webSettings = web.getSettings();
webSettings.setJavaScriptEnabled(true);
web.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
view.loadUrl(request.getUrl().toString());
return false;
}
});
web.setWebChromeClient(new WebChromeClient() {
#Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
return super.onJsAlert(view, url, message, result);
}
});
web.loadUrl("http://mywebsite.com/login");
web.getSettings().setAppCacheEnabled(false);
web.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
web.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
return (event.getAction() == MotionEvent.ACTION_MOVE);
}
});
}
And this is how the redirecting works:
function loginUser() {
emailVal = document.getElementById("email").value;
passwordVal = document.getElementById("password").value;
firebase.auth().signInWithEmailAndPassword(emailVal, passwordVal)
.then((userCredential) => {
var user = userCredential.user;
})
.catch((error) => {
});
}
firebase.auth().onAuthStateChanged((user) => {
if (user) {
window.location.replace('http://mywebsite.com/home');
}
});

So, after having some google search, I've found this StackOverflow topic:
firebase google authentication in web does not work on android app webview
The problem was that I hadn't enabled the DOM storage. By inserting these two lines to my Java code solved the problem:
WebSettings webSettings = myWebView.getSettings();
webSettings.setDomStorageEnabled(true); // localStorage

Related

WebView not downloading pop-up file

I'm new to Android studio.
So I have been writing some code that helps my job.
When the imgView and Layout clicked the app will go into WebView
On the WebView they will fill the form, after that the web should automatically downloading the .pdf file.
When I Opened it with chrome, chrome will make a new tab/pop up with some link that triggers downloading files.
How this webView could download the pdf file too? because When I opened it on the Web View, the WebView will go back to previous activity.
public class biling extends AppCompatActivity {
private WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_biling);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_DENIED) {
Log.d("permission", "permission denied to WRITE_EXTERNAL_STORAGE - requesting it");
String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permissions, 1);
}
}
webView = findViewById(R.id.bilingweb);
webView.setWebViewClient(new WebViewClient(){
public boolean shouldOverrideUrlLoading (WebView view, String url) {
if (url.endsWith(".pdf")) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
// if want to download pdf manually create AsyncTask here
// and download file
return true;
}
return false;
}
});
webView.loadUrl("https://sse2.pajak.go.id");
webView.setDownloadListener(new DownloadListener()
{
#Override
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimeType,
long contentLength) {
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(url));
request.setMimeType(mimeType);
String cookies = CookieManager.getInstance().getCookie(url);
request.addRequestHeader("cookie", cookies);
request.addRequestHeader("User-Agent", userAgent);
request.setDescription("Downloading File...");
request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(
url, contentDisposition, mimeType));
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getApplicationContext(), "Downloading File", Toast.LENGTH_LONG).show();
}});
webView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_UP:
if (!v.hasFocus()){
v.requestFocus();
}
break;
}
return false;
}
});
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowContentAccess(true);
webSettings.setAllowFileAccess(true);
webSettings.setDisplayZoomControls(true);
webSettings.setAllowFileAccess(true);
webSettings.setSupportMultipleWindows(true);
Toolbar toolbar = findViewById(R.id.toolbar1);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("e-Biling");
getSupportActionBar().setSubtitle("Bayar Pajak Online");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public void onBackPressed() {
if (webView.canGoBack()){webView.goBack();}
else
{super.onBackPressed();}
}
}

Android webview not rendering CSS and angular

I am trying to load a URL in to android native webview, but it does not render CSS and Angular
CODE:
WebView wvFAQs = (WebView) mFragmentView.findViewById(R.id.wvUrls);
Map<String, String> headersMap = new HashMap<>();
headersMap.put(ApiConstants.AUTHORIZATION, BuildConfig.SS_API_AUTH);
wvFAQs.setWebViewClient(new WebViewClient() {
#SuppressWarnings("deprecation")
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
#TargetApi(Build.VERSION_CODES.N)
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
return false;
}
});
wvFAQs.getSettings().setJavaScriptEnabled(true);
wvFAQs.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
wvFAQs.loadUrl(mUrl,headersMap);
ERRORS:
"Uncaught ReferenceError: _ is not defined",
"Uncaught ReferenceError: angular is not defined",
"Uncaught ReferenceError: $ is not defined",
but this URL works fine in mobile browsers (chrome & default android browser).
when i googled this issue, i came to know that i need to enable html5 support feature in webiew, here is the link, but still not working.
Can anyone tell me what might be the issue? is there any issue with the URL or webview?
I use this Java code to load the webview:
public class MainActivity extends AppCompatActivity {
private WebView view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view = (WebView) this.findViewById(R.id.webView);
view.getSettings().setJavaScriptEnabled(true);
view.setWebViewClient(new MyBrowser());
view.loadUrl("file:///android_asset/www/index.html"); //try js alert
view.setWebChromeClient(new WebChromeClient()); // adding js alert support
}
private class MyBrowser extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && view.canGoBack()) {
view.goBack(); //method goback()
return true;
}
return super.onKeyDown(keyCode, event);
}
What I can say is if that you use Jquery you need to add it to your assets because external links like from cdn like:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
would not load.

how to properly open google play links on html page in android webview with setWebViewClient?

Basically My question is HOW CAN I POSSIBLY PUT THESE TWO CODES TOGETHER TO FUNCTION PROPERLY!!! this is killing my trying to figure it out so i'll explain in deep detail...Any help would be much appreciated!!!
i have a webpage at http://s-ka-paidbeats.com/app_tree/ourotherapps it lists a bunch of apps i have made in google play.in the webpage html i have them listed with standard links like - https://play.google.com/store/apps/details?id=com.yesorno.app.yesorno
i've created a tab in ALL the android applaications that i've made called "My Other Apps"this tab is a webview window that shows the same html page i was talking about above- http://s-ka-paidbeats.com/app_tree/ourotherapps
the problem is when a user visits the webview window in any of my android applications and clicks on any of the apps i have listed on the html webpage (https://play.google.com/store/apps/details?id=) it takes them to google play in the webview window and asks them to login to google play in the webview window (even if they are already logged in to google play on their device)... this is extremely ugly and annoying for users to face.
i want to make it so when a user visits the "my other apps" tab in any of my applications, and clicks on one of the apps in the webview window it opens the actual google play application (if google play is installed) or opens in the default browser installed on the device (if google play is not installed)
i have tried to change all the (https://play.google.com/store/apps/details?id=) links to (market://details?id=) links on the html page and then visited the webview window again in my app however this time when i click on any of the apps listed i just get a page error "page does not exist" window
i have looked into setWebViewClient and i am sure that there is someway to do this using something like the code posted below
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getScheme().equals("market")) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
Activity host = (Activity) view.getContext();
host.startActivity(intent);
return true;
} catch (ActivityNotFoundException e) {
// Google Play app is not installed, you may want to open the app store link
Uri uri = Uri.parse(url);
view.loadUrl("http://play.google.com/store/apps/" + uri.getHost() + "?" + uri.getQuery());
return false;
}
}
return false;
} });
I tried adding the code above to my current code but now my loading dialog box wont close when the webview is loading.... it just stays loading forever.... so i took the code snippet above out of my code again because i dont think i am placing it in the right place or that i am integrating the two codes together properly....
i noticed my current code already has a setWebViewClient defined so im not sure if im allowed to have two in the same code or if i am suppose to try and combine it with the current one....... I HAVE NO CLUE where to begin and i have been reading for hours....
Here is my current code
package com.yesorno.app.yesorno;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.support.v7.widget.Toolbar;
import android.widget.Toast;
import com.yesorno.app.yesorno.NetorkConnection;
#SuppressLint("SetJavaScriptEnabled")
public class OtherApps extends AppCompatActivity {
private WebView webView;
NetorkConnection ntwrk_con = new NetorkConnection(this);
ProgressDialog dialog;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView toolsresources5 = (TextView)findViewById(R.id.feedbacktextview);
toolsresources5.setVisibility(View.INVISIBLE);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
webView = (WebView) findViewById(R.id.activity_main_webview);
dialog = new ProgressDialog(OtherApps.this);
if (ntwrk_con.isConnectingToInternet()) {
webView();
} else {
dialog_box_for_internet();
}
}
public void dialog_box_for_internet() {
if (ntwrk_con.isConnectingToInternet()) {
webView();
} else {
// dismis_dialog_box_for_internet = true;
AlertDialog.Builder builder = new AlertDialog.Builder(
OtherApps.this);
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.dialog_custom_titile, null);
TextView title = (TextView) view.findViewById(R.id.myTitle);
title.setText("Unable To Connect");
builder.setCustomTitle(view);
builder.setMessage("No Internet Connection")
.setCancelable(false)
.setPositiveButton("Retry",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
if (ntwrk_con.isConnectingToInternet()) {
webView();
} else {
new Thread_for_internet().execute();
}
// dialog.cancel();
}
})
.setNegativeButton("Okay",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
finish();
// Gridview.super.onBackPressed();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
class Thread_for_internet extends AsyncTask<String, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog.setMessage("Loading..Please wait.");
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
#Override
protected Boolean doInBackground(String... args) {
try {
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Boolean result) {
dialog.dismiss();
dialog_box_for_internet();
}
}
public void webView() {
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
});
dialog.setMessage("Loading All Our Apps...\nPlease wait...");
dialog.setCanceledOnTouchOutside(false);
dialog.show();
webView.loadUrl("http://s-ka-paidbeats.com/app_tree/ourotherapps.html");
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (webView.canGoBack()) {
webView.goBack();
} else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
boolean bRet=false;//set true is menu selection handled
switch (item.getItemId()) {
case R.id.action_settings_3:
Toast.makeText(this, Html.fromHtml("<big><b>Develeped By S-Ka-Paid</b></big><br>© 2016 S-Ka-Paid"), Toast.LENGTH_LONG).show();
bRet=true;
break;
case R.id.action_settings_4:
Intent intent2 = new Intent(Intent.ACTION_VIEW);
//Try Google play
intent2.setData(Uri.parse("market://details?id=com.yesorno.app.yesorno"));
startActivity(intent2);
bRet=true;
break;
default:
bRet=super.onOptionsItemSelected(item);
}
return bRet;
} }
Basically My question is HOW CAN I POSSIBLY PUT THESE TWO CODES TOGETHER TO FUNCTION PROPERLY!!! this is killing my trying to figure it outAny help would be much appreciated!!!
i have tried to change all the (https://play.google.com/store/apps/details?id=) links to (market://details?id=) links on the html page
Don't do that. Use the google play URLs you started with.
i noticed my current code already has a setWebViewClient defined so im not sure if im allowed to have two in the same code or if i am suppose to try and combine it with the current one
You combine them. You create one WebViewClient to handle all the needs of one WebView. It's not difficult:
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// is this a play store URL?
String partialUrl = "/store/apps/details?id=";
if (url.contains(partialUrl)) {
// extract the app id from the URL
int pos = url.indexOf(partialUrl) + partialUrl.length();
String appId = url.substring(pos);
try {
// open the google play app
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("market://details?id=" + appId));
OtherApps.this.startActivity(intent);
return true; // we overrode the url load
} catch (ActivityNotFoundException e) {
// no google play app, load URL in device browser
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
OtherApps.this.startActivity(intent);
return true;
}
}
return false; // no override, let the webview load this url
}
});
for anyone looking for the answer to this... here is the correct code
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// is this a play store URL?
String partialUrl = "/store/apps/details?id=";
if (url.contains(partialUrl)) {
// extract the app id from the URL
int pos = url.indexOf(partialUrl) + partialUrl.length();
String appId = url.substring(pos);
try {
// open the google play app
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("market://details?id=" + appId));
OtherApps.this.startActivity(intent);
return true; // we overrode the url load
} catch (ActivityNotFoundException e) {
// no google play app, load URL in device browser
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
OtherApps.this.startActivity(intent);
return true;
}
}
return false; // no override, let the webview load this url
}
});

not able to call web service from webview

I am not able to call web service or no alert is being shown:
my activity code:
mWebView = (WebView)findViewById(R.id.webViewRootAciviy);
mWebView.setWebViewClient(new WebViewClient());
mWebView.setWebChromeClient(new WebChromeClient());
mWebView.loadUrl("file:///android_asset/splashscreen.html");
html code:
<html>
<body>
this is a demo html file.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js">
$.ajax({
type: 'GET',
url: 'http://192.168.11.50/ar/service.svc/ProductCategories?$format=json',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data)
{
alert("success");
},
error: function (error)
{
alert("error");
}
});
</script>
</body>
</html>
Also given the Internet permission. Please help me find what i missed.
Edit:
We have our own server in our company and service is hosted on it. I am using wifi to access internet and server is also connected to the same wifi router with ethernet cable.
Update: I dont know why this happened. The problem was arised due to the type of service created. The web service was created using WCF Data service, but after creating web service again using normal WCF Service, the URL is working fine now.
apply this to your webview.
webView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
} else {
return false;
}
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
}
});
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(give your url);
// I used this class and my code is working fime at my side please try this may be it will help you
public class WebViewActivity extends Activity {
private WebView webview;
private static final String TAG = "Main";
private ProgressDialog progressBar;
private TextView header_maintext;
private TextView headeroptiontext;
private RelativeLayout back;
private String url_string="http://www.google.com";
private String header_maintext_string="Your text";
/** Called when the activity is first created. */
#SuppressLint("SetJavaScriptEnabled") #Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.webview_layout);
webview = (WebView)findViewById(R.id.webview01);
header_maintext= (TextView)findViewById(R.id.header_maintext);
header_maintext.setText(header_maintext_string);
headeroptiontext = (TextView)findViewById(R.id.headeroptiontext);
headeroptiontext.setVisibility(View.GONE);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webview.getSettings().setLoadWithOverviewMode(true);
webview.getSettings().setUseWideViewPort(true);
back = (RelativeLayout) findViewById(R.id.back_layout);
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
if(webview.canGoBack() == true)
{
webview.goBack();
}
else
{
finish();
}
}
});
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
progressBar = ProgressDialog.show(WebViewActivity.this, "My application", "Loading...");
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
Log.i(TAG, "Finished loading URL: " +url);
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(WebViewActivity.this, "Oh no! " + description, Toast.LENGTH_SHORT).show();
alertDialog.setTitle("Error");
alertDialog.setMessage(description);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}
});
alertDialog.show();
}
});
webview.loadUrl(url_string);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_DOWN){
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(webview.canGoBack() == true){
webview.goBack();
}else{
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}

setJavaScriptEnabled(true) in 'doInBackground' override force closes app

I have followed this very basic example tutorial for loading a URL in a WebView async:
android-asynctask-example.
However the app force closes when i click 'Load Webpage', with the error:
"Can't create handler inside thread that has not called
Looper.prepare()".
When I remove the line "webView.getSettings().setJavaScriptEnabled(true);", the app works fine, and displays a WebView (obviously with no JavaScript enabled in the WebView).
If i leave that line in, but set enabled to false, the app also works without crashing.
I wish to modify this project, however i need JavaScript enabled, so was wondering if anyone had a clue as to why it was failing?
Any help will be greatly appreciated!
Try it this way,
public class MainActivity extends Activity {
final Context context = this;
WebView webView =null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
private class LoadWebPageASYNC extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute(String result) {
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
}
#Override
protected String doInBackground(String... urls) {
webView.loadUrl(urls[0]);
return null;
}
#Override
protected void onPostExecute(String result) {
}
}
public void dummyFunc(View view){
Toast.makeText(MainActivity.this, "Button Clicked", Toast.LENGTH_SHORT).show();
}
public void readWebpage(View view) {
LoadWebPageASYNC task = new LoadWebPageASYNC();
task.execute(new String[] { "http://www.javacodegeeks.com" });
}
}

Categories

Resources