Your MobiLoud app adds "canvas" to the user agent string when users browse through the app. Simply check if "canvas" is present in the user agent to detect app users.
App user: User agent contains "canvas"
Website user: User agent doesn't contain "canvas"
Check the user agent directly whenever you need to detect app users:
if (navigator.userAgent.toLowerCase().includes('canvas')) {
// User is in the mobile app
console.log('App user detected');
} else {
// User is on the website
console.log('Website user');
}
// Don't show app download prompts to users already in the app
if (navigator.userAgent.toLowerCase().includes('canvas')) {
document.querySelector('.app-download-banner').style.display = 'none';
}
Track app vs website sessions by setting a user property:
// Set app_session property based on user agent
if (navigator.userAgent.toLowerCase().includes('canvas')) {
gtag('set', { app_session: true });
} else {
gtag('set', { app_session: false });
}
Add different styles for app users by adding a CSS class:
// Add 'in-app' class to body for app users
if (navigator.userAgent.toLowerCase().includes('canvas')) {
document.body.classList.add('in-app');
}
Then use CSS to style differently:
/* Hide elements for app users */
.in-app .web-only {
display: none;
}
/* Show elements only for app users */
.app-only {
display: none;
}
.in-app .app-only {
display: block;
}
/* Adjust styling for app */
.in-app .header {
padding-top: 0;
}
That's it! The detection is straightforward and reliable across all devices.