Check if third-party cookies are enabled

Viewed 73791

I have an application that needs to check whether the client browser has third-party-cookies enabled. Does anyone know how to do this in JavaScript?

8 Answers

My solution works by loading a <script> from an external domain that sets a cookie, checks if it was successful, and then passes the result (1 or 0) as an argument to a callback function.

The HTML:

<script>
function myCallback(is_enabled) {
    if (is_enabled===1) {//third party cookies are enabled
    }
}
</script>
<script src="https://third-party-domain/third-party-cookies.php?callback=myCallback"></script>

If you prefer to run it asynchronously, you may use the async and defer attributes.

This also works with jQuery:

<script>
$.ajax({
    url: 'https://third-party-domain/third-party-cookies.php',
    dataType: 'jsonp',
}).done(function(is_enabled) {
    if (is_enabled===1) {//third party cookies are enabled
    }
})
</script>

Here is the third-party-cookies.php code. This must be hosted on a different domain. The server must support PHP:

<?php

header('Cache-Control: no-store');
header('Content-Type: text/javascript');

if ($_GET['callback']=='') {
    echo 'alert("Error: A callback function must be specified.")';
}
elseif (!isset($_GET['cookieName'])) {// Cookie not set yet
    $cookieName = strtr((string)$_SERVER['UNIQUE_ID'], '@', '_');
    while (isset($_COOKIE[$cookieName]) || $cookieName=='') {
        $cookieName = dechex(mt_rand());// Get random cookie name
    }
    setcookie($cookieName, '3rd-party', 0, '/');
    header('Location: '.$_SERVER['REQUEST_URI'].'&cookieName='.$cookieName);
}
elseif ($_COOKIE[$_GET['cookieName']]=='3rd-party') {// Third party cookies are enabled.
    setcookie($_GET['cookieName'], '', -1, '/'); // delete cookie
    echo $_GET['callback'].'(1)';
}
else {// Third party cookies are not enabled.
    echo $_GET['callback'].'(0)';
}

Third Party Cookie detection with Whitelisting of URLs

Alan H & Gojko Adzic are good enough for majority of use cases, but these solutions won't work if you want your users to do whitelisting of third party cookies only to certain domains.

I'm presenting a slightly modified version of Gojko Adzic's answer

For this we need two domains :

  • Domain 1, this is the page your user lands, it initially sets tpc=pending, then it redirects to Domain 2
  • Domain 2 injects Domain 1's url in an iFrame, tries to set a cookie tpc=true and redirects back to Domain 1
  • Now, Domain 1 reads the cookie tpc and checks if its true, if we get value as true, third party cookies are allowed if it is still in pending third party cookies are blocked blocked.

Now, you might ask your users to whitelist (allow third party cookies) ONLY for Domain 1, also by this technique third party detection will be accurate if the users had white listed your domain.


This is tested in Chrome 74, 75, 76 & Edge 78

Unfortunately, Mozilla doesn't provide whitelisting of urls like Chrome does and Safari has it own mechanisms of detecting third party cookies (ITP).

P.S. Will upload this demo in my github when I get time.

This is something that I did to check if third-parties cookies have been blocked by the user.

I just try to access the browser's local storage. If the user has enabled third-party cookies then it should be available, else it would throw an error.

try {
        if(window.localStorage) {
            //cookies enabled
        }
    } catch (err) {
        //cookies disabled
    }

Steps to check if third party cookies are enabled with Greg and Alan's solutions:

I modify the files as my only need was to check if third party cookies are enabled or not, depends on that i would do something like route them to a page telling users to enable third party cookies.

1) Edit your nginx sites config

(In debian 9 is in /etc/nginx/sites-enabled/default)

$ sudo nano /etc/nginx/sites-enabled/default

You'll need to have TLS/SSL on your domain or else you won't be able to set cookies from a third party domain and you'll get an error saying:

Because a cookie’s SameSite attribute was not set or is invalid, it defaults to SameSite=Lax, which prevents the cookie from being sent in a cross-site request. This behavior protects user data from accidentally leaking to third parties and cross-site request forgery. Resolve this issue by updating the attributes of the cookie: Specify SameSite=None and Secure if the cookie should be sent in cross-site requests. This enables third-party use. Specify SameSite=Strict or SameSite=Lax if the cookie should not be sent in cross-site requests.

  • Specify your allowed domains in "Access-Control-Allow-Origin", not recomended to leave it with "*" (public access).

  • You can specify 'Access-Control-Allow-Methods "GET";' as is the only method being used.

