I have been given the task to update our website to check if our mobile application is installed. If it is installed, ask if the user wants to open our mobile application. If it is not installed, ask if the user wants to go to our mobile app page. There is more around the logic here that does not apply (whether it’s a good idea to do this, or how often, etc.).
I have implemented the intent filter on my android app, and I am able to successfully launch it from my site. No problem there.
I am struggling on finding if there is an app that can handle the intent. Included below is my code that I’ve gotten it to work but only when the commented out alert is in place. This alert cannot be in place. I have tried putting in delays/timeouts to set the iframe source thinking maybe the alert is causing some kind of timing issue. I’ve tried onblur, visibility changes.
function OpenApp(isAppInstalled) {
if (isAppInstalled) {
var launchApp = confirm("Do you want to launch the mobile app?");
if (launchApp) {
window.location.href = "myintent://www.myintent.com";
}
} else {
var launchApp = confirm("We have a mobile app available. Would you like to view more information on how to get it?");
if (launchApp) {
window.location.href = "https://linktomobileapp.com";
}
}
}
function isIntentFilterHandled(intentUrl) {
var isAppChecked = false;
var start = Date.now();
// Create an iframe to attempt to open the app
var iframe = document.createElement('iframe');
iframe.style.display = 'none';
document.body.appendChild(iframe);
// Function to clean up and call OpenApp only once
function cleanUpAndCallApp(isAppInstalled) {
if (!isAppChecked) {
isAppChecked = true;
OpenApp(isAppInstalled);
document.removeEventListener('visibilitychange', handleVisibilityChange);
document.body.removeChild(iframe);
}
}
// Handle visibility change
function handleVisibilityChange() {
if (document.hidden) {
cleanUpAndCallApp(true);
}
}
// Add event listener for visibility change
document.addEventListener('visibilitychange', handleVisibilityChange);
// Handle the onblur event
window.onblur = function() {
if (!isAppChecked) {
cleanUpAndCallApp(true);
}
};
// Set a timeout to check if the app was opened
var delay = 2000; // 2 seconds
setTimeout(function() {
var elapsed = Date.now() - start;
if (!isAppChecked) {
cleanUpAndCallApp(false);
}
}, delay);
// Attempt to open the app
iframe.src = intentUrl;
// alert("Iframe src set to: " + intentUrl); // Code works with this alert, does not without it
}
window.onload = function() {
var intentUrl = 'myintent://www.myintent.com';
isIntentFilterHandled(intentUrl);
};