Skip to content

Cross-domain cookies in Safari

September 21, 2011

The Problem

Safari does not allow cross-domain cookies. In other words, if on XYZ.com, you load an iFrame with contents of ABC.com and set a cookie in the iFrame, Safari will not save the cookie. This problem also occurs in IE6/7 but can be resolved by sending a P3P header.

The hack !!! (can’t say it a solution)

The cookie gets saved if a POST is made to the iFrame. By making it POST we are actually converting the request to first party. This solution relies of jQuery but can be adapted to any other.

Here is the code that goes on the remote domain:

<script>
var isSafari = (/Safari/.test(navigator.userAgent));
var firstTimeSession = 0;

function submitSessionForm() {
if (firstTimeSession == 0) {
firstTimeSession = 1;
$("#sessionform").submit();
setTimeout(processApplication(),2000);
}
}
if (isSafari) {
$("body").append('http://ahref=<form id="sessionform" enctype="application/x-www-form-urlencoded" action="http://www.yourdomain.com/startsession.php" target="sessionframe" action="post"></form>');
} else {
processApplication();
}

function processApplication() {
alert('Session has been set. Now you can start your application!');
}
</script>

The contents for startsession.php would be as simple as:

<?php
header('P3P: CP="IDC DSP COR CURa ADMa OUR IND PHY ONL COM STA"');
session_start();

To make sure that your site is compatible with IE6/7, always output the following header:

<?php
header('P3P: CP="IDC DSP COR CURa ADMa OUR IND PHY ONL COM STA"');

Unfortunately, there is no way to find out when the browser has completed submitting the form. Thus, I have placed a delay of 2 seconds. This form needs to be submitted only once per user session. Then you can set your session data in PHP and it will be picked up by your remote domain. You can adapt the same example if you want to set cookies instead of starting a PHP session.

About these ads

From → Web Development

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: