popstate event of the Window interface is fired when the active history entry changes while the user navigates the session history. It changes the current history entry to that of the last page the user visited or, if history.pushState() has been used to add a history entry to the history stack, that history entry is used instead.

冒泡 Yes
可取消 No
接口 PopStateEvent
事件处理程序特性 onpopstate

The history stack

If the history entry being activated was created by a call to history.pushState() or was affected by a call to history.replaceState() popstate event's state property contains a copy of the history entry's state object.

These methods and their corresponding events can be used to add data to the history stack which can be used to reconstruct a dynamically generated page, or to otherwise alter the state of the content being presented while remaining on the same Document .

Note that just calling history.pushState() or history.replaceState() won't trigger a popstate event. The popstate event will be triggered by doing a browser action such as a click on the back or forward button (or calling history.back() or history.forward() in JavaScript).

Browsers tend to handle the popstate event differently on page load. Chrome (prior to v34) and Safari always emit a popstate event on page load, but Firefox doesn't.

注意 : When writing functions that process popstate event it is important to take into account that properties like window.location will already reflect the state change (if it affected the current URL), but document might still not. If the goal is to catch the moment when the new document state is already fully in place, a zero-delay setTimeout() method call should be used to effectively put its inner callback function that does the processing at the end of the browser event loop: 窗口。 onpopstate = () => setTimeout(doSomeThing, 0);

When popstate is sent

When the transition occurs, either due to the user triggering the browser's "Back" button or otherwise, the popstate event is near the end of the process to transition to the new location. It happens after the new location has loaded (if needed), displayed, made visible, and so on, after the pageshow event is sent, but before the persisted user state information is restored and the hashchange event is sent.

