2021-12-10

Tech Programing

程式人小天地

Opening an URL in Webview after clicking on notification (when app is closed)

2 min read


I have a React Native (Expo managed worflow) app that receives push notifications. I pass an url, so that when the user clicks on the notification, it will open the Webview to that url.

When the app is in the foreground and background it works fine.

If the user gets the notification when the app is closed (and not currently running) then the app opens, but does not go to that url. After som investigation I found that this Notifications.addNotificationResponseReceivedListener does not fire:

      // User tapped on notification
      responseListener.current = Notifications.addNotificationResponseReceivedListener(
          (response) => {
              console.log('This does not output to the console when app was closed!');
              setNotification(response.notification);
              setWebViewUri(response.notification.request.content.data.url);
          }
      );

Full simplified code:

// Notification handler settings
Notifications.setNotificationHandler({
  handleNotification: async () => {
    return {
      shouldShowAlert: true,
      shouldPlaySound: false,
      shouldSetBadge: false
    };
  },
});


// Main app component
export default function App() {
  // Reference to Webview
  const webviewRef = useRef(null);

  // States
  const [webviewUri, setWebViewUri] = useState('https://www.......');

  // Push notification related states
  const [expoPushToken, setExpoPushToken] = useState('');
  const [notification, setNotification] = useState();
  const notificationListener = useRef();
  const responseListener = useRef();

  // Receive push notifications
  useEffect(() => {
      // Get token and send it to backend after launching the app
      // sendTokenToBackend();

      // Notification is received and app is running in foreground
      notificationListener.current = Notifications.addNotificationReceivedListener(setNotification);

      // User tapped on notification and app is running in background
      responseListener.current = Notifications.addNotificationResponseReceivedListener(
          (response) => {
              console.log('This does not output to the console when app was closed!');
              setNotification(response.notification);
              setWebViewUri(response.notification.request.content.data.url);
          }
      );

      return () => {
          notificationListener.current &&
              Notifications.removeNotificationSubscription(notificationListener.current);
          responseListener.current &&
              Notifications.removeNotificationSubscription(responseListener.current);
      };
  }, []);

  // Main application screen
  return (
        <WebView ref={webviewRef} source={{ uri: webviewUri }} />}
  );
}

Thanks!



Source link

資料來源:Stackoverflow

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *