首页 > 解决方案 > 一键打开两个网址

问题描述

我是 Google 表格和 Apps 脚本的新手。我有一张带有两个 URL 的表格。在单元格 F1 中http://testurl1.com,在单元格 G1 中是http://testurl2.com

我想在单元格 D1 中有一个按钮或链接或其他东西,当我单击它时,它将打开这两个链接。我可以使用 Alt-Enter 手动执行此操作,但无法将其转换为代码。

我已经能够从菜单项中打开这两个 url,但是当我尝试从单元格调用代码时,它说

例外:无法从此上下文中调用 SpreadsheetApp.getUi()。

但是代码从菜单项中工作。诡异的。我目前正在尝试使用的代码如下,但我愿意接受任何建议!

function callOthers() {
  myFunction()
   Utilities.sleep(1500);
  myFunction2() 
}

function myFunction() {    
  var sheet = SpreadsheetApp.getActiveSheet();  
  var selection = sheet.getRange("F1").getValue(); 
    var html = "<script>window.open('" + selection + "');google.script.host.close();</script>";  
    var userInterface = HtmlService.createHtmlOutput(html);
  SpreadsheetApp.getUi().showModalDialog(userInterface, 'Open Tab');  
}

function myFunction2() {  
    var sheet = SpreadsheetApp.getActiveSheet();  
   var selection2 = sheet.getRange("G1").getValue(); 
   var html2 = "<script>window.open('" + selection2 + "');google.script.host.close();</script>";  
   var userInterface2 = HtmlService.createHtmlOutput(html2);  
     SpreadsheetApp.getUi().showModalDialog(userInterface2, 'Open Tab');  
}

标签: javascripthtmlgoogle-apps-scriptgoogle-sheets

解决方案


问题

自定义函数在单元格中使用时被阻止运行

解释

在电子表格 UI 中提供绑定脚本函数的主要方法有以下三种:

  1. 作为可以像公式一样使用的自定义函数
  2. 作为将在单击时运行功能的菜单项
  3. 作为通过图像或绘图创建的“按钮”,将在单击时运行该功能

这三个都有不同的执行上下文和对他们可以访问和不能访问的限制,最严格的是第一个。自定义函数执行上下文绑定到调用它的单元格,因此您不能做任何影响整个 UI 的事情,这是getUi()允许的。

此外,由于showModalDialog是一种需要代表用户授权的方法,即使该getUi()方法可用,您也无法显示对话框,因为自定义函数从不要求用户授权访问个人数据

解决方案

如果您想与 UI 交互,您应该创建一个菜单或一个按钮,如前所述。

请注意,用户必须在以下范围内授予您的脚本权限:

https://www.googleapis.com/auth/script.container.ui

参考

  1. 自定义功能指南
  2. showModalDialog方法参考
  3. getUi()方法参考

推荐阅读