• Audience Targeting

    Table of contents

    In short

    With audience targeting, you define which target group should be part of your experiment. For example, you can target only users who visit your website from a specific source. You can also target only mobile, tabllet or desktop traffic, for example. The use cases are almost limitless.

    Audience targeting can be performed with the help of JavaScript. For the individual use cases, we also provide you with corresponding templates here, with which you can implement your preferred targeting.

    If you want to start an experiment without audience targeting, you can leave the default value (return true;) in the field

    Step-by-Step Tutorial
    Audience Targeting

    Use Cases

    Overview of exemplary Use Cases

    Ad Campaign

    Important Notice:
    Do you want to use two different use case examples together, but are unsure about how to do it? Do not hesitate to contact us: https://varify.io/kontakt/

    Target only users who come to your site from a specific ad campaign.

    Code Example - UTM Source = ad_campaign

    				
    					const AD_CAMPAIGN = 'YOUR_AD_CAMPAIGN_HERE';
    
    return new URL(window.location).searchParams.get('utm_source') === AD_CAMPAIGN;
    
    				
    			

    Browser

    Important Notice:
    Do you want to use two different use case examples together, but are unsure about how to do it? Do not hesitate to contact us: https://varify.io/kontakt/

    Target only users who use a specific browser.

    Code example - Google Chrome

    				
    					return /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
    				
    			

    Device targeting (desktop, tablet, mobile)

    Important Notice:
    Do you want to use two different use case examples together, but are unsure about how to do it? Do not hesitate to contact us: https://varify.io/kontakt/

    For example, with the following code you can target only mobile users.

    Code Example - Targeting: Mobile Devices Only

    				
    					return window.innerWidth < 768;
    				
    			

    Code example - Targeting: Tablet devices only

    				
    					return window.innerWidth > 768 && window.innerWidth < 1024;
    				
    			

    Code example - Targeting: Desktop devices only

    				
    					return window.innerWidth > 1023;
    				
    			

    Important Notice:
    Do you want to use two different use case examples together, but are unsure about how to do it? Do not hesitate to contact us: https://varify.io/kontakt/

    Check if your users have a cookie entry and define only these users as test participants. 

    Code example - cookie is set

    				
    					const COOKIE_KEY = 'YOUR_COOKIE_KEY_HERE';
    const COOKIE_VALUE = 'YOUR_COOKIE_VALUE_HERE';
    
    const cookies = document.cookie.split(/\s*;\s*/)
      .map(cookie => cookie.split('='));
    
    return Object.fromEntries(cookies)[COOKIE_KEY] === COOKIE_VALUE;
    				
    			

    Session & Local Storage Targeting

    Important Notice:
    Do you want to use two different use case examples together, but are unsure about how to do it? Do not hesitate to contact us: https://varify.io/kontakt/

    Check if your users have a corresponding entry in the Session or Local Storage and define only these users as test participants. 

    Code example - Session Storage value is set

    				
    					const STORAGE_KEY = 'YOUR_SESSION_STORAGE_KEY';
    const STORAGE_VALUE = 'YOUR_SESSION_STORAGE_VALUE';
    
    return sessionStorage.get(STORAGE_KEY) === STORAGE_VALUE;
    				
    			

    Code example - Local Storage value is set

    				
    					const STORAGE_KEY = 'YOUR_LOCAL_STORAGE_KEY';
    const STORAGE_VALUE = 'YOUR_LOCAL_STORAGE_VALUE';
    
    return localStorage.get(STORAGE_KEY) === STORAGE_VALUE;
    				
    			

    Event Targeting

    Important Notice:
    Do you want to use two different use case examples together, but are unsure about how to do it? Do not hesitate to contact us: https://varify.io/kontakt/

    Polling and asynchronous JavaScript

    Check for asynchronous properties by using promises. In the example here, we are waiting for an element that does not yet exist on the page. Once the element exists, the targeting applies.

    Code example - Target only when an element is on the page

    				
    					return new Promise(resolve => {
        window.varify.helpers.waitFor('.class', () => resolve(true))
    })
    				
    			

    Code example - Handling polling with Promises

    This starts the query for 2 seconds, just as would be the case if false (without promies) were returned.

    				
    					return new Promise((resolve, reject) => {
        resolve(false)
    });
    				
    			

    Does not start a query, or ends an existing query loop and skips this experiment

    				
    					return new Promise((resolve, reject) => {
        reject()
    });
    				
    			

    Language and region

    Important Notice:
    Do you want to use two different use case examples together, but are unsure about how to do it? Do not hesitate to contact us: https://varify.io/kontakt/

    Only target users who have set a defined default language in their browser. Here you can find all supported ISO language codes.

    Code example - English language

    				
    					return navigator.language.startsWith('en');
    				
    			
    Only target users who are in a specific country. Here you can find all supported ISO County Codes.

    Code example - Language English & Region USA

    				
    					return navigator.language.startsWith('en-US');
    				
    			

    New / Returning Visitors

    Important Notice:
    Do you want to use two different use case examples together, but are unsure about how to do it? Do not hesitate to contact us: https://varify.io/kontakt/

    Target only users who have visited your site before or have been in a previous test. Alternatively, you can also target users who have not yet been on your site or test participants.

    Code example - retargeting test participant from specific experiment - variant seen

    				
    					const EXPERIMENT_ID = 'YOUR_EXPERIMENT_ID';
    
    const storageValue = localStorage.getItem(`varify-experiment-${EXPERIMENT_ID}`);
    return JSON.parse(storageValue)?.variationId === Number(EXPERIMENT_ID);
    				
    			

    Code example - Target only new users

    				
    					const EXPERIMENT_ID = 'YOUR_EXPERIMENT_ID';
    
    return !localStorage.getItem(`varify-experiment-${EXPERIMENT_ID}`);
    				
    			

    Platform / OS

    Important Notice:
    Do you want to use two different use case examples together, but are unsure about how to do it? Do not hesitate to contact us: https://varify.io/kontakt/

    Target only users who use a specific operating system.

    Code example - Android

    				
    					return /Android/i.test(navigator.userAgent);
    				
    			

    Query parameters

    Important Notice:
    Do you want to use two different use case examples together, but are unsure about how to do it? Do not hesitate to contact us: https://varify.io/kontakt/

    Target only users who visit your website using a specific query parameter. You can use this use case, for example, to test your variant. In this example, the variant is called with the URL query parameter ?varify-testing=true.

    Code example - ?varify-testing=true

    				
    					const QUERY_PARAM_KEY = 'varify-testing'
    const QUERY_PARAM_VALUE = 'true'
    
    const params = new URLSearchParams(window.location.search);
    return params.get(QUERY_PARAM_KEY) === QUERY_PARAM_VALUE;
    				
    			

    Referrer URL

    Important Notice:
    Do you want to use two different use case examples together, but are unsure about how to do it? Do not hesitate to contact us: https://varify.io/kontakt/

    Target only users who visited your initial website from a specific referrer (source).

    Code example - Referrer = https://www.google.com/

    				
    					const REFERRER_URL = 'https://www.google.com/'
    
    return document.referrer === REFERRER_URL;
    				
    			

    Traffic exclusion for experiments

    Important Notice:
    Do you want to use two different use case examples together, but are unsure about how to do it? Do not hesitate to contact us: https://varify.io/kontakt/

    If you don't want all visitors of the targeted page to participate in the experiment, then you can assign only a part of the visitors to an experiment using the following code. For example, you want only 30% of the page visitors to become experiment participants.

    Important: Enter the corresponding Experiment_ID of the experiment concerned and replace 1234 (line 1).

    Important: If you want to adjust the proportion of participants, change the number 10 (10%) in this code to the desired proportion, e.g. 30 (30%). (line 11)

    A visitor is now either assigned to or excluded from the experiment based on the set probability. If they are assigned, the value "true" is saved in the local storage and "false" if they are excluded. Audience Targeting only plays the experiment if the value "true" is in the Local Storage and the user is therefore identified as an experiment participant.

    				
    					const EXPERIMENT_ID = 1234;
    const STORAGE_KEY_PREFIX = 'varify-experiment-';
    const specificStorageKey = STORAGE_KEY_PREFIX + EXPERIMENT_ID;
    const PARTICIPANT_KEY = 'experiment-participant';
    
    // Retrieve the existing isInAudience value if it exists
    const storedIsInAudience = localStorage.getItem(PARTICIPANT_KEY);
    
    // If the isInAudience value is not set, determine it and store it
    if (storedIsInAudience === null) {
        const isInAudience = Math.floor(Math.random() * 100) < 10;
        console.log("99");
        localStorage.setItem(PARTICIPANT_KEY, isInAudience ? 'true' : 'false');
    } 
    
    // Check if the specific experiment ID entry exists in localStorage
    const isExperimentStored = localStorage.getItem(specificStorageKey) !== null;
    
    if (!isExperimentStored) {
        if (localStorage.getItem(PARTICIPANT_KEY) === 'true') {
    
            // Set the PARTICIPANT_KEY to true once the specificStorageKey is set
            localStorage.setItem(PARTICIPANT_KEY, 'true');
    
            // Return true
            console.log("true");
            return true;
        } else {
            // If the participant is not in the audience, return false
            console.log("false");
            return false;
        }
    } else {
        // If the specific experiment ID entry exists, return true
        console.log("true");
        return true;
    }
    				
    			

    You can check whether it works as desired via the browser's developer console. To do this, go to your local storage in the "Application" tab. Once you have started the experiment and are on the page where the experiment is running, you should see the following in the local storage, depending on whether you are in the participant group or not:

    Participants:

    • Key: experiment-participant Value: true
    • The experiment should also be visible: Key: varify-experiment-1234 Value: {"variationId":1234/Original, "timestamp":12456789}

    Not a participant:

    • Key: experiment-participant Value: false
    • Values for the experiment should not be found in Local Storage

    If you want to test again whether it works, for example to get into the group of participants, you must manually delete the entries in the Local Storage. To do this, click on the icon with the crossed-out circle to the right of the filter to delete all entries in the Local Storage and then reload the page.

    Time or day of the visit

    Important Notice:
    Do you want to use two different use case examples together, but are unsure about how to do it? Do not hesitate to contact us: https://varify.io/kontakt/

    Target only users who are on your site from a certain time or, for example, on a certain day of the week. For example, you can use the following example if you want your experiment to start on a certain day at a certain time.

    Code Example - Scheduling Test Start

    				
    					const currentDate = new Date();
        const specificDate = new Date('2024-01-01T10:00:00'); // ISO format for 10:00 on 01.01.2024
    
        return currentDate > specificDate;
    				
    			

    Traffic source

    Important Notice:
    Do you want to use two different use case examples together, but are unsure about how to do it? Do not hesitate to contact us: https://varify.io/kontakt/

    Target only users who come from a specific traffic source, such as newsletters.

    Code Example - Newsletter

    				
    					const QUERY_PARAM_KEY = 'source'
    const QUERY_PARAM_VALUE = 'newsletter'
    
    const params = new URLSearchParams(window.location.search);
    return params.get(QUERY_PARAM_KEY) === QUERY_PARAM_VALUE;
    				
    			

    Show experiment or campaign booster only once

    Important Notice:
    Do you want to use two different use case examples together, but are unsure about how to do it? Do not hesitate to contact us: https://varify.io/kontakt/

    If you want to prevent users from seeing an experiment or a campaign booster again after they have already seen it, you can easily implement this with the help of audience targeting.

    To do this, we use session storage for a single playout per session or local storage for a single playout across multiple sessions. The first time the experiment is played out, a corresponding entry is created in the storage and we then check whether this entry already exists on the next attempt. If this is the case, the experiment is not displayed again.

    Session Storage - one-time playout per session

    Add this code to the JavaScript of your variant using the editor. It is best to change the experiment ID 1234 at "experiment-seen-1234" to the experiment ID of your experiment.

    				
    					window.varify.helpers.onDomLoaded(() => {
      sessionStorage.setItem('experiment-seen-1234', 'true');
    });
    				
    			

    Then add this code to the audience targeting of the experiment. This checks whether the session storage entry already exists and executes or blocks the experiment accordingly.

    				
    					// Check if 'experiment-seen-1234' is not in session storage
    return sessionStorage.getItem('experiment-seen-4374') === null;
    				
    			

    If the entry experiment-seen-1234 with the value true exists in the session storage, the experiment is no longer played.

    Local Storage - One-time playout over several sessions

    Add this code to the JavaScript of your variant using the editor. It is best to change the experiment ID 1234 at "experiment-seen-1234" to the experiment ID of your experiment.

    				
    					window.varify.helpers.onDomLoaded(() => {
      localStorage.setItem('experiment-seen-1234', 'true');
    });
    				
    			

    Then add this code to the audience targeting of the experiment. This checks whether the Local Storage entry already exists and executes or blocks the experiment accordingly.

    				
    					// Check if 'experiment-seen-1234' is not in local storage
    return localStorage.getItem('experiment-seen-4374') === null;
    				
    			

    If the entry experiment-seen-1234 with the value true exists in the session storage, the experiment is no longer played.

    JavaScript variable with specific value

    Important Notice:
    Do you want to use two different use case examples together, but are unsure about how to do it? Do not hesitate to contact us: https://varify.io/kontakt/

    You can use the following code in Audience Targeting to specify that an experiment is only played if a JavaScript variable has a certain value. 

    Important: Replace "myVariable" with the corresponding variable name and "myValue" with the corresponding variable value. (Also note whether the value is a string, integer, Boolean, etc. and adjust the check if necessary).

    				
    					return window.myVariable === 'myValue';
    				
    			

    Mutual exclusion of experiments (traffic distribution configurable)

    Important Notice:
    Do you want to use two different use case examples together, but are unsure about how to do it? Do not hesitate to contact us: https://varify.io/kontakt/

    In some cases, it is necessary to exclude participants who are assigned to a particular experiment from another experiment. This is particularly relevant when two experiments are conducted on the same pages of a website. The aim here is to prevent the results from being distorted by the mutual influence of the experiments. It must therefore be ensured that users participating in one of the experiments cannot view the other.

    To achieve this, certain codes can be inserted into the audience targeting of each experiment.

    The codes provided here assign users to one of the two experiments with a probability of 50 percent and at the same time exclude the other experiment for the user. This distribution can be adjusted, as explained below.

    The following code was to be implemented in audience targeting in one of the experiments:

    				
    					const PARTICIPANT_KEY = 'experiment-participant';
    // Retrieve the existing isInAudience value if it exists
    const storedIsInAudience = localStorage.getItem(PARTICIPANT_KEY);
    console.log('storedIsInAudience:', storedIsInAudience);
    if (storedIsInAudience === 'false') {
    return true;
    } else {
    return false;
    }
    				
    			

    For the second experiment, it is necessary to insert the following code:

    It is important to note that the example experiment ID 1234 in the first line of the code must be replaced by the actual ID of the experiment in which this code is used.

    It should also be noted that this code is set by default to a 50:50 distribution of users between the two experiments. If a different distribution is desired, this can be done by adjusting the value 50 in line 9 of the code (const isInAudience = Math.floor(Math.random() * 100) < 50;). For example, if you change 50 to 75, 75% of the users are assigned to the current experiment and only 25% to the other experiment.

    				
    					const EXPERIMENT_ID = 1234;
    const STORAGE_KEY_PREFIX = 'varify-experiment-';
    const specificStorageKey = STORAGE_KEY_PREFIX + EXPERIMENT_ID;
    const PARTICIPANT_KEY = 'experiment-participant';
    // Retrieve the existing isInAudience value if it exists
    const storedIsInAudience = localStorage.getItem(PARTICIPANT_KEY);
    // If the isInAudience value is not set, determine it and store it
    if (storedIsInAudience === null) {
    const isInAudience = Math.floor(Math.random() * 100) < 50;
    console.log("99");
    localStorage.setItem(PARTICIPANT_KEY, isInAudience ? 'true' : 'false');
    }
    // Check if the specific experiment ID entry exists in localStorage
    const isExperimentStored = localStorage.getItem(specificStorageKey) !== null;
    if (!isExperimentStored) {
    if (localStorage.getItem(PARTICIPANT_KEY) === 'true') {
    // Set the PARTICIPANT_KEY to true once the specificStorageKey is set
    localStorage.setItem(PARTICIPANT_KEY, 'true');
    // Return true
    console.log("true");
    return true;
    } else {
    // If the participant is not in the audience, return false
    console.log("false");
    return false;
    }
    } else {
    // If the specific experiment ID entry exists, return true
    console.log("true");
    return true;
    }
    				
    			

    Targeting the original variant participants of an experiment in a second experiment

    Important Notice:
    Do you want to use two different use case examples together, but are unsure about how to do it? Do not hesitate to contact us: https://varify.io/kontakt/

    To ensure that a second experiment is only shown to those users who have previously seen the original version of a first experiment, this can be precisely controlled in audience targeting using the following code. Users who have already seen the variant of the first experiment will not be shown the second experiment.

    Important: The experiment ID "1234" in line 1 must be replaced by the corresponding experiment ID of the first experiment for which only the participants of the original variant should see the second experiment.

    				
    					const EXPERIMENT_ID = 1234;
    const STORAGE_KEY_PREFIX = 'varify-experiment-';
    const specificStorageKey = STORAGE_KEY_PREFIX + EXPERIMENT_ID;
    
    // Retrieve the value for specificStorageKey
    const storedValue = localStorage.getItem(specificStorageKey);
    
    if (storedValue) {
        // Parse the stored JSON string
        const storedData = JSON.parse(storedValue);
    
        // Check if variationId is null
        if (storedData.variationId === null) {
            //console.log('True - variationId is null');
            return true;
        }
    }
    
    // Default return if condition is not met
    //console.log('False - variationId is not null or specificStorageKey does not exist');
    return false;
    				
    			

    It should also be mentioned that by adapting the code, participants of the original variant can also be excluded and the variant participants included.

    CSS class selector

    Important Notice:
    Do you want to use two different use case examples together, but are unsure about how to do it? Do not hesitate to contact us: https://varify.io/kontakt/

    Do you only want to play or block an experiment if an element with a specific CSS class is present on the page? The following code examples will help you.

    Swap CSS_CLASS_NAME simply by the corresponding class name to which you want to target the experiment.

    Show experiment if CSS class exists

    				
    					//Include experiement when CSS class exists on page
    const className = 'CSS_CLASS_NAME';
    return (document.querySelector('.' + className) !== null);
    				
    			

    Do not display experiment if CSS class exists

    				
    					//Exclude experiement when CSS class exists on page
    const className = 'CSS_CLASS_NAME';
    return !(document.querySelector('.' + className) !== null);
    				
    			

    Combine application examples with each other

    You can easily combine different application scenarios with each other. To do this, you first save the return values of the application examples in your own variables. You can then link these variables in a general return value with a logical operator (AND, OR), which then ensures that audience targeting shows or blocks the experiment.

    The question here is whether audience targeting conditions of the linked use cases must be fulfilled at the same time (AND), or whether it is sufficient for only one condition to be fulfilled (OR). You will find examples of this below.

    Important Notice:
    Do you want to use two different use case examples together, but are unsure about how to do it? Do not hesitate to contact us: https://varify.io/kontakt/

    All conditions should be fulfilled (AND)

    A classic use case for this example would be that an experiment should only be played out for mobile users. However, you also want to carry out the QA via the session storage.

    The experiment should only be played if the QA session storage exists AND the display width corresponds to a mobile device.

    				
    					//Audience Targeting for QA with Session Storage
    const STORAGE_KEY = 'varify-test';
    const STORAGE_VALUE = 'true';
    let isValueMatched = sessionStorage.getItem(STORAGE_KEY) === STORAGE_VALUE;
    
    //Audience Targeting for mobile users
    let mobileWidth = window.innerWidth < 768;
    
    // //Combined with AND operator. Return true if both variables are true.
    return isValueMatched && mobileWidth;
    				
    			
    • In the application example for QA with session storage, the return creates a variable (let isValueMatched =)
    • Likewise for the return of the mobile audience targeting code (let mobileWidth =)
    • You can define the variable names yourself, but they must be different
    • A new line with "return" has been added, in which the two variables with a UND condition are linked -> &&

    The experiment is only shown if both variables have the value true own.

    One condition must be fulfilled (OR)

    Sometimes, however, you also want to combine audience targeting scenarios where not all conditions have to be met. In this case, the variables are linked with an OR operator.

    An example would be if you only want to play an experiment to visitors of a certain campaign or referrer. To do this, the two scenarios must be linked with an OR.

    				
    					//Audience Targeting for Specific Campaign
    const AD_CAMPAIGN = 'YOUR_AD_CAMPAIGN_HERE';
    let specificCampaign = new URL(window.location).searchParams.get('utm_source') === AD_CAMPAIGN;
    
    
    //Audience Targeting for Specific Referrer
    const REFERRER_URL = 'https://www.google.com/'
    let specificReferrer = document.referrer === REFERRER_URL;
    
    //Combined with OR operator
    return specificCampaign || specificCampaign;
    
    				
    			
    • From the return of the campaign scenario, a variable (let specificCampaign =) created
    • From the return of the referrer scenario, the variable (let specificReferrer =) created
    • A new return query was created from both variables with a OR Operator || created

    If at least one of the two variables contains the value true, the experiment is played.

    Technical explanation

    Any JavaScript can be defined in the Audience Targeting field, which will be executed to determine if the targeting applies. As long as the return value falsy is executed, the JavaScript is reloaded after each execution. 100ms executed until 2000ms are reached. After that, it is canceled and the user does not fall in the audience targeting. It can be checked for asynchronous properties by using a Promise returns.

    If an experiment is to be played without audience targeting, you must leave the default value (return true;) as shown in the screenshot.

  • First steps

    Tracking & Evaluation

    Targeting

    Advanced

    Function overview