Skip to content

Commit

Permalink
Strip jQuery's cache-busting parameter
Browse files Browse the repository at this point in the history
If jQuery `cache: false` ajax parameter is set, the `&_=<TIMESTAMP>`
param will have been appended to the request URL. Because this URL will
eventually be used to replace the page URL, we need to ensure that we're
stripping the cache-busting parameter before that, like we do with the
"_pjax" internal parameter as well.
  • Loading branch information
mislav committed Mar 2, 2015
1 parent e34a213 commit abb8079
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 9 deletions.
23 changes: 15 additions & 8 deletions jquery.pjax.js
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ function pjax(options) {
settings.timeout = 0
}

options.requestUrl = parseURL(settings.url).href
options.requestUrl = stripInternalParams(parseURL(settings.url).href)
}

options.complete = function(xhr, textStatus) {
Expand Down Expand Up @@ -366,7 +366,7 @@ function pjax(options) {
// Cache current container element before replacing it
cachePush(pjax.state.id, context.clone().contents())

window.history.pushState(null, "", stripPjaxParam(options.requestUrl))
window.history.pushState(null, "", options.requestUrl)
}

fire('pjax:start', [xhr, options])
Expand Down Expand Up @@ -544,16 +544,22 @@ function uniqueId() {
return (new Date).getTime()
}

// Internal: Strips _pjax param from url
// Internal: Strips named query param from url
//
// url - String
//
// Returns String.
function stripPjaxParam(url) {
function stripParam(url, name) {
return url
.replace(new RegExp('[?&]' + name + '=[^&]*'), '')
.replace(/[?&]$/, '')
.replace(/[?&]/, '?')
}

function stripInternalParams(url) {
url = stripParam(url, '_pjax')
url = stripParam(url, '_')
return url
.replace(/\?_pjax=[^&]+&?/, '?')
.replace(/_pjax=[^&]+&?/, '')
.replace(/[\?&]$/, '')
}

// Internal: Parse URL components and returns a Locationish object.
Expand Down Expand Up @@ -669,7 +675,8 @@ function extractContainer(data, xhr, options) {

// Prefer X-PJAX-URL header if it was set, otherwise fallback to
// using the original requested url.
obj.url = stripPjaxParam(xhr.getResponseHeader('X-PJAX-URL') || options.requestUrl)
var serverUrl = xhr.getResponseHeader('X-PJAX-URL')
obj.url = serverUrl ? stripInternalParams(serverUrl) : options.requestUrl

// Attempt to parse response html into elements
if (fullDocument) {
Expand Down
4 changes: 3 additions & 1 deletion test/unit/pjax.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,13 @@ if ($.support.pjax) {

frame.$('#main').on('pjax:success', function() {
equal(frame.location.pathname, "/hello.html")
equal(frame.location.search, "")
start()
})
frame.$.pjax({
url: "hello.html",
container: "#main"
container: "#main",
cache: false
})
})

Expand Down

0 comments on commit abb8079

Please sign in to comment.