Cookie 设置为 iframe javascript 中的父窗口

Cookie set to parent window from iframe javascript

本文关键字:窗口 javascript 设置 iframe Cookie      更新时间:2023-09-26

请任何人帮助我在JavaScript中的iframe上设置一个cookie。如果可能,请提供一些相关的链接。例如:父页面具有域 ABC.com

在该页面上指向 XYZ.com 的 IFRAME,我想在 iframe 中编写一个脚本,以便在父页面上的 ABC.com 上放置一个 cookie。

您可以使用postMessage从子窗口(即iFrame(发布,然后在父窗口收听事件。

  window.parent.postMessage("Value", "*");
  window.addEventListener();

这篇文章可能会帮助你了解更多。您如何跨域使用 window.postMessage?

这是你如何做到的。

iFrame 网站
将以下代码粘贴到 iFrame 网站中:

<script>
    /* Sends a hello from the iframe to the parent */    
    parent.postMessage('hello_from_the_iframe', 'https://parentwebsite.com/');
</script>

家长网站
将以下代码粘贴到嵌入 iFrame 的父网站中以设置 cookie:

<script> 
    window.addEventListener("message",function (e) { 
            /*Check if the iframe website is sending the message*/
            if(e.origin === 'https://iframewebsite.com'){ 
                    /*Check if you got a hello from the iframe*/
                    if(e.data === 'hello_from_the_iframe'){
                        /*Function to set Cookie*/
                        function setCookie(cname, cvalue, exdays) {
                            var d = new Date();
                            d.setTime(d.getTime() + (exdays*24*60*60*1000));
                            var expires = "expires="+ d.toUTCString();
                            document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
                        }
                        /* Set the cookie 'set_my_cookie'*/
                        setCookie('set_my_cookie',1,365);
                        /* Get notification that the cookie is set*/
                        alert('cookie set');
                    }
            }
    },false);
</script>

您需要将https://parentwebsite.com/替换为嵌入 iframe 的网站的域。

您还需要将https://iframewebsite.com替换为 iFrame 的原点。如果您不知道iFrame的来源,则只需将以下代码粘贴到iFrame HTML中,它将在警告框中向您显示原点。

<script>
    alert(window.location.origin);
</script>

希望这有帮助。