From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- files/zh-cn/web/api/history_api/example/index.html | 413 +++++++++++++++++++++ files/zh-cn/web/api/history_api/index.html | 213 +++++++++++ .../working_with_the_history_api/index.html | 126 +++++++ 3 files changed, 752 insertions(+) create mode 100644 files/zh-cn/web/api/history_api/example/index.html create mode 100644 files/zh-cn/web/api/history_api/index.html create mode 100644 files/zh-cn/web/api/history_api/working_with_the_history_api/index.html (limited to 'files/zh-cn/web/api/history_api') diff --git a/files/zh-cn/web/api/history_api/example/index.html b/files/zh-cn/web/api/history_api/example/index.html new file mode 100644 index 0000000000..a59e531ad6 --- /dev/null +++ b/files/zh-cn/web/api/history_api/example/index.html @@ -0,0 +1,413 @@ +--- +title: Ajax navigation example +slug: Web/API/History_API/Example +translation_of: Web/API/History_API/Example +--- +

这是一个仅由三个页面组成的 AJAX 网站示例 (first_page.php, second_page.php and third_page.php). 要查看其如何工作的,请创建以下文件  (或 git clone https://github.com/giabao/mdn-ajax-nav-example.git ):

+ +
注意: 为了在该机制中很好地整合{{HTMLElement("form")}}元素 , 请看一下这段 Submitting forms and uploading files.
+ +

first_page.php:

+ +
+
<?php
+    $page_title = "First page";
+
+    $as_json = false;
+    if (isset($_GET["view_as"]) && $_GET["view_as"] == "json") {
+        $as_json = true;
+        ob_start();
+    } else {
+?>
+<!doctype html>
+<html>
+<head>
+<?php
+        include "include/header.php";
+        echo "<title>" . $page_title . "</title>";
+?>
+</head>
+
+<body>
+
+<?php include "include/before_content.php"; ?>
+
+<p>This paragraph is shown only when the navigation starts from <strong>first_page.php</strong>.</p>
+
+<div id="ajax-content">
+<?php } ?>
+
+    <p>This is the content of <strong>first_page.php</strong>.</p>
+
+<?php
+    if ($as_json) {
+        echo json_encode(array("page" => $page_title, "content" => ob_get_clean()));
+    } else {
+?>
+</div>
+
+<p>This paragraph is shown only when the navigation starts from <strong>first_page.php</strong>.</p>
+
+<?php
+        include "include/after_content.php";
+        echo "</body>\n</html>";
+    }
+?>
+
+
+ +

second_page.php:

+ +
+
<?php
+    $page_title = "Second page";
+
+    $as_json = false;
+    if (isset($_GET["view_as"]) && $_GET["view_as"] == "json") {
+        $as_json = true;
+        ob_start();
+    } else {
+?>
+<!doctype html>
+<html>
+<head>
+<?php
+        include "include/header.php";
+        echo "<title>" . $page_title . "</title>";
+?>
+</head>
+
+<body>
+
+<?php include "include/before_content.php"; ?>
+
+<p>This paragraph is shown only when the navigation starts from <strong>second_page.php</strong>.</p>
+
+<div id="ajax-content">
+<?php } ?>
+
+    <p>This is the content of <strong>second_page.php</strong>.</p>
+
+<?php
+    if ($as_json) {
+        echo json_encode(array("page" => $page_title, "content" => ob_get_clean()));
+    } else {
+?>
+</div>
+
+<p>This paragraph is shown only when the navigation starts from <strong>second_page.php</strong>.</p>
+
+<?php
+        include "include/after_content.php";
+        echo "</body>\n</html>";
+    }
+?>
+
+
+ +

third_page.php:

+ +
+
<?php
+    $page_title = "Third page";
+    $page_content = "<p>This is the content of <strong>third_page.php</strong>. This content is stored into a php variable.</p>";
+
+    if (isset($_GET["view_as"]) && $_GET["view_as"] == "json") {
+        echo json_encode(array("page" => $page_title, "content" => $page_content));
+    } else {
+?>
+<!doctype html>
+<html>
+<head>
+<?php
+        include "include/header.php";
+        echo "<title>" . $page_title . "</title>";
+?>
+</head>
+
+<body>
+
+<?php include "include/before_content.php"; ?>
+
+<p>This paragraph is shown only when the navigation starts from <strong>third_page.php</strong>.</p>
+
+<div id="ajax-content">
+<?php echo $page_content; ?>
+</div>
+
+<p>This paragraph is shown only when the navigation starts from <strong>third_page.php</strong>.</p>
+
+<?php
+        include "include/after_content.php";
+        echo "</body>\n</html>";
+    }
+?>
+
+
+ +

css/style.css:

+ +
#ajax-loader {
+    position: fixed;
+    display: table;
+    top: 0;
+    left: 0;
+    width: 100%;
+    height: 100%;
+}
+
+#ajax-loader > div {
+    display: table-cell;
+    width: 100%;
+    height: 100%;
+    vertical-align: middle;
+    text-align: center;
+    background-color: #000000;
+    opacity: 0.65;
+}
+
+ +

include/after_content.php:

+ +
<p>This is the footer. It is shared between all ajax pages.</p>
+
+ +

include/before_content.php:

+ +
<p>
+[ <a class="ajax-nav" href="first_page.php">First example</a>
+| <a class="ajax-nav" href="second_page.php">Second example</a>
+| <a class="ajax-nav" href="third_page.php">Third example</a>
+| <a class="ajax-nav" href="unexisting.php">Unexisting page</a> ]
+</p>
+
+
+ +

include/header.php:

+ +
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+<script type="text/javascript" src="js/ajax_nav.js"></script>
+<link rel="stylesheet" href="css/style.css" />
+
+ +

js/ajax_nav.js:

+ +
+
"use strict";
+
+const ajaxRequest = new (function () {
+
+    function closeReq () {
+        oLoadingBox.parentNode && document.body.removeChild(oLoadingBox);
+        bIsLoading = false;
+    }
+
+    function abortReq () {
+        if (!bIsLoading) { return; }
+        oReq.abort();
+        closeReq();
+    }
+
+    function ajaxError () {
+        alert("Unknown error.");
+    }
+
+    function ajaxLoad () {
+        var vMsg, nStatus = this.status;
+        switch (nStatus) {
+            case 200:
+                vMsg = JSON.parse(this.responseText);
+                document.title = oPageInfo.title = vMsg.page;
+                document.getElementById(sTargetId).innerHTML = vMsg.content;
+                if (bUpdateURL) {
+                    history.pushState(oPageInfo, oPageInfo.title, oPageInfo.url);
+                    bUpdateURL = false;
+                }
+                break;
+            default:
+                vMsg = nStatus + ": " + (oHTTPStatus[nStatus] || "Unknown");
+                switch (Math.floor(nStatus / 100)) {
+                    /*
+                    case 1:
+                        // Informational 1xx
+                        console.log("Information code " + vMsg);
+                        break;
+                    case 2:
+                        // Successful 2xx
+                        console.log("Successful code " + vMsg);
+                        break;
+                    case 3:
+                        // Redirection 3xx
+                        console.log("Redirection code " + vMsg);
+                        break;
+                    */
+                    case 4:
+                        /* Client Error 4xx */
+                        alert("Client Error #" + vMsg);
+                        break;
+                    case 5:
+                        /* Server Error 5xx */
+                        alert("Server Error #" + vMsg);
+                        break;
+                    default:
+                        /* Unknown status */
+                        ajaxError();
+                }
+        }
+        closeReq();
+    }
+
+    function filterURL (sURL, sViewMode) {
+        return sURL.replace(rSearch, "") + ("?" + sURL.replace(rHost, "&").replace(rView, sViewMode ? "&" + sViewKey + "=" + sViewMode : "").slice(1)).replace(rEndQstMark, "");
+    }
+
+    function getPage (sPage) {
+        if (bIsLoading) { return; }
+        oReq = new XMLHttpRequest();
+        bIsLoading = true;
+        oReq.onload = ajaxLoad;
+        oReq.onerror = ajaxError;
+        if (sPage) { oPageInfo.url = filterURL(sPage, null); }
+        oReq.open("get", filterURL(oPageInfo.url, "json"), true);
+        oReq.send();
+        oLoadingBox.parentNode || document.body.appendChild(oLoadingBox);
+    }
+
+    function requestPage (sURL) {
+        if (history.pushState) {
+            bUpdateURL = true;
+            getPage(sURL);
+        } else {
+            /* Ajax navigation is not supported */
+            location.assign(sURL);
+        }
+    }
+
+    function processLink () {
+        if (this.className === sAjaxClass) {
+            requestPage(this.href);
+            return false;
+        }
+        return true;
+    }
+
+    function init () {
+        oPageInfo.title = document.title;
+        history.replaceState(oPageInfo, oPageInfo.title, oPageInfo.url);
+        for (var oLink, nIdx = 0, nLen = document.links.length; nIdx < nLen; document.links[nIdx++].onclick = processLink);
+    }
+
+    const
+
+        /* customizable constants */
+        sTargetId = "ajax-content", sViewKey = "view_as", sAjaxClass = "ajax-nav",
+
+        /* not customizable constants */
+        rSearch = /\?.*$/, rHost = /^[^\?]*\?*&*/, rView = new RegExp("&" + sViewKey + "\\=[^&]*|&*$", "i"), rEndQstMark = /\?$/,
+        oLoadingBox = document.createElement("div"), oCover = document.createElement("div"), oLoadingImg = new Image(),
+        oPageInfo = {
+            title: null,
+            url: location.href
+        }, oHTTPStatus = /* http://www.iana.org/assignments/http-status-codes/http-status-codes.xml */ {
+            100: "Continue",
+            101: "Switching Protocols",
+            102: "Processing",
+            200: "OK",
+            201: "Created",
+            202: "Accepted",
+            203: "Non-Authoritative Information",
+            204: "No Content",
+            205: "Reset Content",
+            206: "Partial Content",
+            207: "Multi-Status",
+            208: "Already Reported",
+            226: "IM Used",
+            300: "Multiple Choices",
+            301: "Moved Permanently",
+            302: "Found",
+            303: "See Other",
+            304: "Not Modified",
+            305: "Use Proxy",
+            306: "Reserved",
+            307: "Temporary Redirect",
+            308: "Permanent Redirect",
+            400: "Bad Request",
+            401: "Unauthorized",
+            402: "Payment Required",
+            403: "Forbidden",
+            404: "Not Found",
+            405: "Method Not Allowed",
+            406: "Not Acceptable",
+            407: "Proxy Authentication Required",
+            408: "Request Timeout",
+            409: "Conflict",
+            410: "Gone",
+            411: "Length Required",
+            412: "Precondition Failed",
+            413: "Request Entity Too Large",
+            414: "Request-URI Too Long",
+            415: "Unsupported Media Type",
+            416: "Requested Range Not Satisfiable",
+            417: "Expectation Failed",
+            422: "Unprocessable Entity",
+            423: "Locked",
+            424: "Failed Dependency",
+            425: "Unassigned",
+            426: "Upgrade Required",
+            427: "Unassigned",
+            428: "Precondition Required",
+            429: "Too Many Requests",
+            430: "Unassigned",
+            431: "Request Header Fields Too Large",
+            500: "Internal Server Error",
+            501: "Not Implemented",
+            502: "Bad Gateway",
+            503: "Service Unavailable",
+            504: "Gateway Timeout",
+            505: "HTTP Version Not Supported",
+            506: "Variant Also Negotiates (Experimental)",
+            507: "Insufficient Storage",
+            508: "Loop Detected",
+            509: "Unassigned",
+            510: "Not Extended",
+            511: "Network Authentication Required"
+        };
+
+    var
+
+        oReq, bIsLoading = false, bUpdateURL = false;
+
+    oLoadingBox.id = "ajax-loader";
+    oCover.onclick = abortReq;
+    oLoadingImg.src = "data:image/gif;base64,R0lGODlhEAAQAPIAAP///wAAAMLCwkJCQgAAAGJiYoKCgpKSkiH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAADMwi63P4wyklrE2MIOggZnAdOmGYJRbExwroUmcG2LmDEwnHQLVsYOd2mBzkYDAdKa+dIAAAh+QQJCgAAACwAAAAAEAAQAAADNAi63P5OjCEgG4QMu7DmikRxQlFUYDEZIGBMRVsaqHwctXXf7WEYB4Ag1xjihkMZsiUkKhIAIfkECQoAAAAsAAAAABAAEAAAAzYIujIjK8pByJDMlFYvBoVjHA70GU7xSUJhmKtwHPAKzLO9HMaoKwJZ7Rf8AYPDDzKpZBqfvwQAIfkECQoAAAAsAAAAABAAEAAAAzMIumIlK8oyhpHsnFZfhYumCYUhDAQxRIdhHBGqRoKw0R8DYlJd8z0fMDgsGo/IpHI5TAAAIfkECQoAAAAsAAAAABAAEAAAAzIIunInK0rnZBTwGPNMgQwmdsNgXGJUlIWEuR5oWUIpz8pAEAMe6TwfwyYsGo/IpFKSAAAh+QQJCgAAACwAAAAAEAAQAAADMwi6IMKQORfjdOe82p4wGccc4CEuQradylesojEMBgsUc2G7sDX3lQGBMLAJibufbSlKAAAh+QQJCgAAACwAAAAAEAAQAAADMgi63P7wCRHZnFVdmgHu2nFwlWCI3WGc3TSWhUFGxTAUkGCbtgENBMJAEJsxgMLWzpEAACH5BAkKAAAALAAAAAAQABAAAAMyCLrc/jDKSatlQtScKdceCAjDII7HcQ4EMTCpyrCuUBjCYRgHVtqlAiB1YhiCnlsRkAAAOwAAAAAAAAAAAA==";
+    oCover.appendChild(oLoadingImg);
+    oLoadingBox.appendChild(oCover);
+
+    onpopstate = function (oEvent) {
+        bUpdateURL = false;
+        oPageInfo.title = oEvent.state.title;
+        oPageInfo.url = oEvent.state.url;
+        getPage();
+    };
+
+    window.addEventListener ? addEventListener("load", init, false) : window.attachEvent ? attachEvent("onload", init) : (onload = init);
+
+    // Public methods
+
+    this.open = requestPage;
+    this.stop = abortReq;
+    this.rebuildLinks = init;
+
+})();
+
+
+ +


