I'm looking for way to remove all my web cookies which have similar name "SID12345UID123456789" , all have SID and UID in their name ..
it can be done by jquery or pure JavaScript
thanks for any advices
Update: worked
base on other script i made this one it work but simple with indexOf .. i know some one can do better by regex match ..
please help
var cookies = document.cookie.split(";");
for(var i=0; i < cookies.length; i++) {
var equals = cookies[i].indexOf("="),
name = equals > -1 ? cookies[i].substr(0, equals) : cookies[i];
if ( name.indexOf('SID') > 0 && name.indexOf('UID') > 0 ){
alert(name);//for test
document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}
}
If you are creating these in your own code, you should delete the existing one before creating the new one (thus avoiding the problem).
Otherwise you can use a function like one found on this page. Run a loop that looks for a cookie with that name. If it finds it, delete it and then look again (until there are none left).
Related
I have a cookie split into an array:
var cooks = document.cookie.split(';');
[dogs=bla, cats=sdfgh, cabbages=kjhgfdfg]
If I wanted to find the index of 'cats=sdfgh' I could use
cooks.indexOf('cats=sdfgh');
1
But if I wanted to search to see if the value cats has been set, how would I do that? cooks.indexOf(find('cat=')); or something to that effect?
So without knowing the value of cats, how can I tell if it exists in the cookie?
And, how can I get the index number of that cookie?
you could run a simple regular expression:
if(fun = document.cookie.match(/(^cats=|;cats=)([^;]+)/)){
console.log(fun);
}
it will give you an array where the 3rd member is your value if it matches :)
JSFIDDLE
However, if you dont have to support shitty browsers its worth taking a look at the the MDN cookie framework referenced in the comments.
You can use Array.prototype.some method to find the first matching value in array:
var cooks = document.cookie.split(';'); // ["dogs=bla", "cats=sdfgh", "cabbages=kjhgfdfg"]
var isSet = cooks.some(function(cookie) {
return cookie.indexOf('cats') == 0;
}); // => true
I need to set a cookie whenever a user clicks through one of our affiliate links and lands on our site with "src=uni" in the URL. The URLs will look something like this:
http://www.myadmin.com?src=uni&utm_source=uni&utm_content=[publisher_ID]
Function to create cookie:
function SetCookie() {
var url = window.location.href;
if(url.indexOf('?src' + uni) = 1)
document.cookie="QueryCookie";
}
Can somebody help me by telling where I am going wrong in creating this Cookie based on query parameters?
A few things here:
function SetCookie() {
var url = window.location.search;
if(url.indexOf('?src=uni') !== -1)
document.cookie="src=uni";
}
1) Use location.search to narrow down your range, not necessary, but less room for error,
2) Use !== -1 to test the indexOf method. indexOf returns "-1" if it does not find a match. And "0" if it finds a match at the beginning of the string. The string is "zero indexed" which means the first character in the string is in position "0".
3) Add the equal sign = along with your parameter name: src=.
4) Also, use the string "uni" if that is what you're looking for, rather than a variable named uni. If "src" can be a variety of values, then we'll need to add some more logic to account for that.
5) And when assigning to document.cookie use key/value pairs as in: key=value.
First thing you need to fix is:
if(url.indexOf('?src' + uni) = 1)
should be (this checks that it exists at index 1):
if(url.indexOf('?src=' + uni) === 1)
or (this checks it exists at all)
if(url.indexOf('?src=' + uni) !== -1)
Next, you need to set src to the uni and make it accessible to the entire site:
document.cookie="src="+uni+"; path=/; domain=.myadmin.com";
Adding the path=/ and domain=.myadmin.com will allow you to access the cookie at all paths on that domain, and the domain part lets it be accessible on all subdomains (i.e. www.myadmin.com as well as blog.myadmin.com, etc)
so all together:
function SetCookie() {
var url = window.location.href;
if(url.indexOf('?src='+uni) !== -1)
document.cookie="src="+uni+"; path=/; domain=.myadmin.com";
}
Here is some basic info:
http://www.w3schools.com/js/js_cookies.asp
Or the more in depth, accurate documentation:
https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie
I am trying to store the highscore of a player local, on his pc itself. I don't know if this is possible and I didn't find a question about it on this site. I just have a var wich contains a number. I want to store it on his pc soo when the player plays the game again in his browser his highscore still will be available.
use localstorage:
window.localStorage.score="20" // storing
window.localStorage.score // getting the score again.
localStorage is not supported by old browser . so use cookie as a fall back.
if(window.localStorage)
window.localStorage.setItem("highscore",1000);
else
document.cookie="highscore=1000; expires=Thu, 31 Dec 2018 12:00:00 UTC";
to retrieve the value
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0)
return c.substring(name.length,c.length);
}
return "";
}
if(window.localStorage)
var highscore=window.localStorage.getItem("highscore");
else
var highscore=getCookie("highscore");
It's a bit of an odd thing to do, unless we are talking about nodeJS (?) storing to file system or some other local store.
if you'de like to persist a certain value so next load it'll be taken from a stored location on javascript you'll have to do it using cookies,
but than again it'll be cleared every time you are clearing your cookies and will no be shared across multiple browser on your machine.
that being said, this is how you store a value to a cookie using javascript:
document.cookie="somekey=savedValue";
var readValue = document.cookie;
You can also use Cookies besides localStorage.
var expDate=new Date();
var score=20;
expDate.setDate(expDate.getDate()+365); // expiration after one year
// Setting cookie
document.cookie='score='+score+';expires='+expDate;
// Retrieving the cookie
var yourOldScore = document.cookie.match(/score=(.*?)\;/)[1];
It appears that JavaScript auto-converts certain special characters into HTML entities when outputting content via the innerHTML() function. This is a problem, since I need to be able to output < and > without converting to gt; and lt;
Can this auto-conversion be prevented, reversed, or escaped? So far, no matter what I do, < and > are always automatically encoded into HTML entities.
Example code:
function DisplayQueries() {
var IDs = ['AllOpenedINC','AllOpenedCRQ','AllClosedINC','AllClosedCRQ','SameDayINC','SameDayCRQ','NotSameDayINC','NotSameDayCRQ',
'StillOpenINC','StillOpenCRQ','OpenOldINC','OpenOldCRQ','OtherQueuesINC','OtherQueuesCRQ']
for (var i = 0; i < IDs.length; i++) {
if (eval(IDs[i]))
document.getElementById(IDs[i]).innerHTML = eval(IDs[i]);
}
}
Example query variable:
AllOpenedINC = "('Company*+' = \"test\" OR 'Summary*' = \"%test%\") AND ('Submit Date' >= \"" + theDate +
" 12:00:00 AM\" AND 'Submit Date' <= \"" + theDate + " 11:59:59 PM\")" + nameINC;
You should focus on what you want to accomplish as a result, rather than the way of doing it. innerHTML() does encode, innerText() and textContent() do encoding too. So you should decode your strings if you want them as < or > back.
You can use this unescapeHTML() function to get your results as you want them.
function unescapeHTML() {
return this.stripTags().replace(/</g,'<').replace(/>/g,'>').replace(/&/g,'&');
}
I hope this helps. I've copied it from Prototype.
I think your question is based on a false premise. Just make a very simple test:
document.getElementById("testdiv").innerHTML = '<h1><em>Hello</em></h1>';
if this works fine then the problem is not on the JS side, instead you use some other components in your system which HTML-encode your characters.
I figured out what's going on. There's no easy way to prevent innerHTML from converting special characters to HTML entities, but since the problem was surfacing when copying the content of a DIV to the clipboard (using IE-only JS, which works since this is in a government environment where everyone has to use IE), I just used the replace() function to re-convert the HTML entities back to < and >.
You can use jquery and .append()
First off, let me preface this question by saying that my professor is firmly entrenched in the past. Our last assignment required us to float links on top of pictures.
You might also say that he's insane as in order to test our pages he requires that all functionality (including cookies) be implemented with "client side technology" i.e. not on the server. He uses Firefox to test the pages, so the single blessing is that he doesn't care about cross-browser compatibility.
That being said, I'm having a problem with our latest assignment. We're making a "shopping cart" system using Javascript and cookies to store the items to be purchased. This is fine, except for some reason in my function that adds a new element to the cookie, assigning something to document.cookie doesn't work.
You can find my entire site here .zip file download (if there's anything that you wonder, "why on earth would you do that? That's crazy!" - that's either a direct assignment or a way to try and minimize the pain.)
This is my code in question that should be modifying the cookie:
var mycookies = new function (){
var cookies = document.cookie.split(';');
var cookie, values;
this.items = [];
for(var x = 0; x < cookies.length; x++){
if(cookies[x] != ""){
cookie = cookies[x].split('=')[0].trim()
values = cookies[x].split('=')[1]
values = values.split(',');
if(!this.items[cookie]){
this.items.push(cookie);
this[cookie] = new function(){};
}
this[cookie].size = values[0];
this[cookie].qty = parseInt(values[1]);
}
}
this.render = function(){
var values, cookies = "", cookie;
for(var x = 0; x < this.items.length; x++){
cookie = this.items[x];
values = [this[cookie].size, this[cookie].qty].join(',');
cookies += cookie + "=" + values + '; ';
}
return cookies;
}
this.clear = function(){
for(var x = 0; x < this.items.length; x++){
delete this[this.items[x]];
}
this.items = [];
document.cookie['expires'] = '26 Aug 1984 01:01:01 UTC;';
}
this.additem = function(){
var i = document.forms[0].size.selectedIndex;
if (this.items[page]){
this[page].size = document.getElementById('size').value;
this[page].qty = document.getElementById('qty').value;
}
else{
this.items.push(page);
this[page] = new function(){};
this[page].size = document.getElementById('size').value;
this[page].qty = document.getElementById('qty').value;
}
console.log(this.render()); // For use with firebug
document.cookie = this.render();
console.log(document.cookie); // For use with firebug
}
}
When I fire this off, firebug provides this output:
expires=12 Aug 2001 01:01:01 UTC,NaN; whitec=Small,3;
expires=12 Aug 2001 01:01:01 UTC,NaN
Now, I would expect 1) my cookie to have expired (I set the expiration manually through firebug, my parsing added the NaN later, - yet there it stays), and 2) the value for the cookie to be changed to the result of this.render()
Other than the obvious fact that client-side cookie behavior is not guaranteed by the w3 spec, am I missing something here? (EDIT - what I mean is when the page is client-side, opened as a file - not served by a server) This is really aggravating - I've tried a multitude of different angles, and no "javascript cookie" search or "modify cookies javascript" leads me to anything useful. Any suggestions about how I can fix it?
Or should I just email my professor with a link to the w3 specs and tell him that requiring us to support cookies client side is stupid?
The workings of document.cookie are not what you apparently think they are. When you set a value into the variable, you set one cookie at a time. Thus, if you wanted to set all the cookies you're holding in your object, you'd loop through your "items" array and set document.cookie successively to each name/value pair (transformed into a "cookieName=cookieValue" string).
This is a fact in all modern browsers. See this Mozilla documentation page for example.
Other comments on the code, since you were nice enough to post it:
cookie = cookies[x].split('=')[0].trim()
values = cookies[x].split('=')[1]
Better to call "split" just once.
this[cookie] = new function(){};
That's essentially equivalent to this[cookie] = {}; to set the property to a new empty object.
Looks something may be bad with the dates ?
Try to set expiration time in the far future when setting the cookie.
Your programming class sounds a bit strange.
But in my experience, manipulating cookies on the client side is really well supported in the browsers.
Quirksmode has a great article about cookies with some examples of helper functions to set and read cookies: http://www.quirksmode.org/js/cookies.html