How do I close a showModalDialog() generated via a polyfill from another function?

1.2k Views Asked by At

I have used the following showModalDialog polyfill for my code. It seems to be working fine except I cannot close it without pressing the close button on the iframe.

(function() {window.showModalDialog = window.showModalDialog || function(url, arg, opt) {
    url = url || ''; //URL of a dialog
    arg = arg || null; //arguments to a dialog
    opt = opt/* || 'dialogWidth:300px;dialogHeight:200px'*/; //options: dialogTop;dialogLeft;dialogWidth;dialogHeight or CSS styles
    var caller = showModalDialog.caller.toString();
    var dialog = document.body.appendChild(document.createElement('dialog'));
    dialog.setAttribute('style', opt.replace(/dialog/gi, ''));
    dialog.setAttribute('id', 'dialogID');
    dialog.innerHTML = '<a href="#" id="dialog-close" style="position: absolute; top: 0; right: 4px; font-size: 20px; color: #000; text-decoration: none; outline: none;">&times;</a><iframe id="dialog-body" src="' + url + '" style="border: 0; width: 100%; height: 100%;"></iframe>';
    document.getElementById('dialog-body').contentWindow.dialogArguments = arg;
    document.getElementById('dialog-close').addEventListener('click', function(e) {
        e.preventDefault();
        dialog.close();
    });
    dialog.showModal();
    document.getElementById('dialog-body').addEventListener('click', function(e) {
        e.preventDefault();
        dialog.close();
    });
    dialog.addEventListener('close', function() {
       var returnValue = document.getElementById('dialog-body').contentWindow.returnValue;
        document.body.removeChild(dialog);
       nextStmts[0] = nextStmts[0].replace(/(window\.)?showModalDialog\(.*\)/g, JSON.stringify(returnValue));
       eval('{\n' + nextStmts.join('\n'));
    });        
    throw 'Execution stopped until showModalDialog is closed';
};
})();`

I need to close the generated dialogbox on the press of a yes or no button from the passed URL. The url is of a web page that has a yes and a no button and calls this function onClick.

function dialogButtonClick(dialogFlag)
{      
       if(dialogFlag=='YES')
       {
              window.returnValue = 'YES';
       }
       window.close();

}

Window.close() does not seem to work. I am unable to return the click value from the dialogbox to the parent code. Could anyone help me find a solution for this?

1

There are 1 best solutions below

0
Mike K On

Try this:

dialogButtonClick = (dialogFlag) => {   
    if (dialogFlag == 'YES') { open(location, '_self').close(); }
        return false;   
}