Javascript 将cookie数据从父级发送到iframe

Javascript 将cookie数据从父级发送到iframe,javascript,cookies,google-tag-manager,setcookie,Javascript,Cookies,Google Tag Manager,Setcookie,我正在尝试将网站上捕获的cookie中的数据发送到iframe中 我有两个独立的Google Tag Manager帐户-一个用于iframe,一个用于我的网站 如何将cookie数据发送到iframe中 var form='1https://test/l/xxxxxx/xxxx-xx-xx/xxxx'; var params=window.location.search; var thisScript=document.scripts[document.scripts.length-1];

我正在尝试将网站上捕获的cookie中的数据发送到iframe中

我有两个独立的Google Tag Manager帐户-一个用于iframe,一个用于我的网站

如何将cookie数据发送到iframe中


var form='1https://test/l/xxxxxx/xxxx-xx-xx/xxxx';
var params=window.location.search;
var thisScript=document.scripts[document.scripts.length-1];
var iframe=document.createElement('iframe');
setAttribute('src',form+params);
setAttribute('width','100%');
iframe.setAttribute('height',500);
setAttribute('type','text/html');
iframe.setAttribute('frameborder',0);
setAttribute('allowTransparency','true');
iframe.style.border='0';
thisScript.parentElement.replaceChild(iframe,thisScript);
window.parent.getCookie('gclid');

只需在父窗口中查找带有名称的iframe并发送消息,就可以发布消息:

<iframe src="http://example.com" name="iframe">

<script>
    let win = window.frames.iframe;
    win.postMessage("message", "*");
</script>

例如。

您还可以访问iframe中的父窗口
window.parent

插图 在主窗口中,假设您有一个名为id的cookie,并且您已经实现了一个名为getCookie的实用函数来获取cookie值

主窗口 Iframe加载的页面中出现了一些错误
您可以查看跨窗口消息传递,将cookie从父站点发送到iframe。唯一可行的方法是使用
window.postMessage()
iframe窗口发送消息。你这是什么意思?对不起,我对这一切都很陌生,所以我的理解非常有限。我试着按照你说的做,但似乎没有奏效。我在上面编辑了我的原始帖子,加入了iframe代码。所以我不是100%确定我在这里做什么。这个例子给我留下了几个问题。我不确定该在“消息”中放什么,特别是如果我有9个曲奇,我正试图传递。好的。我不完全明白,如果您控制了父窗口,您需要将9个cookie传递给iframe窗口的原因是什么。没关系。我只需要递一块饼干。我真的不知道我在做什么。我试着在上面写代码,但是cookie没有进入我的iframe。我不知道你到底想实现什么,但这种方法是用于在窗口之间传递数据,以便你可以在父窗口内读取cookie并将数据传递给iframe。我正在尝试将ReferringURL cookie传递给iframe,并将其传递到我表单上的隐藏表单字段中。
window.addEventListener("message", function(event) {
  // your logic for messages
});
getCookie('id')  //for instance returns abc 

window.parent.getCookie('id')  //returns same abc  from above