0

On www.mypage.com i have an iframe with www.search.mypage.com. Both parent frame and iframe have a GTM container I have access to. When a search is made in the iframe, the iframe GTM container sends a message to the parent frame, with the data. This message is picked up by a eventlistener in the parent frame, parsed and pushed to the DL (datalayer of the parent frame).

But when the user refines the search term, a new message is send. I want to be able to store these search terms done in the same session, in an Array to be pushed to the datalayer, so I can see see the refinement done be the user of the session.

Example:

  1. search: [term1]
  2. search: [term1, term2]
  3. search: [term1, term2, term3]

Any suggestions on how this can be achieved? I have the following event listener attached to the parent frame, that listens for an event, iframeSearchSubmit.

event listener added to window on first page load

<script type="text/javascript">
    (function(window) {
    
        addEvent(window, 'message', function(message) {
          
          try{
            
           var data = JSON.parse(message.data);
           var dataLayer = window.dataLayer || (window.dataLayer = []);
          
          
           if (data.event) {
            
             dataLayer.push({
               'event': data.event,
               'postMessageData': data,
               'query': data.query
            });
          } 
            
         }catch(e){}
          
        });
        
        // Cross-browser event listener
        function addEvent(el, evt, fn) {
          if (el.addEventListener) {
            el.addEventListener(evt, fn);
          } else if (el.attachEvent) {
            el.attachEvent('on' + evt, function(evt) {
              fn.call(el, evt);
            });
          } else if (typeof el['on' + evt] === 'undefined' || el['on' + evt] === null) {
            el['on' + evt] = function(evt) {
              fn.call(el, evt);
            };
          }
        }
    
    })(window);
</script>
Aymen TAGHLISSIA
  • 1,675
  • 13
  • 30
Alubu
  • 11
  • 2

1 Answers1

0

I want to be able to store these search terms done in the same session

The dataLayer has a page scope, ie whenever the page is reloaded it gets cleared, so that won't work. Thus you need to add some form of persistence yourself, a few options:

Because browser support can vary and coding can be a bit heavy, you might want to look at libraries which wrap/abstract those storage options so you can write a more robust implementation with less code:

Here is an example showing how to persist GTM data layer:

https://www.simoahava.com/analytics/two-ways-to-persist-data-via-google-tag-manager/

Max
  • 12,794
  • 30
  • 90
  • 142