Open a URL using Google Apps Script

ADW
2 min readFeb 22, 2021

This question was asked and answered on StackOverflow.

I have simplified the solution suggested by “The Master”.

In this example, I am going to use a Google Apps Script attached to a Google Sheet.

And I will use a menu item to trigger the script to open the URL.

Step 1: Add a menu to the Google Sheets UI to trigger the script:

function onOpen() {   var ui = SpreadsheetApp.getUi();   ui.createMenu(‘📮 Open Gmail’)     .addItem(‘Open Gmail’, ‘openGmail’)     .addToUi();}

This part of the script will add a menu item. onOpen() is a special type of function that runs each time the Google Sheet is opened.

The postbox emoji is from Emojpedia. Adding an emoji helps users find the custom menu easily.

Once the onOpen() script is in place, each time you open the Google Sheet, you should see the custom menu on the right of the Help menu.

To understand the script:

createMenu(‘📮 Open Gmail’) : name of the menu.

.addItem(‘Open Gmail’, : name of the menu item.

‘openGmail’) : name of the function to run when this menu item is chosen.

Google Sheets user interface with custom menu to open a URL

Step 2: Write the openGmail() function. This will use an HTML file to open the target URL.

function openGmail() {   var htmlOutput = HtmlService.createHtmlOutputFromFile('openUrl').setHeight(100);   SpreadsheetApp.getUi().showModalDialog(htmlOutput, 'Opening Gmail');}

HtmlService is used to create an HTML file. [Ref docs]

To understand the script:

HtmlService.createHtmlOutputFromFile : creates an HTML output from the HTML file ‘openURL.html’. [Ref docs]

showModalDialog(htmlOutput, ‘Opening Gmail’) : This displays a dialogue with the title ‘Opening Gmail’. [Ref docs]

Step 3: Add the HTML file and call it openUrl

<!DOCTYPE html><html>   <head>      <script>         var urlToOpen =’https://mail.google.com/mail/u/0/#inbox';         var winRef = window.open(urlToOpen);         google.script.host.close();      </script>   </head></html>

To understand the HTML code:

Use the variable urlToOpen to set the URL you want to open. In this example, I am opening my Gmail inbox.

window.open(urlToOpen) : triggers the opening of the URL.

google.script.host.close() : closes the dialogue box in Google Sheets.

Your editor should look like this:

The Google Apps Script code
The HTML code

If you like, make a copy of my Google Sheet. Or copy the code from Github.

--

--