Use this API to add a listener for native notifications.
How to use the addNotifyListener API
AlipayJSBridge.call('addNotifyListener', {
name:'fortest'
}, function (result) {
console.log(result);
});Code sample
The following example demonstrates the basic features:
<h1>Click the buttons below to test</h1>
<p>This example only tests communication within a single page. This API can also be used for communication 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, 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' // Events sent from HTML5 must be listened for with the NEBULANOTIFY_ prefix.
}, callback);
});
document.querySelector('.stop').addEventListener('click', function() {
AlipayJSBridge.call('removeNotifyListener', {
name:'NEBULANOTIFY_TEST_EVENT' // Events sent from HTML5 must be listened for with the NEBULANOTIFY_ prefix.
}, function(e) {
alert(JSON.stringify(e));
});
});
document.querySelector('.send').addEventListener('click', function() {
AlipayJSBridge.call('postNotification', {
name:'TEST_EVENT', // Events sent from HTML5 must be listened for with the NEBULANOTIFY_ prefix.
data: {
hello: 'world'
}
});
});
});
</script>API
When you listen for an event sent from an HTML5 page, add the
NEBULANOTIFY_prefix to the event name.Before you call
addNotifyListener, call the remove operation to prevent errors caused by adding the same listener multiple times.If you set keep to false, the listener is automatically unregistered after the event is triggered once.
On Android, the data returned in the callback is a single-level key-value pair. If the value is an Object when postNotification is called, Android stringifies it using
JSON.stringify. You must then parse the value usingJSON.parse.
AlipayJSBridge.call('addNotifyListener', {
name, keep
}, fn)Input parameters
Name | Type | Description | Required | Default |
name | String | The name of the notification. | Yes | "" |
keep | String | Specifies whether to listen for the notification throughout the ViewController lifecycle. | N | "true" |
fn | Function | The callback function. | N | - |
Output parameter
result: {}: The parameter that is passed to the callback function. This object contains the event message.
Error codes
Error code | Description |
4 | No permission to call. |
12 | Listening for a notification with the same name multiple times on the same page. |