Can I save a cookie and use it on an other page? - javascript

[RESOLVED]
I have a little website stored at file:/// with multiple pages with a quiz in each pages. I need to save the results of the quiz in a cookie. When I am changing page, the cookie turn undefined and I don't know how to access the cookie of the previous page. How could I do that ? Is using a cookie the best idea ?
Thank you and have a great day.
Ben
On first page, I put the number 1 in a cookie. When I try to access it on the second page, the cookie is undefined. I would want it to have 1 in it.

No, not directly (because of CORS).
But you can:
Centralize all cookies (cookiepot.com)
When some body visits one of your "share cookie"-sites you redirect him to cookiepot.
Cookiepot redirects the user back with the information you need
This is how Google+Youtube, Stackoverflow+Stackexchange do it. There is no other way except when servers change the information directly with each other.

EDIT: after the quesion owner edited the question, is was discovered that he used a local file.
local files cannot use cookies in most browsers. you can use SessionStorage instead.
ORIGINAL ANSWER
2 pages can use the same cookies as long as they are in the same domain.
for example, website.com/a.html and website.com/b.html can use the same cookies, but otherwebsite.com/c.html wouldn't be able to use that cookie.
are your two pages in the same website?
If they aren't, there it is possible to allow one website to use another website's cookies but I have a feeling that's not the case.

Sure you can save a cookie (document.cookie = 'testcookie=;expires=Thu, 01 Jan 1970 00:00:01 GMT;';) and use it on any other page as long as the pages are on the same domain. This is how you save a cookie on a form submit or any other trigger:
https://codepen.io/hac/pen/oOKOOe

Related

How to set cookies client-side taking into account Intelligent Tracking Protection?

According to this blog post on webkit.org, cookies set client-side using document.cookie are capped to a 7 day expiry.
I understand the rationale behind using httpOnly for sensitive cookies such as auth tokens, but if I need to store something for a long duration and have it available across subdomains of a site, then cookies are the only option, right?
With these new ITP restrictions, setting cookies client-side which should live for any longer duration of time is not going to work, so what's the best way to approach this? One idea was make a route which takes params and converts them into a Set-Cookie header and then make a request to that instead of using document.cookie. Is there a better way?
One attempt would be to use localStorage instead of cookies, technically they don't expire. The Problem however can be, that the user can decide to empty the localStorage.
Here's an example
//use this if you only need it for the current page and remove it after leaving the page
const exampleStorage = window.localStorage;
exampleStorage.setItem('currentUser', 'Manuel');
//use this if you need to keep it even after leaving the page
localStorage.setItem('glob_currentUser', 'Max');
//and finally this if you need to keep it only for the session
sessionStorage.setItem("session", "Morning")
If you need more Information about LocalStorage here are 2 helpful websites:
MDN Window​.local​Storage
The W3C Specification for localStorage

Is Cookies the best way?

