How to add a custom error page in Cordova InAppBrowser or hide the error url?

4.2k views Asked by At

pleas check this attached image I'm building an Ionic Android app with the InAppBrowser plugin. When the internet connection is not available, the plugin shows web page not available and requesting url.

Please help me customise the InAppBrowser error page (404 page). Or help me hide the requesting url.

Thank you.

6

There are 6 answers

11
dloeda On

I think I misunderstood your problem, first time, sorry about that. I'm reading again your problem and I'm figuring out what's happening. You need to add a custom configuration at config.xml to redirect to an error page when Cordova detect it. I hope this solve your problem.

<preference name="ErrorUrl" value="myErrorPage.html"/>

The original response works when you want to open a link through Cordova inAppBrowser plugin. If this doesn't sort out your problem, please reformulate your question.

Original response

You could be listening inAppBrowser events to figure what's happening.

Here, you can see how listen browser events, such as loaderror and manage the 404 error as you want. You must save a reference to inAppBrowser when open method is called, and then you could listen for error event.

function loadErrorCallBack(params) {
    // Do stuff
}

inAppBrowserRef = cordova.InAppBrowser.open(url, target, options);
inAppBrowserRef.addEventListener('loaderror', loadErrorCallBack);
1
Ced On

I am using Ionic 4 and I couldn’t manage to make the solution based on config.xml editing to work :

preference name="ErrorUrl" value="myErrorPage.html"/

Placing an addEventListener on loaderror didn’t work neither. It looks like it is not triggered by http errors and the plugin need a fix.

But we found a hack that is much simpler.

On loadstop we wait 500 milliseconds and then we get the loaded url by triggering executeScript with and window.location.href

If the loaded url is of the custom error page, in Cordova (not in IAB) we display a custom message with a back button.

It's a hack but that cover the requirement for now

0
Konrad Gałęzowski On

I couldn't manage solution with setting ErrorUrl in Ionic 4 on Android to work.

Finally I came up with another solution - hide default error page and redirect user to any page (I use last page from event.url).

constructor(private iab: InAppBrowser) {
}

private openUrl(url: string)
{
    this.platform.ready().then(() => {
        if (this.platform.is('cordova')) {
            this.openBrowser(url);
        }
    });
}

private openBrowser(url: string): InAppBrowserObject
{
    const options: InAppBrowserOptions = {
        location: 'no',
        zoom: 'no',
        hidden: 'no'
    };

    const browser = this.iab.create(url, '_blank', options);

    browser.on('loaderror').subscribe(
        event => this.onLoadError(event, browser)
    );

    return browser;
}

private onLoadError(event: InAppBrowserEvent, browser: InAppBrowserObject): void
{
    browser.executeScript({
            code: `
                window.addEventListener('DOMContentLoaded', function () {
                    document.querySelector('body').style.background = 'black';
                    document.querySelector('body').innerHTML = '';
                }, true);

                window.addEventListener('load', function () {
                    window.location.replace('${event.url}');
                }, true);                    
            `,
        }
    ).then();
}

Changing background and redirecting is tricky - from my experiments using injectCss won't work, because body is generated in the meantime. Using DOMContentLoader makes it black and clears text on screen. But redirecting won't work in DOMContentLoader (don't ask me why), so you need to use load event.

It works great when user is using hardware back and returns to POST request - this way he will be redirected to GET of the same url (but you can use any url you want).

0
Bax On

For Cordova inappbrowser offline error

  1. Create error.html in www folder next to index.html
  2. install cordova plugin (cordova-plugin-network-information)
  3. update index.js by following code

Code starts from here |

document.addEventListener('deviceready', onDeviceReady, false);

function onDeviceReady() {

document.addEventListener("offline", onOffline, false);
document.addEventListener("online", onOnline, false);

function onOffline() {
  cordova.InAppBrowser.open('error.html', '_self');
}

function onOnline() {
  cordova.InAppBrowser.open('https://google.com', '_blank', 'location=no, toolbar=no');
}

console.log('Running cordova-' + cordova.platformId + '@' + cordova.version);
document.getElementById('deviceready').classList.add('ready');

}

| Code ends here.

make sure you copy entire code from start to end not just colorful rectangle. (don't include "Code starts from here |" and "| Code ends here".

it works for me.

0
Danny Mora On

When the components do not work, I perform the following procedure

  • ionic state reset

  • ionic platform remove android

  • ionic platform remove ios

  • ionic platform add android

  • ionic platform add ios

and try with ionicPlatform ready

<button class="button button-balanced" ng-click="OpenBrowser()">Test</button>

In controller

    $scope.OpenBrowser = undefined;
    $ionicPlatform.ready(function () {
        $scope.OpenBrowser = function () {
            $cordovaInAppBrowser.open('http://ngcordova.com', '_blank', options)
                .then(function (event) {
                })
                .catch(function (event) {
                    $scope.Error = event;
                });
        };
    });
0
Nargesh Rana On

I just came across the same problem and here's what I did. The code is for Android and works on IOS as well. But you would want to remove navigator.app.exitApp(); for IOS as Apple does not allow apps to take exit without pressing the home button.

Let me know if this works for you. It will hide default error page and open your custom error page. Write your own error code in myerrorpage.html

document.getElementById("openBrowser").addEventListener("click", openBrowser);

document.addEventListener("offline", onOffline, false);

function onOffline(e) {
    e.preventDefault();
    var src = 'myErrorPage.html';
    var target = '_blank';
    var option = "loaction=no, toolbar=no, zoom=no, hidden=yes, hardwareback=no";
    var ref = cordova.InAppBrowser.open(src, target, option);
    alert('Your device is Offline. Please check your connection and try again.');
    navigator.app.exitApp();

}

function openBrowser() {
    var url = 'https://www.yourlink.com';
    var target = '_self';
    var options = "location=no,toolbar=no,zoom=no, hardwareback=no, hidden=yes" ;
    var ref = cordova.InAppBrowser.open(url, target, options);

}