Bypass SSL Error in InAppBrowser Cordova Plugin - javascript

I have added an InAppBrowser plugin into a Cordova project to access a site and get token but while the site is opening normally in desktop browsers the same is giving error while opening from mobile browser.
Also the default native browser will ask to continue in case of SSL error but the Cordova InAppBrowser is not asking for such option and instead showing an error page. I am opening the IAB using the following code :
var iab = window.open('http://www.example.com', '_blank', 'location=yes');
Any idea on how to bypass SSL erros in InAppBrowser ?

I'm going to expand on the answer to the related question (phonegap inappbrowser https pages not loading). This pertains only to Android, sorry still working on iOS.
Add this code:
public void onReceivedSslError(WebView view,
SslErrorHandler handler, SslError error) {
Log.e("Error", "Received SSL error"+ error.toString());
handler.proceed();
}
to the InAppBrower.java file from the plugin. Specifically, it should be under the InAppBrowserClient class.
Hope this helps!

Insert Proper Code from below InAppBrowser.java in to your plugin
LOCATED IN platforms\android\src\org\apache\cordova\inappbrowser\InAppBrowser.java
Filtered code from below java code:
import android.net.http.SslError;
import android.webkit.SslErrorHandler;
#SuppressLint("SetJavaScriptEnabled")
public class InAppBrowser extends CordovaPlugin {
private boolean ignoreSSLError = false;
private HashMap<String, Boolean> parseFeature(String optString) {
if (optString.equals(NULL)) {
return null;
} else {
HashMap<String, Boolean> map = new HashMap<String, Boolean>();
StringTokenizer features = new StringTokenizer(optString, ",");
StringTokenizer option;
while(features.hasMoreElements()) {
option = new StringTokenizer(features.nextToken(), "=");
if (option.hasMoreElements()) {
String key = option.nextToken();
if(key.equalsIgnoreCase(IGNORE_SSL_ERROR)) {
Boolean value = option.nextToken().equals("no") ? Boolean.FALSE : Boolean.TRUE;
map.put(key, value);
}
else {
Boolean value = option.nextToken().equals("no") ? Boolean.FALSE : Boolean.TRUE;
map.put(key, value);
}
}
}
return map;
}
}
public String showWebPage(final String url, HashMap<String, Boolean> features) {
// Determine if we should hide the location bar.
showLocationBar = true;
showZoomControls = true;
openWindowHidden = false;
ignoreSSLError = false;
if (features != null) {
Boolean show = features.get(LOCATION);
if (show != null) {
showLocationBar = show.booleanValue();
}
Boolean SSLError = features.get(IGNORE_SSL_ERROR);
if(SSLError != null){
ignoreSSLError = SSLError.booleanValue();
}
Boolean zoom = features.get(ZOOM);
if (zoom != null) {
showZoomControls = zoom.booleanValue();
}
Boolean hidden = features.get(HIDDEN);
if (hidden != null) {
openWindowHidden = hidden.booleanValue();
}
Boolean hardwareBack = features.get(HARDWARE_BACK_BUTTON);
if (hardwareBack != null) {
hadwareBackButton = hardwareBack.booleanValue();
}
Boolean cache = features.get(CLEAR_ALL_CACHE);
if (cache != null) {
clearAllCache = cache.booleanValue();
} else {
cache = features.get(CLEAR_SESSION_CACHE);
if (cache != null) {
clearSessionCache = cache.booleanValue();
}
}
}
#SuppressLint("NewApi")
public void run() {
((InAppBrowserClient) client).setSSLErrorFlag(ignoreSSLError);
}
};
this.cordova.getActivity().runOnUiThread(runnable);
return "";
}
public class InAppBrowserClient extends WebViewClient {
EditText edittext;
CordovaWebView webView;
boolean ignoreSSLError = false;
#Override
public void onReceivedSslError(WebView view, SslErrorHandler handler,
SslError error) {
if(this.ignoreSSLError) {
handler.proceed();
return;
}
else{
super.onReceivedSslError(view, handler, error);
}
}
public void setSSLErrorFlag(boolean flag) {
this.ignoreSSLError = flag;
}
}
}
THEN ADD THIS LINE IN JAVASCRIPT
var options = {
location: 'yes',
//clearcache: 'no',
toolbar: 'yes',
//clearsessioncache:'no',
zoom:'no',
ignoresslerror:'yes'
};
$scope.init = function () {
$ionicPlatform.ready(function() {
$cordovaInAppBrowser.open('https://192.168.1.80', '_blank', options)
.then(function(event) {
})
.catch(function(event) {
});
});
AFTER DONE THIS COMPILE AND EXECUTE THAT'S IT
FULL VERSION CODE
Local https links are blocked by default in InAppBrowser (links using fake SSL certificate which can't be verified by a 3rd party). Ideally, user should be given an option to proceed or cancel the request like the default desktop browsers do.
Right now, we have to additional method for accessing fake ssl in the InAppBrowser like location,zoom,hardwareback

Related

Using Ionic (angular).Unable to access Hardware back button of mobile devices which have buttons inside the display/screen

I am facing a problem when I trying to access hardware back button so that I can produce an alert message to the user before the app get closed.
Initially I was unable to do , so I raised a question on stack overflow (link of the question) and with the help of the answers I almost solved my problem until I observed on some particular devices I unable to access the back button.
Noticing those devices which has back button inside the display (I think we can call this type of buttons as soft back button ) in those device I unable to produce alert box,to be more precise unable to access the back button.
But If I touch on the screen and than press the button, it is working fine . basically if someone just launch the app and presses the back button the app gets exit.
It is very difficult for me to write and produce my issue properly, therefore I am sharing a link of video please watch and try to understand and ask for any clarification
Link-1, The type of devices on which alert is not working
Link-2 On this type devices working fine
When you are in the app on another screen and press back button that time you go to the back screen. and when your screen is home or login, and that time within two seconds you press twice the time back button app is closed.
public astTimeBackPress = 0;
public timePeriodToExit = 2000;
constructor(
public toastController: ToastController,
private platform: Platform,
private nav: NavController,
private router: Router,
) { }
handleBackButton() {
this.platform.backButton.subscribe(() => {
if (this.loaderOff) {
document.addEventListener(
'backbutton',
() => {},
false);
} else {
if (
this.router.url === '/tabs/home' ||
this.router.url === '/signin'
) {
if (new Date().getTime() - this.lastTimeBackPress < this.timePeriodToExit) {
navigator['app'].exitApp();
} else {
this.presentToast('Press again to exit');
this.lastTimeBackPress = new Date().getTime();
}
} else {
this.nav.back();
}
}
});
}
async presentToast(msg, color = 'dark') {
const toast = await this.toastController.create({
color,
message: msg,
duration: 3000,
showCloseButton: true,
closeButtonText: 'Close',
});
toast.present();
}
public void callAlert(){
AlertDialog.Builder builder1 = new AlertDialog.Builder(appCompatActivity);
builder1.setMessage("Do you want to close.");
builder1.setCancelable(true);
builder1.setPositiveButton(
"Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
finish();
}
});
builder1.setNegativeButton(
"No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
callAlert();
return true;
}
return super.onKeyDown(keyCode, event);
}

