On-Site Messaging Implementation Guide
Overview
Metrix On-Site Messaging displays targeted messages and campaigns to users while they are browsing your website. Campaigns are created and configured in the Metrix dashboard, and the SDK automatically handles delivery and display.
Key Requirements
- User Identification: Users must be identified using
authorizeUser()before they can receive On-Site Messages - Automation User ID: The SDK obtains an
automationUserIdfor identified users to load targeted messages - Anonymous Users: Anonymous users do NOT receive On-Site Messages through this integration
Quick Start
Enable On-Site Messaging and authorize the user:
import { init, authorizeUser } from '@metrixorg/websdk';
// Step 1: Initialize SDK with on-site messaging enabled
init('APP_ID', 'API_KEY', {
onSiteMessaging: {
enabled: true, // Enable on-site messaging
},
});
// Step 2: Identify the user
authorizeUser('CUSTOM_USER_ID');Configuration
Enable On-Site Messaging
Set onSiteMessaging.enabled to true in the SDK configuration:
init('APP_ID', 'API_KEY', {
onSiteMessaging: {
enabled: true,
},
});Configuration Interface
interface OnSiteMessageConfig {
enabled: boolean; // Enable/disable on-site messaging (default: false)
}| Field | Type | Description | Default |
|---|---|---|---|
enabled | boolean | Enables delivery and display of campaigns. | false |
How It Works
Message Delivery Flow
- SDK waits for page
DOMContentLoadedevent - SDK waits for user identification (automation ID)
- SDK listens for On-Site Message campaigns for that user
- When campaigns are available, they are displayed one at a time
- When a message closes or expires, the next queued message displays
Message Display
Messages are rendered in an iframe inside a Shadow DOM. This isolation:
- Protects host page from campaign styles and markup
- Prevents campaign scripts from affecting your application
- Allows automatic close button and iframe sizing
User Management
Authorize User (Required)
Identify users before they need personalized messages:
import { authorizeUser } from '@metrixorg/websdk';
authorizeUser('user@example.com');
// or
authorizeUser('user-123');
// or
authorizeUser('custom_identifier');The custom user ID must be stable and unique per user.
Deauthorize User (Logout)
Clear the current SDK identity when users log out:
import { deauthorizeUser } from '@metrixorg/websdk';
deauthorizeUser();After deauthorization:
- No further activity is associated with the previous user
- On-Site Messages stop displaying for that user
- Call
authorizeUser()again to re-enable for a new user
Campaign Message Actions
Campaigns can trigger these actions:
1. Close Message
User closes the current message by clicking the close button or campaign-provided close action.
2. Open URL
Campaign can open a URL in a new browser tab:
// Campaign triggers this internally
window.open('https://example.com', '_blank');3. Send Event
Campaign sends a Metrix event using an event slug:
// Campaign includes event slug
import { newEvent } from '@metrixorg/websdk';
newEvent('campaign_click', {
campaign_id: 'campaign-123',
});Events must include an event slug. Custom attributes are optional.
4. Send Response
Campaign sends response data associated with the campaign ID:
// Response payload from campaign
{
type: 'SEND_RESPONSE',
payload: {
action: 'subscribe',
email: 'user@example.com'
}
}Response payloads are associated with the campaign’s ID for tracking.
5. Adjust Display Size
Campaign can adjust iframe dimensions based on content:
// Campaign scales iframe to fit content
{
type: 'SCALE_IFRAME',
width: 600,
height: 400
}Complete Example
import { init, authorizeUser, deauthorizeUser } from '@metrixorg/websdk';
// Initialize SDK on app startup
init('APP_ID', 'API_KEY', {
onSiteMessaging: {
enabled: true,
},
});
// When user logs in
document.getElementById('login-btn').addEventListener('click', async () => {
// ... perform login ...
const userId = 'user@example.com';
// Authorize user to receive on-site messages
authorizeUser(userId);
console.log('User authorized, on-site messages enabled');
});
// When user logs out
document.getElementById('logout-btn').addEventListener('click', () => {
// Clear SDK identity
deauthorizeUser();
console.log('User deauthorized, on-site messages disabled');
});Dashboard Setup
Before testing message delivery:
-
Create Campaign
- Log in to Metrix dashboard
- Create an On-Site Messaging campaign
- Design message content and actions
-
Configure Targeting
- Set audience conditions (e.g., specific user segments)
- Define trigger conditions (e.g., page URL, time on page)
- Set message duration (optional)
-
Activate Campaign
- Ensure campaign status is “Active”
- Verify targeting rules match your test user
-
Test Delivery
- Initialize SDK with
onSiteMessaging.enabled: true - Identify test user with
authorizeUser(testUserId) - Load website matching campaign conditions
- Verify message displays
- Initialize SDK with
Campaign availability and targeting are controlled entirely by the Metrix dashboard. The SDK does not expose a public method to force message display.
Configuration Reference
SDK Initialization
init('APP_ID', 'API_KEY', {
onSiteMessaging: {
enabled: boolean; // Required
},
});User Methods
// Authorize user
authorizeUser(customUserId: string): void
// Deauthorize user
deauthorizeUser(): voidMessage Structure
OnSiteMessage Interface
interface OnSiteMessage {
url: string; // URL to iframe content
alignment: string | null; // Message position
duration: number | null; // Display duration in milliseconds
campaignId: string; // Campaign identifier
}Iframe Message Types
enum IframeMessageType {
CLOSE_ONSITE = 'CLOSE_ONSITE', // Close current message
OPEN_URL = 'OPEN_URL', // Open URL in new tab
SEND_EVENT = 'SEND_EVENT', // Send Metrix event
SEND_RESPONSE = 'SEND_RESPONSE', // Send response payload
SCALE_IFRAME = 'SCALE_IFRAME', // Adjust iframe size
}Best Practices
1. Initialize Before Authorization
Always call init() before authorizeUser():
// ✓ Correct order
init('APP_ID', 'API_KEY', { onSiteMessaging: { enabled: true } });
authorizeUser('user-id');
// ✗ Wrong order
authorizeUser('user-id');
init('APP_ID', 'API_KEY', { onSiteMessaging: { enabled: true } });2. Use Stable User IDs
Use consistent, unique identifiers:
// ✓ Good - stable across sessions
authorizeUser('user@example.com');
authorizeUser('db-user-id-12345');
// ✗ Bad - changes each session
authorizeUser(Math.random().toString());
authorizeUser(Date.now().toString());3. Clear Identity on Logout
Always deauthorize when users log out:
// ✓ Good
document.getElementById('logout-btn').addEventListener('click', () => {
deauthorizeUser(); // Clear identity
redirectToLoginPage();
});
// ✗ Bad - user still receives messages
document.getElementById('logout-btn').addEventListener('click', () => {
redirectToLoginPage(); // Forgot to deauthorize
});4. Test After Page Load
Messages are loaded after DOMContentLoaded, so test after full page load:
// ✓ Good - test after page loads
window.addEventListener('load', () => {
authorizeUser('test-user');
// Messages will now display if campaign matches
});
// ✗ Bad - may miss messages
authorizeUser('test-user');
// Don't reload or page might miss message loading5. Check Browser Compatibility
Ensure browser supports required APIs:
- JavaScript enabled
- iframes allowed
- Shadow DOM support
- Notification APIs (if using push)
Troubleshooting
Messages Not Displaying
Problem: Messages never appear
- Check: Confirm
init()runs beforeauthorizeUser() - Check: Confirm
onSiteMessaging.enabledistrue - Check: Confirm user is identified with
authorizeUser() - Check: Verify campaign is active in Metrix dashboard
- Check: Verify campaign audience/targeting matches test user
- Check: Wait for page
DOMContentLoadedbefore testing
Messages Display But Disappear
Problem: Messages close immediately
- Solution: Check campaign duration setting in dashboard
- Solution: Verify message content loads correctly
- Solution: Check browser console for errors
Only One Message Displays
Problem: Queue stops after first message
- Solution: Verify second campaign is active and properly targeted
- Solution: Check that first message closes properly
- Solution: Wait between message closes for next to load
Campaign Actions Not Working
Problem: Click, URL, or event actions don’t work
- Check: Confirm browser allows popups (URL action)
- Check: Verify event slug is correct (event action)
- Check: Check browser console for JavaScript errors
- Check: Verify campaign content loads (check Network tab)
JavaScript Errors in Console
Problem: Errors appear related to on-site messaging
- Solution: Ensure SDK is loaded correctly
- Solution: Check for conflicting scripts or browser extensions
- Solution: Clear browser cache and reload
- Solution: Test in incognito/private mode to rule out extensions
Support
For issues or questions:
- Messages not displaying? Check troubleshooting section above
- Campaign not triggering? Verify campaign is active in Metrix dashboard
- User identification issue? Ensure
authorizeUser()called afterinit() - JavaScript errors? Check browser console and check for conflicting scripts
Metrix On-Site Messaging requires the SDK to be properly initialized and users to be identified for message delivery.