Beacon JavaScript API

The Beacon JS API exposes the following methods to the global object: Beacon. You can use them to control your Beacon programmatically.

Beacon(‘init’, beaconId)

Call this method to load the Beacon. Additional configuration methods must be called in a separate string or object.

Beacon('init', 'YOUR_BEACON_ID_HERE')

Beacon(‘destroy’)

Unmounts the Beacon from the DOM. You can call init again to re-render it.

Beacon('destroy')

Beacon(‘open/close’)

Use these methods to manually open or close the Beacon:

Beacon('open')
Beacon('close')
Beacon('toggle')

Beacon(‘search’, query)

Searches Docs articles and loads the results screen

Beacon('search', 'hipaa')

Beacon(‘suggest’)

Using Beacon Builder, you can suggest articles based upon the page URL.

This suggest method allows you to go one step further by programmatically allowing you to change these suggestions based on any criteria that you specify, not just URL.

Article IDs can be found in Help Scout by navigating to the article, opening it in the editor, and copying the ID from the URL. The URL is structured like this: https://secure.helpscout.net/docs/[COLLECTION ID]/article/[ARTICLE ID]/. They can also be pulled from the Docs API.

Beacon('suggest', ['DOCS_ARTICLE_ID_1', 'DOCS_ARTICLE_ID_2'])

You can also suggest URLs that are not Docs articles. This is what the syntax would need to look like for custom links:

Beacon('suggest', [
  'DOCS_ARTICLE_ID_1',
  {
    text: 'Label for the Suggestion',
    url: 'https://www.helpscout.com',
  },
  'DOCS_ARTICLE_ID_2',
])

To expand a little further… Perhaps you’d like to display localised docs articles based upon a customer’s browser language. In the below example, we detect a browser language of Spanish 🇪🇸 (“es”), and return Spanish articles:

var language = navigator.language
if (language === 'es') {
  Beacon('suggest', [
    'SPANISH_DOCS_ARTICLE_ID_1',
    'SPANISH_DOCS_ARTICLE_ID_1',
    'SPANISH_DOCS_ARTICLE_ID_1',
  ])
})

API Limits

You can include a maximum of ten (10) Article suggestions in the suggest method.

Beacon(‘article’)

There are many ways to open a Docs Article with Beacon via any element on your site, and you can choose to do it using a custom HTML data attribute, or with a the article JavaScript method.

All you’ll need is the Article’s ID, which can be found in Help Scout by navigating to the article, opening it in the editor, and copying the ID from there. They can also be pulled from the Docs API. The editor URL is structured like this:

https://secure.helpscout.net/docs/[COLLECTION ID]/article/[ARTICLE ID]/.

Using data attributes

Data attributes are the simplest way to open a Docs Article via any link or button on your site. There are four different attributes you can choose from, which can be used to open the article in Beacon, or in a popover, sidebar, or modal. Check out the examples and demos below for more information on how to use them.

Example

<!-- Open Article in Beacon -->
<a href="#" data-beacon-article="ARTICLE_ID"></a>

<!-- Open Article in a popover -->
<a href="#" data-beacon-article-inline="ARTICLE_ID"></a>

<!-- Open Article in a sidebar -->
<a href="#" data-beacon-article-sidebar="ARTICLE_ID"></a>

<!-- Open Article in a modal -->
<a href="#" data-beacon-article-modal="ARTICLE_ID"></a>

Demos

Using the JS API Method

Alternatively, you can use the Beacon('article') method to open the Article within Beacon, or in a sidebar or modal. This is helpful when your trigger is something other than a link or a button, or when you’d like the article to show up automatically using your own custom logic.

Note: If the Beacon is closed when this method is called, it will also open the Beacon automatically.

Example

// Open Article in Beacon
Beacon('article', 'ARTICLE_ID')

// Open Article in a sidebar
Beacon('article', 'ARTICLE_ID', { type: 'sidebar' })

// Open Article in a modal
Beacon('article', 'ARTICLE_ID', { type: 'modal' })

Troubleshooting

There are some cases in which the data-beacon-article attributes do not work correctly, such as when the anchor tag has other tags inside it (like a span, div or i). As a workaround, you can always use this approach:

