I am using the following cookie:
var $j = jQuery.noConflict();
$j(document).ready(function(){
if (document.cookie.indexOf('visited=true') == -1)
{
var thirtyDays = 1000*60*60*24*30;
var expires = new Date((new Date()).valueOf() + thirtyDays);
document.cookie = "visited=true;expires=" + expires.toUTCString();
$j.colorbox({ inline:true, href:"#gallery-nav-instruct"});
}
});
Everything works fine with one exception. The above cookie is for displaying instructions the first time a user visit the gallery yet the gallery has multiple pages. What happens is the user sees the instructions for each page in the gallery the first time they visit that specific page. These instructions need to load only once when they visit the gallery no matter which page they start on. How do I go about changing this so it displays only once across my gallery pages?
Couple Notes:
The gallery is wrapped inside a Dreamweaver Template and the cookie is inside that template. I cannot move the cookie outside of the template for a few reasons.
Also I use a hosted CMS and I DO NOT have server side access so it must be done using javascript.
Add ;path=/ to make your cookie into a site cookie. See this article on JavaScript Cookies for more details.
document.cookie = valuename + "=" + value + "; " + expires + ";domain=;path=/";
This "domain=;path=/"; will take dynamic domain as its cookie will work in subdomain.
It will work if you want to test in localhost.
Related
We are using gatsby to develop our website and I am using the gatsby-plugin-google-tagmanager plugin in order to fire google analytic events..
One issue we face is that when the user visits our site from utm links the session seems to split the exact same second he lands on the page.
What I do so far
Fire a Page View Google Analytics: Universal Analytics tag using the gatsby-route-change trigger.
GA debug report
One thing that seems abnormal is that on every route change, using the GA Debug tool, a new Creating new tracker log is created.
Ways I tried to fix this
Read an article that on single page applications you might get faulty values for page, location and referrer properties, so this fools google analytics to create a new session each time, so that might be the reason why the session breaks.
What I tried to do was to override these values in the GA tag. However, this does not seem to fix the issue.
// Location override gtm variable
function () {
return window.document.location.protocol + '//' +
window.document.location.hostname +
window.document.location.pathname +
window.document.location.search
}
// Referrer override gtm variable
function () {
return window.history.state.referrer
}
// Page override gtm variable
function() {
var path = window.location.pathname + window.location.search + window.location.hash
var index = path.indexOf('?');
if(index > -1){
path = path.substring(0, index);
}
return path;
}
Got any idea on this? Is it possible that this behavior splits our session? Is there anything else you recommend?
https://www.simoahava.com/gtm-tips/fix-rogue-referral-problem-single-page-sites/
This article answers the question.
With Google Tag Manager, every single Universal Analytics Tag that fires on the site creates a new, unique tracker object. This means that the Document Location field is updated with every Tag you fire, which is a problem if the URL changes due to browser history manipulation. Thus you can end up with a situation where the first Universal Analytics Tag has gclid in the URL, attributing the session to AdWords, but the next pageview doesn’t have this in the URL anymore, as you would not include it in the “virtual” pageview path names. Instead, since gclid is no longer in the URL, GA looks at the HTTP referrer of the page to see what the previous page was for attribution. It finds google.com, as you came from the search engine (HTTP referrer is not updated when manipulating the URL with the browser History API). Thus a new session starts with attribution to Google Organic! I’ve dubbed this as the Rogue Referral problem.
Solution
Manually Set Document Location To Prevent Rogue Referrals
Create a script to save the landing URL in the dataLayer
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
originalLocation: document.location.protocol + '//' +
document.location.hostname +
document.location.pathname +
document.location.search
});
Create a script variable to get the current page. (if you don't need hash remove it)
function() {
return window.location.pathname + window.location.search +
window.location.hash
}
Add variables to all you Universal Analytics by manually setting the fields location and page
I am having a bizarre issue that I'm thinking may be a Chrome bug or possibly a bug with Visual Studio. My script is getting loaded twice. To verify the issue I created a test script that sets a cookie with a timestamp to show the code is getting appended twice. If I navigate to the page via a hyperlink it works fine. Also if I hit the back and forth buttons it also works fine -- but if I manually type the url for the second page in the browser it calls the script twice.
This only happens in Chrome and only when using a Asp.Net Web Application. If I use a Asp.Net website, it does not occur. These are new empty web applications with no extra files or settings changed.
My example html pages look like this:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Page 1</title>
<script src="chromebug.js"></script>
</head>
<body>
<h1>Page 1</h1>
Page 1
Page 2
Page 3
</body>
</html>
And the chromebug.js look like this:
function getCookieTest(name) {
var cookie, cookies = document.cookie.split(';');
name = name + '=';
while ((cookie = cookies.pop())) {
cookie = cookie.replace(/^\s+/, '');
if (cookie.indexOf(name) === 0) {
return cookie.substring(name.length, cookie.length);
}
}
return null;
}
function setCookieTest(name, value, secs) {
var c;
if (secs > 0) {
c = new Date();
c.setSeconds(c.getSeconds() + secs);
c = name + '=' + value + '; expires=' + c.toGMTString() + '; path=/';
} else {
c = name + '=' + value + '; path=/';
}
document.cookie = c;
return
}
console.log('chromebug loaded');
var getdata = getCookieTest('loaded') || '';
setCookieTest('loaded', getdata.toString() + document.title + ':' + new Date().getTime().toString() + '|', 10000);
getdata = getCookieTest('loaded');
console.log(getdata); // show what has been saved in the cookie
Am I missing something? Any way to work around this?
I even created a video where the issue is demonstrated:
http://screencast.com/t/MpXfbDMBvfY
Thanks so much to stdob for pointing me to the Live HTTP Headers extension. I'd recommend it if you are having a similar issue.
https://chrome.google.com/webstore/detail/live-http-headers/iaiioopjkcekapmldfgbebdclcnpgnlo?hl=en
The issue in my case is with the Google Chrome prefetch optimization. When you type in the address bar, Google anticipates the page you will be loading and starts pulling down the scripts. If your script preforms some loading or cookie action upon loading this is problematic. When you uncheck this option you should see the duplicate loads go away.
However this is an easy way to control this without changing your settings. This is especially important since you have no control over your end-user's settings.
if (document.webkitVisibilityState && document.webkitVisibilityState == 'prerender') {
// avoid performing load logic
}
It's look like Chrome have non-obvious behavior when user manualy typing url in address bar. You can use some tools like Chrome live http headers to catch this behavior.
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 have a javascript engine that creates a 'magazine' out of a typical web page. Several web pages would have separate 'issues', all using the same javascript engine that drives the formatting and behaviour.
The engine uses local storage to remember which 'page' of the issue the user was on when they last read the issue of the magazine.
localStorage.setItem('currentPage',JSON.stringify(currentPage));
var currentPage = JSON.parse(localStorage.getItem('currentPage'));
var remover = $('.article-wrapper:eq(' + currentPage + ')');
my problem is, if I visit page 5 of a magazine titled 'autumn', close it and open a magazine titled 'spring', then I will start on page 5 of spring automatically.
Is there a way I can set a unique 'currentPage' variable name for each issue in the html for that issue, read it with the javascript for the engine and then have it save to local storage for the computer/device the user is using?
You can test the problem by visiting these two sites. Open both. Go to page five of one site and then refresh the other. It will change to the others page number.
http://straathof.acadnet.ca/autumn/
http://straathof.acadnet.ca/portfolio/
Instead of storing the currentPage as a simple integer, store an object that keeps track of both the current page's url and the page for that url.
For example:
// When saving the current page.
var currentPage = new Object();
var url = window.location.pathname;
currentPage[url] = 9;
localStorage.setItem('currentPage', JSON.stringify(currentPage));
// When loading the current page.
var currentPage = JSON.parse(localStorage.getItem('currentPage'));
var remove = $('.article-wrapper:eq(' + currentPage[url] + ')');
If you do not like having the full URL as the key, then you could use indexOf to find the pages name. See this StackOverflow answer for more.