Skip to content

Instantly share code, notes, and snippets.

@thanhtungka91
Forked from andreban/trusted-web-activity.mjs
Created October 13, 2021 05:57
Show Gist options
  • Save thanhtungka91/ee029e8454be0111c2dbaa20cbc60512 to your computer and use it in GitHub Desktop.
Save thanhtungka91/ee029e8454be0111c2dbaa20cbc60512 to your computer and use it in GitHub Desktop.
/*
* Copyright 2020 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const TWA_PROTOCOL = 'android-app:';
const KEY_IS_TWA = 'isTrustedWebActivity';
/**
* This method should run on every page load. `packageName` corresponds to the ID
* of the app on the Play Store. This is important to differentiate from the page
* being opened from a Custom Tab, for instance.
*/
export function isTrustedWebActivity(packageName) {
const sessionStorageStatus = sessionStorage.getItem(KEY_IS_TWA);
if (sessionStorageStatus === 'true') {
return true;
}
const referrer = document.referrer.trim();
if (referrer.length === 0) {
return false;
}
const referrerUrl = new URL(referrer);
if (referrerUrl.protocol === TWA_PROTOCOL
&& referrerUrl.hostname === packageName) {
sessionStorage.setItem(KEY_IS_TWA, 'true');
return true;
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment