如何使用javascript在1天内只显示1次弹出窗口

时间:2017-12-04 13:04:59

标签: javascript html popup

我有这样的代码。我希望在1天内只显示一次弹出。

<script type="text/javascript">
    var popup = function() {
        window.open ("http://example.com", "Window","status=1,toolbar=1");
    }
</script>
<body onclick="popup()">    </body>

当我点击页面上的任何地方时,代码会弹出,但每次点击都会弹出一个窗口,所以我想让弹出窗口只显示1天内的一次。

3 个答案:

答案 0 :(得分:0)

您可以使用localStorage或Cookie来存储上次显示弹出窗口的时间。如果当前时间与最后一次之间的差异大于24小时,您将呈现弹出窗口。

答案 1 :(得分:0)

您需要使用浏览器的LocalStorage,以了解用户看到弹出窗口的内容,并且每天都不会显示更多内容。

您可以使用:

localStorage.setItem('PopupName', 'true')
localStorage.getItem('PopupName') // that return true

使用此方法,您可以调用一个函数来检查该变量是否已存在于LocalStorage中,如果它不存在,则执行显示弹出窗口的代码并在LocalStorage中设置变量,如示例所示。

答案 2 :(得分:0)

您需要在last-shown中保存localstorage时间戳,并将其与当前时间戳进行比较(在剥离小时/分钟/秒/毫秒后)

演示请仅在本地查看

&#13;
&#13;
<script type="text/javascript">
  var popup = function() {
    var lastShownTs = +localStorage.getItem("lastShown");
    var currentDate = new Date();
    currentDate.setHours(0, 0, 0, 0);
    var lastShown = null;
    if (!isNaN(lastShownTs)) {
      lastShown = new Date(lastShownTs);
      lastShown.setHours(0, 0, 0, 0);
    }
    if (lastShown == null || lastShown.getTime() != currentDate.getTime()) {
      window.open("http://example.com", "Window", "status=1,toolbar=1");
      localStorage.setItem("lastShown", currentDate.getTime());
    }
  }
</script>

<body onclick="popup()"> </body>
&#13;
&#13;
&#13;