Cef Sharp not showing popup window called using window.open

I've build an application using CefSharp.WinForms. All is good but when any website uses to show a popup using javascript window.open() it won't work.
I've implemented ILifeSpanHandler it working very fine for the links but fails when used window.open(). Can any one help me how to handle window.open().
EDIT-1 LifeSpanHandler Implementation
public class LifeSpanHandler : ILifeSpanHandler
{
public bool DoClose(IWebBrowser browserControl, IBrowser browser)
{
return false;
}
public void OnAfterCreated(IWebBrowser browserControl, IBrowser browser)
{
//throw new NotImplementedException();
}
public void OnBeforeClose(IWebBrowser browserControl, IBrowser browser)
{
//throw new NotImplementedException();
}
public bool OnBeforePopup(IWebBrowser browserControl, IBrowser browser, IFrame frame, string targetUrl, string targetFrameName, WindowOpenDisposition targetDisposition, bool userGesture, IWindowInfo windowInfo, ref bool noJavascriptAccess, out IWebBrowser newBrowser)
{
var chromiumWebBrowser = (ChromiumWebBrowser)browserControl;
ChromiumWebBrowser chromiumBrowser = null;
var windowX = windowInfo.X;
var windowY = windowInfo.Y;
var windowWidth = (windowInfo.Width == int.MinValue) ? 600 : windowInfo.Width;
var windowHeight = (windowInfo.Height == int.MinValue) ? 800 : windowInfo.Height;
chromiumWebBrowser.Invoke(new Action(() =>
{
var owner = chromiumWebBrowser.FindForm();
chromiumBrowser = new ChromiumWebBrowser(targetUrl)
{
LifeSpanHandler = this
};
chromiumBrowser.SetAsPopup();
var popup = new Form
{
Left = windowX,
Top = windowY,
Width = windowWidth,
Height = windowHeight,
Text = targetFrameName
};
owner.AddOwnedForm(popup);
//popup.Controls.Add(new Label { Text = "CefSharp Custom Popup" });
popup.Controls.Add(chromiumBrowser);
popup.Show();
}));
newBrowser = chromiumBrowser;
return false;
}
}