+ For more information, please see: Manipulating the browser history.

+ +

See also

+ + diff --git a/files/zh-cn/web/api/history_api/index.html b/files/zh-cn/web/api/history_api/index.html new file mode 100644 index 0000000000..2c4edffce9 --- /dev/null +++ b/files/zh-cn/web/api/history_api/index.html @@ -0,0 +1,213 @@ +--- +title: History API +slug: Web/API/History_API +tags: + - API + - History + - History API +translation_of: Web/API/History_API +--- +
{{DefaultAPISidebar("History API")}}
+ +

DOM {{ domxref("window") }} 对象通过 {{ domxref("window.history", "history") }} 对象提供了对浏览器的会话历史的访问(不要与 WebExtensions history搞混了)。它暴露了很多有用的方法和属性,允许你在用户浏览历史中向前和向后跳转,同时——从HTML5开始——提供了对history栈中内容的操作。

+ +

意义及使用

+ +

使用 {{DOMxRef("History.back","back()")}},  {{DOMxRef("History.forward","forward()")}}和  {{DOMxRef("History.go","go()")}} 方法来完成在用户历史记录中向后和向前的跳转。

+ +

向前和向后跳转

+ +

在history中向后跳转:

+ +
window.history.back();
+
+ +

这和用户点击浏览器回退按钮的效果相同。

