How to track if a web page is opened in TWA app

The Trusted Web Activity (TWA) in Chrome has made it so easy to package and publish any website as an app.

But the problem arises when we want to track when your website was opened inside the TWA app.

Usually we can easily do this in a webview app by appending a custom string to the user agent. But that option is not available in TWA.

However, we can easily track the entry into the app using a custom query string.

TWA apps allow us to set start_url of the app to include any custom query string. So, when the app will be launched, it will open the first page after appending the given query string. You can detect that to track the entry into the app.

But this does not work when app is directly opened because of the intent when user clicked on a link to the website. In that case, you can detect the HTTP referer which is in the format- android-app://<package name>/

So, to summarize, you just need to check both these conditions to identify if a user has opened a page in your app.

If you want to track each and every page view of the user inside the app, it is possible by persisting the state through the query string. I have written an article about persisting state through query string using Javascript- How to persist state through query string in url

But this query string method may or may not be reliable as TWA apps allows users to directly open links from inside the TWA app into the main Chrome app. So, query string will then be passed to the Chrome app and your analytics will be skewed. But in any case, you will get a fair idea about user activity inside your TWA app.

Leave a Comment

Your email address will not be published. Required fields are marked *