With the Custom Script feature for Campaigns, the possibilities are endless when it comes to styling, additional tracking, and actions for your campaigns. JavaScript is also very useful for targeting campaigns.
The custom Script Feature is available from the PRO plan and up! π
General best practices with JavaScript in Triggerbee
We only support Vanilla JavaScript, not compiled versions like TypeScript.
For the JavaScript Session Condition, we recommend that you only use one-liner expressions, not full functions. If you wish to target a campaign on a JavaScript function, please put it in your account Client Script, and call the function from the Session Condition.
We do not support async or await functions in the JavaScript Session Condition.
β
All of these snippets are examples of what can be done. They are not copy-paste-and-go; they must be configured to match your website.
Targeting Campaigns with JavaScript
Target campaigns based on URL parameters:
The visitor is on a page that includes the word "products":
window.location.pathname.includes("products");
The visitor is NOT on a page that include the word "products":
!window.location.pathname.includes("products");
The visitor is on a page that include the word "facebook" in the query (query = everything after the ? in the URL):
window.location.search.includes("facebook");
The visitor is NOT on a page that include the word "facebook" in the query:
!window.location.search.includes("facebook");
The visitor is on the domain "subdomain.yourwebpage.com":
window.location.host == "subdomain.yourwebpage.com"
The visitor is NOT on the domain "subdomain.yourwebpage.com":
window.location.host != "subdomain.yourwebpage.com"
Target campaigns based on a cart value
window.getCart().subtotal_price > 300
Target campaigns based on whether there is a certain product in the cart
window.getCart().products.include("productName")
Target campaigns based on a logged-in status
It is common to target campaigns depending on whether the visitor is logged in or not. This is usually done by looking at the Login Button in the HTML. For instance, you can check if it contains the word "log in" or "my account" (very simplified example):
Logged out visitors:
document.querySelector("#login-button").innerText.includes("Log in");
Logged in visitors:
document.querySelector("#login-button").innerText.includes("My account");
Target campaigns to every 10th session
Function to randomize a number and return true if within the correct percentile, to be put in Client Script
function displayForEachTenth() {
return Math.random() < 0.1;
}
Expression to put in JavaScript Session Condition:
displayForEachTenth()
Handling Campaigns with JavaScript
Replace {word} with a JavaScript variable
Popular Use Cases
Replacing {firstname} with actual first name
Replacing {points} with results from a quiz
Requirements:
Your variable must be accessible on the site, frontend in the browser
Your campaign must have a text element with {word} in it, to replace
var tbVariable = {your variable}
var fallBack = " Member"; // can be empty
var tbTextContent = widget.querySelector(".text-content-wrapper > .text-content").innerHTML;
if(tbVariable){ // if tbVariable is found, replace {word}
var tbNewContent = tbTextContent.replace("{word}", tbVariable);
widget.querySelector(".text-content-wrapper > .text-content").innerHTML = tbNewContent;
}else{ // if tbVariable is not found, replace {word} with your fallback word
var tbEmptyContent = tbTextContent.replace(" {word}", fallBack);
widget.querySelector(".text-content-wrapper > .text-content").innerHTML = tbEmptyContent;
}
Restart Campaign
By default, Triggerbee remembers what step the visitor saw last. Usually, this is not an issue, as most campaigns are hidden after signing up or performing the desired action. But in some cases, such as embedded forms and guides, you want the visitor to be able to do the guide again or re-enter a signup.
To achieve this, you must delete the campaign ID from the cookie that remembers what campaigns have already been interacted with. Here's an example of how to do that.
Put this code on the submit or final CTA button in your campaign or on the
afterFormSubmit
JS-event.change {siteID} to your siteID, which you'll find in your Account Settings.
change {stateID} to the current step ID, which is in the URL of your campaign when you're on the last step in the campaign, eg.
https://app.triggerbee.com/campaigns/12345/widgets/136370/editor?state=197808
var tbStateCookie = mtr.get_cookie("triggerbee_widgets_state_{siteID}");
var parsedCookie = JSON.parse(tbStateCookie);
parsedCookie.widgets = parsedCookie.widgets.filter(state => state.id != {stateID});
mtr.set_cookie("triggerbee_widgets_state_{siteID}",JSON.stringify(parsedCookie));
Open a campaign with a click or interaction on the site
If you want to open a campaign based on a click or any other type of interaction on your website, you can use the Campaign API to open your campaign. This is an example of opening a campaign on a button click.
Note: You must publish your campaign with the manual trigger for this function to work. Use api.trigger
to open your campaign and consider targeting, and api.open
to force open without targeting
const buttonToClick = document.querySelectorAll(".click-button");
buttonToClick.addEventListener("click",function () {
triggerbee.widgets.api.trigger(1234);
})
Change the deadline component to count 30 minutes from campaign open
Use this snippet if you want the deadline component to count down from when the campaign opens, eg. "Offer only valid for 30 minutes". The campaign will automatically close after the given number of minutes.
The deadline component must be set to:
Occurance: Every day
Deadline: 00:00
Format: Minutes, Seconds
// Set your time here, eg. 30 minutes countdown
const countDownTime = 30;
// Get the deadline component element
const deadlineElement = widget.querySelector('.deadline-component');
// Set the deadline time to 3 minutes from now
const deadlineTime = new Date();
deadlineTime.setMinutes(deadlineTime.getMinutes() + countDownTime);
deadlineElement.querySelector('.minutes .deadline-section-slide1').textContent = 0;
deadlineElement.querySelector('.seconds .deadline-section-slide1').textContent = 0;
function updateCountdown() {
// Calculate the time remaining until the deadline
const now = new Date();
const timeRemaining = deadlineTime - now;
// Calculate the minutes, and seconds remaining
const minutes = Math.floor((timeRemaining % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((timeRemaining % (1000 * 60)) / 1000);
// Update the HTML elements with the new values
deadlineElement.querySelector('.minutes .deadline-section-slide2').style.display = "none";
deadlineElement.querySelector('.seconds .deadline-section-slide2').style.display = "none";
deadlineElement.querySelector('.minutes .deadline-section-value2').style.display = "none";
deadlineElement.querySelector('.seconds .deadline-section-value2').style.display = "none";
deadlineElement.querySelector('.minutes .deadline-section-slide1').textContent = String(minutes).padStart(2, '0');
deadlineElement.querySelector('.seconds .deadline-section-slide1').textContent = String(seconds).padStart(2, '0');
}
// Update the countdown every second
setInterval(updateCountdown, 1000);
setTimeout(() => {
triggerbee.widgets.api.close(event.detail.id)
}, countDownTime*1000);
Get data from GTM Datalayer
var checkoutValue = google_tag_manager['GTM-ABC1234'].dataLayer.get('ecommerce.checkout.value');