如何用JavaScript给含/product/的URL追加固定查询字符串?nowprocket
功能实现方案
适用场景说明
以下提供两种实现方案,可根据你的业务需求选择:
- 需要后端识别该参数、或参数要参与服务端逻辑:选择带页面跳转刷新的实现
- 仅前端逻辑使用该参数、不需要服务端感知:选择无刷新修改地址栏URL的实现
完整代码实现
方案1:带跳转刷新的实现
if (window.location.href.indexOf("/product/") > -1) { // 校验是否已经追加过参数,避免重复添加 if (window.location.search.indexOf('nowprocket') === -1) { const hasExistQuery = !!window.location.search const newUrl = hasExistQuery ? `${window.location.href}&nowprocket` : `${window.location.href}?nowprocket` // 使用replace跳转不会在浏览历史中遗留旧地址,避免后退时出现跳转死循环 window.location.replace(newUrl) } }
方案2:无刷新修改地址栏URL的实现
if (window.location.href.indexOf("/product/") > -1) { // 校验是否已经追加过参数,避免重复添加 if (window.location.search.indexOf('nowprocket') === -1) { const hasExistQuery = !!window.location.search const newUrl = hasExistQuery ? `${window.location.href}&nowprocket` : `${window.location.href}?nowprocket` // 调用history API仅更新地址栏内容,不会触发页面重载 window.history.pushState({ path: newUrl }, '', newUrl) } }
边界兼容说明
- 自动兼容原URL已存在其他查询参数的场景:如果原地址已有
?开头的查询串,会自动用&拼接参数,不会破坏原有参数 - 自带重复校验逻辑:多次触发代码也不会重复追加
nowprocket参数 - 跳转方案无历史冗余:使用replace跳转不会留下旧地址记录,用户点击浏览器后退不会回到未加参数的页面,避免反复跳转的死循环问题
内容的提问来源于stack exchange,提问作者Rosalito Udtohan
相关产品推荐
相关产品推荐

