Month: June 2018

How To Debug White Screen Ionic error on devices

How To Debug White Screen Ionic error on devices

Debug White Screen Ionic error on devices

This type of error occurs when your Ionic app is working fine in your desktop browser (ionic serve) and then you deploy it to a device or emulator and it doesn't work at all! What you see is a white screen when you open the app.
It is easy to debug your ionic app when doing `ionic serve` you just open the browser's console, but once you deploy to a device or emulator, it is easy to know what is causing the error since the device doesn't have a console to see JavaScript errors.

There are two ways to figure out what is happening one is using the cli livereload with consolelogs when using run or emulate command, and the second one is using the chrome developer tool.

Ionic livereload with consolelogs

note:
You can only use --consolelogs if you also use --livereload.

The --livereload option will instantly reload/update the app on your device or emulator it is similar to when you run ionic serve for testing your app on the desktop browser, the --consolelogs will log on the cmd console all the JavaScript error, etc. providing feedback of what is happening.

ionic run android --livereload --consolelogs

You can use the shorthand version:

ionic run android -l -c

Chrome Developer Tool

You need to configure your device to enable developer mode. For more information go here: https://developers.google.com/web/tools/chrome-devtools/remote-debugging/

Now you need to run your app on an Android device, you can attach the Chrome Developer Tools to the app and see the error in the Console, you need to connect your device with a USB cable to your computer, open your desktop Chrome browser and type chrome://inspect on the address bar.

You should see your device listed, click on inspect and from there you can use the Developer Tools the same way you use it for your desktop browser when do ionic serve. You should see the error causing the white screen, and any other relevant information like the console.log() that you placed on your ionic app code.

This doesn't work for iOS and Safari web inspector, the most universal way is to use the --livereload option, which will work for both iOS and Android.

Happy Coding,
Cheers

Add to Home Screen your ionic PWA

Add to Home Screen your ionic PWA

add-to-home-screen

One of the feature of Progressive Web Apps is the ability to add to home screen your application, in a mobile phone or on a desktop computer, if using Chrome (recommended) it handles most of the heavy lifting for you, and on Android, Chrome will generate a WebAPK creating an even more integrated experience for your users.

Starting on Chrome 68 (beta in early June 2018), Chrome will not automatically show the Add to Home Screen banner, instead, you must show it by calling prompt() on the beforeinstallprompt event.

Criteria to fire the "beforeinstallprompt" event

- The web app is not already installed
- Meets a user engagement heuristic (currently, the user has interacted with the domain for at least 30 seconds)
- Includes a web app manifest that includes:
   short_name or name
   icons must include a 192px and a 512px sized icons
   start_url
   display must be one of: fullscreen, standalone, or minimal-ui
- Served over HTTPS (required for service workers)
- Has registered a service worker with a fetch event handler

Note: Other browsers may have different criteria to trigger the beforeinstallprompt event, check their respective sites for full details: Edge, Firefox, Opera.

Show the add to home screen prompt

In order to prompt to the users the Add to Home Screen prompt, you need to:

1- Listen for the beforeinstallprompt event
2- Notify the user your app can be installed with a button or other element that will generate a user gesture event.
3- Show the prompt by calling prompt() on the saved beforeinstallprompt event.

let deferredPrompt;

window.addEventListener('beforeinstallprompt', (e) => {
  // Prevent Chrome 67 and earlier from automatically showing the prompt
  e.preventDefault();
  // Stash the event so it can be triggered later on the button event.
  deferredPrompt = e;
// Update UI by showing a button to notify the user they can add to home screen
  btn.style.display = 'block';
});

//button click event to show the promt
btn.addEventListener('click', (e) => {
  // hide our user interface that shows our button
  btn.style.display = 'none';
  // Show the prompt
  deferredPrompt.prompt();
  // Wait for the user to respond to the prompt
  deferredPrompt.userChoice
    .then((choiceResult) => {
      if (choiceResult.outcome === 'accepted') {
        console.log('User accepted the prompt');
      } else {
        console.log('User dismissed the prompt');
      }
      deferredPrompt = null;
    });
});

