Rails 6 with js-cookie library: cookie is set but not persistent - javascript

I've been trying to set up a very simple cookie just to see if the user has clicked the cookie consent banner. I'm trying to set the cookie with an expiration date in the future so the user doesn't get this message every visit. It works to set the cookie, but it only sets it for the current session. In IE11, it doesn't work at all.
My JavaScript for this is:
in custom.js:
import Cookies from 'js.cookie';
// Hide cookie disclaimer on agreement
$('.cookies-disclaimer button').on('click', function() {
$('.cookies-disclaimer').hide();
Cookies.set('cookies_consent', true, { expires: 365, sameSite: 'strict' });
});
// Check if the cookie disclaimer has already been accepted
function hideAlreadyAcceptedCookieDisclaimer() {
var consent = Cookies.get('cookies_consent');
if (!consent) {
$('.cookies-disclaimer').show();
}
}
hideAlreadyAcceptedCookieDisclaimer();
in my application.js I require the js file from node_modules:
require('js-cookie/src/js.cookie')
...
require('custom')

UPDATE:
The problem seemed to be in the way I imported the file:
I removed import Cookies from 'js.cookie'; from custom.js
In my application.js I added the library with window.Cookies = require('js-cookie/src/js.cookie')
All credits to this post for helping me out: https://discuss.rubyonrails.org/t/js-cookie/73808 and his original blogpost: https://translate.google.com/translate?hl=&sl=ru&tl=en&u=https%3A%2F%2Ftheglitchy.com%2Fn%2Fkak-ustanovit-js-cookie-na-rails-6-yarn-webpack

Related

Gatsby GDPR Cookie Banner how to implement multiple cookies + disable tracking?

So I set up a basic cookie banner following the gatsby-plugin-gdpr-cookies plugin and I used react-cookie-consent but it only shows a simple we use cookies on our website with an accept button.
How do I pass in both google analytics and google tag manager in my cookieconsent component? The docs only show one cookieName and I don't know how to add more than just the google analytics?
Also, how do I check if it actually disables cookie tracking?
I added the plugin to my gatsby-config.js
{
resolve: `gatsby-plugin-gdpr-cookies`,
options: {
googleAnalytics: {
trackingId: 'YOUR_GOOGLE_ANALYTICS_TRACKING_ID', // leave empty if you want to disable the tracker
cookieName: 'gatsby-gdpr-google-analytics', // default
anonymize: true, // default
allowAdFeatures: false // default
},
googleTagManager: {
trackingId: 'YOUR_GOOGLE_TAG_MANAGER_TRACKING_ID', // leave empty if you want to disable the tracker
cookieName: 'gatsby-gdpr-google-tagmanager', // default
dataLayerName: 'dataLayer', // default
},
facebookPixel: {
pixelId: 'YOUR_FACEBOOK_PIXEL_ID', // leave empty if you want to disable the tracker
cookieName: 'gatsby-gdpr-facebook-pixel', // default
},
// defines the environments where the tracking should be available - default is ["production"]
environments: ['production', 'development']
},
},
Then I added the Cookie Banner to my layout.js
<CookieConsent
location="bottom"
buttonText="Accept"
declineButtonText="Decline"
cookieName="gatsby-gdpr-google-analytics"
>
This website uses cookies to enhance the user experience.
</CookieConsent>
Plus the cookie only tracks gatsby-gdpr-google-analytics but i need it to track gatsby-gdpr-google-tagmanager as well
Both questions have the same answer: you have to initialize the tracking once the user has clicked the "Accept" button. That will untrack everything until the user accepts the consent. To start tracking when the user accepts it:
import { useLocation } from "#reach/router" // this helps tracking the location
import { initializeAndTrack } from 'gatsby-plugin-gdpr-cookies'
And inside your accept function (onAccept):
initializeAndTrack(location)
In addition, according to the documentation of the react-cookie-consent package, you have exposed an onDecline event that is triggered when the user rejects the GDPR policy. To allow it, you must add the enableDeclineButton property.
<CookieConsent
enableDeclineButton
onDecline={() => {
alert("nay!");
}}
></CookieConsent>
You can set a parameter, local storage, or another cookie there.
Your final code should look like:
<CookieConsent
enableDeclineButton
onDecline={() => {
alert("nay!"); // your stuff here
}}
onAccept={() => {
initializeAndTrack(location)
}}
location="bottom"
buttonText="Accept"
declineButtonText="Decline"
cookieName="gatsby-gdpr-google-analytics">
This website uses cookies to enhance the user experience.
</CookieConsent>
To answer your question, you can import Cookies (from js-cookie) and set cookies manually with the onAccept function.
Something like this
import CookieConsent, { Cookies } from "react-cookie-consent";
<CookieConsent
location="bottom"
buttonText="Accept"
declineButtonText="Decline"
cookieName="gatsby-gdpr-google-analytics"
onAccept={() => {
Cookies.set("gatsby-gdpr-google-tagmanager", true)
}}
>
This site uses cookies ...
</CookieConsent>

How do i set a cookie on different node js routes?

I'm developing a user based project, using node ( express, mongoose etc. )
I currently use JWT and the token has the user id in it, I know how to send a cookie when someone logs in, but I don't know how to make the cookie work on all routes, like basically when a user is logged in and goes on route /test the cookie is still there.
I think what I'm trying to achieve is called "session/cookie based authentication", could be wrong idk.
Once you set a cookie, from within any route, with
const myCookieValue = 'whatever'
res.cookie('myCookieName', myCookieValue, {
maxAge: 3600*1000, /* one hour */
httpOnly: true
})
you can retrieve its value, from within any route, with
const myCookieValue = req.cookies.myCookieName || 'yo! no cookie! something is wrong!'
The cookie-parser package makes this possible, handling the gnarliness of the the HTTP header for you.

