history.replaceState(null,null,this.urlR); //关键代码
history.replaceState是将指定的URL替换当前的URL
注意:用于替换掉的URL必须是同域的
示例:
先保存三个页面
goto1.html
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>goto1</title>
- </head>
- <body>
- <h1>这是goto1</h1>
- <a href='goto2.html'>去2</a>
- </body>
- </html>
goto2.html
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>goto2</title>
- </head>
- <body>
- <h1>这是goto2</h1>
- <a href='goto3.html'>去3</a>
- </body>
- <script>
- history.replaceState({}, "goto1", "goto1.html");//将该页面的url替换为goto1.html,而不刷新页面
- </script>
- </body>
- </html>
goto3.html
- <pre name="code" class="html"><!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>goto3</title>
- </head>
- <body>
- <h1>这是goto3</h1>
- </body>
- </html>
先从goto1点击链接进入goto2,goto2点链接进入goto3;
此时点击浏览器的后退键应该返回到goto2,然而由于我们已经用
history.replaceState({}, "goto1", "goto1.html");将goto2的url历史记录换成goto1;
所有从goto3点击后退直接返回到了goto1页面;这里的goto1也可以换成所有你想要用户返回的页面
奉上个人封装的一个控制返回小函数
- var url='goto1';
- var param=new Object();
- param.userid='123';
- param.status='1';//最后得到path=goto1.html?userid=123&status=1 ;
- function changeBackUrl(url,param){ //url表示链接地址
- if(typeof(param)=='object'){
- param=JSON.stringify(param).replace(/{|}|"|'/g,'').replace(',','&').replace(/:/g,'=');
- }else{
- try{ param=param.toString().replace(',','&').replace(/:/g,'=').replace(/"|'/g,''); }catch(e){''}
- }
- var path=+url+".html?"+param; history.replaceState(null, null, path);
- }