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