+ +

类似地,你可以向前跳转(如同用户点击了前进按钮):

+ +
window.history.forward();
+
+ +

跳转到 history 中指定的一个点

+ +

你可以用 go() 方法载入到会话历史中的某一特定页面, 通过与当前页面相对位置来标志 (当前页面的相对位置标志为0).

+ +

向后移动一个页面 (等同于调用 back()):

+ +
window.history.go(-1);
+
+ +

向前移动一个页面, 等同于调用了 forward():

+ +
window.history.go(1);
+
+ +

类似地,你可以传递参数值2并向前移动2个页面,等等。

+ +

您可以通过查看长度属性的值来确定的历史堆栈中页面的数量:

+ +
 let numberOfEntries = window.history.length;
+
+ +
注意: IE 支持传递URLs作为参数给 go(); 这在Gecko是不标准且不支持的。
+ +

添加和修改历史记录中的条目

+ +

{{ gecko_minversion_header("2") }}

+ +

HTML5引入了 history.pushState() 和 history.replaceState() 方法,它们分别可以添加和修改历史记录条目。这些方法通常与{{ domxref("window.onpopstate") }} 配合使用。

+ +

使用 history.pushState() 可以改变referrer,它在用户发送 XMLHttpRequest 请求时在HTTP头部使用,改变state后创建的 XMLHttpRequest 对象的referrer都会被改变。因为referrer是标识创建  XMLHttpRequest 对象时 this 所代表的window对象中document的URL。

+ +

