Vojkovic

iframe - parent page

Jul 1st, 2025
20
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <script>
  2.   (function() {
  3.     // Universal Analytics tracking ID whose _ga cookie to use.
  4.     // If using GA4, you can leave this setting untouched.
  5.     var trackingId = 'UA-XXXXX-Y';
  6.    
  7.     // Maximum time in milliseconds to wait for GA tracker to load.
  8.     // Again, irrelevant for GA4.
  9.     var maxGATime = 2000;
  10.    
  11.     // Set to the origin ("https://www.domain.com") of the iframe you want to communicate with
  12.     var childOrigin = 'https://www2.apptoto.com';
  13.    
  14.     // Don't touch anything that follows
  15.     var pollInterval = 200;
  16.    
  17.     var postCallback = function(event) {
  18.       if (event.origin !== childOrigin) return;
  19.       if (event.data !== 'childReady' && !event.data.event) return;
  20.      
  21.       if (event.data === 'childReady') {
  22.         // Send event that parent is ready
  23.         event.source.postMessage('parentReady', event.origin);
  24.  
  25.         var pollCallback = function() {
  26.           // Stop polling if maxTime reached
  27.           maxGATime -= pollInterval;
  28.           if (maxGATime <= 0) window.clearInterval(poll);
  29.          
  30.           // Only proceed if GA loaded and tracker accessible
  31.           var ga = window[window['GoogleAnalyticsObject']];
  32.           if (ga && ga.getAll) {
  33.             // Get tracker that matches the Tracking ID you provided
  34.             var tracker = ga.getAll().filter(function(t) {
  35.               return t.get('trackingId') === trackingId;
  36.             }).shift();
  37.            
  38.             // Send message back to frame with Client ID
  39.             if (tracker) {
  40.               event.source.postMessage({
  41.                 event: 'clientId',
  42.                 clientId: tracker.get('clientId')
  43.               }, event.origin);
  44.             }
  45.             // Stop polling if not already done so
  46.             window.clearInterval(poll);
  47.           }
  48.         };
  49.        
  50.         // Start polling for Google Analytics tracker
  51.         var poll = window.setInterval(pollCallback, pollInterval)
  52.       }
  53.      
  54.       // Push dataLayer message from iframe to dataLayer of parent
  55.       if (event.data.event) {
  56.         window.dataLayer.push(event.data);
  57.       }
  58.     };
  59.    
  60.     // Start listening for messages from child frame
  61.     window.addEventListener('message', postCallback);
  62.   })();
  63. </script>
Add Comment
Please, Sign In to add comment