Google Apps 脚本:从菜单中打开文档



我知道,没有办法用Google Apps Script自动打开文档。但是有没有办法从自定义菜单打开文档?从菜单中选择一个项目并直接打开特定文档比打开一个对话框更舒服,我必须在其中单击指向该文档的链接。

稍微考虑一下,侧边栏可以充当一种菜单,您可以强制它在打开时显示,并提供在侧边栏关闭时恢复的功能。 这可能适合您的需求,因为它提供了一种菜单项和仅选择链接的功能。 使用 G Suite 文档中的对话框和侧边栏中的示例,以下代码将允许使用您知道的对话框场景以及侧边栏菜单项,并在打开时打开侧边栏菜单项:

在 Code.gs 文件中,放置:

function onOpen() {
showSidebar();
SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
.createMenu('Dialog')
.addItem('Open', 'openDialog')
.addItem('Show sidebar', 'showSidebar')
.addToUi();
}
function openDialog() {
var html = HtmlService.createHtmlOutputFromFile('dialog');
SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
.showModalDialog(html, 'Dialog title');
}

function showSidebar() {
var html = HtmlService.createHtmlOutputFromFile('sidebar')
.setTitle('My custom sidebar')
.setWidth(300);
SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
.showSidebar(html);
}

接下来,创建 2 个 HTML 文件,"对话框"和"侧边栏",并为每个文件添加以下内容,以便显示: 在对话框中.html放置以下内容:

<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
Hello, World!
<input type="button" value="Close"
onclick="google.script.host.close()" />
</body>
</html>

在侧边栏中.html放置以下内容:

Hello, world! <input type="button" value="Close" onclick="google.script.host.close()" />
<br/>
<a href="https://drive.google.com/open?id=16HHKXBMmWXh5NBZRAnFDiwGrZ">Open My Sample File here</a>
<br/>
<a href="https://drive.google.com/open?id=16HHKXBMmWXh5NBZRAnFDiwGrZ" target="_blank">Open My Sample File in a new tab</a>

如果您在编辑器中运行onOpen((,或者保存并关闭文件,然后重新打开,您应该在文件中获取侧边栏。 将 HTML 中的 Hello World 项替换为相应的项。 请注意,提供的链接将不起作用,因为我删除了 URL 的一部分。

最新更新