pushState() 方法的例子

+ +

假设在 http://mozilla.org/foo.html 页面的console中执行了以下 JavaScript 代码:

+ +
window.onpopstate = function(e) {
+   alert(2);
+}
+
+let stateObj = {
+    foo: "bar",
+};
+
+history.pushState(stateObj, "page 2", "bar.html");
+
+ +

这将使浏览器地址栏显示为 http://mozilla.org/bar.html,但并不会导致浏览器加载 bar.html ,甚至不会检查bar.html 是否存在。

+ +

假如现在用户在bar.html点击了返回按钮,将会执行alert(2)。

+ +

假设现在用户在bar.html又访问了 http://google.com,然后点击了返回按钮。此时,地址栏将显示 http://mozilla.org/bar.html,history.state 中包含了 stateObj 的一份拷贝。页面此时展现为bar.html。且因为页面被重新加载了,所以popstate事件将不会被触发,也不会执行alert(2)。

+ +

如果我们再次点击返回按钮,页面URL会变为http://mozilla.org/foo.html,文档对象document会触发另外一个 popstate 事件(如果有bar.html,且bar.html注册了onpopstate事件,将会触发此事件,因此也不会执行foo页面注册的onpopstate事件,也就是不会执行alert(2)),这一次的事件对象state object为null。 这里也一样,返回并不改变文档的内容,尽管文档在接收 popstate 事件时可能会改变自己的内容,其内容仍与之前的展现一致。

+ +

如果我们再次点击返回按钮,页面URL变为其他页面的url,依然不会执行alert(2)。因为在返回到foo页面的时候并没有pushState。

+ +

pushState() 方法

+ +

pushState() 需要三个参数: 一个状态对象, 一个标题 (目前被忽略), 和 (可选的) 一个URL. 让我们来解释下这三个参数详细内容:

+ + + +
注意: 从 Gecko 2.0 {{ geckoRelease("2.0") }} 到 Gecko 5.0 {{ geckoRelease("5.0") }},传递的对象是使用JSON进行序列化的。 从  Gecko 6.0 {{ geckoRelease("6.0") }}开始,该对象的序列化将使用结构化克隆算法。这将会使更多对象可以被安全的传递。
+ +

        在某种意义上,调用 pushState() 与 设置 window.location = "#foo" 类似,二者都会在当前页面创建并激活新的历史记录。但 pushState() 具有如下几条优点:

+ + + +

注意 pushState() 绝对不会触发 hashchange 事件,即使新的URL与旧的URL仅哈希不同也是如此。

+ +

在 XUL 文档中,它创建指定的 XUL 元素。

+ +

在其它文档中,它创建一个命名空间URI为null的元素。

+ +

replaceState() 方法

+ +

history.replaceState() 的使用与 history.pushState() 非常相似,区别在于  replaceState()  是修改了当前的历史记录项而不是新建一个。 注意这并不会阻止其在全局浏览器历史记录中创建一个新的历史记录项。

+ +

replaceState() 的使用场景在于为了响应用户操作,你想要更新状态对象state或者当前历史记录的URL。

+ +
注意: 从Gecko 2.0 {{ geckoRelease("2.0") }} 到 Gecko 5.0 {{ geckoRelease("5.0") }},传递的对象是使用JSON进行序列化的。 从  Gecko 6.0 {{ geckoRelease("6.0") }}开始,该对象的序列化将使用结构化克隆算法。这将会使更多对象可以被安全的传递。
+ +

replaceState() 方法示例

+ +

假设 http://mozilla.org/foo.html 执行了如下JavaScript代码:

+ +
let stateObj = {
+    foo: "bar",
+};
+
+history.pushState(stateObj, "page 2", "bar.html");
+
+ +

上文2行代码可以在 "pushState()方法示例" 部分找到。然后,假设http://mozilla.org/bar.html执行了如下 JavaScript:

+ +
history.replaceState(stateObj, "page 3", "bar2.html");
+
+ +

这将会导致地址栏显示http://mozilla.org/bar2.html,,但是浏览器并不会去加载bar2.html 甚至都不需要检查 bar2.html 是否存在。

+ +

假设现在用户重新导向到了http://www.microsoft.com,然后点击了回退按钮。这里,地址栏会显示http://mozilla.org/bar2.html。假如用户再次点击回退按钮,地址栏会显示http://mozilla.org/foo.html,完全跳过了bar.html。