To better understand when the popstate event is fired, consider this simplified sequence of events that occurs when the current history entry changes due to either the user navigating the site or the history being traversed programmatically. Here, the transition is changing the current history entry to one we'll refer to as new-entry . The current page's session history stack entry will be referred to as current-entry .

  1. new-entry doesn't currently contain an existing Document , fetch the content and create its Document before continuing. This will eventually send events such as DOMContentLoaded and load Window containing the document, but the steps below will continue to execute in the meantime.
  2. current-entry 's title wasn't set using one of the History API methods ( pushState() or replaceState() , set the entry's title to the string returned by its document.title 属性。
  3. If the browser has state information it wishes to store with the current-entry before navigating away from it, it then does so. The entry is now said to have "persisted user state." This information the browser might add to the history session entry may include, for instance, the document's scroll position, the values of form inputs, and other such data.
  4. new-entry has a different Document object than current-entry , the browsing context is updated so that its document property refers to the document referred to by new-entry , and the context's name is updated to match the context name of the now-current document.
  5. Each form control within new-entry 's Document that has autocomplete configured with its autofill field name set to off is reset. See The HTML autocomplete attribute for more about the autocomplete field names and how autocomplete works.
  6. new-entry 's document is already fully loaded and ready—that is, its readyState is complete —and the document is not already visible, it's made visible and the pageshow event is fired at the document with the PageTransitionEvent 's persisted 属性设置为 true .
  7. The document's URL is set to that of new-entry .
  8. If the history traversal is being performed with replacement enabled, the entry immediately prior to the destination entry (taking into account the delta parameter on methods such as go() ) is removed from the history stack.
  9. new-entry doesn't have persisted user state and its URL's fragment is non- null , the document is scrolled to that fragment.
  10. Next, current-entry 被设为 new-entry . The destination entry is now considered to be current.
  11. new-entry has serialized state information saved with it, that information is deserialized into History.state ;否则, state is null .
  12. 若值 state changed, the popstate event is sent to the document.
  13. Any persisted user state is restored, if the browser chooses to do so.
  14. If the original and new entry's shared the same document, but had different fragments in their URLs, send the hashchange event to the window.

As you can see, the popstate event is nearly the last thing done in the process of navigating pages in this way.

范例

A page at http://example.com/example.html running the following code will generate logs as indicated:

window.addEventListener('popstate', (event) => {
  console.log("location: " + document.location + ", state: " + JSON.stringify(event.state));
});
history.pushState({page: 1}, "title 1", "?page=1");
history.pushState({page: 2}, "title 2", "?page=2");
history.replaceState({page: 3}, "title 3", "?page=3");
history.back(); // Logs "location: http://example.com/example.html?page=1, state: {"page":1}"
history.back(); // Logs "location: http://example.com/example.html, state: null"
history.go(2);  // Logs "location: http://example.com/example.html?page=3, state: {"page":3}"
					

The same example using the onpopstate 事件处理程序特性:

window.onpopstate = function(event) {
  console.log("location: " + document.location + ", state: " + JSON.stringify(event.state));
};
history.pushState({page: 1}, "title 1", "?page=1");
history.pushState({page: 2}, "title 2", "?page=2");
history.replaceState({page: 3}, "title 3", "?page=3");
history.back(); // Logs "location: http://example.com/example.html?page=1, state: {"page":1}"
history.back(); // Logs "location: http://example.com/example.html, state: null"
history.go(2);  // Logs "location: http://example.com/example.html?page=3, state: {"page":3}"
					

Note that even though the original history entry (for http://example.com/example.html ) has no state object associated with it, a popstate event is still fired when we activate that entry after the second call to history.back() .

规范

规范 状态
HTML 实时标准
The definition of 'popstate' in that specification.
实时标准

浏览器兼容性

更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
popstate event Chrome 5
5
Before version 34, Chrome would fire a popstate event on page load.
Edge 12 Firefox 4
4
Firefox emits a popstate event on page load.
IE 10 Opera 11.5 Safari 6
6
Before version 10, Safari would fire a popstate event on page load.
WebView Android ≤37
≤37
Before version 37, WebView would fire a popstate event on page load.
Chrome Android 18
18
Before version 34, Chrome would fire a popstate event on page load.
Firefox Android 4
4
Firefox emits a popstate event on page load.
Opera Android 11.5 Safari iOS 5.1
5.1
Before version 10, Safari would fire a popstate event on page load.
Samsung Internet Android 1.0
1.0
Before version 2.0, Samsung Internet would fire a popstate event on page load.

图例

完整支持

完整支持

见实现注意事项。

另请参阅

元数据

  • 最后修改:
  1. Window
  2. 特性
    1. applicationCache
    2. caches
    3. closed
    4. console
    5. controllers
    6. crossOriginIsolated
    7. crypto
    8. customElements
    9. defaultStatus
    10. devicePixelRatio
    11. dialogArguments
    12. 目录
    13. document
    14. event
    15. frameElement
    16. frames
    17. fullScreen
    18. history
    19. indexedDB
    20. innerHeight
    21. innerWidth
    22. isSecureContext
    23. isSecureContext
    24. length
    25. localStorage
    26. location
    27. locationbar
    28. menubar
    29. mozAnimationStartTime
    30. mozInnerScreenX
    31. mozInnerScreenY
    32. mozPaintCount
    33. 名称
    34. navigator
    35. onabort
    36. onafterprint
    37. onanimationcancel
    38. onanimationend
    39. onanimationiteration
    40. onappinstalled
    41. onauxclick
    42. onbeforeinstallprompt
    43. onbeforeprint
    44. onbeforeunload
    45. onblur
    46. oncancel
    47. oncanplay
    48. oncanplaythrough
    49. onchange
    50. onclick
    51. onclose
    52. oncontextmenu
    53. oncuechange
    54. ondblclick
    55. ondevicelight
    56. ondevicemotion
    57. ondeviceorientation
    58. ondeviceorientationabsolute
    59. ondeviceproximity
    60. ondragdrop
    61. ondurationchange
    62. onended
    63. onerror
    64. onfocus
    65. onformdata
    66. ongamepadconnected
    67. ongamepaddisconnected
    68. ongotpointercapture
    69. onhashchange
    70. oninput
    71. oninvalid
    72. onkeydown
    73. onkeypress
    74. onkeyup
    75. onlanguagechange
    76. onload
    77. onloadeddata
    78. onloadedmetadata
    79. onloadend
    80. onloadstart
    81. onlostpointercapture
    82. onmessage
    83. onmessageerror
    84. onmousedown
    85. onmouseenter
    86. onmouseleave
    87. onmousemove
    88. onmouseout
    89. onmouseover
    90. onmouseup
    91. onmozbeforepaint
    92. onpaint
    93. onpause
    94. onplay
    95. onplaying
    96. onpointercancel
    97. onpointerdown
    98. onpointerenter
    99. onpointerleave
    100. onpointermove
    101. onpointerout
    102. onpointerover
    103. onpointerup
    104. onpopstate
    105. onrejectionhandled
    106. onreset
    107. onresize
    108. onscroll
    109. onselect
    110. onselectionchange
    111. onselectstart
    112. onstorage
    113. onsubmit
    114. ontouchcancel
    115. ontouchstart
    116. ontransitioncancel
    117. ontransitionend
    118. onunhandledrejection
    119. onunload
    120. onuserproximity
    121. onvrdisplayactivate
    122. onvrdisplayblur
    123. onvrdisplayconnect
    124. onvrdisplaydeactivate
    125. onvrdisplaydisconnect
    126. onvrdisplayfocus
    127. onvrdisplaypointerrestricted
    128. onvrdisplaypointerunrestricted
    129. onvrdisplaypresentchange
    130. onwheel
    131. opener
    132. origin
    133. outerHeight
    134. outerWidth
    135. pageXOffset
    136. pageYOffset
    137. parent
    138. 性能
    139. personalbar
    140. pkcs11
    141. screen
    142. screenLeft
    143. screenTop
    144. screenX
    145. screenY
    146. scrollbars
    147. scrollMaxX
    148. scrollMaxY
    149. scrollX
    150. scrollY
    151. self
    152. sessionStorage
    153. sidebar
    154. speechSynthesis
    155. status
    156. statusbar
    157. toolbar
    158. top
    159. visualViewport
    160. window
  3. 方法
    1. alert()
    2. atob()
    3. back()
    4. blur()
    5. btoa()
    6. cancelAnimationFrame()
    7. cancelIdleCallback()
    8. captureEvents()
    9. clearImmediate()
    10. clearInterval()
    11. clearTimeout()
    12. close()
    13. confirm()
    14. convertPointFromNodeToPage()
    15. convertPointFromPageToNode
    16. createImageBitmap()
    17. dump()
    18. fetch()
    19. find()
    20. focus()
    21. forward()
    22. getAttention()
    23. getComputedStyle()
    24. getDefaultComputedStyle()
    25. getSelection()
    26. home()
    27. matchMedia()
    28. minimize()
    29. moveBy()
    30. moveTo()
    31. open()
    32. openDialog()
    33. postMessage()
    34. print()
    35. prompt()
    36. queueMicrotask()
    37. releaseEvents()
    38. requestAnimationFrame()
    39. requestFileSystem()
    40. requestIdleCallback()
    41. resizeBy()
    42. resizeTo()
    43. restore()
    44. routeEvent()
    45. scroll()
    46. scrollBy()
    47. scrollByLines()
    48. scrollByPages()
    49. scrollTo()
    50. setCursor()
    51. setImmediate()
    52. setInterval()
    53. setTimeout()
    54. showModalDialog()
    55. sizeToContent()
    56. stop()
    57. updateCommands()
  4. 事件
    1. event
    2. afterprint
    3. animationcancel
    4. animationend
    5. animationiteration
    6. beforeprint
    7. beforeunload
    8. blur
    9. copy
    10. cut
    11. DOMContentLoaded
    12. error
    13. focus
    14. hashchange
    15. languagechange
    16. load
    17. message
    18. messageerror
    19. offline
    20. online
    21. orientationchange
    22. pagehide
    23. pageshow
    24. paste
    25. popstate
    26. rejectionhandled
    27. storage
    28. transitioncancel
    29. unhandledrejection
    30. unload
    31. vrdisplayconnect
    32. vrdisplaydisconnect
    33. vrdisplaypresentchange

版权所有  © 2014-2026 乐数软件    

工业和信息化部: 粤ICP备14079481号-1