0

我搜索了我的要求并找到了我的问题的答案。但我无法让它工作。因此,我想在这里发布我的要求。

我的网站由第三方供应商托管,我无法控制他们的服务器。我在他们的一个 html 页面中设置了 iframe。这个 iframe 将指向我的服务器,我应该能够访问供应商在其主页中设置的 cookie。为了尝试这个,我创建了两个 html 页面。一个命名为 SetCookie.html,另一个命名为 GetCookie.html。两者都驻留在不同的计算机中。请在下面找到源代码:

SetCookie.html

<html>
    <head>
        <title>Set Cookie</title>
    </head>
    <body>

        <script type="text/javascript">
            function setCookie() {
                var cookieValue = document.getElementById("txtCookie").value;
                var cookieName = "TestCookie";
                document.cookie = cookieName + "=" + cookieValue;
                document.getElementById("tdCookieMessage").innerHTML = cookieName + "=" + cookieValue + " is set!";
            }
        </script>

        <table>
            <tr>
                <td>
                    Cookie
                </td>
                <td>
                    <input type="text" id="txtCookie" value="" />
                </td>
                <td>
                    <input type="button" id="btnGetCookie" onclick="setCookie();" value="Set Cookie!" />
                </td>
            </tr>
            <tr>
                <td colspan="3" id="tdCookieMessage">
                </td>
            </tr>
        </table>
        <table>
            <tr>
                <td>
                    <iframe src="http://myServer/GetCookie.html"></iframe>
                </td>
            </tr>
        </table>
    </body>
</html>

获取Cookie.html

<html>
<head>
    <title>Get Cookie</title>

    <script type="text/javascript">
        function getCookie(cookieName) {
            var i, x, y, ARRcookies = document.cookie.split(";");
            for (i = 0; i < ARRcookies.length; i++) {
                x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
                y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
                x = x.replace(/^\s+|\s+$/g, "");
                if (x == cookieName) {
                    document.getElementById("tdCookie").innerHTML = unescape(y);
                    expireCookie(cookieName);
                }
            }
        }
        function expireCookie(cookieName) {
            document.cookie = cookieName + '=; expires=Thu, 01-Jan-70 00:00:01 GMT;';
        }
    </script>

</head>
<body>
    <table>
        <tr>
            <td>
                <input type="button" id="btnGetCookie" onclick="getCookie('TestCookie');" value="Test Cookie Value is: " />
            </td>
            <td id="tdCookie">
            </td>
        </tr>
    </table>
</body>
</html>

任何建议表示赞赏。

4

1 回答 1

0

只有为页面所在的域设置的 cookie 才会发送到页面。即您在 mywebsite.com 上,而他们在 theirdomain.com 上,您将不会收到他们的 cookie,他们也不会收到您的。出于安全原因,这就是 cookie 的工作方式。

如果您的站点和供应商的站点都在同一个域上,您可以解决这个问题,那么您可以在应用程序之间共享 cookie。

IE them.mywebsite.com 和 me.mywebsite.com 都会收到 *.mywebsite.com 的 cookie。

于 2012-07-11T20:29:37.357 回答