How to programatically close dialogs?
dooart opened this issue · comments
I've tried everything I could think of and I couldn't find a way to close dialogs. The GAS docs say you just need to call google.script.host.close()
but I couldn't find a way to access the google
object, it's always undefined.
Any tips?
Found the problem. The google
object is only accessible from the parent frame where the react app is rendered.
My workaround was to inject a message listener via HtmlService
into the parent frame and then used window.postMessage
from the child frame to close the dialog.
Injecting listener:
function openDialog(dialogFile, dialogTitle) {
const html = HtmlService.createHtmlOutputFromFile(dialogFile)
.append(
`<script>
window.addEventListener('message', function(event) {
if (event.data === "closeDialog") {
google.script.host.close();
}
}, false);
</script>`
)
.setWidth(600)
.setHeight(600);
SlidesApp.getUi().showModalDialog(html, dialogTitle);
}
Invoking from React component:
window.parent?.postMessage('closeDialog', '*');
Yep google.script.host.close()
will work in production, just not with local development since as you mention the google
object is not available directly.
See #104 for discussion on how you could modify my GASClient helper utility to work in both development and production for closing dialogs. Or you could use the workaround you describe to test it out in development. Under the hood the GASClient utility uses postmessage to call methods on the google
object.