[javascript] Safari 3rd party cookie iframe trick no longer working?

So this is the umteenth revenge of the "how do I get 3rd party cookies to work in Safari" question but I'm asking again because I think the playing field has changed, perhaps after February 2012. One of the standard tricks to get 3rd party cookies in Safari was as follows: use some javascript to POST to a hidden iframe. It (used to) trick Safari into thinking that the user had interacted with the 3rd party content and so then allow cookies to be set.

I think this loophole has been closed in the wake of the mild scandal where it was revealed that Google was using that trick with its ads. At the very least, while using this trick I have been completely unable to set cookies in Safari. I unearthed some random internet postings that claimed that Apple was working on closing the loophole but I haven't found any official word.

As a fallback I even tried redesigning the main third party frame so that you had to click on a button before the content would load but even that level of direct interaction was not enough to melt Safari's cold cold heart.

So does anyone know for certain if Safari has indeed closed this loophole? If so, are there other workarounds (other than manually including a session ID in every request)?

This question is related to javascript facebook iframe safari

The answer is


I tricked Safari with a .htaccess:

#http://www.w3.org/P3P/validator.html
<IfModule mod_headers.c>
Header set P3P "policyref=\"/w3c/p3p.xml\", CP=\"NOI DSP COR NID CUR ADM DEV OUR BUS\""
Header set Set-Cookie "test_cookie=1"
</IfModule>

And it stopped working for me too. All my apps are losing the session in Safari and are redirecting out of Facebook. As I'm in a hurry to fix those apps, I'm currently searching for a solution. I'll keep you posted.

Edit (2012-04-06): Apparently Apple "fixed" it with 5.1.4. I'm sure this is the reaction to the Google-thing: "An issue existed in the enforcement of its cookie policy. Third-party websites could set cookies if the "Block Cookies" preference in Safari was set to the default setting of "From third parties and advertisers". http://support.apple.com/kb/HT5190


Safari now blocks all third party cookies. You can only use the Storage API to try to get user access to their third party cookies.

https://www.infoq.com/news/2020/04/safari-third-party-cookies-block/


