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

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

问题描述

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

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;

}

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

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

更新代码:

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

虽然我可以在浏览器中看到 cookie,但我得到的 cookie 数组为空.

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

推荐答案

这会给你 iframe 的 cookie:

This will give you the cookie of the iframe:

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

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

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

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

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

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