<a href="javascript:void(0)" onclick="Beacon('article', 'DOCS_ARTICLE_ID')"></a>

Beacon(‘navigate’, route)

Navigates to a specific screen. Available routes are:

Beacon('navigate', '/') // Welcome screen
Beacon('navigate', '/ask/') // Ask screen
Beacon('navigate', '/ask/message/') // Message screen
Beacon('navigate', '/ask/chat/') // Chat screen
Beacon('navigate', '/answers/') // Answers screen
Beacon('navigate', '/previous-messages/') // Previous Conversations screen
Beacon('navigate', '/docs/search?query=help') // === Beacon('search')

Beacon(‘identify’, userObject)

The identify method serves four purposes:

  1. It creates a new customer profile for each visitor that opens your Beacon. If a customer profile already exists, it will update the existing profile for that visitor.

  2. It tells Beacon that we know the name and email address of the visitor. We use their name and email address to pre-populate and hide the fields on the ‘Create a message’ screen. We also use their name and email address to skip asking these questions at the start of a Beacon chat.

  3. It can be used to record custom data attributes that can be synced as Customer Properties and used to trigger Messages. The attribute keys must exactly match existing Customer Property IDs (including capitalization) and value types must match the types associated with the linked Customer Properties. (Customer Properties are available on current Standard, Plus, and Company plans. Learn more here.).

  4. If a valid signature is provided, it can be used to authenticate a user in Secure Mode and retrieve their previous conversations. Secure Mode ensures that the visitor is who they say they are.

Note: if the “ask for a name” flag is flipped to required for a particular Beacon, the customer must have a valid name provided in the identify request, or provide the name themselves. Passing a space character as a name will return a 400 error and prevent the user from submitting their request.

Code examples

Identify a user in Normal Mode:

Beacon('identify', {
  name: 'Steve Aoki',
  email: 'steve@aoki.com',
})

Directly update the customer’s Help Scout profile as well by sending values for the company, jobTitle, and avatar attributes:

Beacon('identify', {
  name: 'Steve Aoki',
  email: 'steve@aoki.com',
  company: "Steve's Tyres",
  jobTitle: 'Tyre Aficionado',
  avatar: 'URL_TO_AVATAR_HERE',
})

Identify a user in Secure Mode:

Beacon('identify', {
  name: 'Steve Aoki',
  email: 'steve@aoki.com',
  signature: 'YOUR_SERVER_GENERATED_SIGNATURE_HERE',
})

Identify a user in Secure Mode and log Customer Properties (if there are matching Customer Properties in the account):

Beacon('identify', {
  name: 'Steve Aoki',
  email: 'steve@aoki.com',
  signature: 'YOUR_SERVER_GENERATED_SIGNATURE_HERE',
  Subscription: 'Free Plan',
  'Favorite-Movie': 'Zoolander',
})

Remove a Customer Property value by setting its value to an empty string:

Beacon('identify', {
  name: 'Steve Aoki',
  email: 'steve@aoki.com',
  signature: 'YOUR_SERVER_GENERATED_SIGNATURE_HERE',
  'Favorite-Movie': '',
})

This would remove the current value of the Favorite-Movie Customer Property for this customer. Keep in mind that Properties excluded from an Identify call (in this example: Subscription) are not affected by this behavior.

API Limits

Type Char Limit Description
name (attribute) 80 Updates the "Name" field on the customer's profile. E.g: "Steve Aoki".
company (special attribute) 60 Updates the "Company" field on the customer's profile. E.g: "Dunder Mifflin, Inc".
jobTitle (special attribute) 60 Updates the "Title" field on the customer's profile. E.g: "Regional Manager".
avatar (special attribute) 200 Updates the customer profile's avatar with the provided image. This value must also be a valid URL. E.g: "http://path.to/image.png".
Property ID 100 This value must be a string, is case-sensitive, and can include letters, numbers, hyphens, and underscores, but no other special characters. E.g: "Favourite-Movie"
Property value - text type 255 This value must be a string. E.g: "Zoolander" from above.
Property value - number type 255 This value must be an integer (range of [-9223372036854775808, 9223372036854775807]). E.g: 10.
Property value - url type 255 This value must be a string which is a valid URL. E.g: "www.google.com".
Property value - date type 10 This value must be a string in the form `YYYY-MM-DD`. E.g: "2021-04-01".
Property value - dropdown type n/a This value must be a string which is a valid dropdown option label (labels can be pulled via the Mailbox API List Properties Definitions endpoint or found within the given Property in-app.) Property labels are case-sensitive.