You can only call deferredPrompt.prompt() on the deferred event once, if the user dismissed it, you'll need to wait until the beforeinstallprompt event is fired on the next page navigation.

How to determine if the app was installed

To determine if the application was successfully added to the user's home screen once they accepted the prompt, you need to listen for the appinstalled event.

window.addEventListener('appinstalled', (event) => {
 console.log('installed');
});

Detecting with JavaScript if you app is launched from the home screen

if (window.matchMedia('(display-mode: standalone)').matches) {
  console.log('display-mode is standalone');
}

Safari

if (window.navigator.standalone === true) {
  console.log('display-mode is standalone');
}

Easiest way to test if the beforeinstallprompt event will be fired

Easiest way is to use Lighthouse to audit your app, and check the results of the User Can Be Prompted To Install The Web App test.

Practical example with ionic

For this example I going to use ionic, we are going to generate a PWA with ionic, for this example I assume you are familiar with ionic and you have installed it on your computer, if not, then you can read the here

Lets generate our ionic app:

After you create the ionic blank app, lets run ionic serve:

cd pwa
ionic serve

You should see something like this on your browser:

Open your application using google chrome, open the dev tool, go to audit and run the Progressive web app audit:

You'll notice that the app is only 45% PWA out of the box, we should make some changes first to comply with the requirements to trigger the beforeinstallprompt event:

Registering the service worker

Open the ionic app on your preferred IDE (I'll use Microsoft code) and go to ./src/index.html and uncomment this line:

<!-- un-comment this code to enable service worker
  <script>
    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.register('service-worker.js')
        .then(() => console.log('service worker installed'))
        .catch(err => console.error('Error', err));
    }
  </script>-->

The another requirement is to have a manifest.json, fortunately ionic generates one for us:

{
  "name": "Ionic",
  "short_name": "Ionic",
  "start_url": "index.html",
  "display": "standalone",
  "icons": [{
    "src": "assets/imgs/logo.png",
    "sizes": "512x512",
    "type": "image/png"
  }],
  "background_color": "#4e8ef7",
  "theme_color": "#4e8ef7"
}

Now lets provide a fallback when JavaScript is not available by just adding a < noscript > tag on the index:

<noscript>
This application needs JavaScript to work, please enable JavaScript on your browser
</noscript>

With just that, we were able to go from 45 to 82:

Now we need to deploy our app to firebase hosting to be able to have HTTPS, and a 100 score on the lighthouse.

Install firebase tools

npm install -g firebase-tools

Initialize your site

$ firebase init

To deploy your site, run the following command from your project's root directory:

$ firebase deploy

For more info go to https://firebase.google.com/docs/hosting/deploying

Now you can sun the lighthouse tool and obtain a 100 score:

Capturing the event

Go back to the ionic app code, locate the pages folder on src/pages/home and edit the home.html and home.ts as follow:

home.html

<ion-header>
  <ion-navbar>
    <ion-title>
      Ionic Blank
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  The world is your oyster.
  <p>
    If you get lost, the <a href="http://ionicframework.com/docs/v2">docs</a> will be your guide.
  </p>
  <button class="btn" ion-button full (click)="add_to_home(event)" *ngIf="showBtn" >Install</button>
</ion-content>

