Tracking search queries within an iframe

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:

  1. search: [term1]
  2. search: [term1, term2]
  3. 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>

Answer №1

I am seeking a way to retain search terms within the same browsing session

Due to the page scope of dataLayer, it is cleared upon reloading the page, making it unsuitable for this purpose. To achieve persistence, one must implement additional measures, such as:

  • Session cookies
  • Session Storage
  • Local Storage which should be cleared at the beginning of each session
  • Web Storage API offering an abstraction over session and local storage
  • IndexDB serving as a client-side database that can be cleared at the start of each session

Considering variations in browser support and complexity of coding, utilizing libraries that simplify or abstract these storage options may lead to a more efficient implementation with reduced code:

An illustrative example demonstrating how to persist GTM data layer can be found here:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

If any modifications are made to the database, the script will re-execute

Is there a way to make my script only automatically execute again if the database undergoes changes? Currently, it runs continuously based on the variable timer and setInterval, updating the output of the textboxes whenever I alter the database value witho ...

Prevent Button Click in ASP.NET After Validating Regular Expression in Textbox

How can I ensure that the asp button is disabled only after the user submits the form with the correct regular expression? Below is the form code: <asp:TextBox ID="TextBox2" runat="server" placeholder="Email" class="form-control" type="email" Font-Siz ...

Adding up table rows created using AngularJS with the help of jQuery

It might seem a bit strange, but I have a scenario where I need to use jQuery to sum all rows in a table. In this particular table, I'm utilizing angularjs to display a list of users, but I want to calculate the total sum of all rows using jQuery. Th ...

Combining HTML, CSS, and Javascript to create a single JS file

I am designing a form component from scratch, free of any frameworks. My aim is to provide clients with a simple solution by delivering the component through a single JavaScript file. All they will need to do is create a div element with a specific id, and ...

Using PHP to validate a read-only textbox

I am trying to implement validation on a Datepicker that is set to readonly, but I am facing issues with my current code. Can someone please assist me? Below is the JavaScript code used for error trapping: <script type="text/javascript"> $(func ...

The mystery of the missing body in a Node.js post request

I have developed an API in Node.js and I am facing an issue with the POST method where the body is coming as undefined. How can I extract the value passed using fetch? Node.js Code------------------------------------------ const express=require('expr ...

The resetting of checkboxes in the Boostrap form validation form is not functioning properly

I am currently working on form validation using Bootstrap. Although resetForm(); is functioning properly, I am facing an issue with resetting the checkbox upon form submission. I have attempted methods like $('.form-check-input').val();, $(' ...

Problems encountered when attempting to create a link between two nodes on a force-directed graph using a mouse click

I'm currently working on creating an interactive graph where users can click on two nodes to establish a link between them (which can be removed later). My approach was inspired by Mike Bostock's example at: https://bl.ocks.org/mbostock/1095795 ...

Error: 'error' is undefined

Error Alert: The code is encountering a ReferenceError, indicating that 'error' is not defined in the following snippet: app.post('/register', function(req, res) { var hash = bcrypt.hashSync(req.body.password, bcrypt.genSaltSync(10)) ...

Discover how to generate nested dynamic routes in NextJS by linking to MongoDB data using the getStaticProps and getStaticPaths functions

Currently, I am facing a challenge with implementing dynamic paths in NextJS and I'm struggling to find a solution. Let me provide some context for better understanding. I am working on developing an ecommerce application using NextJS, and the folder ...

React.js - state variable becomes undefined upon uploading app to Amplify

I am encountering a perplexing error and am struggling to determine the root cause. To provide a brief overview, I have a dialog containing a jsonschema form along with an image that is uploaded to an input and saved in b64 format within a state variable c ...

Issue - The 'defaultValue' is failing to load the state value, and the 'value' is not being updated when changed

My current setup involves an input field in my MovieInput.tsx file: <input id="inputMovieTitle" type="text" onChange={ e => titleHandleChange(e) } value={ getTitle() }> </input> This is how the titleHandleChange function ...

Implementing embedded divs within other divs for all elements sharing the same class

How can I insert or wrap my second div into a new div container with the same class name? I attempted to do this but it didn't work. Can you help me identify what is missing? <div class="section" id="section1"> <div id="myDIV"> --> I ...

Custom script for Greasemonkey that modifies a parameter within the URL

While using Google Analytics, I have noticed that some pages display a variable in the URL with a default value of 10. The format usually looks like this: ...&trows=10&... Is there a method to alter this to trows=100 in order to change th ...

Utilizing cache for the onclick function on a multilingual website

I am currently working on developing a multi-language index page with a language change area. When I click on each language text, the language changes as expected. However, although the language changes when I click on my language links (AZ, EN, RU), it r ...

What is the best way to split a single column into two using blocks?

I am working with a container that currently has all its blocks lined up in a column. I need to divide them into two columns, with 5 blocks in each. Unfortunately, the plugin I am using generates the code for me and does not allow me to insert my own div e ...

Iterate through an array and append individual elements to a fresh array - ensuring only a single item is present in the new

I have been working on a project where I need to call a backend API and retrieve a JSON response. I have come across various solutions, but none seem to address my specific problem. The JSON data returned from the API is structured like this: [ { ...

How to eliminate a variable-named option_for_select item using JavaScript

Looking for help with this code snippet: function remove_name(i) { var phase_name = document.getElementById('phase_rates_phase_name' + '-c' + i).value; $("select#payer_contract option[value='Phase 3']").remove(); } T ...

What is the correct way to integrate HTML input elements into JavaScript code without encountering a type error?

I'm having some trouble with this code snippet. It's my first time coding and I can't figure out what's causing the issue. The error message I'm receiving is: "TypeError: Cannot read properties of null (reading 'value&ap ...

Is there a hover function in jQuery that works with both mouseenter and mouseout events?

I've been facing a slight issue with a list of items using the <li> element. I have a plugin running that dynamically adds a data-tag ID to the data-* attribute of these items. As a result, all items are dynamically added and another function I ...