Beacon(‘prefill’, formObject)

This method can be used to pre-populate the “Create a message” contact form with data. You can fill any of the fields: name, email, subject, body of the message (text), and custom fields (fields). Unlike the ‘identify’ method, the name and email fields will remain visible and editable when you use the prefill method.

Note: After sending a message, the pre-filled values will be cleared from the contact form.

Beacon('prefill', {
  name: 'Steve Aoki',
  email: 'steve@aoki.com',
  subject: 'Need help with invoice',
  text: 'Hello, I need some help with my invoice',
  fields: [
    {
      id: 5678, // dropdown field ID
      value: 1234, // option ID
    },
    {
      id: 5679, // date field ID
      value: 'YYYY-MM-DD', // YYYY-MM-DD format
    },
    {
      id: 5680, // single, multi-line, or number field ID
      value: 'Question', // value expressed as a string
    },
  ],
})

Pre-filling Custom Fields

Pre-filling custom fields first requires that any fields you wish to pre-fill are selected in your Beacon settings as seen below.

custom fields

It also requires some manual mapping for field labels and values so that if they ever change in the future, your Beacon won’t break. It’s more tedious upfront, but will stand the test of time.

All custom field types require you to include the field ID. To find the field ID, click on a Custom Field in Help Scout, and you’ll see the ID in the URL: https://secure.helpscout.net/settings/custom-fields/[Mailbox ID/[Field ID].

For dropdown field types, you’ll also have to fetch the option ID so that you can pre-fill the value properly. Finding the option ID requires you to open your web inspector and select the option. Each option has markup that includes the ID, like so: data-option-id="[Option ID]".

Finally for date field types, the value will need to be in a specific format: YYYY-MM-DD.

Beacon(‘reset’)

Resets the contact form by clearing all of its fields, custom fields and attachments. If your Beacon is in Normal Mode, calling Beacon(‘reset’) will clear all contact form fields, including name and email address.

If your Beacon is in Secure Mode, calling Beacon(‘reset’) will not clear the customer’s name or email address. Those inputs will remain hidden.

Please note that if a customer has been identified using the Beacon(‘identify’) method, then their name and email address won’t be cleared with this method, you’ll have to use Beacon(‘logout’) for this purpose.

Beacon('reset')

Beacon(‘logout’)

If your Beacon is in Normal Mode (you aren’t using Secure Mode), there may be a case for calling this method, which clears all data from the Beacon, including:

  • identify data
  • Device ID
  • Conversation history
Beacon('logout')

There is one available option for this method, which will end any chats in progress immediately when the method is called. By default, in progress chats are allowed to be completed.

Beacon('logout', { endActiveChat: true })

Beacon(‘config’, formObject)

This method allows you to programmatically customize and transform Beacon in a multitude of different ways, allowing you to update Beacon functionality and appearance as often as required. Keep in mind that any attributes set via the ‘config’ method will override manual settings in the Beacon Builder in Help Scout. If you don’t set any values with this method, the Beacon Builder settings will be used.

General Options

General options can be included in the main Beacon config object.

