Home > OS >  Can the same Google Apps Script script that opened the tab, also close the tab?
Can the same Google Apps Script script that opened the tab, also close the tab?

Time:09-29

This question: Google Apps Script to open a URL leaves one thing unanswered: After opening the URL, can the script close the tab (or window) used to open the URL? Specifically, I'm using the code from that post to open a PDF for printing. After printing, and closing the PDF file, the tab opened by the script remains. Can the same script that opened the tab ("_blank"), also close the tab?

<script> window.open('<?=url?>', '_blank', 'width=100, height=100'); 
google.script.host.close(); 
window.close(); 
</script>

The code above comes from code posted by stephen-m-harris

CodePudding user response:

window refers to the current window. To close the window that was opened, you should call window.close on that widow. window.open gives a reference to the window that was opened.

<script> 
  const openedWindow = window.open('<?=url?>', '_blank', 'width=100, height=100'); 
  //google.script.host.close(); 
  setTimeout(() => openedWindow.close(), 5000);
  const closeSelf = () => openedWindow.closed && google.script.host.close();
  setInterval(closeSelf, 5000) 
</script>

A timeout is added because the openedWindow might not have been loaded and may not respond to .close() request as soon as it was opened. setInterval is used to check if the window is closed every 5s and if closed, close the current window too.

  • Related