如何更改当前 URL?

我使用下面的代码从 JavaScript 中更改页面:

var newUrl = [some code to build up URL string];
window.location.replace(newUrl);

但是它不会改变顶部的 URL,所以当有人点击后退按钮时,它不会返回到上一个页面。

我怎样才能让 JavaScript 改变顶部的网址,以便浏览器返回按钮工作。

292425 次浏览

嗯,我会用

window.location = 'http://localhost/index.html#?options=go_here';

我不确定你是不是这个意思。

Simple assigning to window.location or window.location.href should be fine:

window.location = newUrl;

但是,您的新 URL 将导致浏览器加载新页面,但是听起来您希望在不离开当前页面的情况下修改 URL。你有两个选择:

  1. 使用 URL 散列。例如,您可以从 example.comexample.com#foo而不加载新页面。您可以简单地设置 window.location.hash使其变得容易。然后,您应该监听 HTML5hashchange事件,当用户按下后退按钮时将触发该事件。这在旧版本的 IE 中不受支持,但是请查看 JQuery BBQ,它可以在所有浏览器中使用。

  2. You could use HTML5 History to modify the path without reloading the page. This will allow you to change from example.com/foo to example.com/bar. Using this is easy:

    window.history.pushState("example.com/foo");

    当用户按下“ back”键时,您将收到窗口的 popstate事件,您可以很容易地听到(jQuery) :

    $(window).bind("popstate", function(e) { alert("location changed"); });

    不幸的是,这只支持非常现代的浏览器,如 Chrome、 Safari 和 Firefox 4 beta。

如果你只是想更新相对路径,你也可以这样做

window.location.pathname = '/relative-link'

"http://domain.com" -> "http://domain.com/relative-link"

<script>
var url= "http://www.google.com";
window.location = url;
</script>

这样就行了:

window.history.pushState(null,null,'https://www.google.com');