As your URL is the only way to make resources unique (or: save settings), you can use anything it it to store data. Note that only the hash part is not sent to the server.
location
properties for the URL http://www.iana.org/domains/example/page?data=xyz#hash
:
{
"hash": "#hash",
"host": "www.iana.org",
"hostname": "www.iana.org",
"href": "http://www.iana.org/domains/example/page?data=xyz#hash",
"pathname": "/domains/example/page",
"port": "",
"protocol": "http:",
"search": "?data=xyz"
}
It's not recommended to transfer sensitive data (password, personal information) in this way. Even if it's not visible on the server, it will be visible in the browser history.
You can use the encodeURIComponent
function to escape special characters like #
or &
.
Example for hash URLs like #field:data;field2:data2
(other separators could be used as well):
// default settings
var settings = {
"lang": "en",
"style": "green"
};
// this should be called before the settings are used
function loadSettings() {
// get the part after # and split it by `;`
var hashSettingsArray = location.hash.substr(1).split(";");
for (var i=0; i<hashSettingsArray.length; i++) {
var hashSettingArray = hashSettingsArray[i].split(':');
var key = decodeURIComponent(hashSettingArray[0]);
// if the key exists in the settings object, accept it
if (key in settings) {
// accept #field without value, defaulting to an empty string
var value = hashSettingsArray.length > 1 ? decodeURIComponent(hashSettingArray[1]) : "";
settings[key] = value;
}
}
}
function getSettingsHash() {
var settingsArray = [];
for (var setting in settings) {
var key = encodeURIComponent(setting);
var value = encodeURIComponent(settings[setting]);
settingsArray.push(key + ":" + value);
}
// example return value: #lang:en;style:green
return "#" + settingsArray.join(";");
}