Perform Something when Cookie is set - javascript

I have a third-party tracking script enabled on my site. This java-script basically adds a cookie on the first visit and in the subsequent visits it tracks the site.
I have en edge-case scenario(the first page load during which the tracking script adds the cookie for the first time) where on the very first page load I need to perform some operation once the cookie is set. But since I am using a third party tracking code, I cannot change that code and need to know when that script sets the cookie on the page. If I know when the cookie is set then I will write some javascript code to perform some operation based on this cookie value.

Mymodule.cookieReady = function () {
myCookie = Mymodule.getCookie('xyz');
if (cookieReadySet) {
clearTimeout(cookieReadySet);
}
cookieReadySet = setTimeout(Mymodule.cookieReady, 10);
return cookieReadySet;
};
Mymodule.getCookie = function(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i].trim();
if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
}
return "";
}

Related

Show different HTML code after one visit

Only using Javascript, can someone create a html file that uses "XY" html code when the user first visits it, but it should use "ZQ" (so a fully other one) html code after the first visit? So in the second, third, etc. visit of the same user. There could be many users.
Question: how would that html file look like? How to do it? Is it possible using only javascript?
You can use either Cookies or LocalStorage, where the LocalStorage is easier to implement, but requires the latest browser, and users may disable cookies for privacy reasons.
Cookies
function setCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
// First Visit
if (getCookie("visited") == null) {
// XY code.
alert("XY Code here");
// set the cookie
setCookie("visited", "yes", 10);
} else {
// subsequent visit.
// ZQ code.
alert("ZQ Code here");
}
LocalStorage
if (typeof(Storage) !== "undefined") {
if (localStorage.getItem("visited") == "yes") {
// subsequent visit.
// ZQ code.
alert("ZQ Code here");
} else {
// XY code.
alert("XY Code here");
// set the cookie
localStorage.setItem("visited", "yes");
}
} else {
// Sorry! No Web Storage support..
// Use the above cookie method.
}

avoiding setting a cookie based on a specific URL string

