Detecting if a user is offline

How do I check whether a user is online or offline in my app's JS?

I want to disable a certain workflow if the user is offline.

Online/offline is not binary. There are many other intermediate states such as a slow network or intermittent connectivity, which cannot be detected by a single check. The best is to design the online process to degrade gracefully if it fails with a network error.

That being said, you can do a check to see if you reach the JourneyApps servers. You can create a CloudCode task that you call from the app to check for connectivity.

is_online: index.js

Please activate the Apptrigger on your ClodeCode task.

export async function run() {
    return 'Hello from the other side';
}

App side JS code:

Then from your app side JS code, wrap the CloudCode call in a try-catch. If it succeeds, you know that you are not offline.

function isOnline () {
    try {
        var result = CloudCode.callTask('is_online');
        console.log(result);
        return true;
    }catch (e) {
        console.log('Not online! ', e);
        return false;
    }
}
2 Likes

@DavidHoltzhausen what does “The best is to design the online process to degrade gracefully if it fails with a network error.” mean? Could you elaborate?

@KobieBotha Currently OnlineDB calls fail with an ugly message HTTPS 0 Error. You could wrap this in a try-catch and either retry or display a more descriptive error: function getOnlineData () { try { // OnlineDB call } catch (e) { console.log(Online error ${e}); // Do something else dialog(‘Offline’,‘Unable to connect to the online server, please try again.’); }}

This is good advise, except that when you catch an error in a helper function, then the parent function does not know something went wrong and it continues to run. You could use throw ‘Internet error’ but this still produces a dialog with the title ‘Error’ which is also not ideal. Can you suppress the throw dialog?

@martin the function in the example returns either true or false based on if it is online or not. So you could take out the console.log in the catch and leave it up to the parent function to decide what it needs to do with the feedback. The function was just a suggestion for something to start with :slight_smile: