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.
Here is simpler solution:
This will give you the cookie of the iframe:
To get a cookie by name use this function (from stackoverflow):
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-
UPDATE:
I replicated your scenario at my end and found that you should use-
instead of-
Full Code
Parent Window: - http://localhost:8541
iFrame Page: - http://localhost:50761
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.