Key Type Options Description
docsEnabled
Boolean true or false Enable or disable the Docs integration. This can only be enabled via the JS API if it is already enabled in the Beacon settings.
messagingEnabled
Boolean true or false Enable or disable the contact options. This can only be enabled via the JS API if it is already enabled in the Beacon settings.
enableFabAnimation
Boolean true or false Enable or disable the pulse animation shown when Beacon first loads.
enablePreviousMessages
Boolean true or false Enable or disable Previous Messages in Beacon. Defaults to true.
enableSounds
Boolean true or false Enable or disable all notification sounds from Beacon.
color
String "#617DEC" Brand color for your Beacon
mode
String selfService, neutral, askFirst If your Beacon has Docs and Messaging (email or chat) enabled, the mode controls the user experience of the Beacon. Learn more
hideAvatars
Boolean true or false Hides User avatars in the Beacon embed until a customer starts a live chat.
hideFABOnMobile
Boolean true or false Enable or disable the Beacon button on mobile.
hideFABLabelOnMobile
Boolean true or false Enable or disable the Beacon button text on mobile.
showPrefilledCustomFields Boolean true or false (default) When custom field values are pre-filled, set to true to make them visible

Each customization listed below must be included in a designated array.

Display Options

The following customizations should be placed within an object with the key display. See here for an example.

Key Type Options Description
style
String "icon", "text", "iconAndText", "manual" Style of the button being used to toggle the Beacon
text
String "Your button text" Customize the text in your Beacon button, if you have the "text" or "iconAndText" style enabled
textAlign
String "left" or "right" Put the text on the left or right of the icon, if using the "iconAndText" style
iconImage
String message, beacon, search, buoy, question Customize the icon shown in your Beacon, if you have the icon or iconAndText style enabled
position
String "left" or "right" Puts your Beacon on the bottom left or bottom right of the page
zIndex
Number "99999" Update this to change the default
z-index
of the Beacon
horizontalOffset
Number 200 Adjust the horizontal offset of Beacon for web
verticalOffset
Number 200 Adjust the vertical offset of Beacon for web
horizontalMobileOffset
Number 200 Adjust the horizontal offset of Beacon for mobile web
verticalMobileOffset
Number 200 Adjust the vertical offset of Beacon for mobile web

Messaging Options

The following customizations should be placed within an object with the key messaging. See here for an example.

Key Type Options Description
chatEnabled
Boolean true or false Enable or disable Chat. This can only be enabled via the JS API if it is already enabled in the Beacon settings.
contactFormcustomFieldsEnabled Boolean true or false Enable or disable Custom Fields. This can only be enabled via the JS API if it is already enabled in the Beacon settings.
contactFormshowName Boolean true or false Display an editable Name field. This can only be set from false to true as otherwise the field would still be required.
contactFormshowSubject Boolean true or false Display an editable Subject field. This can only be set from false to true as otherwise the field would still be required.
contactFormallowAttachments Boolean true or false Enable or disable file attachments. This can only be enabled via the JS API if it is already enabled in the Beacon settings.
contactFormshowGetInTouch Boolean true or false Show a contact link on the Beacon home screen

N.B: In the above table, options such as contactFormcustomFieldsEnabled denote a nested JSON property.

Translate Options

The following customizations should be placed within an object with the key labels. See here for an example.

Answers

Key Default
suggestedForYou
"Instant Answers"
getInTouch
"Get in touch"
searchLabel
"What can we help you with?"
tryAgain
"Try again"
defaultMessageErrorText
"There was a problem sending your message. Please try again in a moment."
beaconButtonClose
"Close"
beaconButtonChatMinimize
"Minimise chat"
beaconButtonChatOpen
"Open chat"

Ask

Key Default
answer
"Answers"
ask
"Ask"
messageButtonLabel
"Email"
noTimeToWaitAround
"No time to wait around? We usually respond within a few hours"
chatButtonLabel
"Chat"
chatButtonDescription
"We’re online right now, talk with our team in real-time"
wereHereToHelp
"Start a conversation"
whatMethodWorks
"What channel do you prefer?"
previousMessages
"Previous Conversations"

Search Results

Key Default
cantFindAnswer
"Can’t find an answer?"
relatedArticles
"Related Articles"
nothingFound
"Hmm…"
docsSearchEmptyText
"We couldn’t find any articles that match your search."
tryBroaderTerm
"Try searching a broader term, or"
docsArticleErrorText
"There was a problem retrieving this article. Please double-check your internet connection and try again."
docsSearchErrorText
"There was a problem retrieving articles. Please double-check your internet connection and try again."
escalationQuestionFeedback
"Did this answer your question?"
escalationQuestionFeedbackNo
"No"
escalationQuestionFeedbackYes
"Yes"
escalationSearchText
"Browse our help docs for an answer to your question"
escalationSearchTitle
"Keep searching"
escalationTalkText
"Talk with a friendly member of our support team"
escalationTalkTitle
"Talk to us"
escalationThanksFeedback
"Thanks for the feedback"
escalationWhatNext
"What next?"

