使用history.replaceState 控制微信返回


history.replaceState是将指定的URL替换当前的URL

注意:用于替换掉的URL必须是同域的

示例:

先保存三个页面

goto1.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>goto1</title>
  6. </head>
  7. <body>
  8. <h1>这是goto1</h1>
  9. <a href='goto2.html'>去2</a>
  10. </body>
  11. </html>

goto2.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>goto2</title>
  6. </head>
  7. <body>
  8. <h1>这是goto2</h1>
  9. <a href='goto3.html'>去3</a>
  10. </body>
  11. <script>
  12. history.replaceState({}, "goto1", "goto1.html");//将该页面的url替换为goto1.html,而不刷新页面
  13. </script>
  14. </body>
  15. </html>


goto3.html

  1. <pre name="code" class="html"><!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>goto3</title>
  6. </head>
  7. <body>
  8. <h1>这是goto3</h1>
  9. </body>
  10. </html>

先从goto1点击链接进入goto2,goto2点链接进入goto3;

此时点击浏览器的后退键应该返回到goto2,然而由于我们已经用

history.replaceState({}, “goto1”, “goto1.html”);将goto2的url历史记录换成goto1;

所有从goto3点击后退直接返回到了goto1页面;这里的goto1也可以换成所有你想要用户返回的页面

奉上个人封装的一个控制返回小函数

  1. var url='goto1';
  2. var param=new Object();
  3. param.userid='123';
  4. param.status='1';//最后得到path=goto1.html?userid=123&status=1 ;
  5. function changeBackUrl(url,param){ //url表示链接地址
  6. if(typeof(param)=='object'){
  7. param=JSON.stringify(param).replace(/\{|\}|\"|\'/g,'').replace(',','&').replace(/:/g,'=');
  8. }else{
  9. try{ param=param.toString().replace(',','&').replace(/:/g,'=').replace(/\"|\'/g,''); }catch(e){''}
  10. }
  11. var path=+url+".html?"+param; history.replaceState(null, null, path);
  12. }


                                    
粤ICP备17098559号