aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/web/api/history_api
diff options
context:
space:
mode:
authorPeter Bengtsson <mail@peterbe.com>2020-12-08 14:40:17 -0500
committerPeter Bengtsson <mail@peterbe.com>2020-12-08 14:40:17 -0500
commit33058f2b292b3a581333bdfb21b8f671898c5060 (patch)
tree51c3e392513ec574331b2d3f85c394445ea803c6 /files/zh-cn/web/api/history_api
parent8b66d724f7caf0157093fb09cfec8fbd0c6ad50a (diff)
downloadtranslated-content-33058f2b292b3a581333bdfb21b8f671898c5060.tar.gz
translated-content-33058f2b292b3a581333bdfb21b8f671898c5060.tar.bz2
translated-content-33058f2b292b3a581333bdfb21b8f671898c5060.zip
initial commit
Diffstat (limited to 'files/zh-cn/web/api/history_api')
-rw-r--r--files/zh-cn/web/api/history_api/example/index.html413
-rw-r--r--files/zh-cn/web/api/history_api/index.html213
-rw-r--r--files/zh-cn/web/api/history_api/working_with_the_history_api/index.html126
3 files changed, 752 insertions, 0 deletions
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
+---
+<p>这是一个仅由三个页面组成的 AJAX 网站示例 (<em>first_page.php</em>, <em>second_page.php</em> and <em>third_page.php</em>). 要查看其如何工作的,请创建以下文件  (或 git clone <a href="https://github.com/giabao/mdn-ajax-nav-example" title="/en-US/docs/">https://github.com/giabao/mdn-ajax-nav-example.git</a> ):</p>
+
+<div class="note" id="const_compatibility"><strong>注意:</strong> 为了在该机制中很好地整合{{HTMLElement("form")}}元素 , <span class="tlid-translation translation" lang="zh-CN"><span title="">请看一下这段</span></span> <a href="/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Submitting_forms_and_uploading_files">Submitting forms and uploading files</a>.</div>
+
+<p><strong>first_page.php</strong>:</p>
+
+<div style="height: 400px; margin-bottom: 12px; overflow: auto;">
+<pre class="brush: php">&lt;?php
+    $page_title = "First page";
+
+    $as_json = false;
+    if (isset($_GET["view_as"]) &amp;&amp; $_GET["view_as"] == "json") {
+        $as_json = true;
+        ob_start();
+    } else {
+?&gt;
+&lt;!doctype html&gt;
+&lt;html&gt;
+&lt;head&gt;
+&lt;?php
+        include "include/header.php";
+        echo "&lt;title&gt;" . $page_title . "&lt;/title&gt;";
+?&gt;
+&lt;/head&gt;
+
+&lt;body&gt;
+
+&lt;?php include "include/before_content.php"; ?&gt;
+
+&lt;p&gt;This paragraph is shown only when the navigation starts from &lt;strong&gt;first_page.php&lt;/strong&gt;.&lt;/p&gt;
+
+&lt;div id="ajax-content"&gt;
+&lt;?php } ?&gt;
+
+    &lt;p&gt;This is the content of &lt;strong&gt;first_page.php&lt;/strong&gt;.&lt;/p&gt;
+
+&lt;?php
+    if ($as_json) {
+        echo json_encode(array("page" =&gt; $page_title, "content" =&gt; ob_get_clean()));
+    } else {
+?&gt;
+&lt;/div&gt;
+
+&lt;p&gt;This paragraph is shown only when the navigation starts from &lt;strong&gt;first_page.php&lt;/strong&gt;.&lt;/p&gt;
+
+&lt;?php
+        include "include/after_content.php";
+        echo "&lt;/body&gt;\n&lt;/html&gt;";
+    }
+?&gt;
+</pre>
+</div>
+
+<p><strong>second_page.php</strong>:</p>
+
+<div style="height: 400px; margin-bottom: 12px; overflow: auto;">
+<pre class="brush: php">&lt;?php
+    $page_title = "Second page";
+
+    $as_json = false;
+    if (isset($_GET["view_as"]) &amp;&amp; $_GET["view_as"] == "json") {
+        $as_json = true;
+        ob_start();
+    } else {
+?&gt;
+&lt;!doctype html&gt;
+&lt;html&gt;
+&lt;head&gt;
+&lt;?php
+        include "include/header.php";
+        echo "&lt;title&gt;" . $page_title . "&lt;/title&gt;";
+?&gt;
+&lt;/head&gt;
+
+&lt;body&gt;
+
+&lt;?php include "include/before_content.php"; ?&gt;
+
+&lt;p&gt;This paragraph is shown only when the navigation starts from &lt;strong&gt;second_page.php&lt;/strong&gt;.&lt;/p&gt;
+
+&lt;div id="ajax-content"&gt;
+&lt;?php } ?&gt;
+
+    &lt;p&gt;This is the content of &lt;strong&gt;second_page.php&lt;/strong&gt;.&lt;/p&gt;
+
+&lt;?php
+    if ($as_json) {
+        echo json_encode(array("page" =&gt; $page_title, "content" =&gt; ob_get_clean()));
+    } else {
+?&gt;
+&lt;/div&gt;
+
+&lt;p&gt;This paragraph is shown only when the navigation starts from &lt;strong&gt;second_page.php&lt;/strong&gt;.&lt;/p&gt;
+
+&lt;?php
+        include "include/after_content.php";
+        echo "&lt;/body&gt;\n&lt;/html&gt;";
+    }
+?&gt;
+</pre>
+</div>
+
+<p><strong>third_page.php</strong>:</p>
+
+<div style="height: 400px; margin-bottom: 12px; overflow: auto;">
+<pre class="brush: php">&lt;?php
+    $page_title = "Third page";
+    $page_content = "&lt;p&gt;This is the content of &lt;strong&gt;third_page.php&lt;/strong&gt;. This content is stored into a php variable.&lt;/p&gt;";
+
+    if (isset($_GET["view_as"]) &amp;&amp; $_GET["view_as"] == "json") {
+        echo json_encode(array("page" =&gt; $page_title, "content" =&gt; $page_content));
+    } else {
+?&gt;
+&lt;!doctype html&gt;
+&lt;html&gt;
+&lt;head&gt;
+&lt;?php
+        include "include/header.php";
+        echo "&lt;title&gt;" . $page_title . "&lt;/title&gt;";
+?&gt;
+&lt;/head&gt;
+
+&lt;body&gt;
+
+&lt;?php include "include/before_content.php"; ?&gt;
+
+&lt;p&gt;This paragraph is shown only when the navigation starts from &lt;strong&gt;third_page.php&lt;/strong&gt;.&lt;/p&gt;
+
+&lt;div id="ajax-content"&gt;
+&lt;?php echo $page_content; ?&gt;
+&lt;/div&gt;
+
+&lt;p&gt;This paragraph is shown only when the navigation starts from &lt;strong&gt;third_page.php&lt;/strong&gt;.&lt;/p&gt;
+
+&lt;?php
+        include "include/after_content.php";
+        echo "&lt;/body&gt;\n&lt;/html&gt;";
+    }
+?&gt;
+</pre>
+</div>
+
+<p><strong>css/style.css</strong>:</p>
+
+<pre class="brush: css">#ajax-loader {
+    position: fixed;
+    display: table;
+    top: 0;
+    left: 0;
+    width: 100%;
+    height: 100%;
+}
+
+#ajax-loader &gt; div {
+    display: table-cell;
+    width: 100%;
+    height: 100%;
+    vertical-align: middle;
+    text-align: center;
+    background-color: #000000;
+    opacity: 0.65;
+}
+</pre>
+
+<p><strong>include/after_content.php</strong>:</p>
+
+<pre class="brush: php">&lt;p&gt;This is the footer. It is shared between all ajax pages.&lt;/p&gt;
+</pre>
+
+<p><strong>include/before_content.php</strong>:</p>
+
+<pre class="brush: php">&lt;p&gt;
+[ &lt;a class="ajax-nav" href="first_page.php"&gt;First example&lt;/a&gt;
+| &lt;a class="ajax-nav" href="second_page.php"&gt;Second example&lt;/a&gt;
+| &lt;a class="ajax-nav" href="third_page.php"&gt;Third example&lt;/a&gt;
+| &lt;a class="ajax-nav" href="unexisting.php"&gt;Unexisting page&lt;/a&gt; ]
+&lt;/p&gt;
+
+</pre>
+
+<p><strong>include/header.php</strong>:</p>
+
+<pre class="brush: php">&lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /&gt;
+&lt;script type="text/javascript" src="js/ajax_nav.js"&gt;&lt;/script&gt;
+&lt;link rel="stylesheet" href="css/style.css" /&gt;
+</pre>
+
+<p><strong>js/ajax_nav.js</strong>:</p>
+
+<div style="height: 400px; margin-bottom: 12px; overflow: auto;">
+<pre class="brush: js">"use strict";
+
+const ajaxRequest = new (function () {
+
+    function closeReq () {
+        oLoadingBox.parentNode &amp;&amp; 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, "&amp;").replace(rView, sViewMode ? "&amp;" + 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 &lt; nLen; document.links[nIdx++].onclick = processLink);
+    }
+
+    const
+
+        /* customizable constants */
+        sTargetId = "ajax-content", sViewKey = "view_as", sAjaxClass = "ajax-nav",
+
+        /* not customizable constants */
+        rSearch = /\?.*$/, rHost = /^[^\?]*\?*&amp;*/, rView = new RegExp("&amp;" + sViewKey + "\\=[^&amp;]*|&amp;*$", "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;
+
+})();
+</pre>
+</div>
+
+<p><br>
+ For more information, please see: <a href="/en-US/docs/DOM/Manipulating_the_browser_history" title="/en-US/docs/DOM/Manipulating_the_browser_history">Manipulating the browser history</a>.</p>
+
+<h2 id="See_also">See also</h2>
+
+<ul>
+ <li>{{ domxref("window.history") }}</li>
+ <li>{{ domxref("window.onpopstate") }}</li>
+</ul>
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
+---
+<div>{{DefaultAPISidebar("History API")}}</div>
+
+<p>DOM {{ domxref("window") }} 对象通过 {{ domxref("window.history", "history") }} 对象提供了对浏览器的会话历史的访问(不要与 <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/history">WebExtensions history</a>搞混了)。它暴露了很多有用的方法和属性,允许你在用户浏览历史中向前和向后跳转,同时——从HTML5开始——提供了对history栈中内容的操作。</p>
+
+<h2 id="意义及使用">意义及使用</h2>
+
+<p>使用 {{DOMxRef("History.back","back()")}},  {{DOMxRef("History.forward","forward()")}}和  {{DOMxRef("History.go","go()")}} 方法来完成在用户历史记录中向后和向前的跳转。</p>
+
+<h3 id="向前和向后跳转">向前和向后跳转</h3>
+
+<p>在history中向后跳转:</p>
+
+<pre class="brush: js notranslate">window.history.back();
+</pre>
+
+<p>这和用户点击浏览器回退按钮的效果相同。</p>
+
+<p>类似地,你可以向前跳转(如同用户点击了前进按钮):</p>
+
+<pre class="brush: js notranslate">window.history.forward();
+</pre>
+
+<h3 id="跳转到_history_中指定的一个点">跳转到 history 中指定的一个点</h3>
+
+<p>你可以用 <code>go()</code> 方法载入到会话历史中的某一特定页面, 通过与当前页面相对位置来标志 (当前页面的相对位置标志为0).</p>
+
+<p>向后移动一个页面 (等同于调用 <code>back()</code>):</p>
+
+<pre class="brush: js notranslate">window.history.go(-1);
+</pre>
+
+<p>向前移动一个页面, 等同于调用了 <code>forward()</code>:</p>
+
+<pre class="brush: js notranslate">window.history.go(1);
+</pre>
+
+<p>类似地,你可以传递参数值2并向前移动2个页面,等等。</p>
+
+<p>您可以通过查看长度属性的值来确定的历史堆栈中页面的数量:</p>
+
+<pre class="brush: js notranslate"> let numberOfEntries = window.history.length;
+</pre>
+
+<div class="note"><strong>注意:</strong> IE 支持传递URLs作为参数给 go(); 这在Gecko是不标准且不支持的。</div>
+
+<h2 id="添加和修改历史记录中的条目">添加和修改历史记录中的条目</h2>
+
+<p>{{ gecko_minversion_header("2") }}</p>
+
+<p>HTML5引入了 <a href="/en-US/docs/Web/API/History/pushState">history.pushState()</a> 和 <a href="/en-US/docs/Web/API/History_API#The_replaceState()_method">history.replaceState()</a> 方法,它们分别可以添加和修改历史记录条目。这些方法通常与{{ domxref("window.onpopstate") }} 配合使用。</p>
+
+<p>使用 <code>history.pushState()</code> 可以改变referrer,它在用户发送 <a href="/en/DOM/XMLHttpRequest" title="en/XMLHttpRequest"><code>XMLHttpRequest</code></a> 请求时在HTTP头部使用,改变state后创建的 <a href="/en/DOM/XMLHttpRequest" title="en/XMLHttpRequest"><code>XMLHttpRequest</code></a> 对象的referrer都会被改变。因为referrer是标识创建  <code><a href="/en/DOM/XMLHttpRequest" title="en/XMLHttpRequest">XMLHttpRequest</a></code> 对象时 <code>this</code> 所代表的window对象中document的URL。</p>
+
+<h3 id="pushState_方法的例子">pushState() 方法的例子</h3>
+
+<p><span class="nowiki">假设在 http://mozilla.org/foo.html</span> 页面的console中执行了以下 JavaScript 代码:</p>
+
+<pre class="brush: js notranslate">window.onpopstate = function(e) {
+  alert(2);
+}
+
+let stateObj = {
+  foo: "bar",
+};
+
+history.pushState(stateObj, "page 2", "bar.html");
+</pre>
+
+<p>这将使浏览器地址栏显示为 <span class="nowiki">http://mozilla.org/bar.html,但并不会导致浏览器加载 </span><code>bar.html</code> ,甚至不会检查<code>bar.html</code> 是否存在。</p>
+
+<p>假如现在用户在bar.html点击了返回按钮,将会执行alert(2)。</p>
+
+<p><span class="nowiki">假设现在用户在bar.html又访问了 http://google.com</span>,然后点击了返回按钮。此时,地址栏将显示 <span class="nowiki">http://mozilla.org/bar.html,<code>history.</code></span><code>state</code> 中包含了 <code>stateObj</code> 的一份拷贝。页面此时展现为<font face='consolas,"Liberation Mono",courier,monospace'><font><code>bar.html</code></font></font>。且因为页面被重新加载了,所以<code>popstate</code>事件将不会被触发,也不会执行alert(2)。</p>
+
+<p>如果我们再次点击返回按钮,页面URL会变为<span class="nowiki">http://mozilla.org/foo.html,文档对象</span>document会触发另外一个 <code>popstate</code> 事件(如果有bar.html,且bar.html注册了onpopstate事件,将会触发此事件,因此也不会执行foo页面注册的onpopstate事件,也就是不会执行alert(2)),这一次的事件对象state object为null。 这里也一样,返回并不改变文档的内容,尽管文档在接收 <code>popstate</code> 事件时可能会改变自己的内容,其内容仍与之前的展现一致。</p>
+
+<p>如果我们再次点击返回按钮,页面URL变为其他页面的url,依然不会执行alert(2)。因为在返回到foo页面的时候并没有pushState。</p>
+
+<h3 id="pushState_方法">pushState() 方法</h3>
+
+<p><code>pushState()</code> 需要三个参数: 一个状态对象, 一个标题 (目前被忽略), 和 (可选的) 一个URL. 让我们来解释下这三个参数详细内容:</p>
+
+<ul>
+ <li>
+ <p><strong>状态对象</strong> — 状态对象state是一个JavaScript对象,通过pushState () 创建新的历史记录条目。无论什么时候用户导航到新的状态,popstate事件就会被触发,且该事件的state属性包含该历史记录条目状态对象的副本。</p>
+
+ <p>        状态对象可以是能被序列化的任何东西。原因在于Firefox将状态对象保存在用户的磁盘上,以便在用户重启浏览器时使用,我们规定了状态对象在序列化表示后有640k的大小限制。如果你给 <code>pushState()</code> 方法传了一个序列化后大于640k的状态对象,该方法会抛出异常。如果你需要更大的空间,建议使用 <code>sessionStorage</code> 以及 <code>localStorage</code>.</p>
+ </li>
+ <li>
+ <p><strong>标题</strong> — Firefox 目前忽略这个参数,但未来可能会用到。在此处传一个空字符串应该可以安全的防范未来这个方法的更改。或者,你可以为跳转的state传递一个短标题。</p>
+ </li>
+ <li>
+ <p><strong>URL</strong> — 该参数定义了新的历史URL记录。注意,调用 <code>pushState()</code> 后浏览器并不会立即加载这个URL,但可能会在稍后某些情况下加载这个URL,比如在用户重新打开浏览器时。新URL不必须为绝对路径。如果新URL是相对路径,那么它将被作为相对于当前URL处理。新URL必须与当前URL同源,否则 <code>pushState()</code> 会抛出一个异常。该参数是可选的,缺省为当前URL。</p>
+ </li>
+</ul>
+
+<div class="note"><strong>注意:</strong> 从 Gecko 2.0 {{ geckoRelease("2.0") }} 到 Gecko 5.0 {{ geckoRelease("5.0") }},传递的对象是使用JSON进行序列化的。 从  Gecko 6.0 {{ geckoRelease("6.0") }}开始,该对象的序列化将使用<a href="/en/DOM/The_structured_clone_algorithm" title="en/DOM/The structured clone algorithm">结构化克隆算法</a>。这将会使更多对象可以被安全的传递。</div>
+
+<p>        在某种意义上,调用 <code>pushState()</code> 与 设置 <code>window.location = "#foo"</code> 类似,二者都会在当前页面创建并激活新的历史记录。但 <code>pushState()</code> 具有如下几条优点:</p>
+
+<ul>
+ <li>新的 URL 可以是与当前URL同源的任意URL 。相反,只有在修改哈希时,设置 <code>window.location</code> 才能是同一个 {{ domxref("document") }}。</li>
+ <li>如果你不想改URL,就不用改。相反,设置 <code>window.location = "#foo";</code>在当前哈希不是 <code>#foo</code> 时, 才能创建新的历史记录项。</li>
+ <li>你可以将任意数据和新的历史记录项相关联。而基于哈希的方式,要把所有相关数据编码为短字符串。 </li>
+ <li>如果 <code>标题</code> 随后还会被浏览器所用到,那么这个数据是可以被使用的(哈希则不是)。</li>
+</ul>
+
+<p>注意 <code>pushState()</code> 绝对不会触发 <code>hashchange</code> 事件,即使新的URL与旧的URL仅哈希不同也是如此。</p>
+
+<p>在 <a href="/en-US/docs/Mozilla/Tech/XUL">XUL</a> 文档中,它创建指定的 XUL 元素。</p>
+
+<p>在其它文档中,它创建一个命名空间URI为<code>null</code>的元素。</p>
+
+<h3 id="replaceState_方法">replaceState() 方法</h3>
+
+<p><code>history.replaceState()</code> 的使用与 <code>history.pushState()</code> 非常相似,区别在于  <code>replaceState()</code>  是修改了当前的历史记录项而不是新建一个。 注意这并不会阻止其在全局浏览器历史记录中创建一个新的历史记录项。</p>
+
+<p><code>replaceState()</code> 的使用场景在于为了响应用户操作,你想要更新状态对象state或者当前历史记录的URL。</p>
+
+<div class="note"><strong>注意:</strong> 从Gecko 2.0 {{ geckoRelease("2.0") }} 到 Gecko 5.0 {{ geckoRelease("5.0") }},传递的对象是使用JSON进行序列化的。 从  Gecko 6.0 {{ geckoRelease("6.0") }}开始,该对象的序列化将使用<a href="/en/DOM/The_structured_clone_algorithm" title="en/DOM/The structured clone algorithm">结构化克隆算法</a>。这将会使更多对象可以被安全的传递。</div>
+
+<h3 id="replaceState_方法示例">replaceState() 方法示例</h3>
+
+<p>假设 <span class="nowiki">http://mozilla.org/foo.html</span> 执行了如下JavaScript代码:</p>
+
+<pre class="brush: js notranslate">let stateObj = {
+  foo: "bar",
+};
+
+history.pushState(stateObj, "page 2", "bar.html");
+</pre>
+
+<p>上文2行代码可以在 "pushState()方法示例" 部分找到。然后,假设<span class="nowiki">http://mozilla.org/bar.html执行了如下</span> JavaScript:</p>
+
+<pre class="brush: js notranslate">history.replaceState(stateObj, "page 3", "bar2.html");
+</pre>
+
+<p>这将会导致地址栏显示<span class="nowiki">http://mozilla.org/bar2.html</span>,,但是浏览器并不会去加载<code>bar2.html</code> 甚至都不需要检查 <code>bar2.html</code> 是否存在。</p>
+
+<p>假设现在用户重新导向到了<span class="nowiki">http://www.microsoft.com,然后点击了回退按钮。这里,地址栏会显示</span><span class="nowiki">http://mozilla.org/bar2.html。假如用户再次点击回退按钮,地址栏会显示http://mozilla.org/foo.html,完全跳过了bar.html。</span></p>
+
+<h3 id="popstate_事件">popstate 事件</h3>
+
+<p>        每当活动的历史记录项发生变化时, <code>popstate</code> 事件都会被传递给window对象。如果当前活动的历史记录项是被 <code>pushState</code> 创建的,或者是由 <code>replaceState</code> 改变的,那么 <code>popstate</code> 事件的状态属性 <code>state</code> 会包含一个当前历史记录状态对象的拷贝。</p>
+
+<p>使用示例请参见 {{ domxref("window.onpopstate") }} 。</p>
+
+<h3 id="获取当前状态">获取当前状态</h3>
+
+<p>        页面加载时,或许会有个非null的状态对象。这是有可能发生的,举个例子,假如页面(通过<code>pushState()</code> 或 <code>replaceState()</code> 方法)设置了状态对象而后用户重启了浏览器。那么当页面重新加载时,页面会接收一个<span style="font-family: courier new;">onload事件,但没有</span><span style="font-family: helvetica;"> <span style="font-family: courier new;">popstate</span> 事件。然而,假如你读取了</span><span style="font-family: courier new;">history.state属性,你将会得到如同</span><span style="font-family: courier new;">popstate</span> 被触发时能得到的状态对象。</p>
+
+<p>你可以读取当前历史记录项的状态对象state,而不必等待<code>popstate</code> 事件, 只需要这样使用<code>history.state</code> 属性: </p>
+
+<pre class="brush: js notranslate"> // 尝试通过 pushState 创建历史条目,然后再刷新页面查看state状态对象变化;
+  window.addEventListener('load',() =&gt; {
+ let currentState = history.state;
+  console.log('currentState',currentState);
+ })
+</pre>
+
+<h2 id="例子">例子</h2>
+
+<p>完整的AJAX网站示例,请参阅: <a href="/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history/Example" title="/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history/Example">Ajax navigation example</a>.</p>
+
+<h2 id="规范">规范</h2>
+
+<table class="standard-table">
+ <tbody>
+ <tr>
+ <th scope="col">Specification</th>
+ <th scope="col">Status</th>
+ <th scope="col">Comment</th>
+ </tr>
+ <tr>
+ <td>{{SpecName('HTML WHATWG', "browsers.html#history", "History")}}</td>
+ <td>{{Spec2('HTML WHATWG')}}</td>
+ <td>No change from {{SpecName("HTML5 W3C")}}.</td>
+ </tr>
+ <tr>
+ <td>{{SpecName('HTML5 W3C', "browsers.html#history", "History")}}</td>
+ <td>{{Spec2('HTML5 W3C')}}</td>
+ <td>Initial definition.</td>
+ </tr>
+ </tbody>
+</table>
+
+<h2 id="浏览器兼容性">浏览器兼容性</h2>
+
+<p>{{Compat("api.History")}}</p>
+
+<h2 id="另见"><strong>另见</strong></h2>
+
+<h3 id="参考"><strong>参考</strong></h3>
+
+<ul>
+ <li>{{ domxref("window.history") }}</li>
+ <li>{{ domxref("window.onpopstate") }}</li>
+</ul>
+
+<h3 id="Guides">Guides</h3>
+
+<ul>
+ <li><a href="https://wiki.developer.mozilla.org/en-US/docs/Web/API/History_API/Working_with_the_History_API">Working with the History API</a></li>
+</ul>
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
+---
+<p>HTML5引入了{{DOMxRef("History.pushState","pushState()")}}和{{DOMxRef("History.replaceState","replaceState()")}}方法,分别用于添加和修改历史记录。这些方法与{{domxref("Window.onpopstate","onpopstate")}} 事件一起工作。</p>
+
+<h2 id="添加和修改历史记录">添加和修改历史记录</h2>
+
+<p>{{ gecko_minversion_header("2") }}</p>
+
+<p>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 <code>this</code> at the time of creation of the {{domxref("XMLHttpRequest")}} object.</p>
+
+<h3 id="pushState方法实例"><a id="Example_of_pushState_method" name="Example_of_pushState_method">pushState()方法实例</a></h3>
+
+<p>假设 <code><span class="nowiki">http://mozilla.org/foo.html</span></code> 执行下面的JavaScript:</p>
+
+<pre class="brush: js notranslate">let stateObj = {
+  foo: "bar",
+}
+
+history.pushState(stateObj, "page 2", "bar.html")
+</pre>
+
+<p>This will cause the URL bar to display <code><span class="nowiki">http://mozilla.org/bar.html</span></code>, but won't cause the browser to load <code>bar.html</code> or even check that <code>bar.html</code> exists.</p>
+
+<p>Suppose now that the user navigates to <code>http://google.com</code>, then clicks the <strong>Back</strong> button. At this point, the URL bar will display <code>http://mozilla.org/bar.html</code> and <code>history.state</code> will contain the <code>stateObj</code>. The <code>popstate</code> event won't be fired because the page has been reloaded. The page itself will look like <code>bar.html</code>.</p>
+
+<p>If the user clicks <strong>Back</strong> once again, the URL will change to <code><span class="nowiki">http://mozilla.org/foo.html</span></code>, and the document will get a <code>popstate</code> event, this time with a <code>null</code> 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 <code>popstate</code> event.</p>
+
+<div class="blockIndicator note">
+<p><strong>Note:</strong> Calling <code>history.back()</code> normally behaves the same way as clicking the <strong>Back</strong> button. But there is one important exception:</p>
+
+<p><em>After</em> using <code>history.pushState()</code>, calling <code>history.back()</code> <em>does not</em> raise a <code>popstate</code> event. Clicking the browser's <strong>Back</strong> button (still) does.</p>
+</div>
+
+<h3 id="The_pushState_method">The pushState() method</h3>
+
+<p><code>pushState()</code> takes three parameters: a <dfn><em>state</em> object</dfn>; a <em><dfn>title</dfn></em> (currently ignored); and (optionally), a <em><dfn>URL</dfn></em>.</p>
+
+<p>Let's examine each of these three parameters in more detail.</p>
+
+<dl>
+ <dt><strong>state object</strong> </dt>
+ <dd>The state object is a JavaScript object which is associated with the new history entry created by <code>pushState()</code>. Whenever the user navigates to the new state, a <code>popstate</code> event is fired, and the <code>state</code> property of the event contains a copy of the history entry's state object.</dd>
+ <dd>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 <code>pushState()</code>, the method will throw an exception. If you need more space than this, you're encouraged to use <code>sessionStorage</code> and/or <code>localStorage</code>.</dd>
+</dl>
+
+<dl>
+ <dt><strong>title</strong></dt>
+ <dd><a href="https://github.com/whatwg/html/issues/2174">All browsers but Safari currently ignore this parameter</a>, 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.</dd>
+</dl>
+
+<dl>
+ <dt><strong>URL</strong></dt>
+ <dd>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 <code>pushState()</code>, 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, <code>pushState()</code> will throw an exception. This parameter is optional; if it isn't specified, it's set to the document's current URL.</dd>
+</dl>
+
+<div class="note"><strong>Note:</strong> 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 <a href="/en/DOM/The_structured_clone_algorithm" title="en/DOM/The structured clone algorithm">the structured clone algorithm</a>. This allows a wider variety of objects to be safely passed.</div>
+
+<p>In a sense, calling <code>pushState()</code> is similar to setting <code>window.location = "#foo"</code>, in that both will also create and activate another history entry associated with the current document.</p>
+
+<p>But <code>pushState()</code> has a few advantages:</p>
+
+<ul>
+ <li>The new URL can be any URL in the same origin as the current URL. In contrast, setting <code>window.location</code> keeps you at the same {{ domxref("document") }} only if you modify only the hash.</li>
+ <li>You don't have to change the URL if you don't want to. In contrast, setting <code>window.location = "#foo";</code> creates a new history entry only if the current hash isn't <code>#foo</code>.</li>
+ <li>You can associate arbitrary data with your new history entry. With the hash-based approach, you need to encode all of the relevant data into a short string.</li>
+ <li>If <code>title </code>is subsequently used by browsers, this data can be utilized (independent of, say, the hash).</li>
+</ul>
+
+<p>Note that <code>pushState()</code> never causes a <code>hashchange</code> event to be fired, even if the new URL differs from the old URL only in its hash.</p>
+
+<p>In a <a href="/en-US/docs/Mozilla/Tech/XUL">XUL</a> document, it creates the specified XUL element.</p>
+
+<p>In other documents, it creates an element with a <code>null</code> namespace URI.</p>
+
+<h3 id="The_replaceState_method">The replaceState() method</h3>
+
+<p><code>history.replaceState()</code> operates exactly like <code>history.pushState()</code>, except that <code>replaceState()</code> 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.</p>
+
+<p><code>replaceState()</code> is particularly useful when you want to update the state object or URL of the current history entry in response to some user action.</p>
+
+<div class="note"><strong>Note:</strong> 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 <a href="/en/DOM/The_structured_clone_algorithm" title="en/DOM/The structured clone algorithm">the structured clone algorithm</a>. This allows a wider variety of objects to be safely passed.</div>
+
+<h3 id="Example_of_replaceState_method">Example of replaceState() method</h3>
+
+<p>Suppose <code><span class="nowiki">http://mozilla.org/foo.html</span></code> executes the following JavaScript:</p>
+
+<pre class="brush: js notranslate">let stateObj = { foo: "bar" }
+history.pushState(stateObj, "page 2", "bar.html")
+</pre>
+
+<p>The explanation of these two lines above can be found at the above section <em><a href="#Example_of_pushState_method">Example of pushState() method</a></em> section.</p>
+
+<p>Next, suppose <code><span class="nowiki">http://mozilla.org/bar.html</span></code> executes the following JavaScript:</p>
+
+<pre class="brush: js notranslate">history.replaceState(stateObj, "page 3", "bar2.html")
+</pre>
+
+<p>This will cause the URL bar to display <code><span class="nowiki">http://mozilla.org/bar2.html</span></code>, but won't cause the browser to load <code>bar2.html</code> or even check that <code>bar2.html</code> exists.</p>
+
+<p>Suppose now that the user navigates to <code><span class="nowiki">http://www.microsoft.com</span></code>, then clicks the <strong>Back</strong> button. At this point, the URL bar will display <span class="nowiki"><code>http://mozilla.org/bar2.html</code>. If the user now clicks <strong>Back</strong> again, the URL bar will display <code>http://mozilla.org/foo.html</code>, and totally bypass <code>bar.html</code>.</span></p>
+
+<h3 id="The_popstate_event">The popstate event</h3>
+
+<p>A <code>popstate</code> 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 <code>popstate</code> event's <code>state</code> property contains a copy of the history entry's state object.</p>
+
+<p>See {{ domxref("Window.onpopstate") }} for sample usage.</p>
+
+<h3 id="Reading_the_current_state">Reading the current state</h3>
+
+<p>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 <code>onload</code><span style="font-family: helvetica;"> event, but no </span><code>popstate</code> <span style="font-family: helvetica;">event.</span> However, if you read the {{DOMxRef("History.state","history.state")}} property, you'll get back the state object you would have gotten if a <code>popstate</code> had fired.</p>
+
+<p>You can read the state of the current history entry without waiting for a <code>popstate</code> event using the {{DOMxRef("History.state","history.state")}} property like this:</p>
+
+<pre class="brush: js notranslate">let currentState = history.state
+</pre>
+
+<h2 id="See_also">See also</h2>
+
+<ul>
+ <li><a href="/en-US/docs/Web/API/History_API">History API</a></li>
+ <li><a href="/en-US/docs/Web/API/History_API/Example">Ajax navigation example</a></li>
+ <li>{{ domxref("window.history") }}</li>
+</ul>