当前位置:首页 > JavaScript

js实现弹窗关闭后刷新

2026-04-04 22:09:00JavaScript

使用window.location.reload()方法

在弹窗关闭时调用window.location.reload()可以强制刷新当前页面。适用于通过window.open()showModalDialog()打开的弹窗。

// 打开弹窗
const popup = window.open('popup.html', '_blank');

// 监听弹窗关闭事件
const checkPopupClosed = setInterval(() => {
  if (popup.closed) {
    clearInterval(checkPopupClosed);
    window.location.reload();
  }
}, 500);

使用postMessage通信

通过postMessageAPI实现父子窗口间的通信,弹窗关闭前发送消息通知父页面刷新。

// 父页面代码
window.addEventListener('message', (event) => {
  if (event.data === 'refreshParent') {
    window.location.reload();
  }
});

// 弹窗页面代码
window.onbeforeunload = () => {
  window.opener.postMessage('refreshParent', '*');
};

模态对话框场景

使用dialog元素的close事件监听,适用于HTML5的<dialog>元素。

const dialog = document.querySelector('dialog');
dialog.addEventListener('close', () => {
  window.location.reload();
});

第三方弹窗库处理

对于使用如SweetAlert等库创建的弹窗,可在回调函数中触发刷新。

Swal.fire({
  title: '操作完成',
  icon: 'success'
}).then((result) => {
  if (result.isConfirmed) {
    window.location.reload();
  }
});

本地存储检测方案

通过localStoragesessionStorage在弹窗关闭时设置标志位,主页面通过轮询检测。

js实现弹窗关闭后刷新

// 弹窗页面
window.onunload = () => {
  sessionStorage.setItem('shouldRefresh', 'true');
};

// 主页面
setInterval(() => {
  if (sessionStorage.getItem('shouldRefresh') === 'true') {
    sessionStorage.removeItem('shouldRefresh');
    window.location.reload();
  }
}, 1000);

标签: js
分享给朋友:

相关文章

js实现验证码

js实现验证码

实现验证码的JavaScript方法 生成随机验证码 使用Math.random()生成随机字符串,结合数字和字母: function generateCaptcha() { const cha…

js实现选题

js实现选题

实现选题功能的JavaScript方法 基础实现方案 使用数组存储选项,通过随机索引选取: const options = ['选项A', '选项B', '选项C', '选项D']; const r…

节流js实现

节流js实现

节流(Throttle)的实现原理 节流是一种限制函数执行频率的技术,确保函数在一定时间间隔内最多执行一次。适用于高频触发事件(如滚动、输入、窗口调整等)的场景。 基础实现方式 使用时间戳判断是否执…

js实现文字滚动

js实现文字滚动

实现文字滚动的几种方法 使用CSS动画实现滚动 通过CSS的@keyframes和transform属性可以实现平滑的文字滚动效果。 <style> .scroll-text { w…

js 实现滚动

js 实现滚动

实现滚动的方法 使用 window.scrollTo() window.scrollTo() 方法可以滚动到文档中的特定位置。可以指定 x 和 y 坐标,或者使用平滑滚动的选项。 // 滚动到指定位…

js 实现页面刷新

js 实现页面刷新

使用 location.reload() location.reload() 是原生 JavaScript 提供的页面刷新方法。调用该方法会重新加载当前页面,相当于点击浏览器的刷新按钮。 // 基本…