javascript - 一键打开两个网址
问题描述
我是 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');
}
解决方案
问题
自定义函数在单元格中使用时被阻止运行
解释
在电子表格 UI 中提供绑定脚本函数的主要方法有以下三种:
- 作为可以像公式一样使用的自定义函数
- 作为将在单击时运行功能的菜单项
- 作为通过图像或绘图创建的“按钮”,将在单击时运行该功能
这三个都有不同的执行上下文和对他们可以访问和不能访问的限制,最严格的是第一个。自定义函数执行上下文绑定到调用它的单元格,因此您不能做任何影响整个 UI 的事情,这是getUi()
允许的。
此外,由于showModalDialog
是一种需要代表用户授权的方法,即使该getUi()
方法可用,您也无法显示对话框,因为自定义函数从不要求用户授权访问个人数据。
解决方案
如果您想与 UI 交互,您应该创建一个菜单或一个按钮,如前所述。
请注意,用户必须在以下范围内授予您的脚本权限:
参考
推荐阅读
- node.js - 当我使用 npm-run-all 时,如何使用 VSCode 启用 Electron Main 和 Renderer 的调试?
- haskell - Haskell Maybe/参数多态性
- elixir - Enum.map 中的 Enum.sum 返回字母而不是整数
- c++ - While Loops:简单的除法程序输出零,不明白为什么
- python - 我如何在 PIL (discord.py) 中添加用户的图像
- yaml - Yaml - 如何打破很长的字符串
- asp.net - asp.net 身份验证访问失败自行重置
- progressive-web-apps - PWA 是否适用于桌面 Web 应用程序?
- javascript - 无法让 ionic v4 CLI 生成的组件工作
- python - 获取距离下一小时开始的秒数