I have found the perfect answer to this, all thanks to a guy called Allan that deserves all of the credit here. (http://www.allannienhuis.com/archives/2013/11/03/blocked-3rd-party-session-cookies-in-iframes/)

His solution is simple and easy to understand.

On iframe content server (domain 2), add a file called startsession.php at the root domain level that contains:

<?php
// startsession.php
session_start();
$_SESSION['ensure_session'] = true;
die(header('location: '.$_GET['return']));

Now on the top level website containing the iframe (domain1), the call to the page containing the iframe should look like:

<a href="https://domain2/startsession.php?return=http://domain1/pageWithiFrame.html">page with iFrame</a>

And that's it! Simples :)

The reason this works is because you are directing the browser to a third party URL and thus telling it to trust it before showing content from it within the iframe.


I decided to get rid of the $_SESSION variable all together & wrote a wrapper around memcache to mimic the session.

Check https://github.com/manpreetssethi/utils/blob/master/Session_manager.php

Use-case: The moment a user lands on the app, store the signed request using the Session_manager and since it's in the cache, you may access it on any page henceforth.

Note: This will not work when browsing privately in Safari since the session_id resets every time the page reloads. (Stupid Safari)


This solution applies in some cases - if possible:

If the iframe content page uses a subdomain of the page containing the iframe, the cookie is no longer blocked.


Here's some code that I use. I found that if I set any cookie from my site, then cookies magically work in the iframe from then on.

http://developsocialapps.com/foundations-of-a-facebook-app-framework/

 if (isset($_GET['setdefaultcookie'])) {
        // top level page, set default cookie then redirect back to canvas page
        setcookie ('default',"1",0,"/");
        $url = substr($_SERVER['REQUEST_URI'],strrpos($_SERVER['REQUEST_URI'],"/")+1);
        $url = str_replace("setdefaultcookie","defaultcookieset",$url);
        $url = $facebookapp->getCanvasUrl($url);
        echo "<html>\n<body>\n<script>\ntop.location.href='".$url."';\n</script></body></html>";
        exit();
    } else if ((!isset($_COOKIE['default'])) && (!isset($_GET['defaultcookieset']))) {
        // no default cookie, so we need to redirect to top level and set
        $url = $_SERVER['REQUEST_URI'];
        if (strpos($url,"?") === false) $url .= "?";
        else $url .= "&";
        $url .= "setdefaultcookie=1";
        echo "<html>\n<body>\n<script>\ntop.location.href='".$url."';\n</script></body></html>";
        exit();
    }

I finally went for a similar solution to the one that Sascha provided, however with some little adjusting, since I'm setting the cookies explicitly in PHP:

// excecute this code if user has not authorized the application yet
// $facebook object must have been created before

$accessToken = $_COOKIE['access_token']

if ( empty($accessToken) && strpos($_SERVER['HTTP_USER_AGENT'], 'Safari') ) {

    $accessToken = $facebook->getAccessToken();
    $redirectUri = 'https://URL_WHERE_APP_IS_LOCATED?access_token=' . $accessToken;

} else {

    $redirectUri = 'https://apps.facebook.com/APP_NAMESPACE/';

}

// generate link to auth dialog
$linkToOauthDialog = $facebook->getLoginUrl(
    array(
        'scope'         =>  SCOPE_PARAMS,
        'redirect_uri'  =>  $redirectUri
    )
);

echo '<script>window.top.location.href="' . $linkToOauthDialog . '";</script>';

What this does is check if the cookie is available when the browser is safari. In the next step, we are on the application domain, namely the URI provided as URL_WHERE_APP_IS_LOCATED above.

if (isset($_GET['accessToken'])) {

    // cookie has a lifetime of only 10 seconds, so that after
    // authorization it will disappear
    setcookie("access_token", $_GET['accessToken'], 10); 

} else {

  // depending on your application specific requirements
  // redirect, call or execute authorization code again
  // with the cookie now set, this should return FB Graph results

}

So after being redirecting to the application domain, a cookie is set explicitly, and I redirect the user to the authorization process.

In my case (since I'm using CakePHP but it should work fine with any other MVC framework) I'm calling the login action again where the FB authorization is executed another time, and this time it succeeds due to the existing cookie.

After having authorized the app once, I didn't have any more problems using the app with Safari (5.1.6)

Hope that might help anyone.


I had this problem on devices running iOS. I made a shop that is embeddable in a normal website using an iframe. Somehow, on every pageload the user got a new sessionid, resulting in users getting stuck halfway the process because some values weren't present in the session.

I tried some of the solutions given on this page, but popups don't work very well on an iPad and I needed the most transparent solution.

I resolved it using a redirect. The website that embeds my site must first redirect the user to my site, so the top frame contains the url to my site, where I set a cookie and redirect the user to the proper page on the website that embeds my site, that is passed through in the url.

Example PHP code

Remote website redirects user to

http://clientname.example.com/init.php?redir=http://www.domain.com/shop/frame

init.php

<?php
// set a cookie for a year
setcookie('initialized','1',time() + 3600 * 24 * 365, '/', '.domain.com', false, false);
header('location: ' . $_GET['redir']);
die;

The user ends up on http://www.domain.com/shop/frame where my site is embedded, storing sessions as it should and eating cookies.

Hope this helps someone.


A slightly simper version in PHP of what others have posted:

if (!isset($_COOKIE, $_COOKIE['PHPSESSID'])) {
    print '<script>top.window.location="https://example.com/?start_session=true";</script>';
    exit();
}

if (isset($_GET['start_session'])) {
    header("Location: https://apps.facebook.com/YOUR_APP_ID/");
    exit();
}

For my specific situation I resolved the problem by using window.postMessage() and eliminating any user interaction. Note that this will only work if you can somehow execute js in the parent window. Either by having it include a js from your domain, or if you have direct access to the source.

In the iframe (domain-b) i check for the presence of a cookie and if it is not set will send a postMessage to the parent (domain-a). Eg;

if (navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1
    && document.cookie.indexOf("safari_cookie_fix") < 0) {
    window.parent.postMessage(JSON.stringify({ event: "safariCookieFix", data: {} }));
}

Then in the parent window (domain-a) listen for the event.

if (typeof window.addEventListener !== "undefined") {
    window.addEventListener("message", messageReceived, false);
}

function messageReceived (e) {
    var data;

    if (e.origin !== "http://www.domain-b.com") {
        return;
    }

    try {
        data = JSON.parse(e.data);
    }
    catch (err) {
        return;
    }

    if (typeof data !== "object" || typeof data.event !== "string" || typeof data.data === "undefined") {
        return;
    }

    if (data.event === "safariCookieFix") {
        window.location.href = e.origin + "/safari/cookiefix"; // Or whatever your url is
        return;
    }
}

Finally on your server (http://www.domain-b.com/safari/cookiefix) you set the cookie and redirect back to where the user came from. Below example is using ASP.NET MVC

public class SafariController : Controller
{
    [HttpGet]
    public ActionResult CookieFix()
    {
        Response.Cookies.Add(new HttpCookie("safari_cookie_fix", "1"));

        return Redirect(Request.UrlReferrer != null ? Request.UrlReferrer.OriginalString : "http://www.domain-a.com/");
    }

}

I recently hit the same issue on Safari. The solution I figured out is based on the Local Storage HTML5 API. Using Local Storage you could emulate cookies.

Here's my blog post with details: http://log.scalemotion.com/2012/10/how-to-trick-safari-and-set-3rd-party.html


Just wanted to leave a simple working solution here that does not require user interaction.

As I stated in a post I made:

Basically all you need to do is load your page on top.location, create the session and redirect it back to facebook.

Add this code in the top of your index.php and set $page_url to your application final tab/app URL and you’ll see your application will work without any problem.

<?php
    // START SAFARI SESSION FIX
    session_start();
    $page_url = "http://www.facebook.com/pages/.../...?sk=app_...";
    if (isset($_GET["start_session"]))
        die(header("Location:" . $page_url));

    if (!isset($_GET["sid"]))
        die(header("Location:?sid=" . session_id()));
    $sid = session_id();
    if (empty($sid) || $_GET["sid"] != $sid):
?>
   <script>
        top.window.location="?start_session=true";
    </script>
<?php
    endif;
    // END SAFARI SESSION FIX
?>

Note: This was made for facebook, but it would actually work within any other similar situations.


Edit 20-Dec-2012 - Maintaining Signed Request:

The above code does not maintain the requests post data, and you would loose the signed_request, if your application relies on signed request feel free to try the following code:

Note: This is still being tested properly and may be less stable than the first version. Use at your own risk / Feedback is appreciated.

(Thanks to CBroe for pointing me into the right direction here allowing to improve the solution)

// Start Session Fix
session_start();
$page_url = "http://www.facebook.com/pages/.../...?sk=app_...";
if (isset($_GET["start_session"]))
    die(header("Location:" . $page_url));
$sid = session_id();
if (!isset($_GET["sid"]))
{
    if(isset($_POST["signed_request"]))
       $_SESSION["signed_request"] = $_POST["signed_request"];
    die(header("Location:?sid=" . $sid));
}
if (empty($sid) || $_GET["sid"] != $sid)
    die('<script>top.window.location="?start_session=true";</script>');
// End Session Fix

Google actually let the cat out of the bag on this one. They were using it for a while to access tracking cookies. It was fixed almost immediately by Apple =\

original Wall Street Journal post


You said you were willing to have your users click a button before the content loads. My solution was to have a button open a new browser window. That window sets a cookie for my domain, refreshes the opener and then closes.

So your main script could look like:

<?php if(count($_COOKIE) > 0): ?>
<!--Main Content Stuff-->
<?php else: ?>
<a href="/safari_cookie_fix.php" target="_blank">Click here to load content</a>
<?php endif ?>

Then safari_cookie_fix.php looks like:

<?php
setcookie("safari_test", "1");
?>
<html>
    <head>
        <title>Safari Fix</title>
        <script type="text/javascript" src="/libraries/prototype.min.js"></script>
    </head>
    <body>
    <script type="text/javascript">
    document.observe('dom:loaded', function(){
        window.opener.location.reload();
        window.close();
    })
    </script>
    This window should close automatically
    </body>
</html>

I have also been suffering from this problem, but finally got the solution, Initially directly the load the iframe url in browser like small popup then only access the session values inside the iframe.


I had the same problem and today I found a fix that works fine for me. If the user agent contains Safari and no cookies are set, I redirect the user to the OAuth Dialog:

<?php if ( ! count($_COOKIE) > 0 && strpos($_SERVER['HTTP_USER_AGENT'], 'Safari')) { ?>
<script type="text/javascript">
    window.top.location.href = 'https://www.facebook.com/dialog/oauth/?client_id=APP_ID&redirect_uri=MY_TAB_URL&scope=SCOPE';
</script>
<?php } ?>

After authentication and asking for permissions the OAuth Dialog will redirect to my URI in the top location. So setting cookies is possible. For all of our canvas and page tab apps I have already included the following script:

<script type="text/javascript">
    if (top.location.href==location.href) top.location.href = 'MY_TAB_URL';
</script>

So the user will be redirected again to the Facebook page tab with a valid cookie already set and the signed request is posted again.


In your Ruby on Rails controller you can use:

private

before_filter :safari_cookie_fix

def safari_cookie_fix
  user_agent = UserAgent.parse(request.user_agent) # Uses useragent gem!
  if user_agent.browser == 'Safari' # we apply the fix..
    return if session[:safari_cookie_fixed] # it is already fixed.. continue
    if params[:safari_cookie_fix].present? # we should be top window and able to set cookies.. so fix the issue :)
      session[:safari_cookie_fixed] = true
      redirect_to params[:return_to]
    else
      # Redirect the top frame to your server..
      render :text => "<script>alert('start redirect');top.window.location='?safari_cookie_fix=true&return_to=#{set_your_return_url}';</script>"
    end
  end
end

You can resolve this issue by adding header as p3p policy..i had same issue on safari so after adding header on top of the files has resolved my problem.

<?php
header('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');
?>

Some context that I haven't seen clearly stated in the existing answers (and also a lot has changed since 2012!):

If you can control both the 3rd party iframe and the parent page (i.e. you are able to insert JavaScript on the parent page), then several workarounds are available. I would suggest the most elegant of these is making use of the postMessage API as described by @Frank's answer, as a) this does not require any redirects and b) does not require any user interactions.

If you do NOT control both the 3rd party iframe and the parent page, e.g. you have a widget hosted on a site you do not control, then most of the answers posted here will not work in Safari as of May 2020, and will stop working in Chrome around 2022. That is, unless a user has already visited your domain or interacts with the iframe, you are not able to set cookies. However, there are some commercial services offering solutions to solve this problem, such as CloudCookie.io


I used modified (added signed_request param to the link) Whiteagle's trick and it worked ok for safari, but IE is constantly refreshing the page in that case. So my solution for safari and internet explorer is:

$fbapplink = 'https://apps.facebook.com/[appnamespace]/';
$isms = stripos($_SERVER['HTTP_USER_AGENT'], 'msie') !== false;

// safari fix
if(! $isms  && !isset($_SESSION['signed_request'])) {

    if (isset($_GET["start_session"])) {
        $_SESSION['signed_request'] = $_GET['signed_request'];
        die(header("Location:" . $fbapplink ));

    }
    if (!isset($_GET["sid"])) {
        die(header("Location:?sid=" . session_id() . '&signed_request='.$_REQUEST['signed_request']));
    }
    $sid = session_id();
    if (empty($sid) || $_GET["sid"] != $sid) {
    ?>
    <script>
        top.window.location="?start_session=true";
    </script>
    <?php
    exit;
    }
}

// IE fix
header('P3P: CP="CAO PSA OUR"');
header('P3P: CP="HONK"');


.. later in the code

$sr = $_REQUEST['signed_request'];
if($sr) {
        $_SESSION['signed_request'] = $sr;
} else {
        $sr = $_SESSION['signed_request'];
}

Let me share my fix in ASP.NET MVC 4. The main idea like in correct answer for PHP. The next code added in main Layout in header near scripts section:

@if (Request.Browser.Browser=="Safari")
{
    string pageUrl = Request.Url.GetLeftPart(UriPartial.Path);
    if (Request.Params["safarifix"] != null && Request.Params["safarifix"] == "doSafariFix")
    {
        Session["IsActiveSession"] = true;
        Response.Redirect(pageUrl);
        Response.End();
    }
        else if(Session["IsActiveSession"]==null)
    {
        <script>top.window.location = "?safarifix=doSafariFix";</script>
    }
}

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to facebook

I am receiving warning in Facebook Application using PHP SDK React-Native: Application has not been registered error Can't Load URL: The domain of this URL isn't included in the app's domains Facebook OAuth "The domain of this URL isn't included in the app's domain" Facebook login message: "URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings." Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `ListView` Open Facebook Page in Facebook App (if installed) on Android App not setup: This app is still in development mode IOS - How to segue programmatically using swift Get ALL User Friends Using Facebook Graph API - Android

Examples related to iframe

Getting all files in directory with ajax YouTube Autoplay not working Inserting the iframe into react component How to disable auto-play for local video in iframe iframe refuses to display iFrame onload JavaScript event YouTube iframe embed - full screen Change New Google Recaptcha (v2) Width load iframe in bootstrap modal Responsive iframe using Bootstrap

Examples related to safari

How to Inspect Element using Safari Browser What does the shrink-to-fit viewport meta attribute do? background: fixed no repeat not working on mobile Swift Open Link in Safari How do I make flex box work in safari? onClick not working on mobile (touch) window.open(url, '_blank'); not working on iMac/Safari HTML5 Video tag not working in Safari , iPhone and iPad NodeJS/express: Cache and 304 status code Video auto play is not working in Safari and Chrome desktop browser