Trigger experiment / personalization changes when an element on the page is modified

Issue

There can be the case that we need to trigger the experiment or personalization changes when an element on the page is modified, instead of displaying the changes when the page loads. This is very relevant when on Single Page Applications (SPAs). However, with the current default is not possible.

Solution

Here is a solution in which with javascript code we will be able to monitor the desired element and trigger the change when this happens.

The solution is based on the MutationObserver javascript interface.

Please use the following code for it:

Insert the following code in the Global Project Javascript section and set the targetNode selector to the one corresponding to the element you are going to monitor. In this case the selector is 'some-id'.


// Select the node that will be observed for mutations
const targetNode = document.getElementById('some-id');

// Options for the observer (which mutations to observe)
const config = { attributes: true, childList: true, subtree: true };

// Callback function to execute when mutations are observed
const callback = function(mutationsList, observer) {
    // Use traditional 'for loops' for IE 11
    for(let mutation of mutationsList) {
    // Use the commmented lines if needed, otherwise remove
        // if (mutation.type === 'childList') {
        //     console.log('A child node has been added or removed.');
        // }
        // else if (mutation.type === 'attributes') {
        //     console.log('The ' + mutation.attributeName + ' attribute was modified.');
        // }
        // Next line sets the variable so the experiment/personalization
        // condition returns true, and triggers the Convert polling
        run_experiment = true;
        window._conv_q = _conv_q || []; 
 				window._conv_q.push(["run","true"]);
    }
};

// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

// Later, you can stop observing
observer.disconnect();

Add a Site Area condition to your experiment / personalization to the following:

run_experiment == true

blobid1.png

Please ask our support channels if you have any questions about configuring this. 

Need assistance? Start a conversation with our Support Team.
CONVERT MORE

Reliably Convert More Site Visitors, Even If Everything Else is Changing in Your Business.

START 15-DAY FREE TRIAL
✓ No Credit Card  ✓ Easy Set-Up  ✓ Access All Features

Comments