点击打开浏览器窗口,窗口已存在,跳转到已有窗口,不存在则新开窗口
可以通过以下方法实现:
window.open()的第二个参数windowName。
给windowName一个值,然后每次打开时,不会新创建浏览器标签,而是跳转到已存在的标签页。
1.原代码
const openUrl = (dd, record) => {
let _record = {
objId: record.id,
questionnaireId: dd.mealId,
objType: dd.questionnaireType,
}
switch (dd.questionnaireType) {
case "A":
const AUrl = `/A/Z?surveyId=${selectProject.id}&queId=${dd.id}&stkey=${record.key}`
window.open(AUrl , "_blank")
break;
case 'B':
const BUrl = `/A/X?surveyId=${selectProject.id}&frekey=${record.key}`
window.open(BUrl , "_blank")
break;
}
}
2.修改后
首先尝试检查是否有与指定名称匹配的窗口,如果有则尝试在该窗口中加载指定页面,否则将新开一个窗口加载页面。
需要注意的是,由于浏览器行为的限制,无法保证能够在已有窗口中加载页面,因此代码只是模拟了这种行为。
const openUrl = (dd, record) => {
....
let existingWindow = null;
// 检查是否有与指定名称匹配的窗口(record.name链接的唯一标识)
if (record.name) {
existingWindow = window.open('', record.name);
}
if (existingWindow && !existingWindow.closed) {
// 已存在窗口,跳转到指定页面
switch (qn.questionnaireType) {
case 'A':
const AUrl = `/A/Z?surveyId=${selectProject.id}&queId=${dd.id}&stkey=${record.key}`;
existingWindow.location.href = AUrl ;
//existingWindow 表示已存在的窗口对象,通过设置其 location.href 属性来使其加载新的 URL 地址。
break;
case 'B':
const BUrl = `/A/X?surveyId=${selectProject.id}&frekey=${record.key}`;
existingWindow.location.href = BUrl ;
break;
}
} else {
// 新开窗口
switch (dd.questionnaireType) {
case 'A':
const AUrl = `/A/Z?surveyId=${selectProject.id}&queId=${dd.id}&stkey=${record.key}`;
window.open(AUrl , '_blank');
break;
case 'B':
const BUrl = `/A/X?surveyId=${selectProject.id}&frekey=${record.key}`;
window.open(BUrl , '_blank');
break;
}
}
};