Last active
August 29, 2015 14:16
-
-
Save sdthornton/d3f6e11734c8549bb731 to your computer and use it in GitHub Desktop.
Add URL params to a page with pushState
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Simply pass in the params you want as an object, e.g. addURLParams({ foo: 'bar' }) | |
var addURLParams = function(newParams) { | |
if (!newParams || typeof(newParams) !== 'object') { | |
return false; | |
} | |
var extend = function(out) { | |
out = out || {}; | |
for (var i = 1; i < arguments.length; i++) { | |
if (!arguments[i]) | |
continue; | |
for (var key in arguments[i]) { | |
if (arguments[i].hasOwnProperty(key)) | |
out[key] = arguments[i][key]; | |
} | |
} | |
return out; | |
}; | |
var jsonify = function(string) { | |
return JSON.parse(string.replace(/\?/, '{"').replace(/&/g, '","').replace(/=/g, '":"').replace(/$/, '"}')); | |
} | |
var search = window.location.search, | |
params; | |
if (search) { | |
var oldParams = jsonify(search); | |
params = extend({}, oldParams, newParams); | |
} else { | |
params = newParams; | |
} | |
var paramString = "?" | |
for (var key in params) { | |
if (params.hasOwnProperty(key)) { | |
paramString += key + '=' + params[key] + '&'; | |
} | |
} | |
paramString = paramString.replace(/&$/, ''); | |
if (window.history && history.pushState) { | |
window.history.pushState(params, '', window.location.pathname + paramString); | |
} else { | |
window.location = window.location.pathname + paramString; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment