16

I'm opening my page inside a Trusted Web Activity and I want to detect when it's being opened inside it to customize behaviour and for analytics purposes. How can I detect that the page is being opened from the TWA?

andreban
  • 4,621
  • 1
  • 20
  • 49

2 Answers2

21

There are three options that will help detecting if the page is being opened from inside a Trusted Web Activity:

  1. When opening the page, the Referral will be android-app://<twa.package.name>, where twa.package.name is the package name used on the Android side of the Trusted Web Activity. In JavaScript, check if the users is in the Trusted Web Activity:
document.referrer.includes('android-app://<twa.package.name>')
  1. Adding an URL parameter. Append a query string to the end of the URL that is launched with the PWA. There's more information in the Passing Information into a Trusted Web Activity using Query Parameters article.

  2. Request Headers: you can now set custom request headers when the origin is verified against the app. This article explains how do do it. This approach is not yet supported by all browsers though.

andreban
  • 4,621
  • 1
  • 20
  • 49
  • 2
    FYI, There is some drawbacks on 1., if the user sets his Android Phone's default browser to others, i.e. Brave, document.referrer will return empty. In the end query parameter was used instead. – Han Sep 24 '20 at 08:24
  • NOTE that the first method is **not reliable** and you should not use it. – shamaseen Mar 05 '21 at 17:34
  • Why isn't the first method reliable? The only caveat is that the referrer will be set when loading the first page. When an internal navigation happens, referrals from the web app will be set accordingly. A script like the following can use to save the information across page loads https://gist.github.com/andreban/550f34ed19cc3d7f51d0f95bd246a1a6 – andreban Apr 17 '21 at 21:07
1

As andreban stated I used:

document.referrer.includes('android-app://')

which returns true if it comes from TWA.

double-beep
  • 5,031
  • 17
  • 33
  • 41
Gedoba
  • 35
  • 3
  • 2
    please not that, the document.referrer will be empty if you call window.location.reload() – dehamzah Jun 20 '19 at 10:12
  • 1
    @DedeHamzah One thing that helps is using sessionStorage to save if this line ever evaluated to true. Then even a reload wouldn't clear it. – jahooma Aug 20 '19 at 07:47
  • 3
    Checking for`android-app://` is not enough and will give you wrong results. You should include the package name as part of the check, other wise **any** android app opening your page inside a regular browser or a Custom Tab will be identified as coming from the Trusted Web Activity. – andreban May 02 '20 at 07:57
  • Does it work on Chromebook? – Alok Jan 04 '22 at 13:06