Push notifications

Hi All

Apologies been snowed under with a few projects

Create a onesignal account setup the basic site paste the below in your header for custom code, get users to click subscribe on mobile or web

get sending push notifications via one singal or build a GUI/ API to send from softr with a custom webhook

<!-- OneSignal SDK -->
<script src="https://cdn.onesignal.com/sdks/web/v16/OneSignalSDK.page.js" defer></script>

<script>
    
    const createNetworkStatusBanner = () => {
        const banner = document.createElement('div');
        banner.id = 'network-status-banner';
        banner.style.display = 'none';
        banner.style.position = 'fixed';
        banner.style.top = '0';
        banner.style.left = '0';
        banner.style.right = '0';
        banner.style.padding = '10px';
        banner.style.textAlign = 'center';
        banner.style.backgroundColor = '#f44336';
        banner.style.color = 'white';
        banner.style.fontWeight = 'bold';
        banner.style.zIndex = '9999';
        document.body.appendChild(banner);
    };

    const checkNetworkStatus = () => {
        const isOnline = navigator.onLine;
        const banner = document.getElementById('network-status-banner');
        banner.style.display = isOnline ? 'none' : 'block';
        banner.textContent = isOnline ? '' : 'You are offline. Please check your internet connection.';
    };

    createNetworkStatusBanner();
    checkNetworkStatus();
    window.addEventListener('online', checkNetworkStatus);
    window.addEventListener('offline', checkNetworkStatus);

    navigator.serviceWorker.ready
        .then((registration) => {
            console.log("Service worker is active and registered:", registration);
            initializeOneSignal();
        })
        .catch((error) => {
            console.error("Service worker registration failed:", error);
        });

    const initializeOneSignal = () => {
        window.OneSignalDeferred = window.OneSignalDeferred || [];
        OneSignalDeferred.push(async function(OneSignal) {
            
            await OneSignal.init({
                appId: "One-Signal ID",
                allowLocalhostAsSecureOrigin: true,
                notifyButton: {},
            });
            
 
   OneSignal.Notifications.addEventListener("event", (event) => {
    console.log('Notification event:', event); // Log all notification events
});         
        // Attach the handler for notification clicks
        OneSignal.Notifications.addEventListener("opened", (payload) => {
    console.log('Notification payload:', payload); // Log the full payload
    handleNotificationClick(payload);
});



            const updateUserTags = async () => {
                const loggedInUser = window.logged_in_user; // Replace with actual user data source
                if (loggedInUser) {
                    const tags = { estate_name: loggedInUser.estate_name };

                    try {
                        await OneSignal.User.addTags(tags);
                        console.log('Tags successfully updated:', tags);
                        await OneSignal.User.addEmail(loggedInUser.email);
                        console.log('Email successfully added:', loggedInUser.email);
                        await OneSignal.User.addSms(loggedInUser.cell.toString());
                        console.log('User logged in with Cell:', loggedInUser.cell);
                        await OneSignal.User.addAlias("full_name", `${loggedInUser.name} ${loggedInUser.surname}`);
                        console.log('Alias successfully added:', loggedInUser.name, loggedInUser.surname);
                        await OneSignal.login(loggedInUser.uuid.toString());
                        console.log('User logged in with External User ID:', loggedInUser.uuid);
                    } catch (error) {
                        console.error('Error updating tags or setting external ID:', error);
                    }
                } else {
                    console.log('No logged-in user found, not sending user-specific tags, email, or external ID.');
                }
            };

            const handleSubscriptionStatusChange = async (isSubscribed) => {
                console.log('Subscription status changed:', isSubscribed ? 'Subscribed' : 'Unsubscribed');
                if (isSubscribed) {
                    await updateUserTags();
                } else {
                    console.log('Unsubscribed - user tags and data not updated');
                }
            };

const checkSubscriptionStatus = async () => {
    try {
        const permission = await OneSignal.Notifications.permission;
        console.log('Current notification permission:', permission, typeof permission);

        if (permission === true) {
            const isSubscribed = await OneSignal.User.PushSubscription.optedIn;
            console.log('Device subscription status:', isSubscribed ? 'Subscribed' : 'Not Subscribed');

            if (isSubscribed) {
                // Retrieve the subscription ID and token
                const subscriptionId = await OneSignal.User.PushSubscription.id; // Save the subscription ID
                
                if (subscriptionId) {
                    const subscriptionToken = await OneSignal.User.PushSubscription.token; // Use await to get the token

                    console.log('Subscription ID:', subscriptionId);
                    console.log('Subscription Token:', subscriptionToken);
                } else {
                    console.log('No subscription ID found.'); // Handle the case where subscriptionId is not available
                }
            } else {
                console.log('User has permission but is not subscribed, prompting for subscription...');
                await OneSignal.User.PushSubscription.optIn(); // Prompt user to subscribe
            }

            await handleSubscriptionStatusChange(isSubscribed);
        } else {
            console.log('Notifications are not permitted by the user.');
        }
    } catch (error) {
        console.error('Error checking subscription status:', error);
    }
};


            OneSignal.Notifications.addEventListener("permissionChange", checkSubscriptionStatus);
            OneSignal.User.PushSubscription.addEventListener("change", (event) => {
                handleSubscriptionStatusChange(event.current.optedIn);
            });

            await checkSubscriptionStatus();

            const sendDataPeriodically = () => {
                const interval = 2 * 60 * 1000; // 2 minutes
                setInterval(async () => {
                    try {
                        const isSubscribed = await OneSignal.User.PushSubscription.optedIn;
                        if (isSubscribed) {
                            await updateUserTags();
                            console.log('User data sent to OneSignal.');
                        } else {
                            console.log('User is not subscribed, skipping data send.');
                        }
                    } catch (error) {
                        console.error('Error sending data to OneSignal:', error);
                    }
                }, interval);
            };

            sendDataPeriodically();
        });
    };
</script>
3 Likes

@cor_prettysim.pl you might want to check this out :eyes:

1 Like

Hi @Jjenglert thank you for tagging me and for continuing to try and help me solve this. However, according to OneSignal and some research this wont work for a PWA.

I managed to get it to work in the browser but not as a PWA and from what I have seen it seems that this is not possilbe and that a native app or native app skin might be the only option.

Thank you anyway @Jjenglert and thank you for sharing and good work @Zaque7

@ cor_prettysim.pl

mines working in the softr PWA and running perfectly

Appreciate the code @Zaque7. Can you share an example app with it configured? Custom codes don’t always work, or work well, even the ones that Softr provides, for a lot of different reasons.

Hey Zaque7, thanks for posting! Is the end result just like an iOS push? Can you post a vid of what it looks like for the receiver to get one of these notifications?

My goal is that the user has the phone in his pocket and gets a notification when he has received a message in my Softr app so he knows to open the PWA app and check the message. Is that what you’re able to accomplish with OneSignal?

Hi, Matt. Can you tell me how do you do that? The badge notification on you app?

Here is the guide to do it: New! In-App Notifications & Notification Center Feature

Although some CSS selectors might have changed (or not!), I haven’t checked them in months. Maybe Matt has insights/updates about it, if necessary.

2 Likes

Thanks! Matthieu.