How to call a function when installing application in Cordova

682 views Asked by At

I want to call a function when installing A Cordova/Phonegap application (for create database and insert records to that).

In fact I just wanna run this function only once.

Any suggestion?

2

There are 2 answers

0
Ivan Gabriele On BEST ANSWER

You can use LocalStorage for that :

document.addEventListener('deviceready', function()
{
    if (typeof window.localStorage.getItem('firstTime') === 'undefined')
    {
        // Execute some code for the installation
        // ...

        window.localStorage.setItem('firstTime', 0);
    }
});
0
vortex On

While adding an event listener to effectively run a single time, as in Ivan's answer, is correct, the syntax needs to be slightly different.

When running the following code:

console.log("First time?");
console.log(window.localStorage.getItem('firstTime'));
console.log(typeof window.localStorage.getItem('firstTime'));
console.log(typeof window.localStorage.getItem('firstTime') === 'undefined');

The following is seen in the Javascript console:

First time?
null
object
false

Additionally, the Mozilla documentation for Storage.getItem() says it returns 'null' when a non-existent key is requested:

Returns

A DOMString containing the value of the key. If the key does not exist, null is returned.

Thus, to make this work, I needed to use the following code:

document.addEventListener('deviceready', function()
{
    if (window.localStorage.getItem('firstTime') == null)
    {
        // Execute some code for the installation
        // ...

        window.localStorage.setItem('firstTime', 0);
    }
});