+ +

popstate 事件

+ +

        每当活动的历史记录项发生变化时, popstate 事件都会被传递给window对象。如果当前活动的历史记录项是被 pushState 创建的,或者是由 replaceState 改变的,那么 popstate 事件的状态属性 state 会包含一个当前历史记录状态对象的拷贝。

+ +

使用示例请参见 {{ domxref("window.onpopstate") }} 。

+ +

获取当前状态

+ +

        页面加载时,或许会有个非null的状态对象。这是有可能发生的,举个例子,假如页面(通过pushState() 或 replaceState() 方法)设置了状态对象而后用户重启了浏览器。那么当页面重新加载时,页面会接收一个onload事件,但没有 popstate 事件。然而,假如你读取了history.state属性,你将会得到如同popstate 被触发时能得到的状态对象。

+ +

你可以读取当前历史记录项的状态对象state,而不必等待popstate 事件, 只需要这样使用history.state 属性: 

+ +
  // 尝试通过 pushState 创建历史条目,然后再刷新页面查看state状态对象变化;
+  window.addEventListener('load',() => {
+    let currentState = history.state;
+    console.log('currentState',currentState);
+  })
+
+ +

例子

+ +

完整的AJAX网站示例,请参阅: Ajax navigation example.

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "browsers.html#history", "History")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName("HTML5 W3C")}}.
{{SpecName('HTML5 W3C', "browsers.html#history", "History")}}{{Spec2('HTML5 W3C')}}Initial definition.
+ +

浏览器兼容性

+ +

{{Compat("api.History")}}

+ +

另见

+ +

参考

+ + + +

Guides

+ + diff --git a/files/zh-cn/web/api/history_api/working_with_the_history_api/index.html b/files/zh-cn/web/api/history_api/working_with_the_history_api/index.html new file mode 100644 index 0000000000..9b9bcaef37 --- /dev/null +++ b/files/zh-cn/web/api/history_api/working_with_the_history_api/index.html @@ -0,0 +1,126 @@ +--- +title: Working with the History API +slug: Web/API/History_API/Working_with_the_History_API +translation_of: Web/API/History_API/Working_with_the_History_API +--- +

HTML5引入了{{DOMxRef("History.pushState","pushState()")}}和{{DOMxRef("History.replaceState","replaceState()")}}方法,分别用于添加和修改历史记录。这些方法与{{domxref("Window.onpopstate","onpopstate")}} 事件一起工作。

+ +

添加和修改历史记录

+ +

{{ gecko_minversion_header("2") }}

+ +

Using {{DOMxRef("History.pushState","pushState()")}} changes the referrer that gets used in the HTTP header for {{domxref("XMLHttpRequest")}} objects created after you change the state. The referrer will be the URL of the document whose window is this at the time of creation of the {{domxref("XMLHttpRequest")}} object.

+ +

pushState()方法实例

+ +

假设 http://mozilla.org/foo.html 执行下面的JavaScript:

+ +
let stateObj = {
+    foo: "bar",
+}
+
+history.pushState(stateObj, "page 2", "bar.html")
+
+ +

This will cause the URL bar to display http://mozilla.org/bar.html, but won't cause the browser to load bar.html or even check that bar.html exists.

+ +

Suppose now that the user navigates to http://google.com, then clicks the Back button. At this point, the URL bar will display http://mozilla.org/bar.html and history.state will contain the stateObj. The popstate event won't be fired because the page has been reloaded. The page itself will look like bar.html.

+ +

If the user clicks Back once again, the URL will change to http://mozilla.org/foo.html, and the document will get a popstate event, this time with a null state object. Here too, going back doesn't change the document's contents from what they were in the previous step, although the document might update its contents manually upon receiving the popstate event.

+ +
+

Note: Calling history.back() normally behaves the same way as clicking the Back button. But there is one important exception:

+ +

After using history.pushState(), calling history.back() does not raise a popstate event. Clicking the browser's Back button (still) does.

+
+ +

The pushState() method

+ +

pushState() takes three parameters: a state object; a title (currently ignored); and (optionally), a URL.

+ +

Let's examine each of these three parameters in more detail.

