According to MDN, cookies set with a path of '/' are available anywhere in the same domain. This is corroborated by several different sources.
However, I just haven't found this to be the case. I ran the following test on (nonexistent) directories on google.com using firefox:
> window.location = 'https://google.com/dir/file.html'
Navigated to https://google.com/dir/file.html
"https://google.com/dir/file.html"
> document.cookie
""
> document.cookie = 'key1=value1,path=/'
"key1=value1,path=/"
> document.cookie
"key1=value1,path=/"
> window.location = '/dir2/file.html'
Navigated to https://google.com/dir2/file.html
"/dir2/file.html"
> document.cookie
""
Am I misunderstanding something? What am I doing wrong? I tried similar tests on Chrome with the same result.
Figured it out. I was setting path with a comma delimiter, not a semicolon delimiter. It was writing the cookie literally as I typed it, instead of interpreting the path and domain.
The correct way to write the cookie would have been document.cookie = 'key1=value1;path=/'.
Related
I have a requirement wherein I need to redirect my page to a different URL when my current URL contains some string.
For instance,
If my current URL contains www.testdomain.com or www.testdomain.com/web/region then it should redirect to www.testdomain.com/group/region. I tried the below code but it returns "The requested resource could not be found -- https://www.testdomain.com/web/region/testdomain.com/group/region".
$(document).ready(function() {
if (window.location.href.indexOf("web/region") > -1) {
window.location.href=window.location.hostname+'/group/region';
}
})
It is adding the URL twice here. But when I pass the direct URL window. location.href="www.testdomain.com/group/region" it is working.
Can someone guide me on how do I force redirect my page if the URL contains www.testdomain.com or www.testdomain.com/web/region?
Thanks
Start with // so that the browser knows it's not a relative URI:
window.location.href = '//' + window.location.hostname+'/group/region';
You can also prepend the protocol:
window.location.href = window.location.protocol + '//' + window.location.hostname+'/group/region';
It's adding the URL twice because browsers interpret /group/region as a relative path, automatically prepending the current domain UNLESS otherwise specified. (Maybe others can explain why window.location.hostname doesn't immediately return, thus preventing the browser from assuming a relative path?)
Example: If you explicitly set a domain, the browser will redirect to it as expected.
window.location.href='http://www.google.com/'
Otherwise, if you take away "www."
window.location.href='google.com/'
Your browser will redirect to "www.testdomain.com/google.com", appending the string.
The fix is simple.
Just delete window.location.hostname+ and it will only return the URL once.
Or... for a better user experience, I would suggest using window.location.replace() which DOES NOT save the current page in session history.(You don't want to go back, just to be redirected again!)
SOLUTION:
Replace your return block with this.
window.location.replace('/group/region')
I need (for practice) to set a cookie via bookmarklet in website X, and read him with another bookmarklet from website Y.
For example, set a cookie named "user" with value of "Guy" in Google, and read this from YouTube.
I managed to set the cookie, but can't think of any idea how to read him from website b.
Thanks!
You need two bookmarklets, a getter and a setter.
You go to site X and use the getter bookmarklet to read the cookie and let the user copy it to his clipboard.
Then you go to site Y and use the setter. The setter will prompt the user for the bookmarklet and the user will then paste it into the prompt. The code will then set the cookie accordingly.
You can of course combine these two bookmarklets into a single getter/setter. The prompt will contain the current cookie for the page. The user can then choose to either copy the cookie and cancel (using it as a getter) or choose to to alter the cookie and click "OK" (using it as a setter).
I was looking for a way to share cookies of a specific website with a friend (reading them in my browser via bookmarklet and my friend setting them on his browser also via bookmarklet). Not quite what you asked for, but searching brought me here. This is my approach:
First there is a bookmarklet for exporting cookies. It will remove unnecessary white-spaces and encode your data in a base64 string for safe transport:
javascript:(
function(){
prompt("GET cookies encoded in base64", btoa(document.cookie.replace(/\s/ig, "")));
}
)
();
Then there is a second bookmarklet for importing all cookies encoded in the string. You can also set an optional lifetime here (thanks to https://www.quirksmode.org/js/cookies.html):
javascript:(
function(){
var inputstring = prompt("SET cookies decoded from base64");
var inputclean = atob(inputstring).replace(/\s/ig, "");
if (confirm("These cookies will be imported:\n\n" + inputclean.replace(/;/ig, "; "))) {
var days = prompt("Cookie lifetime in full days", "365");
var cookiearray = inputclean.split(";");
cookiearray.forEach(function(entry) {
var expires = "";
var split = entry.split("=");
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = split[0] + "=" + (split[1] || "") + expires + "; path=/";
});
}
}
)
();
Do not forget you have to run those on a specific website or tab. It does NOT export the entire collection of the cookies your browser is storing.
According to this StackOverflow, how to get cookies from a different domain with php and javascript you can't get cookies from another domain UNLESS you have access to it, as it would be a huge security flaw.
I'm having a really strange problem and I'm looking for any possible ideas. I have a flyover that I load based on whether or not a cookie is found on the client's machine. In the flyover there is a 'No thanks' checkbox saying "Don't show again". I check to see if it has been checked like this in the flyover page:
$(document).ready(function() {
jQuery(window).bind("beforeunload", function(){ setCookieFO('noShowMerkleCpn','true',180); });
});
function setCookieFO(c_name,value,exdays){
if($('#noThanks').attr('checked') ){
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}else{
}
}
I have ran the code in Firebug and verified that the cookie gets saved on document unload. I can even go into my cookies and find the cookie. Here is how I check for the cookie:
function runFancyBox(){
var idx = document.cookie.indexOf('noShowMerkleCpn');
if(idx < 0 ){
$('#cpnForm').click();
}else{
}
}
I don't really care about the cookie value. I just check to see if it exists and display the flyover if it doesn't. However, for some reason this check will return -1 even when the cookie exists.
Extra info:
The cookie is saved in my flyover.Html page under
server/bank/ima
The script that looks for the cookie is on the same server
server/bank/ima/script
The cookie is saved with this Path value with Host: server
/bank/ima/
Is there anything that jumps out that could be causing this issue? Any suggestions?
two things i would check. first, you are setting document.cookie without appending, so you wipe out all previous cookies (bad idea). second, make sure to set the cookie's domain and path to the same domain as the page reading it.
also be aware of your usage of the checked attribute:
if($('#noThanks').prop('checked'))
http://timmywillison.com/2011/When-to-use-.attr%28%29-and-.prop%28%29.html
I tried your code on both localhost and my server, and it works fine I assume you were careful to close your browser so that the cookie is actually set. My guess is you have a path problem, although from what you say about paths, it is certainly not obvious what it is.
I saved the code on my server, so you can at least examine code that works.
The url to set the cookie is: http://www.bridgesights.com/hondobridge/bbohondo/setcookietest.php
The url to test the cookie is: http://www.bridgesights.com/hondobridge/bbohondo/bbohondo_files/getcookietest.php
Although this has nothing to do with your problem, I highly recommend the jquery-cookie plugin for manipulating cookies. It is very lightweight and easy to use. The link is: https://github.com/carhartl/jquery-cookie
I am trying to redirect to a different page in IE9 (9.0.3).
When I try to get/set document.location, or document.location.href, or window.location/window.location.href, I'm unable to do so. It fails without giving any errors.
I've tried to check whether the document and windows objects are set, and they are, so I have no idea why the location object is "missing".
I tried getting the document.URL and that works fine, but it's read-only.
Anyone know what the problem is or how to achieve this in a cross-browser way?
I was also experiencing the same problem but found that adding
window.event.returnValue = false;
above line in the javascript before the redirection resolved the problem.
See this: http://social.msdn.microsoft.com/Forums/en/iewebdevelopment/thread/c864ae63-66f6-4656-bcae-86b0018d70c9
Apparently it's a caching bug, you can solve it by appending a timestamp to the destination URL (that is, using a "unique" URL every time).
Perhaps your IE9 has some security restrictions in place that prevent JavaScript from directing URL's. window.location.href = "" should work normally on IE9.
Cache may be the reason, try:
location.href='something.php?tmp=' + Date.parse(new Date())
Hope it helps
You should use an absolute URL:
var url = '/section/page/';
var host = window.location.hostname;
window.location = 'http://' + host + url;
Where url is the relative path to your page.
I'm just building a simple ajax site but running into a problem in safari and chrome. I'm just creating a simple redirect if the user goes to a page i.e.
"/blog"
they would be redirected to
"/#/blog"
code :
url = window.location.pathname
if(url != "/") {
window.location.pathname = "/#" + url
}
This is working great in FireFox but unfortunatly webkit browsers are turning the "#" into a "%23" and giving a 404, for example:
"/%23/blog"
How can I prevent this?
Thanks,
Alex
pathname refers to everything after the host, and before the query string and hash. Consider this instead:
window.location.hash = window.location.pathname;
window.location.pathname = "/";
I'm not exactly sure which browser(s) are implementing the JavaScript spec correctly, but WebKit's behavior seems correct to me.
You are setting pathname, which, by definition, does not include the hash. Webkit is trying to fix that for you (Firefox just made a better guess of what you wanted). Try this:
window.location = '/#/blog';