Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Last active January 24, 2023 12:01
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save tanaikech/9115c70eb83558d3af2eea656e4d9c67 to your computer and use it in GitHub Desktop.
Save tanaikech/9115c70eb83558d3af2eea656e4d9c67 to your computer and use it in GitHub Desktop.
Open Site with New Window using Google Apps Script

Open Site with New Window using Google Apps Script

This is a sample script for opening a site with new window using Google Apps Script. It is possible to open the site inside the opened dialog box using iframe. But in my situation, I had to open the site as new window. So I created this. As a sample application, it can think of like this. When the special keyword was inputted, open sites and files in Google Drive as a help window. In this case, the trigger installed onEdit() is required to be used. I think that there are some other applications.

Demo :

Sample script :

function myFunction() {
  var js = " \
    <script> \
      window.open('https://tanaikech.github.io/', '_blank', 'width=800, height=600'); \
      google.script.host.close(); \
    </script> \
  ";
  var html = HtmlService.createHtmlOutput(js)
    .setHeight(10)
    .setWidth(100);
  SpreadsheetApp.getUi().showModalDialog(html, 'Now loading.'); // If you use this on Spreadsheet
//  DocumentApp.getUi().showModalDialog(html, 'Now loading.'); //  If you use this on Document
//  SlidesApp.getUi().showModalDialog(html, 'Now loading.'); //  If you use this on Slides
}

Note :

  • This sample script uses getUi().showModalDialog(). So you can also use this script at not only Spreadsheet, but also Document and Slides.
    • For Spreadsheet
      • SpreadsheetApp.getUi().showModalDialog(html, 'Now loading.');
      • SpreadsheetApp.getActiveSpreadsheet().show(html);
    • For Document
      • DocumentApp.getUi().showModalDialog(html, 'Now loading.');
    • For Slides
      • SlidesApp.getUi().showModalDialog(html, 'Now loading.');
  • When you use this, please be careful for X-Frame-Options:SAMEORIGIN.
@rajatha-imandev
Copy link

@tanaikech While implemeting the same, How to capture the postmessage from the recently opened 3rd party URL
Here is what I have tried,
Could you please let me know where I am going wrong?
function openNewTab() {
var url = ‘third party URL’;
var js = "
<script>
var windowRef = window.open('" + url +"');
console.log(windowRef );
window.addEventListener('message', handleMessage, false);
function handleMessage(e) {
console.log(e);
windowRef.top.window.close();
}
console.log('Window ref');
</script>
var html = HtmlService.createHtmlOutput(js)
.setHeight(10)
.setWidth(100);
DocumentApp.getUi().showModalDialog(html, 'Now loading.');
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment