Cookie 设置为 iframe javascript 中的父窗口
Cookie set to parent window from iframe javascript
请任何人帮助我在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>
希望这有帮助。
相关文章:
- 关闭黑莓浏览器窗口 JavaScript
- 关闭窗口 Javascript
- 清除窗口Javascript幻灯片
- 弹出窗口JavaScript的站点地图生成器
- 根据弹出窗口javascript的返回值更改asp.net面板的可见性
- 将var添加到新窗口Javascript中
- 如何在引导模式弹出窗口(javascript,jquery)上运行函数
- 仅包含某些数组值的单个弹出窗口.JavaScript
- 将值传递给弹出窗口 [JavaScript]
- 在链接后控制父窗口(JavaScript)
- 将数据发送到单独的窗口javascript
- 正在访问窗口.Javascript 中的应用程序函数
- 将变量从父窗口Javascript函数传递到弹出窗口分区
- 在内容进入打印机之前关闭窗口(JavaScript)
- 窗口.JavaScript中的innerWidth
- 是否可以从子窗口关闭父窗口(Javascript)
- 窗口.javascript中的Innerheight减去数字
- 如果我重写窗口.javascript中的onerror应该返回true还是false
- 计数值后关闭窗口javascript
- 如何在缩略图图像的翻转上显示弹出窗口?Javascript、CSS