Check if third-party cookies are enabled

前端 未结 6 1404
既然无缘
既然无缘 2020-11-27 10:58

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?

6条回答
  •  被撕碎了的回忆
    2020-11-27 11:10

    Technical Background

    The third party sets & reads cookies over HTTP (not in JavaScript).

    So we need two requests to an external domain to test if third-party cookies are enabled:

    1. One where the third party sets the cookie(s)
    2. The second, with a differing response depending on whether the browser sent the cookie(s) back to the same third party in a second request.

    We cannot use XMLHTTPRequest (Ajax) because of the DOM security model.

    Obviously you can't load both scripts in parallel, or the second request may be made before the first request’s response makes it back, and the test cookie(s) will not have been set.

    Code Example

    Given:

    1. The .html file is on one domain, and

    2. The .js.php files are on a second domain, we have:

    The HTML test page

    Saved as third-party-cookies.html

    
    
    
      
      Test if Third-Party Cookies are Enabled
    
    
    
    
    
      

    Test if Third-Party Cookies are Enabled

    The first third-party JavaScript file

    Saved as step1.js.php

    This is written in PHP so we can set cookies as the file loads. (It could, of course, be written in any language, or even done in server config files.)

    
    window._3rd_party_test_step1_loaded();
    

    The second third-party JavaScript file

    Saved as step2.js.php

    This is written in PHP so we can read cookies, server-side, before we respond. We also clear the cookie so the test can be repeated (if you want to mess around with browser settings and re-try).

    
    window._3rd_party_test_step2_loaded();
    

    The last line uses the ternary operator to output a literal Javascript true or false depending on whether the test cookie was present.

    Test it here.

    Available for your testing pleasure at https://alanhogan.github.io/web-experiments/3rd/third-party-cookies.html.

    (As a final note — don’t use someone else’s server to test third-party cookies without their permission. It could break spontaneously or inject malware. And it’s rude.)

提交回复
热议问题