triggers.js

The triggers.js file controls when an experience will fire.

Anatomy of the triggers.js file

There are two ways of implementing this function, the callback based method or the promise based method.

Both methods allow you to provide a boolean value to determine whether or not the experience should fire.

However, the promise method has the additional advantage that any asynchronous errors that cause the promise chain to be rejected will be captured and reported in the UI.

Callback based syntax:

module.exports = function triggers (options, cb) {
  cb(true)
}

Promise based syntax:

const Promise = require('sync-p/extra')

// The following are equivalent:
module.exports = function triggers (options) {
  return Promise.resolve()
}

module.exports = function triggers (options) {
  return Promise.resolve(true)
}

module.exports = function triggers (options) {
  return Promise.resolve({ execute: true })
}

Example usage

Let's now look at some examples snippets that can be added to the triggers.jsfile.

In this first example snippet, we ensure that the experience only fires if the visitor is in their first session:

module.exports = function triggers (options) {
  return options.getVisitorState()
    .then(data => data.sessionNumber === 1)
}

Here is another example that ensures that certain elements are on the page before the experience fires:

module.exports = function triggers (options) {
  return options.poll([ '.product_image', '.product_title' ])
}

Hooks

There are several hooks that can be returned from the triggers.js file:

onRemove

This hook allows you to provide some cleanup methods. If smartserve restarts, these methods will be called. You should use this hook to remove any side effects.

If you implement this method, you will also be able to use the hot reloading feature of Qubit ClI.

onActivation

This hook always fires when an experience activates, even if the visitor is allocated to the control group. This can be useful for sending analytic events.

Example Usage

module.exports = function triggers (options) {
  return options.poll([ '.product_image', '.product_title' ])
    .then(() => {
      options.onActivation(trackExperience)
      options.onRemove(cleanupStuff)

      return {
        execute: true
      }
    })
}
Last updated: July 2021
Did you find this article useful?