如何制作饼干并记住iphone / android设备的答案?

时间:2014-10-03 14:09:16

标签: javascript cookies

我在index.html中有这段代码

if((navigator.userAgent.match(/iPhone/i)) ) {
            if (document.cookie.indexOf('iphone_redirect=false') == -1) {
                if (confirm('for your device exist iphone app')) {
                    window.location = 'https://itunes.apple.com/us/app/....';
                }
            }
        }


        var ua = navigator.userAgent.toLowerCase();
        var isAndroid = ua.indexOf('android') > -1;
        if(isAndroid) {
            if (confirm('for your device exist iphone app')) { 
                window.location = 'https://play.google.com/store/apps/details?id=...';
            }
        }

但我不知道如何让cookie记住我的答案。如果用户单击“取消”或“确定”以记住“取消”或“确定”,直到用户清理缓存。

你知道如何让cookie记住回答吗?

1 个答案:

答案 0 :(得分:0)

使用 localStorage (将其设为默认值 falsey

// save a flag
window.localStorage.setItem('iphone_no_redirect', 'true'); // any truthy string

// check a flag
if (window.localStorage.getItem('iphone_no_redirect')) {
     // this has a truthy value
} else {
     // this has a falsey value ("" or null)
}

// remove a flag
window.localStorage.removeItem('iphone_no_redirect');

// make flag falsy without removing it, set to ""
window.localStorage.setItem('iphone_no_redirect', '');

如果您想知道标志是否设置且是否为假,则可以检查null

// flag set but falsey
var x = window.localStorage.getItem('iphone_no_redirect');
if (!x && x !== null) { // x is falsey, x is not null
    // ...
}

将此与confirm

相结合
function ask(question, key, overwrite) {
    var response;
    if (!overwrite) { // if not overwriting, check first
        response = window.localStorage.getItem(key);
        if (response !== null) { // has been asked before
            if (['', 'false', 'no', '0', 'null', 'undefined'].indexOf(response) !== -1)
                return false; // negative answers
            return true; // anything else is a positive answer
        }
    }
    if (overwrite === 2) { // easy cleanup
        window.localStorage.removeItem(key);
        return; // die
    }
    // not been asked before or we are overwriting previous answer
    response = confirm(question);
    window.localStorage.setItem(key, response.toString()); // "true" or "false"
    return response;
}

行动中

console.log(ask('Are you human?', 'is_human')); // this causes confirm dialog
console.log(ask('Are you human?', 'is_human')); // this doesn't need to ask

// changing a previous answer
console.log(ask('Are you human?', 'is_human', 1)); // this causes confirm dialog again

// cleanup
ask(null, 'is_human', 2); // (don't need question for this)