You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

浏览器前进后退时,如何在window导航事件中提取URL参数部分?

提取URL中的查询参数部分

直接用浏览器原生的URL对象来解析是最稳妥的方式,它能帮你精准提取出查询参数部分(即从?开始的内容):

window.navigation.addEventListener("navigate", (event) => {
    const targetUrl = new URL(event.destination.url);
    const queryParams = targetUrl.search; // 结果就是"?url=page3",无参数时为空字符串
    console.log(queryParams);
});

如果不想用URL对象,也可以用字符串操作实现:

window.navigation.addEventListener("navigate", (event) => {
    const fullUrl = event.destination.url;
    const queryStartIndex = fullUrl.indexOf('?');
    const queryParams = queryStartIndex !== -1 ? fullUrl.slice(queryStartIndex) : '';
    console.log(queryParams);
});

推荐第一种方法,URL对象会自动处理各种URL特殊情况,比手动字符串截取更可靠。

内容的提问来源于stack exchange,提问作者Mike M.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 04:24:53