private setupOnCloseHandler()

in src/Popout.tsx [21:67]


    private setupOnCloseHandler(id: string, child: Window) {
        // For Edge, IE browsers, the document.head might not exist here yet. We will just simply attempt again when RAF is called
        // For Firefox, on the setTimeout, the child window might actually be set to null after the first attempt if there is a popup blocker
        if (this.setupAttempts >= 5) {
            return;
        }

        if (child && child.document && child.document.head) {
            const unloadScriptContainer = child.document.createElement('script');
            const onBeforeUnloadLogic = `
            window.onbeforeunload = function(e) {
                var result = window.opener.${
                    globalContext.id
                }.onBeforeUnload.call(window, '${id}', e);

                if (result) {
                    window.opener.${globalContext.id}.startMonitor.call(window.opener, '${id}');

                    e.returnValue = result;
                    return result;
                } else {
                    window.opener.${globalContext.id}.onChildClose.call(window.opener, '${id}');
                }
            }`;

            // Use onload for most URL scenarios to allow time for the page to load first
            // Safari 11.1 is aggressive, so it will call onbeforeunload prior to the page being created.
            unloadScriptContainer.innerHTML = `
            window.onload = function(e) {
                ${onBeforeUnloadLogic}
            };
            `;

            // For edge and IE, they don't actually execute the onload logic, so we just want the onBeforeUnload logic.
            // If this isn't a URL scenario, we have to bind onBeforeUnload directly too.
            if (isBrowserIEOrEdge() || !this.props.url) {
                unloadScriptContainer.innerHTML = onBeforeUnloadLogic;
            }

            child.document.head.appendChild(unloadScriptContainer);

            this.setupCleanupCallbacks();
        } else {
            this.setupAttempts++;
            setTimeout(() => this.setupOnCloseHandler(id, child), 50);
        }
    }