JSAPI

Since 9.1

addNotifyListener

Register listener to listen to native notification event.

Usage

AlipayJSBridge.call('addNotifyListener', {
  name:'fortest'
}, function(result) {
  console.log(result);
});

Example

Basic Function

<h1>Please click on the buttons below</h1>
<p>Although the following test is conducted in one page, you can use this API to listen to events happens in other pages</p>

<a href="#" class="btn start">Start Listening</a>
<a href="#" class="btn stop">Stop Listening</a>
<a href="#" class="btn send">Notify</a>
<script>
function callback(e) {
  alert(JSON.stringify(e));
};

function ready(callback) {
  // Invoke directly if JSBridge is already injected
  if (window.AlipayJSBridge) {
    callback && callback();
  } else {
    // Otherwise listen to `AlipayJSBridgeReady` event
    document.addEventListener('AlipayJSBridgeReady', callback, false);
  }
}
ready(function(){
  document.querySelector('.start').addEventListener('click', function() {
    AlipayJSBridge.call('addNotifyListener', {
      name:'NEBULANOTIFY_TEST_EVENT' 
      // H5 event name must be prefixed with NEBULANOTIFY_
    }, callback);
  });

  document.querySelector('.stop').addEventListener('click', function() {
    AlipayJSBridge.call('removeNotifyListener', {
      name:'NEBULANOTIFY_TEST_EVENT'       // H5 event name must be prefixed with NEBULANOTIFY_
    }, function(e) {
      alert(JSON.stringify(e));
    });
  });

  document.querySelector('.send').addEventListener('click', function() {
    AlipayJSBridge.call('postNotification', {
      name:'NEBULANOTIFY_TEST_EVENT',       // H5 event name must be prefixed with NEBULANOTIFY_
      data: {
        hello: 'world'
      }
    });
  });
});
</script>

API

AlipayJSBridge.call('addNotifyListener', {
  name, keep
}, fn)

Input Parameters

NameTypeDescriptionMandatoryDefault
namestringName of notificationY
keepstringWhether or not to keep listening to this event within the lifecycle of ViewControllerNtrue
fnfunctionCallback functionN

Output Parameters

The event data is described in parameter result:{} that passed to the callback function

Errors

ErrorDescription
4No permission
12Duplicated event name in the same page

Remarks

  • Please prefix the event name with NEBULANOTIFY_ if the event is to be emitted from H5 page
  • Use removeNotifyListener before calling addNotifyListener to avoid duplicated event names
  • The event listening is is automatically revoked after the first event emission if the input parameter keep is set to false
  • The event data from the callback function is stringified in Android platform, please use JSON.parse to extract the data in a try and catch block