How to listen onsignal web push notification events using Javascript?

Viewed 767

I want to show an alert when a new web push notification is received from OneSignal. I tried to create an event listener but alert or log is not showing. I'm not sure what's wrong here. The App is able to get notifications and showing it.

I tried to follow this documentation https://documentation.onesignal.com/docs/web-push-sdk#notification-display

APP: ReactJS

OneSignal: Custom site setup

Here is my code.

index.html

<script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async=""></script>
<script>
    window.OneSignal = window.OneSignal || [];
</script>

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const OneSignal = window.OneSignal
OneSignal.push(function () {
  OneSignal.init({
    appId: 'app id'
  })
})

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

reportWebVitals();

App.js

import './App.css';


function App() {
  const OneSignal = window.OneSignal
  const chkPer = () => {
    OneSignal.push(["getNotificationPermission", function (permission) {
      console.log("Site Notification Permission:", permission);
      // (Output) Site Notification Permission: default
    }]);
  }

  const regPush = () => {
    OneSignal.push(function() {
      OneSignal.showNativePrompt();
    });
  }
  
  OneSignal.push(function() {
    OneSignal.on('notificationDisplay', function(event) {
      console.warn('OneSignal notification displayed:', event);
    });
    
    //This event can be listened to via the `on()` or `once()` listener
  });
  

  window.addEventListener('notificationDisplay', (event) => {
    console.log(event);
    alert('OS event')
  });

  return (
    <div className="App">
      <button onClick={chkPer}>Check Permission</button>
      <button onClick={regPush}>register for Notification</button>
    </div>
  );
}

export default App;

0 Answers
Related