home.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  showBtn: boolean = false;
  deferredPrompt;
  constructor(public navCtrl: NavController) {
    
  }

  ionViewWillEnter(){
    window.addEventListener('beforeinstallprompt', (e) => {
      // Prevent Chrome 67 and earlier from automatically showing the prompt
      e.preventDefault();
      // Stash the event so it can be triggered later on the button event.
      this.deferredPrompt = e;
      
    // Update UI by showing a button to notify the user they can add to home screen
      this.showBtn = true;
    });
    
    //button click event to show the promt
            
    window.addEventListener('appinstalled', (event) => {
     alert('installed');
    });
    
    
    if (window.matchMedia('(display-mode: standalone)').matches) {
      alert('display-mode is standalone');
    }
  }

  add_to_home(e){
    debugger
    // hide our user interface that shows our button
    // Show the prompt
    this.deferredPrompt.prompt();
    // Wait for the user to respond to the prompt
    this.deferredPrompt.userChoice
      .then((choiceResult) => {
        if (choiceResult.outcome === 'accepted') {
          alert('User accepted the prompt');
        } else {
          alert('User dismissed the prompt');
        }
        this.deferredPrompt = null;
      });
  };

}

Test in your browser

To test the functionality, we could make some changes on chrome to force to trigger the event (taken from here https://stackoverflow.com/a/50626433/4320602)

For security reasons, as others have written as well, browsers don't allow you to manually trigger the install event.

However, there is a way you can test it yourself. Go to chrome://flags and enable "Bypass user engagement checks"

This will kick off the prompt so you can test.

now run your app and click on the install button, you should see something like this:

Now the app will run as standalone app:

Happy coding,
Cheers

How to install Multiple Versions of Node Using nvm

How to install Multiple Versions of Node Using nvm

nvm

Keep up with the latest technology and frameworks is hard, specially If you are into the JavaScript/Node environment and surrounded technology, not to mention about the npm and the version incompatibility issues. I've been working lately on create ionic starters to help developers to have an starting point to create ionic applications faster. You can find the starters on the ionic market, here's a list in case you are interested:
https://market.ionicframework.com/starters/ionappfull4pro
https://market.ionicframework.com/starters/ionpushempro
https://market.ionicframework.com/starters/ionshopping
https://market.ionicframework.com/starters/ionrestaurant

Keep up with ionic and packages versions

Ionic is a great technology, you can create multi-platform app with one code base, create PWAs, etc. The problem is when you try to use/run an ionic app made in another environment (using different node version, etc.) on your recently created environment (latest Node.js version), one of the most commons issues is related to the installed Node.js version of the user that are trying to make the code run. This is not only valid to ionic, but to any code that relays on Node.

Lets install the same Node version used to create the original code, and problem solved?

You can certainly do that, and if that's your case, that's it, you are done, problem solved, but what happen if you have more than one Node projects on your computer, that could need to use older versions of node, this is a very common scenario for people that works heavily with different projects and different package versions.

nvm to the rescue

It stands for Node Version Manager. As the name suggests, it helps you manage and switch between different Node versions with ease. It provides a command line interface where you can install different versions with a single command, set a default, switch between them and much more.

Installation

I'm going to focus on windows for this article, if you have a different OS, you can find information on it's official github repo https://github.com/creationix/nvm.

First, make sure you uninstall any Node.js version you might have on your system, as they can collide with the installation. After this, download the latest stable installer here. Run the executable installer, follow the steps provided and you’re good to go!

Installing multiple Node.js Versions

If installed correctly, the nvm command is available anywhere in you terminal. You can run nvm -v command in your terminal to make sure, a list with the help instructions should show.

Managing, installing and switching Node.js versions

To install the latest Node.js version, you can just run:

nvm install node

To install specific version:

nvm install 8.9.4

If you want to install, for example, the latest 8.9 patch, it will then install Node.js version 8.9.X, where X is the highest available version, you can do it by running the following command:

nvm install 8.9

To see the full list of available versions:

nvm ls

You can also uninstall any instance you no longer think is useful, by running:

nvm uninstall 8.9.4

Switching between Versions

To switch through installed versions, nvm provides the nvm use command. This works similar to the install command. So, you need to follow this by a version number, for example:
switch to Node.js version 8.9.4:

nvm use 8.9.4

switch to Node.js version 9.3.0:

nvm use 9.3

switch to latest Node.js version

nvm use node

As you can see it is super easy, hope this helps you.

Cheers