在 Cordova 中安装应用程序时如何调用函数
How to call a function when installing application in Cordova
我想在安装 Cordova/Phonegap 应用程序时调用一个函数(用于创建数据库并向其中插入记录)。
其实我只想运行这个函数只用一次。
有什么建议吗?
你可以使用 LocalStorage :
document.addEventListener('deviceready', function()
{
if (typeof window.localStorage.getItem('firstTime') === 'undefined')
{
// Execute some code for the installation
// ...
window.localStorage.setItem('firstTime', 0);
}
});
虽然像 一样添加事件侦听器以有效 运行 一次是正确的,但语法需要略有不同。
当运行宁以下代码:
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');
在 Javascript 控制台中看到以下内容:
First time?
null
object
false
此外,Storage.getItem() 的 Mozilla 文档说 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.
因此,为了完成这项工作,我需要使用以下代码:
document.addEventListener('deviceready', function()
{
if (window.localStorage.getItem('firstTime') == null)
{
// Execute some code for the installation
// ...
window.localStorage.setItem('firstTime', 0);
}
});
我想在安装 Cordova/Phonegap 应用程序时调用一个函数(用于创建数据库并向其中插入记录)。
其实我只想运行这个函数只用一次。
有什么建议吗?
你可以使用 LocalStorage :
document.addEventListener('deviceready', function()
{
if (typeof window.localStorage.getItem('firstTime') === 'undefined')
{
// Execute some code for the installation
// ...
window.localStorage.setItem('firstTime', 0);
}
});
虽然像
当运行宁以下代码:
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');
在 Javascript 控制台中看到以下内容:
First time?
null
object
false
此外,Storage.getItem() 的 Mozilla 文档说 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.
因此,为了完成这项工作,我需要使用以下代码:
document.addEventListener('deviceready', function()
{
if (window.localStorage.getItem('firstTime') == null)
{
// Execute some code for the installation
// ...
window.localStorage.setItem('firstTime', 0);
}
});