Phonegap - Local storage not working - Android

£可爱£侵袭症+ 提交于 2019-12-21 15:10:06

问题


I'm using Local Storage to pass values between pages in order to create a scroll to effect (user clicks link and is scrolled to particular part of the page based on ID)

I was previously using cookies but that didn't seem to work on Android, I read that local storage was supported so switched over to that. It works completely fine when in the browser but as soon as its packaged as a native app I lose all functionality? The API states that it should be supported, any ideas?

Here's my code:

Base URL:

var storage = window.localStorage;
$("a.scroll_link").click(function(event) {
    event.preventDefault();
    var value = $(this).attr("id");

        storage.setItem("key",value);

    console.log(value);

    window.location=$(this).attr("href");
});

Receiving URL:

$(function () { 

var value = window.localStorage.getItem("key");

if (value != "" && value != "undefined" && value != null) {
    var storage = window.localStorage;
    storage.setItem("key",value);
    var scroll_type = "";

    if ($.browser.webkit) {
        scroll_type = "body";
    } else {
        scroll_type = "html";
    }

    $(scroll_type)
        .stop()
        .animate({
        //get top-position of target-element and set it as scroll target
        scrollTop: ($("#" + value).offset().top - 25)
        //scrolldelay: 1.5 seconds
    }, {
        duration: 1500,
        complete: function () {
            storage.removeItem("key");
        },
    });
  }
});

The code works fine in the browser just not natively, any ideas?

Thanks,


回答1:


Use document.addEventListener("deviceready", onDeviceReady, false) instead of $(function(){...}

http://docs.phonegap.com/en/2.5.0/cordova_events_events.md.html#deviceready




回答2:


1.Glad to know you solve your first problem. As gmh04 say, I think you should replace your init event with 'deviceready' which is triggered when the app start running.

2. You mean window.localStorage.getItem("key") return null in Receiving URL? I do not exactly encounter a problem as what you describe. However, you may try to move your code in receiving url to the same page of base url. I have tried for times and be very sure that the localStorage will work in the same page.




回答3:


I would like add that there's a bug on the 2.6.0 version of cordova.js that make localStorage don't work on Android:

https://issues.apache.org/jira/browse/CB-3063

On the 2.5.0 version it works perfectly, and it is already fix on the 2.7.0 rc.



来源:https://stackoverflow.com/questions/15157245/phonegap-local-storage-not-working-android

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