JS Cookie path not setting - javascript

I am using the following Javascript API for setting a cookie:
https://github.com/js-cookie/js-cookie
I am trying to set the path to the current page, but it is setting to the root. My code to set the cookie is:
Cookies.set('timeElapsed', data.seconds, {path: ''});
Which is part of a wider function which is tracking the progress of a Vimeo video, so I can use the cookie to resume from the last play point when the page is returned to.
But the cookie that is being set has the path /, meaning I can't use the same code for other videos on the site.
How can I set the cookie for just the current page?

just remove the path attribute
document.cookie="timeElapsed="+data.seconds;
UPDATE
JSFIDDLE

The code is correct. By default js-cookie creates the cookie valid to all pages inside / path. If you want to make it available to the path of the current page (not the current page), then you use the code:
Cookies.set('timeElapsed', data.seconds, {path: ''});
Basically, in js-cookie, path: '' is the same as document.cookie='name=value'. If no attribute is declared, then it assumes document.cookie='name=value; Path: /' by default.

Related

Manually generate GA linker parameter with gtag (GA4)

Background
To pass a client_id from one domain to another, Google supports adding a "linker" parameter to outgoing Links that are part of the cross-domain tracking setup. This linker parameter contains the client_id, session_id (I believe, information about Google Ads, e.g. gclid) and a basic fingerprint + timestamp. On the receiving domain, if the browser fingerprint matches and the timestamp is not too far in the past, the passed client_id and session_id are stored in a first party cookie on the 2nd domain and consequently used.
analytics.js / GA-UA
With analytics.js (GA-UA) you could easily do the following, to decorate URLs manually:
function decorateUrl(urlString) {
var ga = window[window['GoogleAnalyticsObject']];
var tracker;
if (ga && typeof ga.getAll === 'function') {
tracker = ga.getAll()[0]; // Uses the first tracker created on the page
urlString = (new window.gaplugins.Linker(tracker)).decorate(urlString);
}
return urlString;
}
Yet, when only gtag is loaded, window.ga and window.gaplugins are not defined. As far as I see, there is currently no documented way to manually generate links with the linker parameter with gtag.
In Google's documentation, they suggest setting up the linker manually. (https://support.google.com/analytics/answer/10071811?hl=en#zippy=%2Cmanual-setup)
But this has several disadvantages, e.g. I have to create a custom "fingerprint" logic (so that decorated URLs are not shared) and e.g. Google Ads information is not included.
Either way, I would like to use the internal gtag logic to decorate URLs.
"Hacky" Workaround Solution
gtag automatically decorates a tags (as soon as they're clicked) that lead to a cross-domain-tracking domain specified in the GA4 data stream settings (e.g. "test.com"), but I specifically need to decorate URLs manually (i.e. without immediately redirecting to them).
I thought about doing the following:
Create a dummy, hidden a tag with the URL to decorate
Prevent redirection with onclick='event.preventDefault();'
Simulate click on hidden element so that gtag automatically adds the linker url parameter to the href attribute
Extract new href attribute
Remove hidden element
function decorateUrlGtag(urlString) {
var tempAnchorEl = document.createElement("a");
tempAnchorEl.setAttribute("type", "hidden");
tempAnchorEl.setAttribute("href", urlString);
tempAnchorEl.setAttribute("onclick", "event.preventDefault(); return false");
document.body.appendChild(tempAnchorEl);
tempAnchorEl.click();
var urlWithLinker = tempAnchorEl.href;
tempAnchorEl.remove();
return urlWithLinker;
}
This also does not work, because gtag does not seem to register the tempAnchorEl.click(); call. If I click the link manually, the URL is decorated - as expected.
Suggested Solutions
The solutions outlined here (Google Analytics gtag.js Manually adding the linker cross-domain parameter to URLs) also do not work for me:
Answer: Even after gtag is initiated, I do not see a global ga element
Answer: Same problem (no ga defined)
Do you (1) know if there is a way to generate the linker parameter manually with gtag that I have overlooked, (2) know how to make my "hacky" solution work or (3) have another possible solution?
I haven't grokked this solution, and I am not sure it answers your question directly, but Simo does give an outline of how to configure GA4 cross domain tracking here:
https://www.simoahava.com/gtm-tips/cross-domain-tracking-google-analytics-4/#how-to-configure-cross-domain-tracking-manually
He breaks the problem down into steps but does not go into great detail. He provides one code snippet:
"...you could also load the URL parameter values directly into the GA4 configuration with something like:
gtag('config', 'G-12345', {
// Namespace roll-up trackers
cookie_prefix: 'roll-up',
// Pull in the Client ID from the URL
client_id: (new URLSearchParams(document.location.search)).get('client_id'),
// Pull in the Session ID from the URL
session_id: (new URLSearchParams(document.location.search)).get('session_id')
});
"
Hope that helps!

cypress goes in an infinite loop to lauch webpage

I am trying to access a URL outside of the defined environment but the page load goes in a loop and does not load the home page once the authentication is completed from Login screen
My implementation is as below:
The below utility.js file launches URL based on the environment the user selects:
export class Utility {
getBaseUrl(){
let envs = Cypress.env('ENV');
console.log(envs)
if(envs == 'production'){
return "https://prodsite.site.com.au";
}else if(envs =='canarys'){
return "https://stagenv2.site.com.au";
}else if(envs =='stage'){
return "https://stageenv.site.com.au";
}
}
}
snippet of Cypress.json file configured as below:
{
"env": {
"nzUrl": "https://search.infotrack.nz"
},
"viewportWidht": 980,
"viewportHeight": 1200,
"baseUrl": "https://stageenv.site.com.au",
}
To call the utility.js, have passed the url in a constant
const url = new Utility().getBaseUrl();
Ideally, to launch the url, i use
cy.visit(url)
To access the environment variable,
cy.visit(Cypress.env('nzUrl'));
After launching the application. The login screen loads up , authenticates itself , but to show up the home page, the page goes in a loop and fails to load it self
The baseurl works as expected , no issues there.
Facing this issue when accessing the the url in env variable
Looking for some help here. I have tried the following:
The website launches perfectly manually
Configured cypress.json with a url for launching a webpage other than baseurl, this approach did not work
Troubleshooted the webelements
I am looking forward for any help / suggestions with this information. Appreciate your kind help in advance
Basically cypress uses baseURL configuration to navigate by the commands cy.visit() and cy.requests() as you can see in the documentation here
I really recommend you to create a config file for each environment like
production.json
canarys.json
stage.json
Using that you can open your page just using cy.visit('/') or a page like cy.visit('/main') and cypress will make all the hard job for you. You don't need an extra class to get baseURL.
It may help you: https://www.cypress.io/blog/2020/06/18/extending-the-cypress-config-file/

Crossroadsjs routing: how to use it?

I am facing the same problem as this one as I am trying to figure out how to use crossroads for a few hours now and nothing seems to work. its webiste is just another poor documented site... I think I am probably daft! I wonder if anyone has made it?
html head,
<title>Crossroads</title>
<script src="js/libs/signals.js"></script>
<script src="js/libs/crossroads.min.js"></script>
<script src="js/app.js"></script>
</head>
app.js, just as simple as this,
crossroads.addRoute('/news/{id}', function(id){
alert(id);
});
so I try it out on my localhost browser,
http://localhost/crossroadjs/#/news/123
nothing happens. I thought it would be 123??
Crossroads doesn't handle history/state change events from the browser. From their site:
A routes system shouldn't do anything else besides routing.
Instead, the site recommends Hasher for this purpose and gives a rather complete looking example:
//setup crossroads
crossroads.addRoute('foo');
crossroads.addRoute('lorem/ipsum');
crossroads.routed.add(console.log, console); //log all routes
//setup hasher
function parseHash(newHash, oldHash){
crossroads.parse(newHash);
}
hasher.initialized.add(parseHash); //parse initial hash
hasher.changed.add(parseHash); //parse hash changes
hasher.init(); //start listening for history change
//update URL fragment generating new history record
hasher.setHash('lorem/ipsum');
Alternatively you could use a different history plugin, or write something yourself. But crossroads leaves that part up to you.
Crossroads.js gives crossroads.addRoute(pattern, [handler], [priority]); API to add route patterns. However, when the first time you load the page Crossroads does not automatically initiate the parser to check against the url of the page. You need to add crossroads.parse(document.location.pathname); on you document load to trigger the route. Check out Crossroads.js Tutorial.

remove cookie using javascript / jQuery

I have a little demo page to show the effect of a website depending on different user cookies.
Then I set the click() function of some div to use the plugin jquery.cookie.js which provides 2 functions:
$.cookie('name', 'val')
$.removeCookie('name')
after I called $.removeCookie(), I call window.open('new page') since I need to go to the content. but httpliveheader always shows that it's not removing the cookie in question.
OK, I found it, it was because the cookie set by my backend code and front end JS are in different path.
my java spring MVC controller has an access path of /MyPath/Blah/ in the code I just did
httpServletResponse.addCookie(new Cookie("something", "something"));
this turns out to default to the path where the code sits under , i.e. /MyPath/Blah/
but the JS sets something like $.cookie("something", "somevalue"), it goes to root. that's why I am seeing 2 different values in httpLiveHeader dump. unfortunately the path thing is controlled by browser, so it doesn't show up on liveheader dump. I only found this after I inspected the "remove cookie" window in mozilla
//for example :
document.cookie = "cookie_name=" + encodeURIComponent(cookie_value) +
"; expires=" + expires.toGMTString() +
"; path=/";
you need to set PATH.

Retrieve a cookie from a different path

My current document URL is http: //127.0.0.1/foo and I need to change the value of a cookie for http: //127.0.0.1/bar.
document.cookie is empty because document's URL is foo.
For the moment, I just want to read the cookie value.
Any clue?
When you create the cookie, if you set the path to '/' instead of 'foo' you will be able to read it anywhere on the domain, including '/foo', '/bar', etc.
You can create an <iframe> pointed at a resource inside /bar, and cross-frame-script into it. eg:
<iframe src="/bar/blank.html" id="barframe"></iframe>
var barframe= document.getElementById('barframe');
var bardocument= 'contentDocument' in barframe? barframe.contentDocument : barframe.contentWindow.document; // IE compat
alert(bardocument.cookie);
Cookie path= is a convenience measure to prevent accidental cookie name clashes. Given that different paths share a JavaScript origin, it is not an effective security mechanism.
You can't access cookies from a different path - otherwise it would be a security hole.
The only way I can think of is making /bar set a cookie whose path=/ so that all pages in / (including /foo) could access it.
As JJ and grawity have mentioned there is no way you can do this from your page. However, you have a work around.
i. Place an iframe which points to http://localhost/bar. Have a hidden element on the "bar" page where you store the cookie value. (let this iframe be 1*1 size so it is not visible).
ii. Use JavaScript on "foo" page to fetch the cookie value.
A similar approach (with modifications) can be used to write the cookie value too!
Thanks,
Ramjee.

Categories

Resources