javascript - 在父窗口中访问 iFrame 的 cookie

标签 javascript iframe cookies

我正在加载不同域的 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;

我是用上面的方法读取cookie的。但它没有成功。请就此向我提出建议。

更新代码:

<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 为空数组。

最佳答案

这将为您提供 iframe 的 cookie:

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

要按名称获取 cookie,请使用此函数 (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;
}

关于javascript - 在父窗口中访问 iFrame 的 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30067870/

相关文章:

javascript - 如何隐藏谷歌组织结构图中所选元素的 HTML 类?

javascript - kendo datepicker javascript 文件

flutter - 我可以在 Flutter Web 上使用两个 iframe 吗?

jquery - 如何从 Iframe 获取 HTTP 状态?

android - 使用 PhoneGap 的 FileTransfer 传递 cookie

javascript - 在 nuxt.js 上为 vuetify app v2.0 添加暗模式切换

javascript - ng-click 从内部数组中删除项目

javascript - 为什么 cookies 是字符串而不是对象?

javascript - 使用 casperjs 通过一级 iframe 对嵌套链接进行分组

internet-explorer - 我可以在 ActiveX 中使用 IHTMLDocument2 访问 HttpOnly cookie 吗?