Cookie not being deleted after session closed

I'm using cookies that should be deleted after user closes the page, but they're not. This is how I set cookies with JS
document.cookie="status=false";
I can see the cookie in console and after I close browser and open it again and go to my webpage there's still cookie status=false any idea why?
I solved it with this "trick", I don't know why I can't get cookies to work
window.onbeforeunload = function() {
document.cookie="status=false";
};
document.cookie = ... sets individual cookie values, it does not set "the entire cookie" to the string you passed, so setting "status=false" simply binds or updates the "status" value, irrespective of whatever else is in the cookie:
document.cookie = "cow=bell";
document.cookie = "cat=lol";
// cookie is now "cow=bell&cat=lol", not just "cat=lol"
If you want to delete the entire cookie, set its expiration time to "in the past" and the browser will do the cleanup for you.
(As pointed out in a comment, if you never set an expiration timestamp for your cookie, it'l expire when the page session ends, e.g. you close the tab/browser)
I was actually doing this today. A great reference is the Mozilla cookie documents if you create a js with their var docCookies code then using the functions provided like docCookies.setItem() docCookies.setItem() docCookies.getItem() or docCookies.removeItem() work incredible well.

PhantomJS setting cookies as Read and Write

I am trying to login to a website with phantomJS by session AUTH cookie, I finished the code for it and everything is working perfect, the problem is the website have like another login system inside with the same cookie, once accessed the other page cookie will update the security auth token, so when I add the First cookie to phantom I see that it is set to read Only because i cant access what is inside the second login system as Website is trying to update the Cookie that I manually added but unfortunately it fails because the cookie is Set to read Only.
code I am using :
phantom.addCookie({
'name': 'some name here', /* required property */
'value': 'some hash here',
'domain': 'ea.some domain here.com', /* required property */
'path': '/',
'httponly': false,
'secure': false,
'expires': (new Date()).getTime() + (10000 * 60 * 60) /* <-- expires in 10 hour */
});
I tried to delete the session cookie before my script auto access the page that needs second Auth but it just log me out because i need to have my old Session auth so it can be updated with the new session authhash.
any ideas how to make manually added cookies to be updated once requested from server side ?
I found the solution,
It appears that server actually created a new cookie with the same name and new value. not by replacing it with the new value. I searched the web for any help regarding this matter but I failed, I fixed this problem by taking the value of the new cookie and saving it to a variable, then executing phantom.clearcookies() to remove all the cookie and adding the new cookie again with the new value that I stores, It was not clean but it did the trick.

Does PhantomJS support cookies?

Does PhantomJS support cookies? If yes, where can I find the API details?
I am not able to figure it out after searching for a while now.
Yes, as of 1.7 Phantom has complete cookie handling, enabled by default. Cookies are retained for the duration of the process's life.
If you'd like to retain cookies across runs of Phantom, there's a command-line option cookies-file where you can specify where to store persistent cookies.
--cookies-file=/path/to/cookies.txt specifies the file name to store the persistent cookies.
In page script, you can use the regular document.cookie property. Like in browsers, this property returns a string similar to that which would be sent in the Cookie: HTTP header.
In Phantom script, you can access cookies for a page (subject to the usual origin restrictions) via page.cookies, which returns objects.
You can also access all cookies (from all domains) using phantom.cookies.
var page = require('webpage').create();
page.open('http://example.com', function (status) {
page.evaluate(function() {
document.cookie; // => "test=test-value;"
});
page.cookies; // => [{
// domain: "example.com",
// expires: "Wed, 08 Jan 2014 00:00:00 GMT"
// httponly: false,
// name: "test",
// path: "/",
// secure: false,
// value: "test-value"
// }]
phantom.cookies; // contains ALL cookies in Phantom's jar
});
To add/edit/delete cookies, use the addCookie, deleteCookie, and clearCookies methods of either a WebPage object or the phantom object.
When you use the methods of a WebPage object, you only modify the cookies that are visible to the page. Access to other domains is blocked.
However, using phantom's cookie methods allow access to all cookies. phantom.addCookie requires a domain (WebPage.addCookie assumes the current domain if you don't specify one), and phantom.deleteCookie deletes any cookie matching the specified name.
It does, through WebPage.addCookie() - which incidentally doesn't work neither for me nor someone else.
You can use this instead:
phantom.addCookie({
'name': 'mycookie',
'value': 'something really important',
'domain': 'example.com'
})
page.open('http://example.com/url/path/', function() {
console.log(page.cookies);
})
The work around I had to do was to execute javascript directly. I am using Geb and did the following:
js.exec("document.cookie='PHPSESSID=${cookie}';")
When selenium fails I always fall back to javascript for functionality.
I haven't tried it yet, but doesn't --cookies-file=/path/to/cookies.txt work?
It's the first item in API reference...
I had graded information within session recently. You should set cookie in page object, like below (coffeescript):
#page.clearCookies()
#page.addCookie
'name' : "JSESSIONID"
'value' : "0000rN3YAlVAU0xdHkKc6BEzWj9:-1"
'domain' : 'some.domain.com'
'path' : '/'

Categories