jQuery loading spinner not showing

I am developing android application and I am trying to show loading spinner while my html is being formatted, but the spinner is not showing and I have no idea why. Here is the code:
$.mobile.loading('show');
if (window.localStorage.getItem("UserTeams") != null && manual == false) {
$(window.localStorage.getItem("UserTeams")).appendTo("#listTeams");
$("#listTeams").listview("refresh").listview();
}
$.mobile.loading('hide');
Any ideas why the spinner is not showing?
Try to use native functions via JavaSriptInterface to show progress.
JavaScriptInterface:
private final class JavaScriptInterface {
public JavaScriptInterface() {
}
/* progressDialog is a field of Your Activity.
JavaScriptInterface is internal class of Your Activity. */
public void showDialog() {
if (progressDialog != null) {
if (!progressDialog.isShowing()) {
progressDialog = ProgressDialog.show(this, "", getString(R.string.common_loading_upper));
}
}
}
public void hideDialog() {
if (progressDialog != null) {
progressDialog.dismiss();
}
}
}
Register JavaScriptInterface:
webView.addJavascriptInterface(new JavaScriptInterface(), "myinterface");
JavaScript code to call dialog:
window.myinterface.showDialog();

How to have Android webview open links that are target “_blank” in default browser

How to have Android webview open links that are target “_blank” in default browser , i tried the following code but it still show all links with the webview , any one have a solution ?
public boolean shouldOverrideUrlLoading(WebView view, String url) {
String myAlternativeURL = "http://example.com";
if (!url.equals(myAlternativeURL)) {
{
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("http://example.com"));
startActivity(i);
}
return true;
} else {
view.loadUrl(url);
return true;
}
}

Safari issue with HttpContext.User.Identity

I try to play mp3 file, which is returned by MyAudio method from ContentController, through html5 audio tag. Following code:
[Authorize]
public class ContentController : Controller
{
private ContentServices Content { get; set; }
protected override void Initialize(RequestContext requestContext)
{
if (requestContext.HttpContext.User.Identity.isAuthenticated)
{
base.Initialize(requestContext);
}
}
public ActionResult MyAudio(string name)
{
var file = Server.MapPath("~/" + name);
return File(file, "audio/mp3");
}
Common html code
When the user is Authorized all works perfect in Chrome. But when I have tested it in Safari there is a strange mystery. The HttpContext.User.Identity.isAuthenticated returns false and of course code doesn't execute further.
The interesting thing is that when I use for example #Html.Action or #Html.RouteLink, HttpContext.User.Identity.isAuthenticated will return true.
I've tried to use javascript and jquery to solve the problem, but I also had wierd things at Safari.
<script type="text/javascript">
function getAudio() {
if (audio.src == "" || audio.src == null) {
// (1) audio.src = '#Url.Content("~/Content/MyAudio")' + "hello.mp3";
// (2) audio.src = '#Url.Action("MyAudio", "Content", new { name = "hello.mp3" } )';
/* (3) $.get('#Url.Content("~/Content/MyAudio")', {"name": "hello.mp3"},
function(data) {
alert("hello");
});
*/
audio.load();
audio.play();
}
}
</script>
Both (1) and (2) have the same problem. But when I use (3), HttpContext.User.Identity.isAuthenticated returns true at Safary. But I guess u can't give file stream through jquery.
Have anyone have an idea what's is go on nad how I can fix the problem?
PS I use ASP.NET Development Server and Safari 5.1.7 Win32 7.

Categories

Resources