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
|
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 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
.
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.
pushState()
or
replaceState()
, set the entry's title to the string returned by its
document.title
属性。
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.
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.
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
.
URL
is set to that of
new-entry
.
delta
parameter on methods such as
go()
) is removed from the history stack.
null
, the document is scrolled to that fragment.
History.state
;否则,
state
is
null
.
state
changed, the
popstate
event is sent to the document.
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. |
实时标准 |
| 桌面 | 移动 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
popstate
event
|
Chrome
5
|
Edge 12 |
Firefox
4
|
IE 10 | Opera 11.5 |
Safari
6
|
WebView Android
≤37
|
Chrome Android
18
|
Firefox Android
4
|
Opera Android 11.5 |
Safari iOS
5.1
|
Samsung Internet Android
1.0
|
完整支持
见实现注意事项。
Window
applicationCache
caches
closed
console
controllers
crossOriginIsolated
crypto
customElements
defaultStatus
devicePixelRatio
dialogArguments
目录
document
event
frameElement
frames
fullScreen
history
indexedDB
innerHeight
innerWidth
isSecureContext
isSecureContext
length
localStorage
location
locationbar
menubar
mozAnimationStartTime
mozInnerScreenX
mozInnerScreenY
mozPaintCount
名称
navigator
onabort
onafterprint
onanimationcancel
onanimationend
onanimationiteration
onappinstalled
onauxclick
onbeforeinstallprompt
onbeforeprint
onbeforeunload
onblur
oncancel
oncanplay
oncanplaythrough
onchange
onclick
onclose
oncontextmenu
oncuechange
ondblclick
ondevicelight
ondevicemotion
ondeviceorientation
ondeviceorientationabsolute
ondeviceproximity
ondragdrop
ondurationchange
onended
onerror
onfocus
onformdata
ongamepadconnected
ongamepaddisconnected
ongotpointercapture
onhashchange
oninput
oninvalid
onkeydown
onkeypress
onkeyup
onlanguagechange
onload
onloadeddata
onloadedmetadata
onloadend
onloadstart
onlostpointercapture
onmessage
onmessageerror
onmousedown
onmouseenter
onmouseleave
onmousemove
onmouseout
onmouseover
onmouseup
onmozbeforepaint
onpaint
onpause
onplay
onplaying
onpointercancel
onpointerdown
onpointerenter
onpointerleave
onpointermove
onpointerout
onpointerover
onpointerup
onpopstate
onrejectionhandled
onreset
onresize
onscroll
onselect
onselectionchange
onselectstart
onstorage
onsubmit
ontouchcancel
ontouchstart
ontransitioncancel
ontransitionend
onunhandledrejection
onunload
onuserproximity
onvrdisplayactivate
onvrdisplayblur
onvrdisplayconnect
onvrdisplaydeactivate
onvrdisplaydisconnect
onvrdisplayfocus
onvrdisplaypointerrestricted
onvrdisplaypointerunrestricted
onvrdisplaypresentchange
onwheel
opener
origin
outerHeight
outerWidth
pageXOffset
pageYOffset
parent
性能
personalbar
pkcs11
screen
screenLeft
screenTop
screenX
screenY
scrollbars
scrollMaxX
scrollMaxY
scrollX
scrollY
self
sessionStorage
sidebar
speechSynthesis
status
statusbar
toolbar
top
visualViewport
window
alert()
atob()
back()
blur()
btoa()
cancelAnimationFrame()
cancelIdleCallback()
captureEvents()
clearImmediate()
clearInterval()
clearTimeout()
close()
confirm()
convertPointFromNodeToPage()
convertPointFromPageToNode
createImageBitmap()
dump()
fetch()
find()
focus()
forward()
getAttention()
getComputedStyle()
getDefaultComputedStyle()
getSelection()
home()
matchMedia()
minimize()
moveBy()
moveTo()
open()
openDialog()
postMessage()
print()
prompt()
queueMicrotask()
releaseEvents()
requestAnimationFrame()
requestFileSystem()
requestIdleCallback()
resizeBy()
resizeTo()
restore()
routeEvent()
scroll()
scrollBy()
scrollByLines()
scrollByPages()
scrollTo()
setCursor()
setImmediate()
setInterval()
setTimeout()
showModalDialog()
sizeToContent()
stop()
updateCommands()
event
afterprint
animationcancel
animationend
animationiteration
beforeprint
beforeunload
blur
copy
cut
DOMContentLoaded
error
focus
hashchange
languagechange
load
message
messageerror
offline
online
orientationchange
pagehide
pageshow
paste
popstate
rejectionhandled
storage
transitioncancel
unhandledrejection
unload
vrdisplayconnect
vrdisplaydisconnect
vrdisplaypresentchange