+ +
+
state object 
+
The state object is a JavaScript object which is associated with the new history entry created by pushState(). Whenever the user navigates to the new state, a popstate event is fired, and the state property of the event contains a copy of the history entry's state object.
+
The state object can be anything that can be serialized. Because Firefox saves state objects to the user's disk so they can be restored after the user restarts the browser, we impose a size limit of 640k characters on the serialized representation of a state object. If you pass a state object whose serialized representation is larger than this to pushState(), the method will throw an exception. If you need more space than this, you're encouraged to use sessionStorage and/or localStorage.
+
+ +
+
title
+
All browsers but Safari currently ignore this parameter, although they may use it in the future. Passing the empty string here should be safe against future changes to the method. Alternatively, you could pass a short title for the state to which you're moving.
+
+ +
+
URL
+
The new history entry's URL is given by this parameter. Note that the browser won't attempt to load this URL after a call to pushState(), but it might attempt to load the URL later, for instance after the user restarts the browser. The new URL does not need to be absolute; if it's relative, it's resolved relative to the current URL. The new URL must be of the same origin as the current URL; otherwise, pushState() will throw an exception. This parameter is optional; if it isn't specified, it's set to the document's current URL.
+
+ +
Note: In Gecko 2.0 {{ geckoRelease("2.0") }} through Gecko 5.0 {{ geckoRelease("5.0") }}, the passed object is serialized using JSON. Starting in Gecko 6.0 {{ geckoRelease("6.0") }}, the object is serialized using the structured clone algorithm. This allows a wider variety of objects to be safely passed.
+ +

In a sense, calling pushState() is similar to setting window.location = "#foo", in that both will also create and activate another history entry associated with the current document.

+ +

But pushState() has a few advantages:

+ + + +

Note that pushState() never causes a hashchange event to be fired, even if the new URL differs from the old URL only in its hash.

+ +

In a XUL document, it creates the specified XUL element.

+ +

In other documents, it creates an element with a null namespace URI.

+ +

The replaceState() method

+ +

history.replaceState() operates exactly like history.pushState(), except that replaceState() modifies the current history entry instead of creating a new one. Note that this doesn't prevent the creation of a new entry in the global browser history.

+ +

replaceState() is particularly useful when you want to update the state object or URL of the current history entry in response to some user action.

+ +
Note: In Gecko 2.0 {{ geckoRelease("2.0") }} through Gecko 5.0 {{ geckoRelease("5.0") }}, the passed object is serialized using JSON. Starting in Gecko 6.0 {{ geckoRelease("6.0") }}, the object is serialized using the structured clone algorithm. This allows a wider variety of objects to be safely passed.
+ +

Example of replaceState() method

+ +

Suppose http://mozilla.org/foo.html executes the following JavaScript:

+ +
let stateObj = { foo: "bar" }
+history.pushState(stateObj, "page 2", "bar.html")
+
+ +

The explanation of these two lines above can be found at the above section Example of pushState() method section.

+ +

Next, suppose http://mozilla.org/bar.html executes the following JavaScript:

+ +
history.replaceState(stateObj, "page 3", "bar2.html")
+
+ +

This will cause the URL bar to display http://mozilla.org/bar2.html, but won't cause the browser to load bar2.html or even check that bar2.html exists.

+ +

Suppose now that the user navigates to http://www.microsoft.com, then clicks the Back button. At this point, the URL bar will display http://mozilla.org/bar2.html. If the user now clicks Back again, the URL bar will display http://mozilla.org/foo.html, and totally bypass bar.html.

+ +

The popstate event

+ +

A popstate event is dispatched to the window every time the active history entry changes. If the history entry being activated was created by a call to {{DOMxRef("History.pushState","pushState")}} or affected by a call to {{DOMxRef("History.replaceState","replaceState")}}, the popstate event's state property contains a copy of the history entry's state object.

+ +

See {{ domxref("Window.onpopstate") }} for sample usage.

+ +

Reading the current state

+ +

When your page loads, it might have a non-null state object.  This can happen, for example, if the page sets a state object (using {{DOMxRef("History.pushState","pushState()")}} or {{DOMxRef("History.replaceState","replaceState()")}}) and then the user restarts their browser. When the page reloads, the page will receive an onload event, but no popstate event. However, if you read the {{DOMxRef("History.state","history.state")}} property, you'll get back the state object you would have gotten if a popstate had fired.

+ +

You can read the state of the current history entry without waiting for a popstate event using the {{DOMxRef("History.state","history.state")}} property like this:

+ +
let currentState = history.state
+
+ +

See also

+ + -- cgit v1.2.3-54-g00ecf