クロスドメインでcookie書き込む方法 +クロスブラウザで
あるサイトから別ドメインのクッキーを書き込む。こういうクッキーは、サードパーティクッキーと呼ばれる。FirefoxとChromeはデフォルトでサードパーティクッキーが書き込めるようになっているが、IEとSafariが問題になる。IEはコンパクトポリシーというものを設定すればいけるが、Safariは出来ない。Safariはデフォルトで”知らないとサイトや広告のみCookieをブロック”となっている。でも、GoogleAdsenseとかは書き込めている。なので調べた。
ポリシーの設定 (P3P) (以下IE対策用)
webサイトで個人情報などを取り扱う場合、ブラウザで設定されたポリシー設定とアクセスしているサイトのポリシーがマッチするか確認する仕組みがある。詳しくは参考サイトを参照。
Platform for Privacy Preferences 1.0 (P3P1.0) 仕様書
http://www.iajapan.org/trans2japanese/w3c/rec-p3p-20020416j.html
【絵で分かるキーワード】P3P
http://ascii.jp/elem/000/000/338/338065/
P3Pコンパクトポリシーをコピペするのが流行らないことを祈る
http://bakera.jp/ebi/topic/3594
今回は下記をHTTPヘッダーに加える。
header("P3P: CP='UNI CUR OUR'");
phpでセッションに書き込むサンプル (以下Safari対策用)
<?php session_start(); header("P3P: CP='UNI CUR OUR'"); var_dump($_SESSION); $_SESSION['writetest'] = 'waaaa';
できない方法
iframeでクロスドメインのURLにアクセスする。
セッションを張るために、HTTPヘッダーでSetCookie: PHPSESSION=****が返ってくるがクロスドメインなので書き込めない。
test-cookie-sample.html
<!DOCTYPE html> <html lang="ja" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Cookie write test of Cross Domain.</title> </head> <body> <iframe name="ifr" src="http://sample.com/test-cookie-send.php"></iframe> </body> </html>
できる方法
iframeの中にform送信すると、クロスドメインのクッキーも書き込める。詳細は不明だが、GoogleAdsenseがこのロジックで書き込んでいる(実際はもっと複雑な行程だが)。つまりGoogleAdsenseは、Safariで広告のクッキーを書き込まないとしているにも関わらず書き込んでいるのだ。良い子は真似しないように。
test-cookie-sample.html
<!DOCTYPE html> <html lang="ja" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Cookie write test of Cross Domain.</title> </head> <body> <form id="postform" method="GET" action="http://sample.com/test-cookie-send.php"target="ifr"> <input type="hidden" name="cookiewrite" value="cookiewritevalue" /> </form> <iframe name="ifr"></iframe> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript"> $(function(){ $("#postform").submit(); }); </script> </body> </html>