Created
March 8, 2018 04:07
-
-
Save bfodeke/7072d3f2a42dac12d66192d01806d0a0 to your computer and use it in GitHub Desktop.
Function to replace url params using the historyAPI
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
Drupal.behaviors.myModule = { | |
attach: function (context, settings) { | |
}, | |
/** | |
* Explicitly save/update a url parameter using HTML5's replaceState(). | |
* | |
* @param {string} key | |
* Url param key. | |
* @param {string} value | |
* Url param value. | |
* | |
* @returns {void} | |
*/ | |
updateQueryStringParam: function (key, value) { | |
var baseUrl = [location.protocol, '//', location.host, location.pathname].join(''); | |
// Grab any existing query params that exist in the URL. | |
var urlQueryString = location.search; | |
var newParam = key + '=' + value; | |
var params = '?' + newParam; | |
// If an existing query param string exists, then process so we can ensure | |
// that any existing keys have their values updated. | |
if (urlQueryString) { | |
var keyRegex = new RegExp('([\?&])' + key + '[^&]*'); | |
// If param exists in the URL already, update it, | |
if (urlQueryString.match(keyRegex) !== null) { | |
params = urlQueryString.replace(keyRegex, '$1' + newParam); | |
} | |
else { // Otherwise, add it to end of query string | |
params = urlQueryString + '&' + newParam; | |
} | |
} | |
// Update the URL. | |
history.replaceState({}, '', baseUrl + params); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment