ref(deep-linking): Improve the window loaded detection logic.

This commit is contained in:
hristoterezov 2018-06-18 16:57:32 -05:00 committed by Hristo Terezov
parent 12dda7acb9
commit fccd0d6b29
1 changed files with 16 additions and 34 deletions

View File

@ -12,42 +12,24 @@ import { _shouldShowDeepLinkingDesktopPage }
from './shouldShowDeepLinkingDesktopPage';
/**
* Indicates whether the window load event was already received.
* Promise that resolves when the window load event is received.
*
* @type {boolean}
* @type {Promise<void>}
*/
let windowIsLoaded = false;
/**
* Handler for the window load event.
*
* @returns {void}
*/
function onWindowLoad() {
windowIsLoaded = true;
window.removeEventListener('load', onWindowLoad);
}
window.addEventListener('load', onWindowLoad);
/**
* Executes the passed function after the window load event was received.
*
* @param {Function} fn - The function that will be executed.
* @returns {void}
*/
function executeAfterWindowLoad(fn) {
if (windowIsLoaded) {
fn();
} else {
const loadHandler = () => {
fn();
window.removeEventListener('load', loadHandler);
};
window.addEventListener('load', loadHandler);
const windowLoadedPromise = new Promise(resolve => {
/**
* Handler for the window load event.
*
* @returns {void}
*/
function onWindowLoad() {
resolve();
window.removeEventListener('load', onWindowLoad);
}
}
window.addEventListener('load', onWindowLoad);
});
/**
* Generates a deep linking URL based on the current window URL.
@ -114,7 +96,7 @@ export function getDeepLinkingPage(state) {
* @returns {void}
*/
export function openDesktopApp() {
executeAfterWindowLoad(() => {
windowLoadedPromise.then(() => {
// If the code for opening the deep link is executed before the window
// load event, something with the internal chrome state goes wrong. The
// result is that no window load event is received which is the cause