Recently, when dealing with iframe cross-domain communication (i.e., PostMessage applications, check out my article), I found a problem: in iframe environments, the cookies of embedded web pages cannot be read across domains, and the results are null.

Originally, iframe was supposed to use PostMessage for cross-domain data sharing, but this issue made me very upset… (´༎ຶ dare༎ ຶ ‘) If it is not settled, all the previous efforts will be vain.

So I started looking at various documents and solutions. According to the documentation:

With Chrome 51, a new SameSite property has been added to browser cookies to prevent CSRF attacks and user tracking. The SameSite attribute of a Cookie is used to limit third-party cookies, thereby reducing security risks. After Chrome version 80, SameSite will be set to Lax by default.

Detailed can check ruan Yifeng “Cookie SameSite properties”, there are very clear instructions.

Conclusion: If you want to share cookies across domains with iframe awareness, you can’t get around the limitations of the browser. Unless you made the browser, the following is your only option… ╥ man ╥

To read a cookie from an embedded web domain, set the cookie’s SameSite property to None, ignoring the co-domain restriction. In addition, set Secure to be used only in HTTPS environments.

php:

header('Set-Cookie: key=value; SameSite=None; Secure');
Copy the code

js:

document.cookie = "key=value; SameSite=None; Secure"
Copy the code

Note that setting SameSite to None alone does not take effect. You must also set Secure; After Secure is enabled, the HTTP and HTTPS cookies are not connected. Be careful not to step into the trap.