簡體   English   中英

如何在單擊按鈕時每天僅刷新一次頁面(加載頁面后)並使用 Javascript 打印上次刷新的時間

[英]How to refresh a page only once in a day (after loading the page) on a button click and print the time of last refresh using Javascript

我有一個代碼可以在單擊按鈕時刷新頁面,但是當我每天只刷新一次時,它不允許我刷新。 有時當我加載頁面時,它不允許我刷新頁面。

 function CheckRefresh(){ var lastRefresh = new Date(); setInterval(function(){ var now = new Date(); if (new Date() - lastRefresh > 1000 * 60 * 60 * 24) { location.reload(); } },60000); //Console.log(lastrefresh); }
 <button type="button" data-toggle="tooltip" onClick="CheckRefresh()" data-placement="bottom" class="btn-shadow mr-3 btn btn-dark">Refresh</button>

我已經在 StackOverflow 上提到了與此相關的帖子。

應該可以工作,但我無法測試它,因為您不允許在第三方網站上設置 cookie。

 <!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> <button id="refresh" type="button" data-toggle="tooltip" data-placement="bottom" class="btn-shadow mr-3 btn btn-dark">Refresh</button> <script> const setRefreshCookie = () => { const now = new Date(); const tomorrow = new Date(); /* * if you want the cookie to expire after 24 hours from the last click * on the refresh button, you use only 'tomorrow.setTime()' otherwise, * if you want the cookie to expire as soon as the date changes (even if * 24 hours have not passed yet) you use both 'tomorrow.setTime()' and * 'tomorrow.setHours()' */ tomorrow.setTime(now.getTime() + 1000 * 60 * 60 * 24); tomorrow.setHours(0, 0, 0, 0); document.cookie = 'preventRefesh=true;expires=' + tomorrow.toUTCString() + 'domain=yourdomain.tld;path=/path/to/page'; }; const checkRefreshCookie = () => { return document.cookie.split('; ').some(cookie => cookie.split('=')[0] === 'preventRefesh'); }; const refreshBtn = document.getElementById('refresh'); const isRefreshCookieSet = checkRefreshCookie(); document.addEventListener('load', () => { if (isRefreshCookieSet ) { /* * disable the button, so that the user has a visual feedback */ refreshBtn.setAttribute('disabled', true); } }); refreshBtn.addEventListener('click', (event) => { if (!isRefreshCookieSet ) { setRefreshCookie(); // location.reload(); console.log('refeshing the page...'); } event.preventDefault(); event.stopPropagation(); }); </script> </body> </html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM