I've been trying to implement a basic cookie storage function in Javascript, which works as intended in most browsers, but not Safari (8.0.3). I've stripped it down to the below example, where every other browser changes the text to the date that is stored in the cookie, but Safari doesn't store a cookie at all and gives out an empty string (no error messages in the console either). Safari is set to accept all cookies.
If I enter the code in the testbed at W3Schools.com, it works in every browser, so is it somehow related to the domain? (In JSFiddle it doesn't seem to work at all, with the console complaining that myFunction is not defined.)
I've only found two older problems of the same type, but in one case the solution was adding the "; path=/" part, which is already in here, and in the other there was a comma in place of a semicolon.
<!DOCTYPE html>
<html>
<body>
<p id="doesitwork" onclick="myFunction()">Does it work?</p>
<script>
function myFunction() {
d = new Date();
document.cookie = (d + "; expires=" + "May 31 2016 23:59:59 GMT+09:00" + "; path=/");
var x = document.cookie;
document.getElementById("doesitwork").innerHTML = x;
}
</script>
</body>
</html>
By default cookie not allowed for iOS safari browser. We have to enable cookies setting from safari browser
So we have implemented local storage(javascript concept)to overcome the cookie problems in safari browser.
You can have a look at this nice article and they show you a function for creating, reading and deleting cookies also it shows pure JS and jQuery. The code on the blog is shown like so:
// Create 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=/";
}
// Read 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;
}
// Erase cookie
function eraseCookie(name) {
createCookie(name,"",-1);
}
Creating cookies like this:
createCookie("cookie-name", "cookie-value", 30);
Reading cookie like this:
readCookie("cookie-name");
// Usually you set it as a variable and then use it somewhere
var colorTheme = readCookie("color-theme");
// Then do some conditional crap with it
if (colorTheme == "Blue") {
// Add a class to the body or elswere
} else {
// Add a different class maybe...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With