JavaScript修改相对路径无法正确跳转URL,如何模拟HTML的parent.location跳转行为?
问题根因
你写的代码和原HTML跳转逻辑有两处核心差异:
- 原HTML操作的是父窗口的地址对象
parent.location,你写的window.location是操作当前窗口 - 原HTML赋值的是无前导斜杠的相对路径,浏览器会自动基于父窗口当前的基础路径拼接完整地址;你给
pathname赋值时加了前导斜杠/,会强制识别为站点根目录下的绝对路径,直接丢失原有前置路径
正确实现代码
完全对齐原HTML逻辑的写法如下:
parent.location = 'page_confirm.html'
如果你实际需求是在当前窗口跳转而非父窗口,调整操作对象即可:
window.location = 'page_confirm.html'
可选稳妥写法
如果需要更可控的路径拼接,避免手动处理路径斜杠问题,可以用原生URL API实现:
// 父窗口跳转版本 const targetUrl = new URL('page_confirm.html', parent.location.href) parent.location.href = targetUrl.href // 当前窗口跳转版本 // const targetUrl = new URL('page_confirm.html', window.location.href) // window.location.href = targetUrl.href
内容的提问来源于stack exchange,提问作者innom
相关产品推荐
相关产品推荐

