Javascript 在父窗口中访问 iFrame 的 cookie

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30067870/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:36:14  来源:igfitidea点击:

Accessing cookies of an iFrame in parent window

javascriptiframecookies

提问by Hasanthi

I am loading an iFrame of a different domain. Both the parent and the iFrame sites are under my control. I'm using iFrame.postMessage to post messages to the iFrame. The site which I'm loading through the iFrame has a cookie(not a http only cookie). I need to read this cookie inside the parent site.

我正在加载不同域的 iFrame。父站点和 iFrame 站点都在我的控制之下。我正在使用 iFrame.postMessage 将消息发布到 iFrame。我通过 iFrame 加载的站点有一个 cookie(不是仅 http cookie)。我需要在父站点内读取此 cookie。

   var opIFrame=document.getElementById('opIFrame').contentWindow;

    /**
 * periodically invoking the Endpoint at OP for every six seconds
 */
setInterval(function(){
    console.log('Sending polling Request From RP Client ... ' + clientId);
    document.all.opIFrame.src = endPoint;
    opIFrame.postMessage(clientId,"https://localhost:9443/oauth2/loginstatus");
    var session=getCookieValue("session_state");
    console.log('**session**'+session);
},6000);


function getCookieValue(cookieName) {
var name = cookieName + "=";
var cookies =document.cookie.split(';');
if (!cookies) {
    return null;
}
for (var i = 0; i < cookies.length; i++) {
    var cookie = cookies[i].trim();
    if (cookie.indexOf(name) == 0) {
        return cookie.substring(name.length, cookie.length);
    }
}
return null;

}

}

I used the above methods to read the cookie. But it was not successful. Please advice me on this.

我用上面的方法来读取cookie。但它没有成功。请就此给我建议。

Updated Code:

更新代码:

<iframe id="opIFrame" style='visibility: hidden;' src=endpoint onload="getCookieValue('session_state')" >
</iframe> 
   <script>function getCookieValue(cookieName) {
        console.log("=====getCookieValue=======");
        var cookies = document.cookie;
        console.log("=====ALL cookies======="+cookies);
    }</script>

I'm getting empty array for cookies though I Can see the cookie in my browser.

尽管我可以在浏览器中看到 cookie,但我的 cookie 数组为空。

回答by dsharew

This will give you the cookie of the iframe:

这将为您提供 iframe 的 cookie:

var cookie = document.getElementById("iframeId").contentDocument.cookie;

To get a cookie by name use this function (from stackoverflow):

要按名称获取 cookie,请使用此函数(来自 stackoverflow):

function getCookie(cookie, name) {
    function escape(s) { return s.replace(/([.*+?\^${}()|\[\]\/\])/g, '\'); };
    var match = cookie.match(RegExp('(?:^|;\s*)' + escape(name) + '=([^;]*)'));
    return match ? match[1] : null;
}

回答by Manik Arora

I am not sure how are you catching the postMessage on the parent window or even catching or not, but below is the code that you should have on the parent window to catch the postMessage from the child iframe-

我不确定您是如何在父窗口上捕获 postMessage 的,甚至是如何捕获的,但下面是您应该在父窗口上捕获来自子 iframe 的 postMessage 的代码-

<script>
    window.addEventListener( "clientId",
      function (e) {
            if(e.origin !== 'https://localhost:9443'){ return; } 
            alert(e.data);
      },
      false);
</script>

UPDATE:
I replicated your scenario at my end and found that you should use-

更新
我最后复制了你的场景,发现你应该使用-

document.cookie.split(';');
parent.postMessage(clientId,"https://localhost:9443/oauth2/loginstatus");

instead of-

代替-

opIFrame.cookie.split(';');
opIFrame.postMessage(clientId,"https://localhost:9443/oauth2/loginstatus");

Full Code
Parent Window:- http://localhost:8541

完整代码
父窗口:- http://localhost:8541

<div>
     <h1>Parent Window</h1>
     <iframe src="http://localhost:50761/parent/test" width="100" height="100"></iframe>
     <script>
         window.addEventListener("message",
         function (e) {
            if (e.origin !== 'http://localhost:50761') { return; }
               alert(e.data);
            },false);
     </script>
</div>

iFrame Page:- http://localhost:50761

iFrame 页面:- http://localhost:50761

<div>
    <h1>iFrame Window</h1>
    <script type="text/javascript">
        function createCookie(name, value, days) {
            if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                var expires = "; expires=" + date.toGMTString();
            }
            else var expires = "";
            document.cookie = name + "=" + value + expires + "; path=/";
        }

        function readCookie(name) {
            var nameEQ = name + "=";
            var ca = document.cookie.split(';');
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) == ' ') c = c.substring(1, c.length);
                if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
            }
            return null;
        }
        createCookie('testCookie', "test content", 1);
        parent.postMessage(readCookie('testCookie'), "http://localhost:8541/");
    </script>
</div>

In the above code you can see I am accessing the cookie value in cross domain environment i.e. parent window is running on different domain and page loading in iframe is running on different domain.

在上面的代码中,您可以看到我在跨域环境中访问 c​​ookie 值,即父窗口在不同的域上运行,而 iframe 中的页面加载在不同的域上运行。

I created a test cookie with test data in it and passed to the parent window using postMessage.

我创建了一个带有测试数据的测试 cookie,并使用 postMessage 传递给父窗口。