32

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

TheMaster
  • 32,296
  • 6
  • 31
  • 56
PY_
  • 989
  • 6
  • 17
  • 27

5 Answers5

35

You can build a small UI that does the job like this :

function test(){
showURL("http://www.google.com")
}
//
function showURL(href){
  var app = UiApp.createApplication().setHeight(50).setWidth(200);
  app.setTitle("Show URL");
  var link = app.createAnchor('open ', href).setId("link");
  app.add(link);  
  var doc = SpreadsheetApp.getActive();
  doc.show(app);
  }

If you want to 'show' the URL, just change this line like this :

  var link = app.createAnchor(href, href).setId("link");

EDIT : link to a demo spreadsheet in read only because too many people keep writing unwanted things on it (just make a copy to use instead).

EDIT : UiApp was deprecated by Google on 11th Dec 2014, this method could break at any time and needs updating to use HTML service instead!

EDIT : below is an implementation using html service.

function testNew(){
  showAnchor('Stackoverflow','http://stackoverflow.com/questions/tagged/google-apps-script');
}

function showAnchor(name,url) {
  var html = '<html><body><a href="'+url+'" target="blank" onclick="google.script.host.close()">'+name+'</a></body></html>';
  var ui = HtmlService.createHtmlOutput(html)
  SpreadsheetApp.getUi().showModelessDialog(ui,"demo");
}
mannyglover
  • 1,533
  • 12
  • 16
Serge insas
  • 42,040
  • 6
  • 89
  • 113
  • see edit, I added a example spreadsheet to show you hor it should be used. – Serge insas Aug 03 '12 at 23:09
  • 1
    Sorry for the slow response. The example spreadsheet is in view only mode so it does not allow me to get to the script editor. But, for some reason, now the above scrip works. Thanks for the help! – PY_ Jan 03 '13 at 12:51
  • Info: see also this other post: http://stackoverflow.com/questions/18151564/how-do-i-open-a-web-browser-using-google-apps-script/18152436#18152436 – Serge insas Aug 20 '13 at 08:31
  • 1
    For those of you checking this out in the year 2018 or later, the above solution no longer works. Please see Stephen M Harris' answer. Works as of the date of writing this comment. – Steve Gon Aug 27 '18 at 20:42
  • 2
    sorry but that is not true, the new version as EDIT works , it uses HTMLService. – Serge insas Aug 27 '18 at 20:52
  • Just a note for anyone trying to use the updated method. If you are trying to open a webpage by running this code from pure Google App Script without it being part of a google sheet will get an error. Exception: Cannot call SpreadsheetApp.getUi() from this context. You will have to use the code inside a spreadsheet or use another method all together. – Mickey D Nov 10 '20 at 19:23
35

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.

Stephen M. Harris
  • 5,796
  • 2
  • 35
  • 42
  • 2
    @MaxMakhrov indeed it does! I just updated the code with a fix. It appears programmatic clicks have long been problematic in Firefox, but now the script reliably shows the 'Failed to open' fallback in Firefox and offers the user a working link. – Stephen M. Harris Mar 02 '18 at 05:50
  • 2
    Stephen, i do not follow the above script. When i run it, it goes to an error page saying the URL was not found. Can you post up an example of a code that will open a site like google.com? – PY_ Feb 15 '19 at 13:49
  • 1
    @PY_ you can pass any URL you want to the function. To open google.com, include the above script, then call `openUrl( 'https://google.com' );` – Stephen M. Harris Feb 17 '19 at 08:48
  • @StephenM.Harris - When you substitue SpreadsheetApp for DocumentApp, it opens two new windows (same url). Any suggestions about how to fix it? I'm trying to limit the scopes in my Google Doc addon. – Jed Grant Dec 24 '19 at 21:46
  • 2
    @PY_, I had same issue, you need to include `http://` at beginning of urls, then it works – toddmo Jan 06 '20 at 16:14
  • This is so great! Thanks! – Ryan Apr 21 '21 at 17:16
