js修改url

摘要:这篇文章主要介绍修改url地址的一些方法,包括:修改url重新加载,修改url但不重新加载。如果修改url但不重新加载,可以使用html5后引入的History.pushState(),History.replaceState()

这篇文章主要介绍修改url地址的一些方法,包括:修改url重新加载,修改url但不重新加载。


修改url重新加载刷新页面

1、window.location.reload(),刷新页面,不重复提交页面。

2、window.location.href=window.location.href,刷新页面,不重复提交页面。

3、location.replace(location.href),刷新页面,不重复提交页面。

4、window.location.replace(location),重定向一个页面,也可以为当前页面。

5、window.opener.location.reload(); 父页面刷新加载,即当一个页面open一个新页面后可以在子页面,reload父页面。

6、其他一些非常用的刷新方法:

history.go(0)
location=location
document.execCommand('Refresh')
window.navigate(location)
document.URL=location.href

7、html中meta标签

页面自动刷新:把如下代码加入区域中,其中20指每隔20秒刷新一次页面

<meta http-equiv="refresh" content="20">

页面自动跳转:把如下代码加入区域中,其中20指隔20秒后跳转到 http://www.shenqiku.cn  页面

<meta http-equiv="refresh" content="20;url="http://www.shenqiku.cn">

场景:使用js修改url地址参数并刷新页面

该方法可以修改url的参数。例如将www.shenqiku.cn修改为www.shenqiku.cn?name=123。代码如下:

function changeURLArg(url,arg,arg_val){
var pattern=arg+'=([^&]*)';
var replaceText=arg+'='+arg_val;
if(url.match(pattern)){
var tmp='/('+ arg+'=)([^&]*)/gi';
tmp=url.replace(eval(tmp),replaceText);
return tmp;
}else{
if(url.match('[\?]')){
return url+'&'+replaceText;
}else{
return url+'?'+replaceText;
}
}
}

使用:

window.location.href = changeURLArg(window.location.href,'name',123)


修改url但不重新加载

如果修改url但不重新加载,可以使用html5后引入的History.pushState(),History.replaceState()。pushState方法往历史记录中添加新记录,replaceState方法修改当前历史记录。

使用到的API

history.state

当前URL下对应的状态信息。如果当前URL不是通过pushState或者replaceState产生的,那么history.state是null。

history.pushState(state, title, url)

将当前URL和history.state加入到history中,并用新的state和URL替换当前。不会造成页面刷新。

  • state:与要跳转到的URL对应的状态信息。
  • title: 新页面的标题,但是所有浏览器目前都忽略这个值,因此这里可以填null或者空字符串 。
  • url:要跳转到的URL地址,不能跨域。
history.replaceState

参数同pushState,区别于pushState会直接替换掉当前url,而不会在history中留下记录。

例子:

//如果当前url为http://www.shenqiku.cn/nav
history.replaceState({},"","/tool");
//现在为http://www.shenqiku.cn/tool

场景:使用js修改url地址参数不刷新页面

同样使用上述方法changeURLArg。

var newurl=changeURLArg(window.location.href,'name',123)
window.history.replaceState({path: newurl}, '', newurl);


本文内容仅供个人学习、研究或参考使用,不构成任何形式的决策建议、专业指导或法律依据。未经授权,禁止任何单位或个人以商业售卖、虚假宣传、侵权传播等非学习研究目的使用本文内容。如需分享或转载,请保留原文来源信息,不得篡改、删减内容或侵犯相关权益。感谢您的理解与支持!

链接: https://shenqiku.cn/article/FLY_10734