I am setting up a cookie based on the user first visit on a website. So every time a new user visit the website I am redirecting them to the landing page otherwise the user will see the index page directly (since time time the cookie is already in the user's browser).
Now what I am trying to achieve is that I would like skip the landing page redirect based on a specific URL (for both new users and existing users).
This is how I am checking the new visit and setting up a redirect cookie.
$(document).ready(function() {
landingPageOnFirstVisit();
createCookie('landingRedirect', 'true', '60');
});
function landingPageOnFirstVisit() {
var setCookieForLanding = readCookie('landingRedirect');
if (!setCookieForLanding) {
window.location = "/en/landing";
}
}
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
How do I make sure that if user visit the website directly using the below mentioned URL pattern: the redirection process would not occur and we wont set any cookies.
https://www.domain.com/en/page?usePromo=XXXXXX
(where XXXXXX are numbers and changes everytime)
Try
$(function() {
if (location.href.indexOf("usePromo")==-1) {
landingPageOnFirstVisit();
createCookie('landingRedirect', 'true', '60');
}
});

Cookie Detection , Redirect if Non javascript

Tying to write a JavaScript code that will detect if a user has cookies disabled in their browser. If they do, they will be redirected to another page. If they have their cookies enabled it just goes straight through as usual.
i have a code that already works but it still hits the page for a split second before redirection. Is there anyway to make it instant.An example of fast detection is here ( try it with cookies disabled) http://optusnet.com.au
You will see it is instant and doesn't load the page request first.
<script type="text/javascript">
/* function to create cookie #param name of the cookie #param value of the cookie #param validity of the cookie */
function createCookie(name, value, days)
{
var expires;
if (days)
{
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = ";
expires=" + date.toGMTString();
}
else
expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name)
{
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++)
{
var c = ca[i];
while (c.charAt(0) == ' ')
c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0)
return c.substring(nameEQ.length, c.length);
}
return null;
}
function eraseCookie(name)
{
createCookie(name, "", -1);
}
/* This function will create a new cookie and reading the same cookie. */
function areCookiesEnabled()
{
var r = false;
createCookie("testing", "Hello", 1);
//creating new cookie
if (readCookie("testing") != null)
{
//reading previously created
cookie r = true;
eraseCookie("testing");
}
return r; //true if cookie enabled.
}
</script>
<script>
if(!areCookiesEnabled())
{
//redirect to page
}
</script>
You won't be able to make it "instant" with client-side code (i.e. JavaScript) because the page has to be loaded for this code to run. You can achieve this with server-side code, however (like the page you link to does). Here's what you'd have to do, in whatever your server-side language is:
On the load of your first page, set a cookie and immediately send a redirect instruction to your main page.
On your main page load, check for the cookie. If no cookie exists, cookies are disabled, so redirect to a third (error) page.
If the cookie exists, allow the page to load normally.
Alternatively, you can try making it faster by reducing the number of HTTP requests required for your "checking" page (i.e. don't include any styles, etc. on the first page and then redirect to a "proper" page if the test passes) and using more efficient detection methods as per Joe's comment; however, you won't be able to implement an immediate redirect with client-side code.

Can I prevent a javascript redirect from firing if the user got to it by using the back button?

I have a script that redirects the user to a new page after X seconds. After being redirected, if the user hits their back button and returns to the page with this script I'd like it if the script does not fire again.
setTimeout(function() {
window.location.href = "/mypage.html";
}, 3000);
You can get the referrer property in JavaScript like this:
var referrer_url = document.referrer;
document.write("You come from this url: " +referrer_url);
Then, just wrap your setTimeout() with a conditional check to see which URL the person is coming from and do (or do not) do the redirect depending on where they came from.
I used the link Cerbrus provided and went the cookie route to solve this. More complicated than I would have liked but it got the job done.
This script will redirect the user to a new page after 3 seconds. It will first check if a cookie exists, and if it does it will not redirect. If there's no cookie, it will create a cookie and then redirect the user. If the user hits the back button the script will find the cookie that was created and it will prevent the script from redirecting the user again.
// Function to create a new cookie
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
// Function to read a cookie
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
// Use the readCookie function to assign the cookie to a variable (if it's available)
var currentcookie = readCookie('mycookie');
// If/else statement to fire javascript if the cookie is not present
if (currentcookie) {
// do nothing since the cookie exists
}
else {
// Cookie doesn't exist, so lets do our redirect and create the cookie to prevent future redirects
// Create a cookie
createCookie('mycookie','true');
// Perform the redirect after 3 seconds
setTimeout(function() {
window.location.href = "/mypage.html";
}, 3000);
}

Reading web-page cookies from a Firefox extension (XUL)

I'm creating an extension for the Firefox browser. I would like to read a cookie which was set by an HTML page using JavaScript in the XUL file. Is it possible?
I tried using document.cookie, but it doesn't work:
function readCookie(name) {
var ca = document.cookie.split(';');
var nameEQ = name + "=";
for(var i=0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1, c.length); //delete spaces
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return "";
}
function createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
Could you help me? Thanks in advance.
These code snippets may help
///By this method you can iterate throug each cookie by its name or value...
function ReadCookie()
{
var cookieMgr = Components.classes["#mozilla.org/cookiemanager;1"]
.getService(Components.interfaces.nsICookieManager);
for (var e = cookieMgr.enumerator; e.hasMoreElements();) {
var cookie = e.getNext().QueryInterface(Components.interfaces.nsICookie);
dump(cookie.host + ";" + cookie.name + "=" + cookie.value + "\n");
///Your code here to check your cookie or your implementation...
///You can use cookie name or value to select your cookie...
}
}
///If you want to read cookies by domain name you can use this code...
function GetCookie(){
try
{
alert("Getting Cookies");
var ios = Components.classes["#mozilla.org/network/io-service;1"]
.getService(Components.interfaces.nsIIOService);
var uri = ios.newURI("http://www.yoursite.com/", null, null);
var cookieSvc =
Components.classes["#mozilla.org/cookieService;1"]
.getService(Components.interfaces.nsICookieService);
var cookie = cookieSvc.getCookieString(uri, null);
///Your logic here...
}
catch (errorInfo)
{
alert(errorInfo);
}
}
Hope these will help :)
You probably want to use the nsICookieService interface: https://developer.mozilla.org/en/Code_snippets/Cookies
(Found via the helpful search on Mozilla's Add-on Developer Hub: https://addons.mozilla.org/en-US/developers/search?q=cookie)
You also might want to look at existing extensions that work with cookies, such as FireCookie.
There are at least two distinct ways of doing this:
Firstly, if you simply want to interact with the Firefox cookie store, you can use the nsICookieManager and nsICookieManager2 interfaces to query, add and remove cookies.
Secondly, if you're more comfortable with the document.cookie approach, and you want to deal with documents which are already loaded in the browser, you can do this, but the important thing to remember is to get the right document to work with. When you simply use document in XUL code, you are referring to the document object associated with the browser window in which you are running. Several pages might be loaded in different tabs within this window, each of which will have its own document object. As a result, you first need to find the document object that you are interested in. One way of doing this, for example, is to register to be notified of pages loads, and then to examine pages as they load to see whether they are of interest. For example, your XUL code might look like this:
function pageLoad (event) {
if (event.originalTarget instanceof HTMLDocument) {
var doc = event.originalTarget;
if (doc.URL.match(/^https?:\/\/[^\/]*\.example\.com\//)) {
⋮
doc.cookie = 'cookie_name' + "=" + value + ";expires=" +
(new Date(2050, 10, 23)).toGMTString();
⋮
}
}
}
var appcontent = document.getElementById("appcontent"); // locate browser
if (appcontent)
appcontent.addEventListener("load", function (e) { pageLoad(e); }, true);
With this approach you can interact with just those cookies associated with that page using the mechanisms with which you are familiar, and without worrying about dealing with cookies associated with completely different pages.

Categories

Resources