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
Visitors and behavior
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');
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.
In order to recognize users who have already visited your website, it is necessary to first create a separate experiment that is used exclusively to mark these users. In your actual experiment, you can then specifically include only those users who have or have not seen the previous experiment.
Insert the corresponding code snippet in the audience targeting of your experiment and enter the experiment ID of the separate experiment in the 'YOUR_EXPERIMENT_ID' field.
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}`);
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;
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()
});
Data layer entry
To target only users who have a certain parameter or a certain value in the data layer, you can navigate through the data layer. In the following example, only users who have previously viewed a specific product with ID 1111 or ID 2222 are targeted.
Code example - Data Layer Targeting
return dataLayer?.some(item => item?.ecommerce?.checkout?.products?.[0]?.id==='1111' || item?.ecommerce?.checkout?.products?.[0]?.id==='2222');
Technical and device targeting
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;
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);
IP address (beta)
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 only want to play or block an experiment when visitors have a certain IP address use.
Swap IP_ADRESS simply replace it with the corresponding IP address to which you want to target the experiment. Here you can determine your IP address.
Display experiment if an IP address is used
const IP_ADDRESS = '12.345.67.891'; //change ip adress for targeting
async function checkUserIp(matchIp) {
return fetch('https://api.ipify.org?format=json')
.then(response => response.json())
.then(data => data.ip == matchIp)
.catch(error => false);
}
return new Promise((resolve) => {
checkUserIp(IP_ADDRESS).then(isMatch => {
resolve(isMatch)
});
})
Show experiment if an IP address is not used
const IP_ADDRESS = '12.345.67.891'; //change ip adress to exclude for targeting
async function checkUserIp(matchIp) {
return fetch('https://api.ipify.org?format=json')
.then(response => response.json())
.then(data => data.ip !== matchIp)
.catch(error => false);
}
return new Promise((resolve) => {
checkUserIp(IP_ADDRESS).then(isMatch => {
resolve(isMatch)
});
})
Campaign and experiment management
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;
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.
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.
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 other experiments. This is particularly relevant when two or more experiments are conducted on the same pages of a website. This is to prevent the results from being distorted by mutual influence between the experiments.
In the following code you will find the two constants at the top EXPERIMENTS
and ALLOCATIONS
.
- EXPERIMENTSEnter the experiment IDs of the experiments concerned that are to be mutually exclusive (for example: 10201, 12345, 11456). At least two experiment IDs must be entered, the maximum number is unlimited.
- ALLOCATIONSHere you define the traffic distribution between the experiments. With an input of
[25, 50, 25]
as in the example underEXPERIMENTS
25 % of users would see experiment 10201, 50 % would see experiment 12345 and 25 % would see experiment 11456.
Please insert the following code in each of the experiments, which are supposed to be mutually exclusive. Make sure that you enter the constant EXPERIMENTS
before starting the test and that exactly the same code is inserted for each experiment.
const EXPERIMENTS = [205, 206, 207, 208]; // Participating experiments in this cluster
const ALLOCATIONS = [25, 25, 25, 25]; // Has to sum up to 100 and be the same length as EXPERIMENTS
const PARTICIPANT_KEY = 'experiment-participant-1'; // should be unique per experiment-cluster
const STORAGE = window.localStorage; // or window.sessionStorage
const storedIsInAudience = STORAGE.getItem(PARTICIPANT_KEY);
if (storedIsInAudience === null) {
let randomNumber = Math.floor(Math.random() * 100);
const selectedExperiment = EXPERIMENTS.find((_, index) => {
const allocation = ALLOCATIONS[index];
if (randomNumber < allocation) {
return true;
}
randomNumber -= allocation;
return false;
});
STORAGE.setItem(PARTICIPANT_KEY, selectedExperiment);
}
const specificStorageKey = `varify-experiment-${experimentId}`;
const isExperimentStored = STORAGE.getItem(specificStorageKey) !== null;
if (isExperimentStored) {
console.log('true');
return true;
}
if (STORAGE.getItem(PARTICIPANT_KEY) === experimentId.toString()) {
console.log('true');
return true;
}
console.log('false');
return false;
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 adjusting the code, participants of the original variant can also be excluded and the variant participants included. The next point shows you how to do this.
Multi Page Experiments - Targeting of a specific variant - Participants of one experiment in a second experiment
The best way to set up Multi Page Experiments is as follows.
1. create one experiment per website on which a change in the variant is to take place.
2. define what the primary experiment is. The primary experiment is the experiment on which page your visitors should become test participants.
3. add the following code to Audience Targeting in all experiments of the Multi Page Experiment except the Primary Experiment.
4. change the Experiment_ID to the ID of your primary experiment
5. change the targetVariationId to the variation ID of your primary experiment.
6. for all experiments except the primary experiment, set the traffic distribution to 100% of the variant
const EXPERIMENT_ID = 13013; // Change this to the experiment ID you're interested in
const STORAGE_KEY_PREFIX = 'varify-experiment-';
const specificStorageKey = STORAGE_KEY_PREFIX + EXPERIMENT_ID;
const targetVariationId = 17347; // The specific variation ID to check for
// Retrieve the value for specificStorageKey
const storedValue = localStorage.getItem(specificStorageKey);
if (storedValue) {
// Parse the stored JSON string
const storedData = JSON.parse(storedValue);
// Check if the current user has the specific variation ID
if (storedData.variationId === targetVariationId) {
console.log('User has the specific variation ID');
return true;
} else {
console.log('User does not have the specific variation ID');
return false;
}
} else {
console.log('No data found for this experiment ID');
return false;
}
Traffic source and content
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 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;
Cookie 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 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.getItem(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.getItem(STORAGE_KEY) === STORAGE_VALUE;
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;
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';
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
Web analytics integrations
Further integrations
Create experiment
Expert functions
Visual editor
- Campaign Booster: Arrow Up
- Campaign Booster: Exit Intent Layer
- Campaign Booster: Information Bar
- Campaign Booster: Notification
- Campaign Booster: USP Bar
- Add Link Target
- Browse Mode
- Custom Selector Picker
- Edit Content
- Edit Text
- Move elements
- Hide Element
- Keyword Insertion
- Redirect & Split URL Testing
- Remove Element
- Replace Image
- Responsive Device Switcher
- Style & Layout Changes
- Campaign Booster: Arrow Up
- Campaign Booster: Exit Intent Layer
- Campaign Booster: Information Bar
- Campaign Booster: Notification
- Campaign Booster: USP Bar
- Add Link Target
- Browse Mode
- Custom Selector Picker
- Edit Content
- Edit Text
- Move elements
- Hide Element
- Keyword Insertion
- Redirect & Split URL Testing
- Remove Element
- Replace Image
- Responsive Device Switcher
- Style & Layout Changes