App Helper Script

Posted on 28. July 2021 by Jan Bunk


We have created a JavaScript script file with a couple of useful helper functions that simplify the communication between your website and your app.

Usage

You can either copy the script (or parts of it) and host it yourself, or load it directly from our website.

View the app helper script

<script src="https://webtoapp.design/static/js/app-helper.js"></script>

The script is minified, but not obfuscated, so you can use a javascript formatter/beautifier if you want to take a look at the functions' implementations.

Functions

executeWhenAppReady

After every page load the app first needs to inject some javascript into the loaded page. This is to allow your website to call javascript functions like setNotificationTopicSubscriptionStatus. Unfortunately, this is not instant, so if you try to call a javascript function that interacts with the app really quickly after the page load, they might not be defined yet.

You can avoid this by wrapping the code that interacts with your app in a call to executeWhenAppReady.

When your website is loaded using a browser, the code inside executeWhenAppReady will not be executed. This means you can also use this function to detect whether your website was loaded by the app or a browser. An alternative method for this is to check the user agent, as explained in our guide on filtering out app users in your website analytics.


<script>
    // setNotificationTopicSubscriptionStatus interacts with the app, so it won't immediately be available after a new page was loaded

    executeWhenAppReady(function () {
        console.log("Website was loaded by the app and the app is ready for interaction");

        // by running inside a executeWhenAppReady call, we avoid potentially calling it while still undefined
        setNotificationTopicSubscriptionStatus(true, "new-games");
    });
</script>

getAppPlatform

You can use this function to find out on what operating system the current user is using the app.

This function doesn't need to be wrapped inside executeWhenAppReady. It can also be used to check if the current user is using the app (check that the returned value is not null). This does not guarantee that the app is ready for JavaScript interaction yet though. If you want to call JavaScript functions that interact with the app, you should still wrap them in executeWhenAppReady.

isInCustomTab, getCustomTabData, closeCustomTab

These functions are used for managing custom tabs.


<script>
    // possible return values are:
    // "android"
    // "ios"
    // null -> not using app, most likely a regular browser
    var platform = getAppPlatform();
</script>