Simulate session cookies in mobile sessions?

前端 未结 5 1775
清歌不尽
清歌不尽 2020-12-31 04:42

I discovered to my astonishment at the first glance that my thinking of how session cookies behave on mobile devices is overruled by reality.

On normal desktop brows

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-31 05:22

    Would it make sense for you to go the HTML5 way and use sessionStorage?

    This way you could be independent of the way different devices handle browser sessions, since HTML5 session storage is per-window, thus it is limited to the lifetime of the browser window.

    Basically all mobile devices support sessionStorage (see here) and you could have a framework/plugin like jQuery-Session-Plugin (follow this link) handle the session data for you (and provide a fallback to session cookies for old browsers that don't support sessionStorage).

    EDIT: In order to show the behavior of sessionStorage vs. localStorage, I've created a fiddle that (for demonstration purpose) uses sessionStorage for storing the width of a div and localStorage for storing the height of the same div:

    var randomWidth,
        randomHeight;
    if (!(randomWidth= $.session.get("randomWidth"))) {    // assignment
        randomWidth = Math.random() * 300;
        $.session.set("randomWidth", randomWidth, true);
        console.log("just assigned and stored in sessionStorage: randomWidth: " + randomWidth);
    } else {
        console.log("from sessionStorage: randomWidth: " + randomWidth);
    }
    if (!(randomHeight= $.domain.get("randomHeight"))) {    // assignment
        randomHeight = Math.random() * 300;
        $.domain.set("randomHeight", randomHeight, true);
        console.log("just assigned and stored in localStorage: randomHeight: " + randomHeight);
    } else {
        console.log("from localStorage: randomHeight: " + randomHeight);
    }
    $(".test").css({width: randomWidth, height: randomHeight});
    

    Look at the console. You will see that when you initiate a new session of your client browser, the width will variate while the height will stay the same (because local Storage is per domain).

    Here is the link to jsfiddle

提交回复
热议问题