window.location.replace vs window.location.href

3,344 阅读1分钟

1)预备:

浏览器对于页面的历史记录使用栈来维护

2)问题:

  浏览器里面点击上一级返回希望可以返回属于业务方的上一级页面

3)window.location.href:

这个是往记录栈里面的栈顶插入url,此时栈顶容量+1,所以点击返回的时候是返回上一层url,例如:

index.html  -> a.html -> b.html,在b.html上点击返回,回到a.html,就是一个出栈的过程。

  • 但是对于一些重定向的页面就会有问题:

index.html -> a.html -> redirect.html ? redirect=a.html(这个页面会重定向回来到a.html)

  • 重定向成功后:

index.html -> a.html -> a.html(点击返回后如果a.html没有判断是否要重定向的条件的话,页面会再次发起重定向,导致用户回不到业务方的页面--index.html)

  • 解决办法:a.html添加是否需要重定向的条件判断

4)window.location.replace:

这个是替换记录栈里面的栈顶url,此时栈顶的容量不变。所以对于一些需要重定向的页面来说,非常有用,例如:

index.html -> a.html 

  •  替换为:

index.html ->  redirect.html ? redirect=a.html(这个页面会重定向回来到a.html)

  • 重定向成功后:

index.html -> a.html(点击返回就可以返回index.html)