Send A Message

Key Default
sendAMessage
"Send a message"
firstAFewQuestions
"Let’s begin with a few questions"
howCanWeHelp
"How can we help?"
responseTime
"We usually respond in a few hours"
history
"History"
uploadAnImage
"Upload an image"
attachAFile
"Attach a file"
continueEditing
"Continue writing…"
lastUpdated
"Last updated"
you
"You"
nameLabel
"Name"
subjectLabel
"Subject"
emailLabel
"Email address"
messageLabel
"How can we help?"
messageSubmitLabel
"Send a message"
next
"Next"
weAreOnIt
"We’re on it!"
messageConfirmationText
"You’ll receive an email reply within a few hours."
viewAndUpdateMessage
"You can view and update your message in"
mayNotBeEmpty
"May not be empty"
customFieldsValidationLabel
"Please complete all fields"
emailValidationLabel
"Please use a valid email address"
attachmentErrorText
"There was a problem uploading your attachment. Please try again in a moment."
attachmentSizeErrorText
"Attachments may be no larger than 10MB"

Previous messages

Key Default
addReply
"Add a reply"
addYourMessageHere
"Add your message here..."
sendMessage
"Send message"
received
"Received"
waitingForAnAnswer
"Waiting for an answer"
previousMessageErrorText
"There was a problem retrieving this message. Please double-check your Internet connection and try again."
justNow
"Just Now"

Chat

Key Default
chatHeadingTitle
"Chat with our team"
chatHeadingSublabel
"We’ll be with you soon"
chatEndCalloutHeading
"All done!"
chatEndCalloutMessage
"A copy of this conversation will land in your inbox shortly."
chatEndCalloutLink
"Return home"
chatEndUnassignedCalloutHeading
"Sorry about that"
chatEndUnassignedCalloutMessage
"It looks like nobody made it to your chat. We’ll send you an email response as soon as possible."
chatEndWaitingCustomerHeading
"Sorry about that"
chatEndWaitingCustomerMessage
"Your question has been added to our email queue and we’ll get back to you shortly."
ending
"Ending..."
endChat
"End chat"
chatEnded
" ended the chat"
chatConnected
"Connected to "
chatbotName
"Help Bot"
chatbotGreet
"Hi there! You can begin by asking your question below. Someone will be with you shortly."
chatbotPromptEmail
"Got it. Real quick, what’s your email address? We’ll use it for any follow-up messages."
chatbotConfirmationMessage
"Thanks! Someone from our team will jump into the chat soon."
chatbotGenericErrorMessage
"Something went wrong sending your message, please try again in a few minutes."
chatbotInactivityPrompt
"Since the chat has gone idle, I’ll end this chat in a few minutes."
chatbotInvalidEmailMessage
"Looks like you’ve entered an invalid email address. Want to try again?"
chatbotAgentDisconnectedMessage
" has disconnected from the chat. It’s possible they lost their internet connection, so I’m looking for someone else to take over. Sorry for the delay!"
chatAvailabilityChangeMessage
"Our team’s availability has changed and there’s no longer anyone available to chat. Send us a message instead and we’ll get back to you."
Transcript Email
emailHeading
"Today’s chat with "
emailGreeting
"Hey "
emailCopyOfDiscussion
"Here’s a copy of your discussion"
emailContinueConversation
"If you’ve got any other questions, feel free to hit reply and continue the conversation."
emailJoinedLineItem
" joined the chat"
emailEndedLineItem
" ended the chat"
emailYou
"You"

API Limits

The maximum number of characters for a Translation value is 160.

Examples

To demonstrate how the above options might be used collectively, see the example below.

