addMessageListener()
The addMessageListener() function (client-side) sets up a listener for incoming messages in the current window. It's used to handle messages received from a parent window. For example, you can use it for messages from transactions, SuiteCommerce web stores, or other ecommerce platforms.
You can listen for all incoming messages by providing a callback function without specifying a message type. Alternatively, you can target specific message types by providing both the message type and a callback function.
You can combine addMessageListener() and sendMessage() to enable messaging between different browser windows. For more information, see sendMessage().
Syntax
Depending on how you want to handle incoming messages, there are two syntax formats for the addMessageListener() function:
-
To listen for all incoming messages, use:
addMessageListener(function(data) { // Handle any message data }); -
To listen for specific message types, use:
addMessageListener('messageType', function(data) { // Handle specific message data type });
Examples
The following examples show how to use the addMessageListener() function.
Listening to Specific Messages
This example sets up a listener for messages of the type get-options. When a message with this type is received, the provide function is called, and the message data will be passed as the argument data. In this example, the data will be logged to the browser console.
addMessageListener('get-options', function(data) {
console.log('Received data:', data);
});
If a window sends this message:
window.postMessage({
type: 'get-options',
data: {
deskType: 'Office Desk'
}
}, '*');
Then, the callback function will log:
Received data: {
deskType: 'Office Desk'
}
Listening to All Messages
This code example sets up a universal message listener, which listens for all messages, regardless of their type. Whenever a message is received, the callback function runs and logs the message data to the console.
addMessageListener(function(data) {
console.log('Received data:', data);
});
If a window sends this message:
window.postMessage({
deskType: 'Office Desk',
model: 'A1000-AB1'
}, '*');
Then, the callback function will log:
Received data: {
deskType: 'Office Desk',
model: 'A1000-AB1'
}
Setting Up a Listener and Sending a Message
In this example, the listener waits for messages of type get-options. When such a message is received, it logs the data to the console. The sendMessage() function sends a get-options message with the specified data to the parent window.
// Setting up a listener for 'get-options' messages
addMessageListener('get-options', function(data) {
console.log('Received options:', data);
});
// Sending a 'get-options' message to the parent window
sendMessage('get-options', {
deskType: 'Office Desk'
});