在父窗口中访问iFrame的Cookie [英] Accessing cookies of an iFrame in parent window

查看:963
本文介绍了在父窗口中访问iFrame的Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在载入其他网域的iFrame。父级网站和iFrame网站都在我的控制之下。我使用iFrame.postMessage发布消息到iFrame。我通过iFrame加载的网站有一个cookie(不是仅http cookie)。我需要在父网站中读取这个cookie。

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

/ **
*每六秒钟周期性地调用OP的Endpoint
* /
setInterval(function(){
console.log 'client','https:// localhost:9443 / oauth2 /')发送轮询请求从RP Client ...'+ clientId);
document.all.opIFrame.src = endPoint;
opIFrame.postMessage 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;

}



读取cookie。但它不成功。

code>< iframe id =opIFramestyle ='visibility:hidden;'src = endpoint onload =getCookieValue('session_state')>
< / iframe>
< script> function getCookieValue(cookieName){
console.log(===== getCookieValue =======);
var cookies = document.cookie;
console.log(=====所有Cookie =======+ cookies);
}< / script>

我得到空数组的cookie,虽然我可以看到我的浏览器中的cookie。 >

解决方案

我不知道你如何在父窗口上捕捉postMessage或者甚至捕捉或不捕捉,但下面是你应该在父窗口上从子iframe捕获postMessage -

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

UPDATE

我复制了您的场景我发现你应该使用 -

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

而不是 -

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

完整代码

窗口: - http:// localhost:8541

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

iFrame页面 - http:// localhost:50761

  div> 
< h1> iFrame窗口< / 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 = /;
}

函数readCookie(name){
var nameEQ = name +=;
var ca = document.cookie.split(';');
for(var i = 0; 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>

在上面的代码中,您可以看到我正在访问跨域环境中的cookie值,即父窗口运行在不同的域上,并且在iframe在不同的域上运行时加载页面。



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

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.

   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.

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.

解决方案

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-

<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

<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

<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.

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

这篇关于在父窗口中访问iFrame的Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