前端开发小技巧 - 【JavaScript】 - 打开页面 + 关闭页面 + 刷新当前页面 + 子页面操作导致父页面刷新 + 子页面发送数据给父页面

215 阅读1分钟

以下都是基于 window对象 进行操作的

1、打开新的页面 / 跳转到别的页面

window.open('新页面Url', 打开方式);
  • 打开方式:
    • _blank:在新窗口中打开;
    • _self:在当前窗口中打开(替换当前窗口的url);

2、刷新当前页面

window.location.reload();

3、子页面操作导致父页面刷新

  • 前提条件:
    • 当前页面必须是在父页面中通过某种方式打开的,否则 window.opener 就是 undefined
if (window.opener) window.opener.location.reload();

4、一个页面发送数据给另一个页面

4.1、发送数据

otherWindow.postMessage(message, targetOrigin, [transfer]);
// window.postMessage('消息', url地址 / '*');
  • image.png

4.2、接收数据

  • e.source – 消息源,消息的发送窗口/iframe。
  • e.origin – 消息源的 URI(可能包含协议、域名和端口),用来验证数据源。
  • e.data – 发送过来的数据。
window.addEventListener('message', function (e) {
    const res = e.data;
    if (res.code === 300) {
        // 相关逻辑操作
    }
});