Saving Riddle events to local storage



Source code to capture Riddle events and store them in local storage

Important:

On the 'Publish' -> 'Tracking' step in the Riddle creator, you need to enable 'Custom tracking'.

Then also select 'Custom even configuration' and enable 'Send form data (User Inputs)'.

Then add the event listener script below into the custom tracking box in Riddle to replace our default script, which merely logs all events to the browser console.

(riddleEvent) => {
  // Create a message object with the event data
  const message = {
    type: "riddleEvent",
    data: riddleEvent
  };
  
  // Send the message to the parent page
  window.parent.postMessage(message, "*");
};

The screenshot below shows where to add this code to your Riddle:

Add your own tracking script to a Riddle

The code to save Riddle events to local storage

Place the code below on the page where you embedded your Riddle.

To use the data on a custom result page you need to create a second page, which you will use as an external result page in your Riddle. If you click through the Riddle on this page, it will take you to a custom result page, where we display the code needed to read data from local storage.

<script>
// Clear local storage when page is loaded
window.onload = function() {
    localStorage.clear();
}
// Define a function to update the event data
function updateEventData(eventData) {
  // Check if the answer property contains multiple values
  if (typeof eventData.answer === 'string' && eventData.answer.includes(':::')) {
    // Split the string into an array of individual answers
    const answers = eventData.answer.split(':::').map((item) => {
      const parts = item.split('::');
      return {
        index: parts[0],
        namefield: parts[1],
        value: parts[2],
      };
    });

    // Replace the answer property with the array of answers
    eventData.answer = answers;
  }

  // Get the existing events from local storage if any
  let events = JSON.parse(localStorage.getItem('events')) || [];

  // Add the new event to the start of the events array
  events.unshift(eventData);

  // Store the updated events array in local storage
  localStorage.setItem('events', JSON.stringify(events));
}

window.addEventListener("message", (event) => {
  // Check that the message is from the iframe

  // Check that the message is a riddleEvent message
  if (event.data.type !== "riddleEvent") {
    return;
  }

  // Log the event data received from the iframe
  console.log("Riddle Event (from iframe): ", event.data.data);

  // Update the event data
  updateEventData(event.data.data);
});
</script>
Download