React Hook to check third-party cookies enabled in your browser

First-party vs Third-party Cookies

In simple words first-party cookies are created only by the host website we are visiting. Mainly used to keep track of user identity, user activities in a particular domain. Third-party cookies are created by parties other than the website owner. Mainly used for advertising purposes.
How can we check whether third-party cookie enabled in the browser using JavaScript?
Approach 1: Detect only using client side code
By using navigator.cookieEnabled
property (https://developer.mozilla.org/en-US/docs/Web/API/Navigator/cookieEnabled) we could detect cookie status of the browser.
But as mentioned in the document this property behaves differently with browsers when detecting third-party cookies. To check third-party cookies,navigator.cookieEnabled
should be invoked inside a third-party iframe.
This approach has different behaviors in some browsers.
Approach 2: Detect using client and server side code
Here we are following the text book definition. We are trying to create a cookie in a different domain and checking we are allowed to do it. We can only create cookies from different domain only if third-party cookies enabled in the browser. What we do here is, host a simple script to create a cookie in a different domain and loading it in a temporary iframe for few seconds in client side. That script should include code to create a cookie in the hosted domain and send a message through event listener to the parent window from iframe. Then our client side code should have a listener to get the message send from the iframe and get the third party cookie status of the browser.
This approach is working fine with different browsers.
Implementation in react
We are creating a custom react hook to put logic related to check cookie status. Logic related to create a iframe, loading the other domain inside the iframe and listener to get cookie supported status from iframe to parent window are put in the react hook. Please note that the script related to create a cookie in a different domain is hosted in github pages. You can replace the iframe source url with your hosted domain.
Cookie check react hook- https://github.com/chambits/react-third-party-cookie-check
Static html page that includes script to create a cookie- https://github.com/chambits/create-third-party-cookie
Thank you for reading this post. If you do have any questions please add as a comment. If you like this post, give a Cheer!
Happy Coding ❤