I have the need to store users initial query string parameters during their stay on a webpage. I decided to parse the query string parameters and stick them in a session cookie so when I have code that needs the initial query parameters I call the cookie.
This seems to not always work, esp in IE. Can anyone give me some suggestions? I thought maybe to store it in the dom storage but I'm not sure if that is the right approach.
The code lives in my page header and is accessible on all the pages of the site.
Here is what I put together:
var urlParams;
(window.onpopstate = function () {
var match,
pl = /\+/g,
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
urlParams = {};
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
function set_cookie(name, value) {
var cookie = [name, '=', JSON.stringify(value), '; domain=.', window.location.host.toString(), '; path=/;'].join('');
document.cookie = cookie;
}
function read_cookie(name) {
var result = document.cookie.match(new RegExp(name + '=([^;]+)'));
result && (result = JSON.parse(result[1]));
return result;
}
if(read_cookie('tbts') === null){
set_cookie('tbts', urlParams);
}
var urlParamsCookie = read_cookie('tbts');
You don't specify which version of IE, but according to Can I Use, popstate isn't available until IE10.
Related
I am grabbing the utm parameters from the URL on my index page, and storing them in local storage, then I am using the script below to grab the parameters from local storage and appending them to the end of the contact page's URL.
<script>
var parameters = localStorage.getItem("url");
const nextURL = window.location.href + parameters;
window.history.replaceState(nextURL);
</script>
Problem: This script works perfectly, except each time I refresh the contact page, it appends the parameters again. How can I fix this?
Use URL and URLSearchParams to parse and modify the URL for you. That way you don't have to do any work to produce a valid string:
function buildUrl(fromURL, fromQuery) {
const url = new URL(fromURL);
const query = new URLSearchParams(fromQuery);
for (const [key, value] of query) {
url.searchParams.set(key, value);
}
return url.toString()
}
function test(fromURL, fromQuery) {
const url = buildUrl(fromURL, fromQuery);
return `fromURL: ${fromURL}
fromQuery: ${fromQuery}
result: ${url}
---------------------`;
}
console.log(test("http://example.com", ""));
console.log(test("http://example.com", "foo=1"));
console.log(test("http://example.com", "foo=1&bar=2"));
console.log(test("http://example.com", "foo=1&bar=2&baz=3"));
console.log(test("http://example.com?hello=world", ""));
console.log(test("http://example.com?hello=world", "foo=1"));
console.log(test("http://example.com?hello=world", "foo=1&bar=2"));
console.log(test("http://example.com?hello=world", "foo=1&bar=2&baz=3"));
console.log(test("http://example.com?bar=someValue", ""));
console.log(test("http://example.com?bar=someValue", "foo=1"));
console.log(test("http://example.com?bar=someValue", "foo=1&bar=2"));
console.log(test("http://example.com?bar=someValue", "foo=1&bar=2&baz=3"));
You can always do a quick if statement to check if parameters exists in the current URL and if not, add it.
if(window.location.href.indexOf("?" + parameters) == -1){
const nextURL = window.location.href + '?' + parameters;
window.history.replaceState('', '', nextURL);
}
I have a url like this
http://localhost:9000/index.html#/acceptRequest?screen_name=kailash&rf=FIN1
Here I want to take FIN1 from the url and store it in another variable
I am using doing this in angularjs
I have made a function like this
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
console.log(hash[1]);
}
return vars;
}
Here the console line hash[1] prints kailash FIN1.I only need the FIN1 to be stored and just print it in the console.How to make that happen?...
Anyway thanks in advance...
If the URL is for a resource in your Angular app, you can simply inject the $location service and use
var anotherVariable = $location.search().rf
See https://docs.angularjs.org/api/ng/service/$location#search
Here is simple solution for you.In core Javascript.
var url = "http://localhost:9000/index.html#/acceptRequestscreen_name=kailash&rf=FIN1";
var test = url.lastIndexOf('=');
var r = url.slice(test+1);
alert(r);
This code will get the url parameter you need. You just have to call it and tell what value you need.
function getUrlParameter(name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results == null) {
return null;
} else {
return results[1] || 0;
}
};
Use it like
var yourVariable= getUrlParameter("rf");
It will return the value of rf.
Hope this helps.
After some research i got an answer
we just have to store the return value of that function to a variable like this
var urlParams = getUrlVars();
then all we need to do is to
console.log(urlParams['rf']);
thats it...
anyway you guys have been a great help... Thank you for responding.
No jQuery.
I want to store an object or array in a cookie.
The object should be usable after page refresh.
How do I do that with pure JavaScript? I read many posts, but do not know how to serialize appropriately.
EDIT:
Code:
var instances = {};
...
instances[strInstanceId] = { container: oContainer };
...
instances[strInstanceId].plugin = oPlugin;
...
JSON.stringify(instances);
// throws error 'TypeError: Converting circular structure to JSON'
How do I serialize instances?
How do I maintain functionality, but change structure of instance to be able to serialize with stringify?
Try that one to write
function bake_cookie(name, value) {
var cookie = [name, '=', JSON.stringify(value), '; domain=.', window.location.host.toString(), '; path=/;'].join('');
document.cookie = cookie;
}
To read it take:
function read_cookie(name) {
var result = document.cookie.match(new RegExp(name + '=([^;]+)'));
result && (result = JSON.parse(result[1]));
return result;
}
To delete it take:
function delete_cookie(name) {
document.cookie = [name, '=; expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/; domain=.', window.location.host.toString()].join('');
}
To serialize complex objects / instances, why not write a data dump function in your instance:
function userConstructor(name, street, city) {
// ... your code
this.dumpData = function() {
return {
'userConstructorUser': {
name: this.name,
street: this.street,
city: this.city
}
}
}
Then you dump the data, stringify it, write it to the cookie, and next time you want to use it just go:
var mydata = JSON.parse(read_cookie('myinstances'));
new userConstructor(mydata.name, mydata.street, mydata.city);
Use either object's own .toString() method if it gives meaningful serialization or JSON.stringify(). Do note, however, that cookies are usually limited in length and won't be able to hold big amounts of data.
A cookie adaptation class from :
http://www.sitepoint.com/cookieless-javascript-session-variables/
All you need to do is to set and get variables you need to store in cookie.
Work with: int, string, array, list, Complex object
Exemple:
var toStore = Session.get('toStore');
if (toStore == undefined)
toStore = ['var','var','var','var'];
else
console.log('Restored from cookies'+toStore);
Session.set('toStore', toStore);
Class:
// Cross reload saving
if (JSON && JSON.stringify && JSON.parse) var Session = Session || (function() {
// session store
var store = load();
function load()
{
var name = "store";
var result = document.cookie.match(new RegExp(name + '=([^;]+)'));
if (result)
return JSON.parse(result[1]);
return {};
}
function Save() {
var date = new Date();
date.setHours(23,59,59,999);
var expires = "expires=" + date.toGMTString();
document.cookie = "store="+JSON.stringify(store)+"; "+expires;
};
// page unload event
if (window.addEventListener) window.addEventListener("unload", Save, false);
else if (window.attachEvent) window.attachEvent("onunload", Save);
else window.onunload = Save;
// public methods
return {
// set a session variable
set: function(name, value) {
store[name] = value;
},
// get a session value
get: function(name) {
return (store[name] ? store[name] : undefined);
},
// clear session
clear: function() { store = {}; }
};
})();
If you can serialize your object into its canonical string representation, and can unserialize it back into its object form from said string representation, then yes you can put it into a cookie.
Is there any javascript function, to parse the first line of the http header?
GET /page/?id=173&sessid=mk9sa774 HTTP/1.1
The url is encoded.
I would like to get an object, like this:
{
"method" : "GET",
"url" : "/page/",
"parameters": {
"id" : 173,
"sessid" : "mk9sa774"
}
}
I searched a lot, but I haven't found anything useful.
thanks in advance,
First you can split on spaces:
var lineParts = line.split(' ');
Now you can get the method, unparsed path, and version:
var method = lineParts[0];
var path = lineParts[1];
var version = lineParts[2];
Then you can split up the path into the query string and non-query string parts:
var queryStringIndex = path.indexOf('?');
var url, queryString;
if(queryStringIndex == -1) {
url = path, queryString = '';
}else{
url = path.substring(0, queryStringIndex);
// I believe that technically the query string includes the '?',
// but that's not important for us.
queryString = path.substring(queryStringIndex + 1);
}
If there is a query string, we can then split it up into key=value strings:
var queryStringParts = [];
if(queryStringIndex != -1) {
queryStringParts = queryString.split('&');
}
Then we can unescape them and stuff them into an object:
var parameters = {};
queryStringParts.forEach(function(part) {
var equalsIndex = part.indexOf('=');
var key, value;
if(equalsIndex == -1) {
key = part, value = "";
}else{
key = part.substring(0, equalsIndex);
value = part.substring(equalsIndex + 1);
}
key = decodeURIComponent(key);
value = decodeURIComponent(value);
parameters[key] = value;
});
If you really wanted to, you could then put all that data into an object:
return {
method: method,
url: url,
version: version,
parameters: parameters
};
If you're in a browser environment, that's the only way to do it. If you're using Node.JS, it can deal with the URL parsing for you.
I would like to redirect a user to a target URL on a button click. The target URL is variable and has to be read from the current page URL parameter 'source':
For instance, I have a url http://w/_l/R/C.aspx?source=http://www.google.com
When the user clicks on a button he's being redirect to http://www.google.com
How would I do that with jQuery?
first of all you need to get the url param : source
this can be done with a function like :
function GetParam(name) {
return decodeURI(
(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}
// you can use it like
var source = GetParam('source');
//then
window.location.href = source
On button click handler, just write window.location.href = http://www.google.com
You will need to parse the query string to get the value of the variable source.
You don't need jQuery for it.
A simple function like this will suffice:
function getFromQueryString(ji) {
hu = window.location.search.substring(1);
gy = hu.split("&");
for (i = 0; i < gy.length; i++) {
ft = gy[i].split("=");
if (ft[0] == ji) {
return ft[1];
}
}
}
location.href = getFromQueryString("source");
Using the url parsing code from here use this to parse your url (this should be included once in your document):
var urlParams = {};
(function () {
var e,
a = /\+/g, // Regex for replacing addition symbol with a space
r = /([^&=]+)=?([^&]*)/g,
d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
q = window.location.search.substring(1);
while (e = r.exec(q))
urlParams[d(e[1])] = d(e[2]);
})();
Then do this to redirect to the source parameter:
window.location.href = urlParams["source"];
Since you are using the jQuery framework, I'd make use of the jQuery URL Parser plugin, which safely parses and decodes URL parameters, fragment...
You can use it like this:
var source = $.url().param('source');
window.location.href = source;
get url params : (copied from another stackoverflow question) :
var params= {};
document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
function decode(s) {
return decodeURIComponent(s.split("+").join(" "));
}
params[decode(arguments[1])] = decode(arguments[2]);
});
window.location = params['source'];
You can do like this,
<a id="linkId" href=" http://w/_l/R/C.aspx?source=http://www.google.com">Click me</a>
$('#linkId').click(function(e){
var href=$(this).attr('href');
var url=href.substr(href.indexof('?'))
window.location =url;
return false;
});