8

我找到了很多关于如何在没有参数的情况下提取 URL 的答案。

如何重写地址栏中的 URL 而不会导致页面重新加载新 URL?

shortURL = top.location.href.substring(0, top.location.href.indexOf('?'));
top.location.href = shortURL // Causes redirect

目标是提取 Javascript 中的参数,但不在地址栏中显示它们。

4

5 回答 5

12

在支持 History 对象的现代浏览器中,您可以使用history.replaceState()history.pushState()更改当前 URL 而无需更改当前页面。您可以更改的内容存在限制(例如,出于安全原因,您不能以这种方式更改域/来源)。

有关这些方法的摘要,请参见此处。

浏览器历史记录是您在浏览会话中所处位置的记录。 .replaceState()允许您将历史列表中的当前项目替换为不同的项目。 .pushState()将新项目添加到浏览器历史记录中,并且都更改浏览器 URL 栏中显示的 URL,而无需重新加载页面。您可以根据您希望浏览器的“后退”按钮在此特定页面条目中的行为方式来选择要使用的方法。

注意:这些 API 在 IE 10 及更高版本中受支持。

在不支持历史 API 的旧浏览器版本中,您可以在不重新加载页面的情况下更改 URL 的唯一部分是 URL#末尾的井号标记(符号后面的部分)。

于 2011-12-14T19:54:17.737 回答
6

在html5中,可以在不重新加载页面的情况下重写url(出于安全原因,您仍然不能更改域名),使用history api您可以编写:

history.replaceState("object or string", "title", "/another-new-url");

其中前两个参数是任意的,第三个参数是新的url(不包括域名)。如果要启用后退按钮以返回上一个 url,请使用pushState而不是replaceState上面。在此博客文章中阅读有关这些功能的更多信息。

Regarding browser support, it is supported in recent Firefox and Chrome versions, but only in IE10+, which is not very common yet. For details see compatibility matrix or browser implementation details.

于 2013-01-20T12:07:58.460 回答
2

您无法在不重定向的情况下更改地址栏中的值。这将是网络钓鱼诈骗者的梦想成真!

但是,您可以更改片段标识符:(在 JavaScript 中,window.location.hash值)

<!DOCTYPE html>
<html>
<head>
<title>This is a test</title>
<script>
window.onload = function() {
    window.location.hash = "Loaded!";
    document.getElementById("click-me").onclick = function() {
        window.location.hash = "Click!";
        document.getElementById("click-me").onclick = function() {
            window.location.hash = "Clicked AGAIN!";
        };
    };
}
</script>
<body>
<div>
<input type="button" id="click-me" value="click me!" />
</div>
</body>
</html>

但是更改查询字符串将重定向页面。

于 2011-12-14T19:57:21.337 回答
1

您也许可以使用作为 HTML 5 历史 API 一部分的新 pushstate,它允许您更改 URL 而无需实际重新加载浏览器。

查看http://badassjs.com/post/840846392/location-hash-is-dead-long-live-html5-pushstate获取快速示例,查看http://diveintohtml5.info/history.html获取更深入的示例和限制:

于 2011-12-14T20:15:19.277 回答
0

我不认为有这种可能性,我的意思是您可能可以在加载后重写 URL 并添加 return false,因此您可以防止重新加载,否则您必须在 url 上执行表单 POST 才能实现没有显示参数。

于 2011-12-14T19:54:40.463 回答