Google Apps Script snippets ᕦʕ •ᴥ•ʔᕤ

Open an url in browser

This snippet shows how to open a link using Apps Script in a browser. As a particular example it shows how to get/create a file and open it in browser. This may not always work as browsers protect tabs from opening spontaneously.

index.js

/**
 * @file
 * @url https://twitter.com/oshliaer/status/1252620823724281862
 */

/**
 * Create menu
 */
function onOpen() {
  SpreadsheetApp.getUi()
    .createMenu('My tools')
    .addItem('Open my Sheet in a new tab', 'userActionOpenMyFile')
    .addItem('Open the url from active cell in a new tab', 'userActionOpenUrl')
    .addToUi();
}

/**
 * User action
 */
function userActionOpenMyFile() {
  const file = DriveApp.getFileById(
    '17mpcNilHA43kWqYm8qHAwiwAqFJ1DQ9QENBXHa6CoDM'
  );
  openUrlInBrowser_(file.getUrl());
}

/**
 * User action
 */
function userActionOpenUrl() {
  const url = SpreadsheetApp.getCurrentCell().getValue();
  openUrlInBrowser_(url);
}

/**
 * Open the url in a new tab
 * @param {string} url
 */
function openUrlInBrowser_(url) {
  const tmp = HtmlService.createTemplateFromFile('app');
  tmp.url = url;
  const htmlOutput = tmp.evaluate();
  SpreadsheetApp.getUi().showModelessDialog(htmlOutput, 'Opening url ...');
}
app.html
<!DOCTYPE html>
<html>
  <head>
    <base target="_top" />
    <noscript>
      <meta http-equiv="refresh" content="0; url=https://google.com" />
    </noscript>
  </head>

  <body>
    <div id="message"></div>
    <script>
      const url = <?= url ?>;
        const newWin = window.open(url, "_blank");
        if(!newWin || newWin.closed || typeof newWin.closed=='undefined'){
          document.getElementById("message").innerHTML =
            'Pop-ups blocked! <a href="https://support.google.com/chrome/answer/95472" target="_blank">Enable</a>.';
        } else {
          google.script.host.close();
        }
    </script>
  </body>
</html>
appsscript.json
{
  "timeZone": "Europe/Moscow",
  "dependencies": {},
  "exceptionLogging": "STACKDRIVER",
  "runtimeVersion": "V8"
}