简体   繁体   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

I have a code that will refresh the page on button click , but when i give only to refresh once in a day , it's not allowing me to refresh .我有一个代码可以在单击按钮时刷新页面,但是当我每天只刷新一次时,它不允许我刷新。 and sometimes when i load the page it will not allow me to refresh the page .有时当我加载页面时,它不允许我刷新页面。

 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>

I had already referred post related to this on StackOverflow .我已经在 StackOverflow 上提到了与此相关的帖子。

This should work, although I could not test it as you are not allowed to set a cookie on a third-party website.应该可以工作,但我无法测试它,因为您不允许在第三方网站上设置 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