At www.mywebsite.com
, there is an embedded iframe from www.search.mywebsite.com
. Both the parent frame and the iframe contain a GTM container that I can access.
Whenever a search is conducted within the iframe, the iframe's GTM container sends a message to the parent frame containing the data. This message is detected by an eventlistener
in the parent frame, then parsed and added to the DL (datalayer
) of the parent frame.
However, if the user refines the search term, a new message is sent. I am looking for a way to store these search terms from the same session in an Array
, which will later be pushed to the datalayer
so I can track the refinements made by the user during the session.
For example:
- search:
[term1]
- search:
[term1, term2]
- search:
[term1, term2, term3]
Are there any suggestions on how this can be accomplished?
I have included an event listener on the parent frame that listens for an event named iframeSearchSubmit
.
event listener added to window upon initial 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>