如何在Laravel7环境下实现整点弹出模态框及桌面通知提醒用户提交报告?
实现方案
1. 整点触发模态框逻辑调整
原有固定间隔setInterval无法对齐整点,调整为先计算距离下一个整点的延时触发首次请求,之后按1小时间隔循环,同时增加10:00~18:00的时间范围校验,以及同小时重复弹出拦截。
2. 桌面通知实现
需要先向用户申请浏览器通知权限,权限验证通过后即可在整点同步推送桌面提示。
完整实现代码
// 记录最后一次弹出模态框的小时,避免同小时重复触发 let lastPopHour = null; // 定时器实例,方便后续清理 let timer = null; // 初始化桌面通知权限 function initNotificationPermission() { if (!('Notification' in window)) { console.log('浏览器不支持桌面通知'); return; } // 申请通知权限 if (Notification.permission !== 'granted' && Notification.permission !== 'denied') { Notification.requestPermission(); } } // 推送桌面通知 function sendNotification() { if (!('Notification' in window) || Notification.permission !== 'granted') { return; } new Notification('工作报告提交提醒', { body: '请提交你的报告', icon: '/favicon.ico' // 可替换为你站点的图标路径 }); } $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); function get_task_data() { const now = new Date(); const currentHour = now.getHours(); // 不在10~18点范围内,或当前小时已经弹过,直接返回 if (currentHour < 10 || currentHour >= 18 || currentHour === lastPopHour) { // 超过18点直接清理定时器,不再触发 if (currentHour >= 18 && timer) { clearInterval(timer); timer = null; } return; } $.ajax({ url: '{{ route('project.employee.task') }}', type: 'GET', data: {} }).done(function(data){ // 后端可判断用户当前小时是否已提交报告,已提交则返回空或特定标识,前端不弹窗 if (!data) return; lastPopHour = currentHour; $('#myModal .modal-body').empty().append(data); // 先清空再追加,避免旧内容残留 $('#myModal').modal('show'); // 同步推送桌面通知 sendNotification(); }); } function initHourlyTrigger() { const now = new Date(); const currentHour = now.getHours(); // 当前时间超过18点,当天不再触发 if (currentHour >= 18) return; // 计算下一个整点的时间 const nextHour = currentHour < 10 ? 10 : currentHour + 1; const nextFullHour = new Date(now.getFullYear(), now.getMonth(), now.getDate(), nextHour, 0, 0, 0); // 首次触发的延时毫秒数 const firstDelay = nextFullHour.getTime() - now.getTime(); // 首次到整点触发,之后每小时触发一次 setTimeout(() => { get_task_data(); timer = setInterval(get_task_data, 3600000); }, firstDelay); // 如果当前刚好是10~18点的整点,立即触发一次 if (currentHour >=10 && currentHour <18 && now.getMinutes() === 0 && now.getSeconds() < 10) { get_task_data(); } } // 页面加载完成后初始化 $(function() { initNotificationPermission(); initHourlyTrigger(); });
后端优化建议(可选)
在Laravel的project.employee.task路由对应方法中,增加当前用户当前小时报告提交状态的判断:如果用户已经提交过当前小时的工作报告,直接返回空内容或状态标识,前端接收后不弹出模态框,避免重复打扰已提交报告的用户。
内容的提问来源于stack exchange,提问作者developer3 onecity
相关产品推荐
相关产品推荐

