Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Apps Script to open a URL

Is there a way to write a google apps script so when ran, a second browser window opens to www.google.com (or another site of my choice)?

I am trying to come up with a work-around to my previous question here: Can I add a hyperlink inside a message box of a Google Apps spreadsheet

like image 315
PY_ Avatar asked May 24 '12 20:05

PY_


1 Answers

This function opens a URL without requiring additional user interaction.

/**  * Open a URL in a new tab.  */ function openUrl( url ){   var html = HtmlService.createHtmlOutput('<html><script>'   +'window.close = function(){window.setTimeout(function(){google.script.host.close()},9)};'   +'var a = document.createElement("a"); a.href="'+url+'"; a.target="_blank";'   +'if(document.createEvent){'   +'  var event=document.createEvent("MouseEvents");'   +'  if(navigator.userAgent.toLowerCase().indexOf("firefox")>-1){window.document.body.append(a)}'                             +'  event.initEvent("click",true,true); a.dispatchEvent(event);'   +'}else{ a.click() }'   +'close();'   +'</script>'   // Offer URL as clickable link in case above code fails.   +'<body style="word-break:break-word;font-family:sans-serif;">Failed to open automatically. <a href="'+url+'" target="_blank" onclick="window.close()">Click here to proceed</a>.</body>'   +'<script>google.script.host.setHeight(40);google.script.host.setWidth(410)</script>'   +'</html>')   .setWidth( 90 ).setHeight( 1 );   SpreadsheetApp.getUi().showModalDialog( html, "Opening ..." ); } 

This method works by creating a temporary dialog box, so it will not work in contexts where the UI service is not accessible, such as the script editor or a custom G Sheets formula.

like image 130
Stephen M. Harris Avatar answered Sep 17 '22 22:09

Stephen M. Harris