Why does cordova-plugin-nativestorage work on browser but not on phone

笑着哭i 提交于 2019-12-08 07:14:54

问题


I am using the Phonegap CLI to serve my project and my plugin version is: 2.3.1 So, I wrote the following code to execute after the device is ready:

NativeStorage.getItem("abcd",function(){
			console.log("success");alert("success");
		},function(){
			console.log("fail");alert("failed :)");
		});

This works perfectly when I am testing it on my browser. However, when I open this app on my android phone, the NativeStorage code does not work at all.

I used weinre to debug my app:

I got the error: ReferenceError: NativeStorage is not defined

I also removed the plugin and all the platforms and reinstalled them again; however, I am still getting the same error.

Can you please help me find the issue ?


回答1:


Are you waiting that your device is ready, before you are calling the NativeStorage plugin?

In your index.js you should add something like the following code for the device handling.

if (window.cordova) {
  document.addEventListener("deviceready", onDeviceReady, false);
}

Note: If you want to use your app in the browser without the Cordova container, you should define an else branch like this. If its not a Cordova container, it will jump to the else branch and execute the function immediately.

if (window.cordova) {
  document.addEventListener("deviceready", onDeviceReady, false);
} else {
  onDeviceReady();
}

document.addEventListener("deviceready", onDeviceReady, false)

  • Parameter 1 - "deviceready": The name of the event
  • Parameter 2 - onDeviceReady: The name of your function to starts your application. The name can of course differ to my name.
  • Parameter 3 - false (optional): A Boolean value that specifies whether the event should be executed in the capturing or in the bubbling phase. (Source: w3schools.com)

For more information about the addEventListener: https://www.w3schools.com/jsref/met_document_addeventlistener.asp

In your "onDeviceReady" function or later, you can now call the plugins you have defined in the config.xml

E.g.:

function onDeviceReady() {
  //call your plugins
  NativeStorage.getItem(<...>);
}

Hope it helps.



来源:https://stackoverflow.com/questions/51042997/why-does-cordova-plugin-nativestorage-work-on-browser-but-not-on-phone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!