Getting setting cookies on different domains, with javascript or other

后端 未结 3 1435
旧巷少年郎
旧巷少年郎 2020-12-02 11:27

Haven\'t been able to find anything particular to this situation online so here i go... I need to set/get the cookies stored at \"first.com\" while browsing \"second.com\",

相关标签:
3条回答
  • 2020-12-02 12:01

    You could inject a script element into HEAD of the document with a callback that passes the cookie you need to whatever function needs it.

    Something like:

     <script type="text/javascript">
       var newfile=document.createElement('script');
       newfile.setAttribute("type","text/javascript");
       newfile.setAttribute("src", 'http://first.com/doAjax?getCookie&callback=passCookie');
       document.getElementsByTagName("head")[0].appendChild(newfile);
     </script>
    

    And the page first.com/doAjax?getCookie could do this:

         passCookie({'name':'mycookie', 'value':'myvalue'});
    
    0 讨论(0)
  • 2020-12-02 12:09

    For SETTING cookies you can change my script as follows:

    The new PHP-Script:

    //writecookie.php
    setcookie($_GET['c'], $_GET['v']);
    

    And the JavaScript:

    function buttonClickOrAnything()
    {
      var refreshObject = new XMLHttpRequest();
      if (!refreshObject)
      {
        //IE6 or older
        try
        {
          refreshObject = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e)
        {
          try
          {
            refreshObject = new ActiveXObject("Microsoft.XMLHTTP");
          }
          catch (e)
          {
            return;
          }
        }
      }
      refreshObject.open("GET", "http://www.first.com/writecookie.php?c=cookiename&v=cookievalue");
      refreshObject.send();
    }
    

    That should work on all browsers.

    0 讨论(0)
  • 2020-12-02 12:23

    Put this PHP-File to first.com:

    //readcookie.php    
    echo $_COOKIE['cookiename'];
    

    On second.com you can use this javascript to get the value:

    function readCookieCallback()
    {
       if ((this.readyState == 4) && (this.status == 200))
       {
         alert("the value of the cookie is: "+this.responseText);
       } 
       else if ((this.readyState == 4) && (this.status != 200))
       {
         //error...
       }
    }
    
    
    function buttonClickOrAnything()
    {
      var refreshObject = new XMLHttpRequest();
      if (!refreshObject)
      {
        //IE6 or older
        try
        {
          refreshObject = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e)
        {
          try
          {
            refreshObject = new ActiveXObject("Microsoft.XMLHTTP");
          }
          catch (e)
          {
            return;
          }
        }
      }
      refreshObject.onreadystatechange = readCookieCallback;
      refreshObject.open("GET", "http://www.first.com/readcookie.php");
      refreshObject.send();
    }
    

    Regards, Robert

    0 讨论(0)
提交回复
热议问题