Html 用于打开 URL 的 Google Apps 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10744760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 00:37:56  来源:igfitidea点击:

Google Apps Script to open a URL

htmlredirectgoogle-apps-scripthyperlink

提问by PY_

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)?

有没有办法编写谷歌应用程序脚本,以便在运行时,第二个浏览器窗口会打开 www.google.com(或我选择的其他网站)?

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

我正在尝试解决我之前的问题: Can I add a hyperlink inside a message box of a Google Apps电子表格

回答by Serge insas

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

你可以构建一个小的 UI 来完成这样的工作:

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 :

如果您想“显示”URL,只需像这样更改这一行:

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

EDIT : link to a demo spreadsheetin read onlybecause 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!

编辑:UiApp 于 2014 年 12 月 11 日被 Google 弃用,此方法可能随时中断,需要更新以使用 HTML 服务!

EDIT : below is an implementation using html service.

编辑:下面是使用 html 服务的实现。

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");
}

回答by Stephen M. Harris

This function opens a URL without requiring additional user interaction.

此功能无需额外的用户交互即可打开 URL 。

/**
 * 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.

此方法通过创建一个临时对话框起作用,因此它在 UI 服务不可访问的上下文中不起作用,例如脚本编辑器或自定义 G Sheets 公式。

回答by TheMaster

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

window.open(url)1会自动打开网页,前提是禁用了弹出窗口阻止程序(斯蒂芬的回答就是这种情况)

openUrl.html

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:

代码.gs:

function modalUrl(){
  SpreadsheetApp.getUi()
   .showModalDialog(
     HtmlService.createHtmlOutputFromFile('openUrl').setHeight(50),
     'Opening StackOverflow'
   )
}    

回答by Rubén

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 objectand methods like addEventListener()to open URLs.

谷歌Apps脚本不会自动打开网页,但它可以被用于显示的链接,按钮的消息,用户可以在他们点击打开所需的网页或甚至使用Window对象等方法的addEventListener()到打开网址。

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

值得注意的是,UiApp 现在已被弃用。来自UiApp 类 - Google Apps 脚本 - Google Developers

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

已弃用。UI 服务已于2014 年 12 月 11 日弃用。要创建用户界面,请改用HTML 服务

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

HTML 服务链接页面中的示例非常简单,

Code.gs

代码.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

自定义版本的 index.html 以显示两个超链接

<a href='http://stackoverflow.com' target='_blank'>Stack Overflow</a>
<br/>
<a href='http://meta.stackoverflow.com/' target='_blank'>Meta Stack Overflow</a>

回答by OaklandFanatic

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

基于较早的示例,我认为有一种更简洁的方法可以做到这一点。index.html在您的项目中创建一个文件并使用上面的 Stephen 代码,只需将其转换为 HTML 文档即可。

<!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.gsscript, you can have something like the following,

然后,在你的Code.gs脚本中,你可以有如下内容,

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 ..." );
}