(I set those headers with "*" (public) just to make sure it works, after that, you can edit them.)

You can change the name of the endpoints (step1.js.php & step2.js.php) but you'll need to change it in you js script. (Requests are made to your-custom-domain.com/step1.js.php o your-custom-domain.com/step2.js.php unless you change it. The extension does not really matter, you can change it for "step1" and "step2" or whatever you like)

# Nginx config start
server {
        server_name your-custom-domain.com;
        # Check if third party cookies are allowed
        # The first third-party "JavaScript file" - served by nginx
        location = /step1.js.php {
                expires -1;
                add_header Cache-Control "private";
                etag off;
                add_header Access-Control-Allow-Origin "*";
                add_header Access-Control-Allow-Methods "*";
                add_header Content-Type 'application/javascript; charset=UTF-8';
                add_header Set-Cookie "third_party_c_t=hey there!;Max-Age=172000; Secure; SameSite=none";
                return 200 'window._3rd_party_test_step1_loaded();';
        }
        # The second third-party "JavaScript file" - served by nginx
        location = /step2.js.php {
                add_header Access-Control-Allow-Origin "*";
                add_header Access-Control-Allow-Methods "*";
                add_header Content-Type 'application/javascript; charset=UTF-8';
                set $test 'false';
                if ($cookie_third_party_c_t = 'hey there!') {
                        set $test 'true';
                        # clear the cookie
                        add_header Set-Cookie "third_party_c_t=;expires=Thu, 01 Jan 1970 00:00:00 GMT; Secure; SameSite=none";
                }
                return 200 'window._3rd_party_test_step2_loaded($test);';
        }

    # managed by Certbot, here is where your certificates goes.
    listen [::]:443 ssl ipv6only=on; 
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/www.couchdb.me/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/www.couchdb.me/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

Save it (ctrl+x - Press letter Y if you want to save it - Enter to confirm) and restart/reload your nginx:

$ sudo systemctl restart nginx.service

2) In your landing page (different from your-custom-domain.com)

You can change the name of the methods (_3rd_party_test_step1_loaded and _3rd_party_test_step2_loaded) but you'll need to change it also in nginx's config. (Make sure names are unique)

2.1) Add this cript to the header of your html (this must be loaded first):

<script type="text/javascript">
window._3rd_party_test_step1_loaded = function () {
      // At this point, a third-party domain has now attempted to set a cookie (if all went to plan!)
      var step2El = document.createElement("script");
      const url = your-custom-domain.com + "/step2.js.php";
      step2El.setAttribute("src", url);
      document.head.appendChild(step2El);
};
window._3rd_party_test_step2_loaded = function (cookieSuccess) {
      // If true, the third-party domain cookies are enabled
      // If false, the third-party domain cookies are disable
      cookieSuccess ? callMethodIfTrue() : callMethodIfFalse();
};
</script>

2.2) Add the script at the end of your body html:

<script type="text/javascript" src="https://your-custom-domain/step1.js.php"></script>

or if your are working in a js file (remember that you need to have your file added on your html landing page eg: <script type="text/javascript" src="path/to/your/js/file"></script>

JS file:

window._3rd_party_test_step1_loaded = function () {
      // At this point, a third-party domain has now attempted to set a cookie (if all went to plan!)
      var step2El = document.createElement("script");
      const url = that.$url + "/step2.js.php";
      step2El.setAttribute("src", url);
      document.head.appendChild(step2El);
};
window._3rd_party_test_step2_loaded = function (cookieSuccess) {
      // If true, the third-party domain cookies are enabled
      // If false, the third-party domain cookies are disable
      cookieSuccess ? callMethodIfTrue() : callMethodIfFalse();
};

window.onload = function () {
      const url = "your-custom-domain.com" + "/step1.js.php";
      var step1El = document.createElement("script");
      step1El.setAttribute("src", url);
      document.body.appendChild(step1El);
};
Related