在父窗口中访问iFrame的cookie

时间:2023-01-10 15:51:20

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.

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

}

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

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

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.

虽然我可以在浏览器中看到cookie,但我正在为cookie获取空数组。

2 个解决方案

#1


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-

我不确定你是如何在父窗口上捕获postMessage甚至是否捕获,但下面是你应该在父窗口上捕获来自子iframe的postMessage的代码 -

<script>
    window.addEventListener( "clientId",
      function (e) {
            if(e.origin !== 'https://localhost:9443'){ return; } 
            alert(e.data);
      },
      false);
</script>

UPDATE:
I replicated your scenario at my end and found that you should use-

更新:我在我的最后复制你的场景,发现你应该使用 -

document.cookie.split(';');
parent.postMessage(clientId,"https://localhost:9443/oauth2/loginstatus");

instead of-

opIFrame.cookie.split(';');
opIFrame.postMessage(clientId,"https://localhost:9443/oauth2/loginstatus");

Full Code
Parent Window: - http://localhost:8541

完整代码父窗口: - http:// localhost:8541

<div>
     <h1>Parent Window</h1>
     <iframe src="http://localhost:50761/parent/test" width="100" height="100"></iframe>
     <script>
         window.addEventListener("message",
         function (e) {
            if (e.origin !== 'http://localhost:50761') { return; }
               alert(e.data);
            },false);
     </script>
</div>

iFrame Page: - http://localhost:50761

iFrame页面: - http:// localhost:50761

<div>
    <h1>iFrame Window</h1>
    <script type="text/javascript">
        function createCookie(name, value, days) {
            if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                var expires = "; expires=" + date.toGMTString();
            }
            else var expires = "";
            document.cookie = name + "=" + value + expires + "; path=/";
        }

        function readCookie(name) {
            var nameEQ = name + "=";
            var ca = document.cookie.split(';');
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) == ' ') c = c.substring(1, c.length);
                if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
            }
            return null;
        }
        createCookie('testCookie', "test content", 1);
        parent.postMessage(readCookie('testCookie'), "http://localhost:8541/");
    </script>
</div>

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.

在上面的代码中,您可以看到我在跨域环境中访问cookie值,即父窗口在不同的域上运行,并且iframe中的页面加载在不同的域上运行。

I created a test cookie with test data in it and passed to the parent window using postMessage.

我在其中创建了一个包含测试数据的测试cookie,并使用postMessage传递给父窗口。

#2


Here is simpler solution:

This will give you the cookie of the iframe:

这将为您提供iframe的cookie:

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

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

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

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

#1


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-

我不确定你是如何在父窗口上捕获postMessage甚至是否捕获,但下面是你应该在父窗口上捕获来自子iframe的postMessage的代码 -

<script>
    window.addEventListener( "clientId",
      function (e) {
            if(e.origin !== 'https://localhost:9443'){ return; } 
            alert(e.data);
      },
      false);
</script>

UPDATE:
I replicated your scenario at my end and found that you should use-

更新:我在我的最后复制你的场景,发现你应该使用 -

document.cookie.split(';');
parent.postMessage(clientId,"https://localhost:9443/oauth2/loginstatus");

instead of-

opIFrame.cookie.split(';');
opIFrame.postMessage(clientId,"https://localhost:9443/oauth2/loginstatus");

Full Code
Parent Window: - http://localhost:8541

完整代码父窗口: - http:// localhost:8541

<div>
     <h1>Parent Window</h1>
     <iframe src="http://localhost:50761/parent/test" width="100" height="100"></iframe>
     <script>
         window.addEventListener("message",
         function (e) {
            if (e.origin !== 'http://localhost:50761') { return; }
               alert(e.data);
            },false);
     </script>
</div>

iFrame Page: - http://localhost:50761

iFrame页面: - http:// localhost:50761

<div>
    <h1>iFrame Window</h1>
    <script type="text/javascript">
        function createCookie(name, value, days) {
            if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                var expires = "; expires=" + date.toGMTString();
            }
            else var expires = "";
            document.cookie = name + "=" + value + expires + "; path=/";
        }

        function readCookie(name) {
            var nameEQ = name + "=";
            var ca = document.cookie.split(';');
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) == ' ') c = c.substring(1, c.length);
                if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
            }
            return null;
        }
        createCookie('testCookie', "test content", 1);
        parent.postMessage(readCookie('testCookie'), "http://localhost:8541/");
    </script>
</div>

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.

在上面的代码中,您可以看到我在跨域环境中访问cookie值,即父窗口在不同的域上运行,并且iframe中的页面加载在不同的域上运行。

I created a test cookie with test data in it and passed to the parent window using postMessage.

我在其中创建了一个包含测试数据的测试cookie,并使用postMessage传递给父窗口。

#2


Here is simpler solution:

This will give you the cookie of the iframe:

这将为您提供iframe的cookie:

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

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

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

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