The frontend can use this API to send notifications to the client. The HTML5 page automatically adds the NEBULANOTIFY_ prefix to the name parameter. The resulting string is then sent as the notification name.
In Android versions earlier than 10.1.0, addNotifyListener could not receive notifications from postNotification if the data field was empty. This restriction was removed in version 10.1.60, and addNotifyListener now accepts empty data.
On Android, broadcasts are sent using LocalBroadcastManager. To receive these broadcasts, you must set up a listener for NEBULANOTIFY_ + name.
Use the postNotification API
AlipayJSBridge.call('postNotification', {
name:'fortest',
data:{}
}, function (result) {
console.log(result);
});Code example
The following example is a demo of a basic feature:
<h1>Click the buttons below to test</h1>
<p>This only tests the case within the same page. This API can communicate between different applications.</p>
<a href="#" class="btn start">Start Listener</a>
<a href="#" class="btn stop">Stop Listener</a>
<a href="#" class="btn send">Send Notification</a>
<script>
function callback(e){
alert(JSON.stringify(e));
};
function ready(callback) {
// If jsbridge is already injected, call it directly
if (window.AlipayJSBridge) {
callback && callback();
} else {
// If not injected, listen for the injection event
document.addEventListener('AlipayJSBridgeReady', callback, false);
}
}
ready(function(){
document.querySelector('.start').addEventListener('click', function(){
AlipayJSBridge.call('addNotifyListener', {
name:'NEBULANOTIFY_TEST_EVENT' // To listen for an event sent from HTML5, you must use the `NEBULANOTIFY_` prefix.
}, callback);
});
document.querySelector('.stop').addEventListener('click', function(){
AlipayJSBridge.call('removeNotifyListener', {
name:'NEBULANOTIFY_TEST_EVENT' // To listen for an event sent from HTML5, you must use the `NEBULANOTIFY_` prefix.
}, function(e){
alert(JSON.stringify(e));
});
});
document.querySelector('.send').addEventListener('click', function(){
AlipayJSBridge.call('postNotification', {
name:'TEST_EVENT', // To listen for an event sent from HTML5, you must use the `NEBULANOTIFY_` prefix.
data: {
hello: 'world'
}
}, function(e){
alert(JSON.stringify(e));
});
});
});
</script>API
AlipayJSBridge.call('postNotification', {
name, data
}, fn)Input parameters
Name | Type | Description | Required | Default value |
name | string | The name of the notification. | Yes | "" |
data | object | The information to send to the client. On Android, the API traverses the JSON-formatted data. It converts the value of each item to a string before sending. Ensure the data format is compatible. | N | - |
fn | function | The callback function. | N | - |
Output parameters
result: {success}: The parameter that is passed to the callback function.
Name | Type | Description |
success | bool | Indicates whether the message was sent successfully. |
Error codes
Error code | Description |
4 | No permission to call. |