Avenues_Q
Avenues_Q

Reputation: 55

Send cookie data from parent to iframe

I am trying to send data from my cookies captured on my website into an iframe.

I have 2 separate Google Tag Manager accounts - one for the iframe and one for my website.

How do I send the cookie data into the iframe?

<noscript>
 <iframe src="https://test/l/xxxxxx/xxxx-xx-xx/xxxx" width="100%" height="500" type="text/html" frameborder="0" allowTransparency="true" style="border: 0"></iframe>
</noscript>

<script type="text/javascript">
 var form = 'https://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');

 iframe.setAttribute('src', form + params);
 iframe.setAttribute('width', '100%');
 iframe.setAttribute('height', 500);
 iframe.setAttribute('type', 'text/html');
 iframe.setAttribute('frameborder', 0);
 iframe.setAttribute('allowTransparency', 'true');
 iframe.style.border = '0';

 thisScript.parentElement.replaceChild(iframe, thisScript);
 window.parent.getCookie('gclid');
</script>

Upvotes: 1

Views: 8875

Answers (2)

Wakeel
Wakeel

Reputation: 5002

You could also access parent window window.parent within the iframe.

Illustration

In the main window, assuming you have a cookie called id and you have implemented a utility function called getCookie to get cookie value.

Main Window

getCookie('id')  //for instance returns abc 

Somewehre in the page loaded by Iframe

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

Upvotes: 2

svyat1s
svyat1s

Reputation: 943

It's definitely a work for post messages just in the parent window find your iframe with name and send a message:

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

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

And then in the iframe window you can subscribe to that messages

window.addEventListener("message", function(event) {
  // your logic for messages
});

Here is example.

Upvotes: 0

Related Questions