Widget Integration
JavaScript API
Control the chat widget programmatically from your application.
The hej! widget exposes a JavaScript API on window.hej that lets you control the chat widget from your application code. Use it to open the chat, send messages, or pre-fill the input based on user actions.
Available Methods
| Method | Description |
|---|---|
open() | Opens the chat widget |
close() | Closes the chat widget |
toggle() | Toggles the chat widget open/closed |
send(message) | Opens the chat and sends a message |
prefill(message) | Opens the chat with pre-filled input text |
Method Details
window.hej.open()Opens the chat widget if it's currently closed. Has no effect if already open.
// Open chat when user clicks a help button
document.querySelector('#help-btn').addEventListener('click', () => {
window.hej.open()
})window.hej.close()Closes the chat widget if it's currently open. Has no effect if already closed.
// Close chat programmatically window.hej.close()
window.hej.toggle()Toggles the chat widget between open and closed states.
// Toggle chat with keyboard shortcut
document.addEventListener('keydown', (e) => {
if (e.key === '?' && e.shiftKey) {
window.hej.toggle()
}
})window.hej.send(message: string)Opens the chat widget and immediately sends a message. Useful for contextual help.
Parameters
messageThe message to send to the chat
// Send a contextual support message when an error occurs
function handleError(error) {
const message = `I got an error: "${error.message}" on page ${location.href}`
window.hej.send(message)
}window.hej.prefill(message: string)Opens the chat widget and pre-fills the input field without sending. The user can review and edit before sending.
Parameters
messageThe text to pre-fill in the input field
// Pre-fill a question about the current product
const productName = document.querySelector('.product-title').textContent
window.hej.prefill(`Tell me more about ${productName}`)Common Use Cases
Custom Help Button
Add a help button anywhere on your site that opens the chat widget.
Error Support
Automatically open chat with error context when something goes wrong.
Contextual Questions
Pre-fill questions based on the page or product the user is viewing.
Keyboard Shortcuts
Let power users open chat with a keyboard shortcut.
Checking Availability
The API is available after the widget script loads. Use optional chaining or check for existence:
// Using optional chaining (recommended)
window.hej?.open()
// Or check explicitly
if (window.hej) {
window.hej.open()
}TypeScript Support
Add type definitions for the API in your project:
// global.d.ts or any .d.ts file
declare global {
interface Window {
hej?: {
open: () => void
close: () => void
toggle: () => void
send: (message: string) => Promise<void>
prefill: (message: string) => void
}
}
}Widget Events
Want to react to chat events like open, close, or new messages? Check out Events & Callbacks.