6

There really isn't a need to create a custom click event as suggested in the bountied answer or to show the url as suggested in the accepted answer.

window.open(url)1 does open web pages automatically without user interaction, provided pop- up blockers are disabled(as is the case with Stephen's answer)

openUrl.html

<!DOCTYPE html>
<html>
  <head>
   <base target="_blank">
    <script>
     var url1 ='https://stackoverflow.com/a/54675103';
     var winRef = window.open(url1);
     winRef ? google.script.host.close() : window.alert('Allow popup to redirect you to '+url1) ;
     window.onload=function(){document.getElementById('url').href = url1;}
    </script>
  </head>
  <body>
    Kindly allow pop ups</br>
    Or <a id='url'>Click here </a>to continue!!!
  </body>
</html>

code.gs:

function modalUrl(){
  SpreadsheetApp.getUi()
   .showModalDialog(
     HtmlService.createHtmlOutputFromFile('openUrl').setHeight(50),
     'Opening StackOverflow'
   )
}    
TheMaster
  • 32,296
  • 6
  • 31
  • 56
5

Google Apps Script will not open automatically web pages, but it could be used to display a message with links, buttons that the user could click on them to open the desired web pages or even to use the Window object and methods like addEventListener() to open URLs.

It's worth to note that UiApp is now deprecated. From Class UiApp - Google Apps Script - Google Developers

Deprecated. The UI service was deprecated on December 11, 2014. To create user interfaces, use the HTML service instead.

The example in the HTML Service linked page is pretty simple,

Code.gs

// Use this code for Google Docs, Forms, or new Sheets.
function onOpen() {
  SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
      .createMenu('Dialog')
      .addItem('Open', 'openDialog')
      .addToUi();
}

function openDialog() {
  var html = HtmlService.createHtmlOutputFromFile('index')
      .setSandboxMode(HtmlService.SandboxMode.IFRAME);
  SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
      .showModalDialog(html, 'Dialog title');
}

A customized version of index.html to show two hyperlinks

<a href='http://stackoverflow.com' target='_blank'>Stack Overflow</a>
<br/>
<a href='http://meta.stackoverflow.com/' target='_blank'>Meta Stack Overflow</a>
Rubén
  • 24,097
  • 9
  • 55
  • 116
3

Building of off an earlier example, I think there is a cleaner way of doing this. Create an index.html file in your project and using Stephen's code from above, just convert it into an HTML doc.

<!DOCTYPE html>
<html>
  <base target="_top">
  <script>
    function onSuccess(url) {
      var a = document.createElement("a"); 
      a.href = url;
      a.target = "_blank";
      window.close = function () {
        window.setTimeout(function() {
          google.script.host.close();
        }, 9);
      };
      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();
    }

    function onFailure(url) {
      var div = document.getElementById('failureContent');
      var link = '<a href="' + url + '" target="_blank">Process</a>';
      div.innerHtml = "Failure to open automatically: " + link;
    }

    google.script.run.withSuccessHandler(onSuccess).withFailureHandler(onFailure).getUrl();
  </script>
  <body>
    <div id="failureContent"></div>
  </body>
  <script>
    google.script.host.setHeight(40);
    google.script.host.setWidth(410);
  </script>
</html>

Then, in your Code.gs script, you can have something like the following,

function getUrl() {
  return 'http://whatever.com';
}

function openUrl() {
  var html = HtmlService.createHtmlOutputFromFile("index");
  html.setWidth(90).setHeight(1);
  var ui = SpreadsheetApp.getUi().showModalDialog(html, "Opening ..." );
}
  • I tried this example. It was working perfectly fine a few days back. Today when I am running it, it only opens the dialog but does not open the external url in a new tab. Is there some setting that has gone wrong in my browser? – shanti Dec 11 '20 at 12:12