I am using Joomla, and there are 2 Sections/Branches, when the user lands on the home page they will be asked where they wan to go to.
If they choose Section A i want the browser to remember their choice for future, however if they decide for some reason to visit Section B later, i want the browser to replace the Section A with B so that in future B will be remembered.
Is using cookies the right way, if so how could this be done, any help would be much appreciated.
If both section/branches are in same domain (or subdomains) cookies are a good way, but local storage can be a good option too.
The following link can help you to use cookies in Joomla http://blog.tormix.com/joomla/set-and-get-cookies-in-joomla-cms/
Today the moist preferred way is storing inside a localstorage and not inside cookie's
because cookies are sent vs every request and storage is not.
(https://developer.mozilla.org/en/docs/Web/API/Window/localStorage)
Also you can pick one of the libs from this article
And you can use modernizer to be compliant with the old browsers version.
Setcookie("path", "A", 3600*31*365); // Set cookie for about a year.
Echo $_cookie["path"]; // Read cookie
Setcookie("path", "B", 3600*31*365); // Replace the cookie with path B.

js function to go back in browser history to last browsed page of specific domain?

I need the js function to go back in history to the last pages used in a specific domain.
reason: I send people to a subdomain to see specific content-galleries (gallery.mydomain.xyz/#1etc). I need them to return to the last page where they left of from the specific tld (mydomain.xyz/pageX) after having clicked through a number of images/videos there at subdomain...
is this possible? any ideas?
thx!
It's not possible using the built-in browser history, no, because your access to that from JavaScript is close to non-existent.
What you can do instead is save the location you want to take them back to in, say, session storage (use local storage instead if this is in a different window), and then link back to that page.
More about session storage / local storage in the web storage spec, but the short version is that it stores strings in a storage area specific to your origin, so for instance:
localStorage.setItem("last-location", "foo");
...stores "foo" in local storage for your origin, with the key "last-location". You can then use getItem to get it later when you need it:
var lastLocation = localStorage.getItem("last-location");
you could use a simple get/post variable to tell where the user is coming from and store that in a session variable for later use when the user is to be returned. As far as I know you cant access the users browsing history from the browsing client with Javascript as its a violation of the sandbox design but that may have changed recently
thx both of you for the quick answer!
... I kind of see, not being a versatile coder myself. but I get the problem involved. and see session-storage is where I want to look at then...
I will have to make this a coding job given my non-skills here :-}
but now I know what to ask for. thx again.

Cookie is set twice; how to remove the duplicate?

So I have a website that uses a cookie to remember the current layout state across visits. Everything was working great until I added a Facebook 'Like' button to the site which generates links that allow users to share a certain UI state (a little confusing but not really relevant to the problem).
The problem is that when I visit the site via one of these Facebook links a second copy of my layout cookie seems to be created (as in, I see two cookies with the same name and different values). This wouldn't be too terrible except that the value of the duplicate cookie appears to be stuck, coupled with the fact that when the user returns to the site the browser remembers the stuck value instead of the most recently set value (so it's kind of like there's a "good" cookie that I can still work with, and a "bad" one which I cannot, and the browser likes to remember the "bad" cookie instead of the "good" cookie). This breaks my layout tracking/remembering functionality.
So there are two questions here:
How do I stop this from happening/why is this happening in the first place?
How do I fix things for any users that already have a stuck cookie (I know I could just pick a new name for the cookie, but I'd rather do it by finding a way to properly unstick the stuck cookie)?
If I use Chrome's developer console after visiting the page in a stuck state, I can see that document.cookie is (formatting added for readability):
layoutState=[{'id':6,'x':8,'y':1525,'z':4,'url':'undefined'}, {'id':1,'x':625,'y':709,'z':2,'url':'undefined'}, {'id':2,'x':8,'y':37,'z':3,'url':'undefined'}, {'id':3,'x':625,'y':1179,'z':5,'url':'undefined'}, {'id':4,'x':626,'y':37,'z':1,'url':'undefined'}, {'id':5,'x':626,'y':357,'z':1000000,'url':'http://m.xkcd.com/303/'}];
WibiyaNotification1=1;
WibiyaNotification213286=213286;
WibiyaNotification213289=213289; wibiya756904_unique_user=1;
JSESSIONID=DONTHIJACKMEPLEASE;
WibiyaProfile={"toolbar":{"stat":"Max"},"apps":{"openApps":{}},"connectUserNetworks":[null,null,null,null,null,null]};
WibiyaLoads=59;
layoutState=[{'id':6,'x':8,'y':1525,'z':4,'url':'undefined'}, {'id':1,'x':625,'y':709,'z':2,'url':'undefined'}, {'id':2,'x':8,'y':37,'z':3,'url':'undefined'}, {'id':3,'x':625,'y':1179,'z':5,'url':'undefined'}, {'id':4,'x':626,'y':37,'z':1,'url':'undefined'}, {'id':5,'x':626,'y':357,'z':6,'url':'http://m.xkcd.com/303/'}]"
Ignore the Wibiya cookies and the JSESSIONID. The stuck cookie is the first 'layoutState' instance, and the one that I can still manipulate in JavaScript is the second 'layoutState' instance. Here is what I get if I change some things around:
layoutState=[{'id':6,'x':8,'y':1525,'z':4,'url':'undefined'}, {'id':1,'x':625,'y':709,'z':2,'url':'undefined'}, {'id':2,'x':8,'y':37,'z':3,'url':'undefined'}, {'id':3,'x':625,'y':1179,'z':5,'url':'undefined'}, {'id':4,'x':626,'y':37,'z':1,'url':'undefined'}, {'id':5,'x':626,'y':357,'z':1000000,'url':'http://m.xkcd.com/303/'}];
WibiyaNotification1=1;
WibiyaNotification213286=213286;
WibiyaNotification213289=213289;
wibiya756904_unique_user=1;
JSESSIONID=DONTHIJACKMEPLEASE;
WibiyaProfile={"toolbar":{"stat":"Max"},"apps":{"openApps":{}},"connectUserNetworks":[null,null,null,null,null,null]};
WibiyaLoads=59;
layoutState=[{'id':1,'x':8,'y':39,'z':1000000,'url':'undefined'}]
The second 'layoutState' has the correct information that I want the browser to remember. However what the browser actually remembers is the value of the first instance.
I've tried unsetting the cookie entirely, which causes the second instance to disappear, but nothing I do seems to get rid of the first instance. I get the same behavior in all major browsers (Chrome, Firefox, IE), which makes me suspect that I must be doing something fundamentally wrong here, but I'm not sure what it is.
You can view the site itself here. Or click here to access it via a Facebook link (should generate a stuck cookie). Any help is much appreciated.
Update:
So the steps to reliably reproduce the error are as follows:
Visit the site via the Facebook-style link
Make some changes to the layout, and then close the tab.
Visit the site via the normal URL.
Your layout from the initial visit should be correctly remembered, so change some things around and then refresh the page. When the page reloads, your changes will no longer be remembered.
I've also noticed that revisiting the site via the Facebook-style URL is able to clear/reset the stuck cookie. So it's like the browser is keeping a separate cookie for each URL path, or something, and not allowing the root page to access the cookie that was set on the other URL path. I thought I might be able to fix this by explicitly setting path=/ on the cookie, but no dice.
Update 2:
I've found that if I set both the path and the domain of the cookie I get different behavior in all browsers:
Firefox - Works correctly now, hooray! Worked correctly once, then broke, boo!
Chrome - No change
IE - Seems to be keeping separate cookies for each URL, so the Facebook-style URL remembers one state, and the standard URL remembers a different state. Both update correctly and independently of each other. This is kind of funky, but still way better than the stuck/broken state.
Dude(tte), there are inconsistencies, and a bug, in your cookie setter.
1. Make sure path and domain is correctly set
The path and domain should be the same for both clearing the cookie and setting it. See your code here:
document.cookie = c_name + "=; expires=Fri, 31 Dec 1999 23:59:59 GMT;";
and compare it to:
var c_value=escape(value) + "; expires=" + exdate.toUTCString(); + "; path=/spring; domain=aroth.no-ip.org";
you will see that the setter has both of them, but the deleter doesn't. You will bring about chaos.
2. Oh, and that nasty semicolon
That second line of code I quoted above, has a semicolon introduced in the middle of a string concatenation expression. Right after exdate.toUTCString(). Kill it. Kill it…now.
At least on my Google Chrome, I managed to get it run correctly, if I set a breakpoint at json = "[" + json + "]"; and modify setCookie before it is executed.
P/S: It was a bizzare debugging experience, where I managed to set 4 layoutState cookies, by fiddling with path & domain.
This may be too simple, but just in case, are the cookies recorded for two different paths? If the URL is different, you may be setting your cookies for a restricted path, so the system would take them differently.
Here is a solution, the / slash help to do not set duplicate cookie of same name
setcookie('YourCookieName','yes', time() + 400, '/');
check in Chrome console -> Resources if your page gets loaded twice. That would be the reason of double cookie.
There is again the problem left after identifying the problem and taking prevention by correctly setting the cookie.
You also need to delete previous incorrectly set cookies in your or in your client's browser.
So observe the cookie set from developer tools and search for path and subdomain and put those explicitly on your code to delete.
function eraseCookie(c_name) {
document.cookie = c_name + "=; expires=Fri, 31 Dec 1999 23:59:59 GMT;";
}
function eraseCookieWithPathDomain(c_name) {
document.cookie = c_name + "=; expires=Fri, 31 Dec 1999 23:59:59 GMT;path=/yourpath/to; domain=sub.domain.com";
//you can remove this function call on your second upload if you are confirm that the previous cookie setter expired
}
You may need to call function eraseCookieWithPathDomain right after eraseCookie or even every time after document load depending in your application.
You can add the following key in the AppSettings in the web config file it solves the issue of duplicate cookie.
<!-- Tell ASPNET to avoid duplicate Set-Cookies on the Response Headers-->
<appSettings>
<add key="aspnet:AvoidDuplicatedSetCookie" value="true" />
</appSettings>
This will help avoiding the duplicate Set-Cookie() in Response Headers.
It seems the issue is not a duplicate cookie (cookies overwrite themselves) but a duplication of the DATA in your cookie.
I think you'll have to modify the script that reads the cookie and clean out the duplicate value if it's detected.

HTTP cookie between two HTML pages

I have two HTML pages. After entering few inputs users will be redirected from first page to second page. Before redirecting the user to second HTML page(using window.location="new HTML URL"), I persist few of the user inputs in cookie using document.cookie DOM API.
When I am in the second HTML page, I could not retrieve the value from this cookie. I think since document object would have changed in the new HTML page, my cookie values become inaccessible.
Can someone tell me: how do I retrieve the value from a cookie persisted by one javascript in one HTML page in other HTML page i.e cookie written by HTML A's javascript in HTML B's javascript?
I don't have any server-side code, so I could not take advantage of server-side logic. Also I am not supposed to pass the values in URL. So I need a solution on plain javascript and HTML.
If some one has a better solution please let me know. Thanks
try to use localStorage instead of cookies,
// set your values in the first page
localStorage.setItem('itemKey', 'values');
// on the second page, retrieve them
var values = localStorage.getItem('itemKey');
you can use a jStorage plugin for cross browser behaviour.
also refer to this question for storing objects instead of strings
JAAulde is on point with his answer.
For what the OP is trying to do something like PHP would be great, in that case I wouldn't bother with cookies in order to just pass data between two pages, that's just silly. However, if true persistence was needed and the data requirements were simple cookies would be the way to go even while using a language such as PHP.
Those are rather draconian constraints, is this a class project? That said there aren't any other ways to do what you're attempting, save for an ugly and highly insecure hack of the DOM.

Categories

Resources