Beacon('config', {
  docsEnabled: true,
  mode: 'selfService',
  display: {
    style: 'icon',
    iconImage: 'search',
  },
  messaging: {
    chatEnabled: true,
    contactForm: {
      customFieldsEnabled: true,
      showName: true,
    },
  },
  labels: {
    chatHeadingSublabel: 'We’ll be with you soon',
    continueEditing: 'Continue Editing…',
    emailValidationLabel: 'Please use a valid email address',
  },
})

Taking it a little further… Perhaps you’d like to localise Beacon and translate the text based upon a customer’s browser language? In the below example, we detect a browser language of Spanish 🇪🇸 (“es”), and translate the label accordingly:

var language = navigator.language
if (language === 'es') {
  Beacon('config', {
    labels: {
      you: ''
  })
})

Beacon(‘on/off/once’)

These methods allow you to hook up to specific events in the lifecycle of the Beacon to perform custom actions.

  • Beacon('on') allows you to subscribe to every instance of an event.
  • Beacon('once') allows you to subscribe only to the very first instance of an event.
  • Beacon('off') allows you to unsubscribe to all instances of an event.

Supported Events

Event name Description Callback param attributes
open Triggered when the Beacon is opened  
close Triggered when the Beacon is closed  
ready Triggered when the Beacon finishes loading on the page  
article-viewed Triggered when a Docs Article is opened in Beacon id
chat-started Triggered when a Chat is started via Beacon name, email, subject
email-sent Triggered when a message is sent via Beacon name, email, text
message-clicked Triggered when a Message’s CTA is clicked id
message-closed Triggered when a Message’s close button is clicked id
message-triggered Triggered when a Message is shown id
search Triggered when a Docs search is performed via Beacon query

Example usage

Beacon('on', event, callback)
Beacon('once', event, callback)
Beacon('off', event, callback?)
Beacon('on', 'open', () => console.log('Beacon opened'))

Beacon('on', 'close', () => console.log('Beacon closed'))

Beacon('once', 'open', () => {
  console.log(
    'This will only get called the first time the open event is triggered'
  )
})

// Called when Beacon is rendered on the page
Beacon('on', 'ready', () => console.log('Beacon is ready'))

// Stop listening to a specific callback
Beacon('off', 'open', callbackPreviouslyAdded)

// Stop listening to ALL callbacks for an event
Beacon('off', 'open')

Beacon (‘event’, eventObject)

This method can be used to “trigger” specific events in Beacon. At the moment this method only supports a single type of event, 'page-viewed', which is particularly useful on Single Page Applications when you want to let Beacon know that the URL of the page has changed.

If your app is an SPA and your Beacon has Messages that show up on Specific URLs, or if you use URL-based Docs suggestions, then you’ll need to call this method, followed by the Beacon('suggest') method, whenever your app’s URL changes, which is typically done by hooking up to a method of your app’s router. Here is an example of where to call this method on a React SPA using React Router.

Usage

Beacon('event', {
  type: 'page-viewed',
  url: document.location.href,
  title: document.title,
})
Beacon('suggest')

Beacon (‘session-data’)

This method allows you to add session-specific information to a new chat or message. Unlike the identify method above, session-data can be used to pass data into the Beacon visitor activity note that’s only relevant to a specific conversation. This data will not be synced to the customer profile nor the Beacon Sidebar app.

You can add up to 20 attribute-value pairs. Each attribute label can contain up to 100 characters and each value can contain up to 10,000 characters.

Example

Beacon('session-data', {
  'App Version': 'v12.2.0 (Beta)',
  'Last Action': 'Update Profile',
})

Beacon (‘show-message’)

This method allows you to modify when Messages are displayed. There are currently two options:

  • delay- pass a value in milliseconds to override the default 3 second delay before a Message is displayed
  • force- force a Message to be displayed, even if it has already been shown to the customer

Example

Beacon('show-message', 'YOUR_MESSAGE_ID_HERE', { delay: 1000 })
Beacon('show-message', 'YOUR_MESSAGE_ID_HERE', { force: true })

Beacon (‘info’)

This method returns information about the state of an embedded Beacon, including ID/name, configuration and display information, details about the identified visitor, and timeline navigation events.

Example

Beacon('info')