Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
659 views
in Technique[技术] by (71.8m points)

javascript - Accessing cookies of an iFrame in parent window

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This will give you the cookie of the iframe:

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...