Sam Derboo Sam Derboo - 2 years ago 227
Javascript Question

Javascript Cookies not working in Safari

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, 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>
<p id="doesitwork" onclick="myFunction()">Does it work?</p>
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;

Answer Source

Well you are not setting a name value pair

document.cookie = (d + "; expires=" + "May 31 2016 23:59:59 GMT+09:00" + "; path=/");

should be something like

document.cookie = "time=" + d + "; expires=" + "May 31 2016 23:59:59 GMT+09:00" + "; path=/";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download