www.webdeveloper.com
Results 1 to 7 of 7

Thread: Javascript Cookies IE Error Message

  1. #1
    Join Date
    Dec 2008
    Posts
    123

    Javascript Cookies IE Error Message

    I used the below javascript to check if cookies is on but in IE it have a error message of object expected on line 89. Line 89 is at the acceptCookies();


    Code:
    /
    var currentDate = new Date();
    
    // Create some DOM elements
    var newCookiesWarningDiv = document.createElement("div");
    
    // Retrieving cookie's information
    function checkCookie(cookieName) {
    	"use strict";
    	var cookieValue, cookieStartsAt, cookieEndsAt;
    
    	// Get all coookies in one string
    	cookieValue = document.cookie;
    	// Check if cookie's name is within that string
    	cookieStartsAt = cookieValue.indexOf(" " + cookieName + "=");
    	if (cookieStartsAt === -1) {
    		cookieStartsAt = cookieValue.indexOf(cookieName + "=");
    	}
    	if (cookieStartsAt === -1) {
    		cookieValue = null;
    	} else {
    		cookieStartsAt = cookieValue.indexOf("=", cookieStartsAt) + 1;
    		cookieEndsAt = cookieValue.indexOf(";", cookieStartsAt);
    
    		if (cookieEndsAt === -1) {
    			cookieEndsAt = cookieValue.length;
    		}
    
    		// Get and return cookie's value
    		cookieValue = unescape(cookieValue.substring(cookieStartsAt, cookieEndsAt));
    		return cookieValue;
    	}
    }
    
    // Cookie setup function
    function setCookie(cookieName, cookieValue, cookiePath, cookieExpires) {
    	"use strict";
    
    	// Convert characters that are not text or numbers into hexadecimal equivalent of their value in the Latin-1 character set
    	cookieValue = escape(cookieValue);
    
    	// If cookie's expire date is not set
    	if (cookieExpires === "") {
    		// Default expire date is set to 6 after the current date
    		currentDate.setMonth(currentDate.getMonth() + 6);
    		// Convert a date to a string, according to universal time (same as GMT)
    		cookieExpires = currentDate.toUTCString();
    	}
    
    	// If cookie's path value has been passed
    	if (cookiePath !== "") {
    		cookiePath = ";path = " + cookiePath;
    	}
    
    	// Add cookie to visitors computer
    	document.cookie = cookieName + "=" + cookieValue + ";expires = " + cookieExpires + cookiePath;
    
    	// Call function to get cookie's information
    	checkCookie(cookieName);
    }
    
    // Check if cookies are allowed by browser //
    function checkCookiesEnabled() {
    	"use strict";
    	// Try to set temporary cookie
    	setCookie("TestCookieExist", "Exist", "", "");
    	// If temporary cookie has been set, delete it and return true
    	if (checkCookie("TestCookieExist") === "Exist") {
    		setCookie("TestCookieExist", "Exist", "", "1 Jan 2000 00:00:00");
    		return true;
    	// If temporary cookie hasn't been set, return false	
    	}
    	if (checkCookie("TestCookieExist") !== "Exist") {
    		return false;
    	}
    }
    
    // Check if cookie has been set before //
    function checkCookieExist() {
    	"use strict";
    	// Call function to check if cookies are enabled in browser
    	if (checkCookiesEnabled()) {
    		// If cookies enabled, check if our cookie has been set before and if yes, leave HTML block empty
    		if (checkCookie("TestCookie") === "Yes") {
    			document.getElementById("cookiesWarning").innerHTML = "";
    		// If our cookie hasn't been set before, call cookies' agreement form to HTML block	
    		} else {
    			acceptCookies();
    		}
    	} else {
    		// Display warning if cookies are disabled on browser
    		document.getElementById("cookies").appendChild(newCookiesWarningDiv).setAttribute("id", "cookiesWarningActive");
    		document.getElementById("cookiesWarningActive").innerHTML = "<span id='cookiesDisabled'>:: please enable your cookies to avoid problems using this website  ::</span>";
    	}
    }
    
    // Get agreement results
    function getAgreementValue() {
    	"use strict";
    
    	// If agreement box has been checked, set permanent cookie on visitors computer
    	if (document.cookieAgreement.agreed.checked) {
    		// Hide agreement form
    		document.getElementById("cookiesWarning").innerHTML = "";
    		setCookie("TestCookie", "Yes", "", "");
    	} else {
    		// If agreement box hasn't been checked, delete cookie (if exist) and add extra warning to HTML form
    		acceptCookiesTickBoxWarning();
    	}
    }

  2. #2
    Join Date
    Dec 2002
    Location
    Seattle, WA
    Posts
    1,843
    cleaned up your code some. your cookie get/set functions were garbage. u_u
    using 'use strict' when you are not throwing errors or using undefined makes no sense.
    without knowing what acceptCookie() is doing it is really difficult to debug.
    Code:
    function getCookie(name)
    {
    	var re = new RegExp("(?:(?:^|.*;)\\s*"
    		+ encodeURIComponent(name).replace(/[\-\.\+\*]/g, "\\$&")
    		+ "\\s*\\=\\s*([^;]*).*$)|^.*$");
    	return decodeURIComponent(document.cookie.replace(re, "$1")) || null;
    }
    function setCookie(name, value, expires, path, domain, secure)
    {
    	if (!name || /^(?:expires|max\-age|path|domain|secure)$/i.test(name))
    		return false;
    	expires = parseInt(expires, 10);
    	expires = (expires !== expires) ? 0 : expires;
    	var s = encodeURIComponent(name) + '=' + encodeURIComponent(value);
    
    	if (expires > 0) {
    		expires = new Date(new Date().getTime() + (expires * 1000));
    		s += '; expires=' +expires.toUTCString()+ '';
    	}
    	else if (expires < 0)
    		s += '; expires=Thu, 01 Jan 1970 00:00:00 GMT';
    	if (!!path)
    		s += '; path=' +path+ '';
    	if (!!domain)
    		s += '; domain=' +domain+ '';
    	if (!!secure)
    		s += '; secure';
    	document.cookie = s;
    	return true;
    }
    
    function hasCookiesEnabled()
    {
    	// let the browser delete the cookie when the browser exits...
    	return !!getCookie('__test__') || (setCookie('__test__', 1) && !!getCookie('__test__'));
    }
    var newCookiesWarningDiv = document.createElement("div"); // ...
    
    function checkCookieExist()
    {
    	if (hasCookiesEnabled()) {
    		if (getCookie('TestCookie') === 'Yes') {
    			document.getElementById('cookiesWarning').innerHTML = '';
    		} else {
    			acceptCookie();
    		}
    	} else {
    		var node = document.getElementById("cookies")
    				.appendChild(newCookiesWarningDiv);
    		node.setAttribute("id", "cookiesWarningActive");
    		node.innerHTML = '<span id="cookiesDisabled">:: please enable your cookies to avoid problems using this website ::</span>';
    	}
    }
    function getAgreementValue()
    {
    	// If agreement box has been checked, set permanent cookie on visitors computer
    	if (document.cookieAgreement.agreed.checked) {
    		// Hide agreement form
    		document.getElementById("cookiesWarning").innerHTML = '';
    		setCookie('TestCookie', 'Yes', 6 * 30 * 24 * 60);
    	} else {
    		// If agreement box hasn't been checked, delete cookie (if exist) and add extra warning to HTML form
    		acceptCookiesTickBoxWarning();
    	}
    }

  3. #3
    Join Date
    May 2014
    Posts
    619
    Quote Originally Posted by ShrineDesigns View Post
    using 'use strict' when you are not throwing errors
    Unless you want it to actually run faster in browsers that support strict...

    Laughably, the massive amount of over-commenting is making the code harder to follow -- I'm having trouble figuring out what the is mess is even TRYING to do. I think that has a lot to do without seeing where the cookies are being set -- or why.
    Java is to JavaScript as Ham is to Hamburger.

  4. #4
    Join Date
    Dec 2008
    Posts
    123
    I copied that script from somewhere. Don't really know javascript enough to create my own. Is there any simpler/cleaner script that I can use for detecting cookies? All I am trying to do is to show a message to user if cookies is not on. thx.

  5. #5
    Join Date
    Dec 2002
    Location
    Seattle, WA
    Posts
    1,843
    I copied that script from somewhere. Don't really know javascript enough to create my own.
    Brilliant. Copying something from god knows where without an understanding of what it does. And you wonder why it doesn't work. u_u

    this is from my previous post you clearly overlooked...
    Code:
    // gets a cookie value by name, returns null if it cannot be found
    function getCookie(name)
    {
    	var re = new RegExp("(?:(?:^|.*;)\\s*"
    		+ encodeURIComponent(name).replace(/[\-\.\+\*]/g, "\\$&")
    		+ "\\s*\\=\\s*([^;]*).*$)|^.*$");
    	return decodeURIComponent(document.cookie.replace(re, "$1")) || null;
    }
    /* expires takes an integer (number of seconds til the cookie valid), 0 or null means the cookie is valid til the browser is closed
    * -1 tells the browser to delete the cookie */
    // sets a cookie, works like the PHP function setcookie()
    function setCookie(name, value, expires, path, domain, secure)
    {
    	if (!name || /^(?:expires|max\-age|path|domain|secure)$/i.test(name))
    		return false;
    	expires = parseInt(expires, 10);
    	expires = (expires !== expires) ? 0 : expires;
    	var s = encodeURIComponent(name) + '=' + encodeURIComponent(value);
    
    	if (expires > 0) {
    		expires = new Date(new Date().getTime() + (expires * 1000));
    		s += '; expires=' +expires.toUTCString()+ '';
    	}
    	else if (expires < 0)
    		s += '; expires=Thu, 01 Jan 1970 00:00:00 GMT';
    	if (!!path)
    		s += '; path=' +path+ '';
    	if (!!domain)
    		s += '; domain=' +domain+ '';
    	if (!!secure)
    		s += '; secure';
    	document.cookie = s;
    	return true;
    }
    // detects if cookies are enabled
    function hasCookiesEnabled()
    {
    	// let the browser delete the cookie when the browser exits...
    	return !!getCookie('__test__') || (setCookie('__test__', 1) && !!getCookie('__test__'));
    }
    @ deathshadow
    I follow the rules of strict mode, I use strict mode only in situations that require it (i.e. throwing errors, polyfills, etc.).
    Last edited by ShrineDesigns; 05-18-2014 at 08:40 PM.

  6. #6
    Join Date
    Dec 2008
    Posts
    123
    @ShrineDesigns
    Your script doesn't have an alert message if cookies is not enable does it? How do I set it to have an alert message when cookies is disabled? thx.

  7. #7
    Join Date
    Dec 2002
    Location
    Seattle, WA
    Posts
    1,843
    you would call hasCookiesEnabled()
    Code:
    if (!hasCookiesEnabled())
        alert('please enable cookies.');
    depending on your usage, you may want to wrap it in a function.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles