General information
Requirements
Frontend SDK is a data transfer method that must be activated for your Manago AI account before you can start transferring Contact data, Key Information, and External Events to your Manago AI database. Following the activation, you can whitelist a domain to get access to the Frontend SDK. You can only whitelist domains with the Manago AI Monitoring Script present. The SDK can be used with the Google Tag Manager (GTM) or can be directly included as a JavaScript integration.
Technology
The Frontend SDK uses JavaScript to transfer Contact data and Key Information directly from the Contact’s browser via GET requests. This method for transferring data to Manago AI is an alternative to the REST API (API v2 and API v3) designed primarily for integrating websites that cannot have their backend modified. The SDK developed by Manago AI works even with browsers that restrict cross-domain requests and divides GET requests into packages to meet the 4096 URL limit for the GET method.
Note: While transferring External Events is possible via client-side JavaScript, it uses a different method to build the requests. For more information, see External Event transfer >>
Security
The technology used to transfer data (i.e., JavaScript) is a client-side technology, and as such, it is prone to manipulation by the end user. Manago AI allows you to take a number of measures to minimize any potential risks:
- Allowed scopes—define the data types (scopes) that will be accepted by Manago AI. For example, you can limit the Frontend SDK to allow only the assigning and removing of tags, and thus prevent any end-user who might have malicious intents from modifying Contact data.
- Limiting—Frontend SDK uses advanced request limiting for each of your domains to reduce the risk of bots interfering with your Contact database. Three limiting ranges are applied: per minute, per hour, and per day.
- Contact creation/update scope—decide whether the Frontend SDK should allow the creation and updating of Contact data or only the creation of new Contacts.
- Requiring subscription confirmation (optional)—decide whether Contacts opting-in for your newsletter should be required to confirm their subscription by clicking a link in an email.
- REST API—The Frontend SDK can be used in combination with the backend REST API that can handle the transfer of the most critical data.
Validations
To make sure the data transferred to Manago AI is well-structured, ordered, and easily accessible, we use validations for specific fields. The most important validations include:
| Data type | Standard | External resources |
|---|---|---|
| RFC882 | RFC882 at ietf.org | |
| URL | Apache URL validator | UrlValidator at apache.org |
| Currency | ISO 4217 | ISO 4217 at SIX |
| Language | ISO 639-1 | ISO 639-1 at loc.gov |
| Language and region | BCP 47 | BCP 47 codes at Microsoft |
Compatibility
The Frontend SDK is compatible with all major browsers and operating systems.
Supported browsers:
- Google Chrome
- Mozilla Firefox
- Apple Safari
- Microsoft Edge
- Opera
- Other browsers supporting cross-domain GET requests
Supported operating systems:
- Windows
- MacOS
- Android
- iOS
- Linux
- Other operating systems without misconfigured firewall
Frontend SDK methods
Simple example:
SMApi.set('email', '[email protected]');
SMApi.set('name', 'John Doe');
SMApi.execute('contact');
Advanced example:
const Contact = {};
Contact.email = '[email protected]';
Contact.name = 'John Doe';
Contact.addTags = ['CAT_FOOD'];
SMApi.setDebugMode(true);
SMApi.setAll(Contact);
SMApi.execute('contact').then((result) => {
console.log(result);
});
The Manago AI Frontend SDK offers a number of methods for managing the transfer of data. You can set a single data field or a number of fields at once, get the data that was previously set, clear the data, and transfer contact and/or keyInformation objects to Manago AI. You can also enter a debug mode to get more information about the SDK during the development.
Methods:
| Method | Description |
|---|---|
| Initialization | When the object is initialized, a post message is sent to window scope: topic: 'FRONTEND_SDK_STARTED'. |
SMApi.set(field, data) |
Allows you to set a field with data. Both arguments are required. |
SMApi.setAll(dataObject) |
Allows you to set a number of fields at once with a JSON dataObject. |
SMApi.get(field) or SMApi.get(null) |
Allows you to get a previously set field. If the field argument is missing, all previously set fields are retrieved. |
SMApi.clear(field) or SMApi.clear(null) |
Allows you to clear a previously set field. If the field argument is missing, all previously set fields are cleared. |
SMApi.execute('contact'); SMApi.execute('keyInformation'); SMApi.execute('productCollection'); |
Allows you to transfer contact, keyInformation, and productCollection objects. The method returns a promise that is resolved once the data transfer is complete. |
SMApi.setDebugMode(true) |
Allows you to enable the debugging mode to get additional information and statuses while setting and transferring data. |
Contact transfer
Sample request:
const ContactData = {
email: "[email protected]",
name: "John Doe",
phone: "+15554443322",
externalId: "U12345",
company: "Acme Inc.",
state: "PROSPECT",
birthday: "19870605",
streetAddress: "Main Street 21",
city: "San José",
zipCode: "90210",
province: "California",
country: "US",
addTags: ["T_SHIRTS", "SWEATERS", "UPSELL"],
removeTags: ["FIRST_PURCHASE"],
emailOptIn: 1,
mobileOptIn: 0,
monitoringOptIn: 1,
consents: [{
name: "TERMS_OF_SERVICE",
status: 1
}],
standardDetails: {
t_shirt_size: "XL",
gender: "Male"
},
numberDetails: {
shoe_size: 10
},
dateDetails: {
member_since: "1459938888"
}
};
SMApi.setAll(ContactData);
SMApi.execute('contact').then((result) => {
console.log(result);
});
Sample response:
When executed, the Frontend SDK returns a promise. A resolved promise contains the following response:
{
"requestId": "a1b2-...-c3d4",
"contactId": "1234-...-cdef",
"finalResponse": true
}
Additionally, an 'smclient' cookie is automatically set with the value of 'contactId'.
Contacts are the most important entities in Manago AI. contact objects contain Contacts’ personal information, consents, and other details. For more information, see Contact upsert method >>
| Field | Limits | Scope | Description |
|---|---|---|---|
| email* | RFC882 | Basic data | In Manago AI, a Contact can be identified in two ways: by email or contactId. If both fields are present, the email address is used. When creating a new Contact, you can only use the email field. |
| contactId* | UUID | Basic data | |
| name | 255 | Basic data | Contact name, for example the first and last name |
| phone | 255; only digits and a plus character | Basic data | Phone number. It should start with + followed by the country code. Only digits and the plus (+) character are allowed. |
| externalId | 255 | Basic data | Contact identifier from your website, for example the userID on your e-commerce platform |
| company | 255 | Basic data | Company the Contact is associated with. In Manago AI, you can list Contacts associated with a given company. |
| state | enum | Basic data | Contact’s state (CUSTOMER, PROSPECT, PARTNER, OTHER, UNKNOWN) |
| birthday | YYYYMMDD or MMDD | Basic data | Contact’s birthday (used for birthday emails). |
| streetAddress | 255 | Basic data | Street and apartment number. Additional data is allowed. |
| city | 255 | Basic data | City. Special characters are allowed. |
| zipCode | 255 | Basic data | Zip code (postcode). Special characters are allowed. |
| province | 255 | Basic data | Administrative division within a country. Special characters are allowed. |
| country | 255 | Basic data | Country. Special characters are allowed. |
| newEmail | Valid email address | Email address change | New email address for a Contact. Note: when changing the email address, the Contact must be identified using the email field. |
| addTags (array) | 16x3-255 per tag | Tags | Array containing tags to be added. Use ASCII characters only. |
| removeTags (array) | 16x3-255 per tag | Tags |
Array containing tags to be removed. Note: Tags present in both the add and remove arrays will be removed only. In that event, Automation Processes based on assigning a tag or increasing a tag scoring will not be triggered. |
| emailOptIn | int (-1, 0, 1) | Opt-in statuses |
Email Marketing consent status:
|
| doubleOptIn (object): emailId, language | UUID, ISO 639-1 | Opt-in statuses | Either the ID of the email to be sent or the Contact’s language to be used in the double opt-in email |
| mobileOptIn | int (-1, 0, 1) | Opt-in statuses | Mobile Marketing consent status: see the description for emailOptIn |
| monitoringOptIn | int (-1, 0, 1) | Opt-in statuses | Status of the consent: see description for emailOptIn. Default value is 1 (Contact will be monitored). |
| consents (array of objects): name, status | 255, int (-1, 0, 1) | Consents |
Name of the custom consent. Consent status:
|
| standardDetails (object): sampleDetail1, sampleDetail2 | 16x255 | Standard and dictionary details | Object containing key-value pairs. Standard details can be used to store additional information about Contacts. |
| numberDetails (object): sampleNumber1, sampleNumber2 | 8 x int | Standard and dictionary details | Object containing key-value pairs. |
| dateDetails (object): sampleDate1, sampleDate2 | 8 x UNIX timestamp [s] | Standard and dictionary details | Object containing key-value pairs. |
Key Information transfer
Sample request:
const KeyInformationData = {
"email": "[email protected]",
"keyInformation": {
"numeric": [{
"name": "Height",
"value": 175
}, {
"name": "Weight",
"value": 75.5
}],
"text": [{
"name": "Favorite color",
"value": "Blue"
}, {
"name": "Favorite food",
"value": "Pizza"
}]
},
"setAsNull": ["Pet owned"]
}
SMApi.setAll(KeyInformationData)
SMApi.execute('keyInformation');
Sample response:
When executed, the Frontend SDK returns a promise. A resolved promise contains the following response:
{
"requestId": "a1b2-...-c3d4",
"finalResponse": true
}
Key Information is a data type used to store zero- and first- party data in Manago AI. Zero-party data is the most powerful data type in Marketing Automation because it is directly collected from the Contact, rather than being inferred or obtained from third parties. Use Key Information transfer to add or update data gathered on your website.
Fields:
| Field | Limits | Description |
|---|---|---|
| email* | RFC882 | Contact identifier (email address or Contact ID) |
| contactid* | UUID | Contact identifier (email address or Contact ID) |
| keyInformation* (object) |
Object wrapping numeric and text arrays | |
| numeric (array of objects) |
Array of numeric Key Information | |
| text (array of objects) |
Array of text Key Information | |
| name | 255 | Key Information name |
| value | 255/BigDecimal | Key Information value |
| setAsNull | 20x255 | Array of Key Information names to be nulled |
External Event transfer
Simple example:
sm('extEvent', {
"owner": "[email protected]",
"email": "[email protected]",
"date": 1659938888,
"contactExtEventType": "DOWNLOAD"
});
Advanced example:
let date = new Date();
sm('extEvent', {
"owner": "[email protected]",
"email": "[email protected]",
"date": date.getTime(),
"contactExtEventType": "PURCHASE",
"products": "p0123, p4567",
"value": 189.99,
"location": "examplecom",
"products": "p0123, p4567",
"externalId": "ID-123456",
"details": ["detail1", "detail2"]
});
External Events represent the most important actions performed by Contacts, such as buying products (PURCHASE) or adding them to the cart (CART). You can use External Events to create Automation Processes, prepare transaction statistics, and feed product recommendation strategies.
Important: External Events require whitelisting of the originating domain in the Monitoring Code settings. If you don’t see such an option, request the free activation by contacting Manago AI Customer Support. External Events are not transferred using the Frontend SDK and are transferred directly with a JavaScript function.
Important: An External Event can only be assigned to an existing Contact. If a Contact does not exist in Manago AI, the Event will be discarded.
Fields:
| Field | Limits | Description |
|---|---|---|
| owner* | 255 | Contact owner (Manago AI user account email) |
| email* | 254[?] | Email of Contact to whom the External Event is added |
| contactId | UUID | Contact ID in Manago AI; you will receive it in response to each request when adding or modifying a Contact. If you identify Contacts using contactId, the email field is optional. |
| date* | timestamp | UNIX timestamp [s] |
| contactExtEventType* | enum | External Event type, e.g., PURCHASE or CART |
| products | 2048 |
A comma-separated list of product IDs. Important: The product IDs sent in the Event should match the product IDs in your Product Catalog / XML Product Feed |
| value | float (19.2) | Event value (e.g., purchase total) |
| E-shop ID (location) | 36 |
Store identifier that matches the location field provided when creating the Product Catalog / XML Product Feed. It allows you to link an External Event to products from a specific store (or a specific language version of a store).
The location field can contain a maximum of 36 characters (only letters a-z, A-Z, numbers 0-9, and _ character). The value must not start with a number.
Tip: You can use the domain name without the dot, as in examplecom (or examplecom_ES for a specific language version of the store). |
| externalId | 255 | Additional External Event identifier, e.g., order ID from your eCommerce platform |
| detail1 | 20x255 |
External Event details that can be used in Automation Processes, in emails, or when exporting data via API. Examples of use: number of products purchased, value or category of the most expensive product, payment method, shipping method, packaging method |
| detail2 | ||
| detailX | ||
| description | 2048 | A general-purpose field that can be used for order notes, an order summary link, a cart recovery link, etc. |
External Event types
Manago AI supports a number of External Event types. PURCHASE and CART Events are automatically included in the analytic panels. The other External Events are general-purpose types—you can use them to transfer any actions performed by Contacts.
Available External Event types:
- PURCHASE
- CART
- TRANSACTION
- CANCELLATION
- RETURN
- VISIT
- PHONE_CALL
- OTHER
- RESERVATION
- CANCELLED
- ACTIVATION
- MEETING
- OFFER
- DOWNLOAD
- LOGIN
- SURVEY
Product Recommendations
Sample request:
const recommendationData = {
"strategyId": "21c2-...-3266",
"productIds": ["P123", "P456"],
"includeProductData": false,
"maxItems": 4
}
SMApi.setAll(recommendationData );
SMApi.execute('recommendation').then((result) => {
console.log(result);
});
Sample response:
When executed, the Frontend SDK returns a promise. A resolved promise contains the following response:
{
"products": [
{
"productId": "P123",
"urlAppendix": "utm_source=salesmanago&prod_id=3243454"
},
{
"productId": "P456",
"urlAppendix": "utm_source=salesmanago&prod_id=4324345"
},
{
"productId": "P789",
"urlAppendix": "utm_source=salesmanago&prod_id=9324354"
},
{
"productId": "P987",
"urlAppendix": "utm_source=salesmanago&prod_id=132436"
}
]
"requestId": "e29ad8ad-3d80-4bcb-92bb-3a3b11960445",
"finalResponse": true,
}
Sample response with product details limited to 2 products:
When executed, the Frontend SDK returns a promise. A resolved promise contains the following response:
{
"success": true,
"productIds": ["P123", "P234"],
"productData": [
{
"productId": "P123",
"urlAppendix": "utm_source=salesmanago&prod_id=4324345",
"name": "White t-shirt",
"mainCategory": "t-shirts",
"categories": [
"Winter collection",
"Linen products"
],
"description": "Classic t-shirt with...",
"productUrl": "https://example.com/shop/t-shirts/white-t-shirt",
"mainImageUrl": "https://example.com/media/white-t-shirt-cover.jpg",
"available": true,
"quantity": 90,
"price": 29.99,
"discountPrice": 19.99,
"systemDetails": {
"brand": "My Brand",
"manufacturer": "My Brand",
"popularity": 40,
"gender": 0,
"season": "summer",
"color": "white",
"bestseller": true,
"newProduct": false
},
"customDetails": {
"detail1": "linen",
"detail2": "short"
}
},
{
"productId": "P234",
"urlAppendix": "utm_source=salesmanago&prod_id=8765421",
"name": "White t-shirt",
"mainCategory": "t-shirts",
"categories": [
"Winter collection",
"Linen products"
],
"description": "Classic t-shirt with...",
"productUrl": "https://example.com/shop/t-shirts/white-t-shirt",
"mainImageUrl": "https://example.com/media/white-t-shirt-cover.jpg",
"available": true,
"active": true,
"quantity": 90,
"price": 29.99,
"discountPrice": 19.99,
"systemDetails": {
"brand": "My Brand",
"manufacturer": "My Brand",
"popularity": 40,
"gender": 0,
"season": "summer",
"color": "white",
"bestseller": true,
"newProduct": false
},
"customDetails": {
"detail1": "linen",
"detail2": "short"
}
}
]
}
This Frontend SDK method enables you to retrieve a list of recommended products – either as an array of product IDs or as an array of objects containing product data. The products are selected based on a recommendation strategy created in the Recommendation Architect. The recommendations can be personalized (per Contact/anonymous visitor) or generic (e.g., Most frequently purchased products or Products from selected brand).
Data obtained through this method can be used to display recommendations across various channels and tools, also external to (not associated with) Manago AI. For example, you can display them in your mobile app or on a POS or print them out.
Fields:
| Field | Limits | Description |
|---|---|---|
| strategyId* | UUID | Unique ID of a recommendation strategy created in the Recommendation Architect AND saved in the Recommendation Library. You can view the IDs of recommendation strategies in Menu → Recommendations → Recommendation Library. |
| productIds+ | 20x255 | Array of product identifiers from your eCommerce platform. IMPORTANT: Refer to the table below to check when this field is required. |
| includeProductData | Bool | Flag indicating whether the request should return only product IDs or the full scope of product data. |
| maxItems | Int | Maximum number of products to be returned. The allowed range is 1–50. The default value is 4. The number of returned products depends on the configuration of the recommendation strategy and may be different for each Contact and/or anonymous visitor. |
+ Important: Depending on the settings of the recommendation strategy created in Manago AI’ Recommendation Architect, this API method requires different input values. The Contact and anonymous visitor identifiers are retrieved automatically when available. To learn more about required fields, check the documentation for the API method >>
Response:
| Field | Description |
|---|---|
| products | Array of recommended products |
| id | Product ID |
| urlAppendix | String with additional URL parameters that should be appended to the product URL for analytical and tracking purposes. These parameters help you monitor user interactions and gather more data on product performance. NOTE: Without these parameters, Manago AI cannot provide analytics for recommendations retrieved via API. |
Product Collections
What are Product Collections?
Product Collections allow you to store information about products associated with individual Contacts. This data can later be used to target Contacts who have a specific product in a Collection or to synchronize Collection contents between different devices via Frontend SDK.
The most representative example is a Wishlist—when a Contact adds a product to their Wishlist, you can add it to the Wishlist Product Collection and later use the selector: Product Collection contains item(s) to select Contacts who took a liking to a specific product. Another example could be Interested in—a Product Collection for storing items a Contact has expressed interest in, for example, by hovering their cursor over a product or scrolling its description to a certain depth.
Product Collection types
There is no fixed list of Product Collection types. You can create a Product Collection using backend API v3 with any name you want. Some examples:
- Wishlist: A collection of products that a Contact has expressed interest in purchasing, and added them to a wishlist
- Interested in: A collection of products that a Contact has shown interest in, but have not added to their wishlist nor purchased.
- Purchased: A collection of products that a Contact has actually bought or ordered.
- Viewed: A collection of products that a Contact has viewed on an e-commerce platform or website.
- Favorites: A collection of products that a Contact has marked as their favorite for easy access.
- Recommended: A collection of products to be recommended to a Contact. This effectively lets you use Manago AI delivery channels with your internal or 3rd-party recommender system
- Reviewed: A collection of products that a Contact has reviewed or given feedback on.
Adding products to a Product Collection
Sample request:
let productCollectionData = {
"collectionUUID": "0a1b-...-2c3d",
"method": "add",
"productIds": [
"P0123",
"P1234",
"P2345"
]
};
SMApi.setAll(productCollectionData);
SMApi.execute('productCollection');
Sample request:
SMApi.set('collectionUUID', '0a1b-...-2c3d');
SMApi.set('productIds', ["P0123", "P1234", "P2345"]);
SMApi.set('method', "add");
SMApi.execute('productCollection');
You can add new products to a Product Collection using the following method:
Fields:
| Field | Limits | Description |
|---|---|---|
| collectionUUID* | UUID | UUID of a Product Collection. You can find it in Manago AI ➔ Integration Center ➔ Product Catalogs. The UUID is also returned when a Product Collection is created using the API v3 product/collection/add method. |
| productsIds* | 100*255 | Array of product IDs. All specified product IDs must match the IDs in the associated Product Catalog. |
Sample response:
When this method is executed, the Frontend SDK returns a promise. A resolved promise will have the following form:
{
"requestId": "a1b2-...-c3d4",
"finalResponse": true
}
Removing products from a Product Collection
Sample request:
let productCollectionData = {
"collectionUUID": "0a1b-...-2c3d",
"method": "remove",
"productIds": [
"P0123",
"P1234",
"P2345"
]
};
SMApi.setAll(productCollectionData);
SMApi.execute('productCollection');
Sample request:
SMApi.set('collectionUUID', "0a1b-...-2c3d");
SMApi.set('productIds', ["P0123", "P1234", "P2345"]);
SMApi.set('method', "remove");
SMApi.execute('productCollection');
You can remove products from a Product Collection using the following method:
| Field | Limits | Description |
|---|---|---|
| collectionUUID* | UUID | UUID of a Product Collection. You can find it in Manago AI ➔ Integration Center ➔ Product Catalogs. The UUID is also returned when a Product Collection is created using the API v3 product/collection/add method. |
| productsIds* | 100*255 | Array of product IDs. All specified product IDs must match the IDs in the associated Product Catalog. |
Sample request:
When this method is executed, the Frontend SDK returns a promise. A resolved promise will have the following form:
{
"requestId": "a1b2-...-c3d4",
"finalResponse": true
}
Live Chat Frontend API
Sample use: Open Live Chat window after 5 seconds on the website
window.addEventListener('message', function(event) {
let json;
try {
json = JSON.parse(event.data);
} catch {
return null;
}
if (json.topic === 'LIVE_CHAT_API_STARTED') {
this.setTimeout(() => {
this.window.smLiveChat.open();
}, 5000);
}
})
Sample use: Close small widget on mobile
window.addEventListener('message', function(event) {
let json;
try {
json = JSON.parse(event.data);
} catch {
return null;
}
if (json.topic === 'LIVE_CHAT_API_STARTED') {
if (window.innerWidth <= 768) {
smLiveChat.closeSmallWidget();
}
}
})
Live Chat is a one-to-one communication channel natively built into Manago AI. Using actions, you can programmatically open and close the Live Chat window and check its current state. Using events, you can set a callback that will be executed whenever the subscribed action is performed.
Actions
Methods available for smLiveChat object:
| Method | Description |
|---|---|
| Initialization | When the object is initialized, a post message is sent to window scope: topic: 'LIVE_CHAT_API_STARTED' |
smLiveChat.open() |
Allows you to force open the Live Chat window. |
smLiveChat.close() |
Allows you to force close the Live Chat window. |
smLiveChat.closeSmallWidget() |
Allows you to force close the small widget view. |
smLiveChat.isOpen() |
Allows you to check the current state of the Live Chat window. Note: The small widget display mode is considered a closed state. |
smLiveChat.toggleChat() |
Allows you to toggle (change to opposite) the state of the Live Chat window. |
Sample use: Add Google Analytics event on open
let liveChatEvent = function() {
gtag('event', 'screen_view', {
'module': 'Manago AI Live Chat'
});
}
window.addEventListener('message', function(event) {
let json;
try {
json = JSON.parse(event.data);
} catch {
return null;
}
if (json.topic === 'LIVE_CHAT_API_STARTED') {
smLiveChat.registerOnAfterOpen(liveChatEvent);
}
})
Sample use: Confirm before closing the Live Chat window
let showConfirmation = function() {
return confirm("Are you sure you want to close the Live Chat?");
}
window.addEventListener('message', function(event) {
let json;
try {
json = JSON.parse(event.data);
} catch {
return null;
}
if (json.topic === 'LIVE_CHAT_API_STARTED') {
smLiveChat.registerOnbeforeClose(showConfirmation);
}
})
Events
Methods available for smLiveChat object:
| Method | Description |
|---|---|
| Initialization | When the object is initialized, a post message is sent to window scope: topic: 'LIVE_CHAT_API_STARTED' |
smLiveChat.registerOnBeforeOpen(callback) |
This callback function is executed before the Live Chat widget is opened. Additionally, this method waits for a boolean response:
|
smLiveChat.registerOnAfterOpen(callback) |
This callback function is executed after the Live Chat widget is opened. This method does not wait for a response. |
smLiveChat.registerOnBeforeClose(callback) |
This callback function is executed before the Live Chat widget is closed. Additionally, this method waits for a boolean response:
|
smLiveChat.registerOnAfterClose(callback) |
This callback function is executed after the Live Chat widget is closed. This method does not wait for a response. |
smLiveChat.registerOnBeforeCloseSmallWidget(callback) |
This callback function is executed before the Live Chat small widget is closed. This method does not wait for a response. |
smLiveChat.registerOnAfterCloseSmallWidget(callback) |
This callback function is executed after the Live Chat small widget is closed. This method does not wait for a response. |
Web Push Frontend API
Sample use (display consent prompt with specified ID):
window.addEventListener('message', (event) => {
if (event.data) {
const data = JSON.parse(event.data);
if (data.topic === 'WEB_PUSH_API_STARTED') {
smWebPushApi.displayConsentForm('08673fa0-dc17-40ac-8b90-5867ae8d5801');
}
}
});
Sample use (display consent prompt with specified ID on button click):
HTML:
<button class="consent__button">Subscribe to our notifications!</button>
JavaScript:
const button = document.querySelector('.consent__button');
button.style.display = 'none';
window.addEventListener('message', (event) => {
if (event.data) {
const data = JSON.parse(event.data);
if (data.topic === 'WEB_PUSH_API_STARTED') {
button.style.display = 'block';
button.addEventListener('click', () => {
smWebPushApi.displayConsentForm('08673fa0-dc17-40ac-8b90-5867ae8d5801');
});
}
}
});
Sample use (capturing the FCM token):
window.addEventListener('message', function(event) {
if (event.origin !== window.location.origin) return;
if (event.data?.topic === 'WEB_PUSH_FCM_TOKEN') {
sendTokenToServer(event.data.token);
}
});
Web Push notifications are brief, browser-based messages that can be sent both to Contacts and anonymous visitors. The Manago AI API offers functionalities for programmatically requesting consent to these notifications and retrieving consent statuses, ensuring adherence to user preferences and regulatory requirements.
Methods available for smWebPushApi object:
| Method | Description |
|---|---|
| Initialization | When the object is initialized, a post message is sent to window scope: topic: 'WEB_PUSH_API_STARTED' |
smWebPushApi.displayConsentForm(consentFormId) |
Allows you to display the consent prompt that has the specified ID. You can find the consentFormId by going to Manago AI → Channels → Web Push → Consent prompts and expanding the selected item. |
var _sm_wp_token_emit = true; |
When this flag is set to true, the Monitoring Code emits a message with the topic WEB_PUSH_FCM_TOKEN containing the FCM token once it is received. |
Visit monitoring Frontend API
Sample use: Register current page, with parameters, without anchor
const currentPathname = window.location.pathname;
sm.api.registerVisit(currentPathname, false, true);
Response:
void
Website visit monitoring is built into the Manago AI Monitoring Code. With this API, you can extend your visitor monitoring capabilities, transferring visit events directly with JavaScript, which can be especially useful for websites built as SPAs. You can also get visit and pageview data for the current visitor.
Register a monitored visit
Method: sm.api.registerVisit(pathname, skipParams, skipAnchor);
| Parameter | Limits | Description |
|---|---|---|
| pathname* | 2048 | The path part of the URL, e.g. store/product/turtleneck-sweater.html |
| skipParams | Boolean | Flag allowing you to skip URL parameters, i.e., the part of the URL after the question mark (?) character |
| skipAnchor | Boolean | Flag allowing you to skip the anchor, i.e., the part of the URL after the hashtag (#) character |
Response:
This method does not return a value (void).
Sample use:
sm.api.pageStats();
Sample response:
{
"visits": 4,
"views": 57,
"ts": 1659938888000,
"isNewSession": false
}
Get visit statistics
Method: sm.api.pageStats();
Response:
| Parameter | Limits | Description |
|---|---|---|
| visits | Integer | Number of visits to any page on the current domain. A new visit is initiated each time a new pageview takes place more than 3 hours after the last pageview. |
| views | Integer | Number of pageviews, i.e., the number of times a new page is loaded on the current domain. |
| ts | UNIX timestamp (ms) | Timestamp of the last pageview (UNIX timestamp, GMT+0). |
| isNewSession | Boolean | This flag will be set to true if the current pageview is the first during this visit. |