You can call this operation to add native notification listening.
addNotifyListener API usage instruction
AlipayJSBridge.call('addNotifyListener', {
name:'fortest'
}, function (result) {
console.log(result);
});
Code sample
The following example shows the basic functions.
<h1>Click the following button to perform a test.</h1>
<p>In this example, multiple operations are called on the same page. This API supports communication among different apps.</p>
<a href="#" class="btn start">Start listening.</a>
<a href="#" class="btn stop">Stop listening.</a>
<a href="#" class="btn send">Send a notification.</a>
<script>
function callback(e) {
alert(JSON.stringify(e));
};
function ready(callback) {
// Call JS Bridge if it has been injected.
if (window.AlipayJSBridge) {
callback && callback();
} else {
// Listen to the injection event if it has not been injected.
document.addEventListener('AlipayJSBridgeReady', callback, false);
}
}
ready(function(){
document.querySelector('.start').addEventListener('click', function() {
AlipayJSBridge.call('addNotifyListener', {
name:'NEBULANOTIFY_TEST_EVENT' // Events sent by the HTML5 must be listened to by adding the prefix NEBULANOTIFY_.
}, callback);
});
document.querySelector('.stop').addEventListener('click', function() {
AlipayJSBridge.call('removeNotifyListener', {
name:'NEBULANOTIFY_TEST_EVENT' // Events sent by the HTML5 must be listened to by adding the prefix NEBULANOTIFY_.
}, function(e) {
alert(JSON.stringify(e));
});
});
document.querySelector('.send').addEventListener('click', function() {
AlipayJSBridge.call('postNotification', {
name:'TEST_EVENT' // Events sent by the HTML5 must be listened to by adding the prefix NEBULANOTIFY_.
data: {
hello: 'world'
}
});
});
});
</script>
API
AlipayJSBridge.call('addNotifyListener', {
name, keep
}, fn)
Input parameters
Name | Type | Description | Required | Default value |
---|---|---|---|---|
name | String | Notification name | Y | “” |
keep | String | Indicates whether to keep listening to this notification within the lifecycle of ViewController | N | “true” |
fn | Function | Callback function | N |
Output parameters
result: {}
: The parameter carried by the callback function, corresponding to an event message.
Error codes
Error code | Description |
---|---|
4 | Unauthorized call |
12 | Listen to the same notification multiple times on the same page |
Precautions
If an event being listened to is sent by the HTML5, add the
NEBULANOTIFY_
prefix.Before configuring
addNotifyListener
, perform a remove operation to avoid errors caused by multiple add operations.If keep is set to false, listening is automatically unregistered after the event is triggered once.
The data returned by Android contains only one layer of key/value pairs. If the value is Object during
postNotification
, Android performs aJSON.stringify
operation on the value. We recommend that you performtry{ JSON.parse }
during usage.