如何实现回到原标签页功能

一、前言

最近接到一个需求,从一个标签页A打开标签页B,在标签页B要通过按钮返回标签页A,也就是回到首页功能,记录一下实现的过程。

二、基本实现原理

借助于window.open(url, name)指定name的方式返回。

在A页面设置window.name = 'A',B页面使用window.open('', 'A')的方式返回

三、第一种方案:使用window.opener.name判断

判断是否有opener以及opener的name是否是A页面

js 复制代码
const AUrl = "A.html";
if(window.opener) {
    if(window.opener.name == "A") {
        window.open("", A)
    }
} else {
    widnow.open(AUrl)
}

实现的过程中发现,A打开B页面后,这时候切换到A页面,从浏览器地址栏更改url,此时B页面访问A页面会出现跨域问题,代码做下兼容

js 复制代码
function toHome() {
    const AUrl = "A.html";
    if(window.opener) {
        try {
            let name = window.opener.name; // 获取name可能出现跨域问题
            if(name == "A") {
                window.open("", 'A'); // 可能会出现A窗口不是所需页面,暂无解决方案
            }
        } catch(e) {
            window.opener = window.open(AUrl)
        }
    } else {
        window.opener = widnow.open(AUrl)
    }
}

四、第二种方案:使用postMessage传递信息

B页面通过postMessage传递指令到A页面,A页面获取后返回当前的window.name到B页面。 B页面接收后使用window.open跳转。

js 复制代码
// A.html
window.addEventListener("message", (e) => {
    let data = e.data;
    if(data.action == "backHome") {
        let name = "A" + Math.round(Math.random() * 10000) // 生成随机数,确保name唯一
        window.name = name;
        e.source.postMessage({
            action: "backHome",
            name: name
        }, '*')
    }
})
// B.html
function toHome() {
    let url = 'A.html';
    let timer
    const callback = (e) => {
        let data = e.data;
        if(data.action && data.action == "backHome") {
            clearTimeout(timer);
            window.open("", data.name)
        }
        window.removeEventListener("message", callback)
    }
    let opener = window.opener;
    if(opener) {
        window.addEventListener("message", callback)
        opener.postMessage({
            action: "backHome"
        })
        timer = setTimeout(() => {
            window.removeEventListener("message", callback)
            window.opener = window.open(url);
        }, 300);
    } else {
        window.opener = window.open(url);
    }
}

总结

本文介绍了如何从一个新标签页跳转到原标签页,有window.opener和postMessage两种方法,window.opener方案有一定缺陷,推荐使用postMessage方式实现
相关推荐
还是大剑师兰特21 分钟前
Vue3 按钮切换示例(启动 / 关闭互斥显示)
开发语言·javascript·vue.js
小金鱼Y24 分钟前
从进程线程到 async/await,一文吃透前端异步核心原理
前端·javascript
SuperEugene25 分钟前
前端代码注释规范:Vue 实战避坑,让 3 年后的自己还能看懂代码|项目规范篇
前端·javascript·vue.js
进击的尘埃38 分钟前
用声明式 YAML Schema 驱动 LLM 做 `Code Review` 自动化
javascript
kyriewen1 小时前
JavaScript 数据类型全家福:谁是大哥大,谁是小透明?
前端·javascript·ecmascript 6
凉辰1 小时前
uniapp实现生成海报功能 (开箱即用)
javascript·vue.js·小程序·uni-app
Moment1 小时前
2026年,TypeScript还值不值得学 ❓❓❓
前端·javascript·面试
angerdream2 小时前
最新版vue3+TypeScript开发入门到实战教程之DOM操作
javascript·vue.js
我命由我123453 小时前
JS 开发问题:url.includes is not a function
开发语言·前端·javascript·html·ecmascript·html5·js