Skip to content

Commit e6a3d7d

Browse files
committed
Initialize pjax.state to history.state
Fixes regression from 3d34af6
1 parent 7e87ab1 commit e6a3d7d

File tree

1 file changed

+24
-6
lines changed

1 file changed

+24
-6
lines changed

jquery.pjax.js

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -358,6 +358,18 @@ function locationReplace(url) {
358358
window.location.replace(url)
359359
}
360360

361+
362+
var initialPop = true
363+
var initialURL = window.location.href
364+
var initialState = window.history.state
365+
366+
// Initialize $.pjax.state if possible
367+
// Happens when reloading a page and coming forward from a different
368+
// session history.
369+
if (initialState && initialState.container) {
370+
pjax.state = initialState
371+
}
372+
361373
// popstate handler takes care of the back and forward buttons
362374
//
363375
// You probably shouldn't use pjax on pages with other pushState
@@ -366,23 +378,28 @@ function onPjaxPopstate(event) {
366378
var state = event.state
367379

368380
if (state && state.container) {
381+
// When coming forward from a seperate history session, will get an
382+
// initial pop with a state we are already at. Skip reloading the current
383+
// page.
384+
if (initialPop && initialURL == state.url) return
385+
369386
var container = $(state.container)
370387
if (container.length) {
371-
var contents = cacheMapping[state.id]
388+
var direction, contents = cacheMapping[state.id]
372389

373390
if (pjax.state) {
374391
// Since state ids always increase, we can deduce the history
375392
// direction from the previous state.
376-
var direction = pjax.state.id < state.id ? 'forward' : 'back'
393+
direction = pjax.state.id < state.id ? 'forward' : 'back'
377394

378395
// Cache current container before replacement and inform the
379396
// cache which direction the history shifted.
380397
cachePop(direction, pjax.state.id, container.clone().contents())
381398
} else {
382-
// Page was reloaded but we have an existing history entry.
383-
// Set it to our initial state.
384-
pjax.state = state;
385-
return;
399+
// Unknown case: If you happen to hit it, please open an issue on
400+
// https://github.com/defunkt/jquery-pjax/issues?sort=updated&state=open
401+
// with steps to reproduce.
402+
throw "missing initial pjax state"
386403
}
387404

388405
var popstateEvent = $.Event('pjax:popstate', {
@@ -420,6 +437,7 @@ function onPjaxPopstate(event) {
420437
locationReplace(location.href)
421438
}
422439
}
440+
initialPop = false
423441
}
424442

425443
// Fallback version of main pjax function for browsers that don't

0 commit comments

Comments
 (0)