如何在用户端只运行一次脚本?

时间:2013-11-21 05:01:54

标签: javascript html

例如,当用户第一次输入网址时, 将出现像“喜欢我们FB上的页面”这样的弹出窗口。

当用户浏览网站并返回首页时, 不应出现上方弹出窗口。

如果我使用window.onload或脚本, 每次加载页面时都会出现。

还有其他办法吗?

谢谢。

2 个答案:

答案 0 :(得分:4)

您可以使用Cookie:http://www.w3schools.com/js/js_cookies.asp

或HTML5网络存储:http://www.w3schools.com/html/html5_webstorage.asp

虽然支持Cookie得多得多......

基本的想法是存储一个cookie,说明你显示了弹出窗口,每当你重新加载主页时,你会检查cookie是否存在。如果存在,则不需要弹出窗口,否则显示弹出窗口。

答案 1 :(得分:1)

您可以执行此操作using cookies。转到我的demo here,你会看到消息,然后,如果你刷新你不会!

//check if we've asked them before (in the last 5 minutes)
if (!(new RegExp('homeFacebookMessage=true')).test(document.cookie)) {
    //take a temporary (5min) note that we've asked them
    document.cookie = 'homeFacebookMessage=true;path=/;max-age=' + 5 * 60 + ';';
    //ask them (your code here)
    alert('Like us on faceface!');
}

你甚至可以尝试一些Web Storage,它将一直运行到IE8。这是a demo

//check if we have asked them already
if (!localStorage.getItem('homeFacebookMessage')) {
    //make a note that we've asked them
    localStorage.setItem('homeFacebookMessage', 'true');
    //ask them (your code here)
    alert('Like us on faceface!');
}

localStorage的区别在于它是永久性的,并且在5分钟后(当我们的cookie在第一个示例中到期时)不会提醒用户“喜欢”。
但是,如果你真的喜欢网络存储方法,你可以为homeFacebookMessage分配一个日期/时间,并检查多久以前它而不是简单地测试它的存在以获得相同的效果。

相关问题