如何通过域B中附加的内联javascript从域B读取域A设置的cookie?

时间:2012-12-11 09:27:53

标签: cookies cross-domain jsonp

我正在尝试通过域B中的内联javascript代码从域B读取由域A设置的cookie(我知道cookie的名称)。

域名B内联javascript代码:

<script type="text/javascript">
        /* * * DON'T EDIT BELOW THIS LINE * * */
        (function() {
            var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
            dsq.src = 'http://domainA.com/classifiead/embed.js';
            (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
        })();

    </script>

http://domainA.com/classifiead/embed.js包含:

     $("#jsonpbtn2").click(function() {

   var url = 'http://domainA.com/classifiead/content2.php?callback=?'; 
  //  var id = info;
   $.getJSON(url, null, function(data) {
                 $('#textDiv').append(data.somecookie);
     });
});

http://domainA.com/classifiead/content2.php包含:

<?php 
 header('Content-type: application/json');
 header('Access-Control-Allow-Origin: *');
 header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
 header("Access-Control-Allow-Credentials: true");
 header("Access-Control-Allow-Headers: Content-Type, *");
 header('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');

 $rtnjsonobj->id = 'test skdfbslkdj';
 $rtnjsonobj->somecookie =$_COOKIE['thisweb_last_75'];
echo $_GET['callback']. '('. json_encode($rtnjsonobj) . ')';  

&GT;

这甚至可能吗?

1 个答案:

答案 0 :(得分:1)

是的,如果您在域A上有代码执行服务器端。当您的JavaScript代码从域A接收cookie时,您可以将cookie发送到域B.

如果cookie是安全cookie或httponly,您只能通过服务器端脚本阅读它。

我建议你这样读: http://en.wikipedia.org/wiki/HTTP_cookie#Cross-site_scripting_.E2.80.93_cookie_theft

请注意:在您的示例中,您应该在分配属性之前创建对象。例如:

$rtnjsonobj = new stdClass();
$rtnjsonobj->id = 'test skdfbslkdj';
$rtnjsonobj->somecookie =$_COOKIE['thisweb_last_75'];