Session only cookies with Javascript
Yes, that is correct.
Not putting an expires
part in will create a session cookie, whether it is created in JavaScript or on the server.
See https://stackoverflow.com/a/532660/1901857
For the use case in the question (no server side code), sessionStorage
is a simpler solution. But sessionStorage
is client only, so would not work if you need to access the stored value on the server (e.g. user logins etc.)
Javascript read session cookies only
A "session cookie" is a normal cookie. It may (or may not) have an expiration date but nothing prevents other cookies to have an expiration date as well. The only reliable way to identify a session cookie is if you know its name (this is website-dependent of course, but isn't a problem if this is your website).
Also, you have no way of knowing a cookie's expiration date from Javascript.
Now document.cookie
gives you all cookies as a semi-colon delimited string. You just need to break it down on semi-colons to retrieve the key-value pairs. So here's a sample code to look for a cookie given its name:
var getCookie = function(name) {
var cookies = document.cookie.split(';');
for(var i=0 ; i < cookies.length ; ++i) {
var pair = cookies[i].trim().split('=');
if(pair[0] == name)
return pair[1];
}
return null;
};
If you don't know the session cookie's name you're out of luck. Period. You could maybe find clever heuristics to determine which one it is (based on the form of name and/or value), but nothing can tell you exactly for all websites with 100% confidence which cookie is the session cookie, and if there is one at all.
How to set session cookies with `__Host-` prefix in Electron?
This detail is not documented in the official documentation at https://www.electronjs.org/docs/latest/api/cookies but it's a logical result of other rules. Specifically the Set-Cookie
HTTP header is defined to follow these rules:
<cookie-name>=<cookie-value>
...
Note: Some<cookie-name>
have a
specific semantic:
__Host-
prefix:
Cookies with
names starting with__Host-
must be set with thesecure
flag, must
be from a secure page (HTTPS), must not have adomain
specified (and
therefore, are not sent to subdomains), and the path must be/
.
...
Attributes
...Secure
Optional
Indicates that the cookie is sent to the server only
when a request is made with thehttps:
scheme (except onlocalhost
),
and therefore, is more resistant to man-in-the-middle attacks.Note: Do not assume that
Secure
prevents all access to sensitive
information in cookies (session keys, login details, etc.). Cookies
with this attribute can still be read/modified either with access to
the client's hard disk or from JavaScript if theHttpOnly
cookie
attribute is not set.Insecure sites (http:) cannot set cookies with the
Secure
attribute
(since Chrome 52 and Firefox 52). For Firefox, the https: requirements
are ignored when the Secure attribute is set by localhost (since
Firefox 75).
Specifically, you cannot set cookie with name starting with __Host-
prefix without also specifying secure
. As a result, setting cookie as described in the question fails. Unfortunately, the exception is just Error: Failed to parse cookie
instead of Error: cannot set cookie with "__Host-" prefix without also setting "secure" attribute
.
Following should work as expected:
var cookie = {
url: cookieurl,
name: cookiename,
value: cookievalue,
secure: true,
// httpOnly: true,
// sameSite: "lax",
};
win.webContents.session.cookies.set(cookie)
.then(function(result)
{
loadUrl(win, indexUrl, output);
})
.catch(function(e)
{
throw Error("Failed to load cookie, e="+e);
});
The above example also has httpOnly
and sameSite
attributes in comments to work as a reminder that you probably want to consider these attributes, too.
Client only cookies - cookie which doesn't ever go to the server
If browser compatibility is a concern you can use a some javascript to wrap around various different technologies. Older versions of IE support (supprise supprise) a proprietary version of localstorage called userData (I don't think it's exactly the same, but should do what you need).
A wrapper script like https://github.com/andris9/jStorage or https://github.com/marcuswestin/store.js should do what you need it to do.
Is it possible to set a cookie to expiry at the end of session and after 1 day?
the cookie will either expire on session end, or on a specific date, because in order to make the cookie expire on session end you actually omit the date to make it work.
unless you create 2 cookies one for session end and one on a date
the function below is from the page you posted. use it to calculate the date and set the cookie where exdays=1
. else just use the last line of the function omitting the expires
so it can expire on session end
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
Related Topics
Using Canvas to Animate a Sorting Algorithm in Js
Sending Message to a Specific Connected Users Using Websocket
HTML Drag and Drop on Mobile Devices
JavaScript Regex Returning True.. Then False.. Then True.. etc
How to Tell Google Translate to Not Translate a Section of a Website
How to Disable Div Element and Everything Inside
How to Make a Button Redirect My Page to Another Page
Dynamically Using the First Frame as Poster in HTML5 Video
Best Way to Execute Js Only on Specific Page
Html5/JavaScript - Dataurl to Blob & Blob to Dataurl
Javascript: Get Image Dimensions
Show Loading Icon Until the Page Is Load
How to Set Preview of Video File, Selecting from Input Type='File'
JavaScript Code Not Work in Head Tag
Onclick Calling Hide-Div Function Not Working
Save File JavaScript with File Name
How to Create Every Combination Possible for the Contents of Two Arrays