google.script.host 类(客户端 API)

google.script.host 是一种异步客户端 JavaScript API,可与 Google 文档、表格或表单中包含 HTML 服务页面的对话框或边栏进行交互。如需通过客户端代码执行服务器端函数,请使用 google.script.run。如需了解详情,请参阅 HTML 服务中与服务器函数通信的指南

属性

媒体资源说明
origin提供主机网域,以便脚本可以正确设置其来源。

方法

方法返回类型简介
close() void 关闭当前对话框或边栏。
editor.focus() void 将浏览器焦点从对话框或边栏切换到 Google 文档、表格或表单编辑器。
setHeight(height) void 设置当前对话框的高度。
setWidth(width) void 设置当前对话框的宽度。

详细文档

close()

关闭当前对话框或边栏。

Code.gs

function onOpen(e) {
  SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
      .createMenu('Sidebar').addItem('Show', 'showSidebar').addToUi();
}

function showSidebar() {
  var html = HtmlService.createHtmlOutputFromFile('Index');
  SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
      .showSidebar(html);
}

Index.html

<input type="button" value="Close"
  onclick="google.script.host.close()" />

editor.focus()

将浏览器焦点从对话框或边栏切换到 Google 文档、表格或表单编辑器。

Code.gs

function onOpen(e) {
  SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
      .createMenu('Sidebar').addItem('Show', 'showSidebar').addToUi();
}

function showSidebar() {
  var html = HtmlService.createHtmlOutputFromFile('Index');
  SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
      .showSidebar(html);
}

Index.html

<input type="button" value="Switch focus"
  onclick="google.script.host.editor.focus()" />

setHeight(height)

设置当前对话框的高度。

Code.gs

function onOpen(e) {
  SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
      .createMenu('Dialog').addItem('Show', 'showDialog').addToUi();
}

function showDialog() {
  var html = HtmlService.createHtmlOutputFromFile('Index')
      .setWidth(300)
      .setHeight(200);
  SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
      .showModalDialog(html, 'Dialog title');
}

Index.html

<script>
  function resizeDialog(width, height) {
    google.script.host.setWidth(width);
    google.script.host.setHeight(height);
  }
</script>
<input type="button" value="Resize dialog"
  onclick="resizeDialog(450, 300)" />

参数

名称类型说明
heightInteger新高度(以像素为单位)

setWidth(width)

设置当前对话框的宽度。

Code.gs

function onOpen(e) {
  SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
      .createMenu('Dialog').addItem('Show', 'showDialog').addToUi();
}

function showDialog() {
  var html = HtmlService.createHtmlOutputFromFile('Index')
      .setWidth(300)
      .setHeight(200);
  SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
      .showModalDialog(html, 'Dialog title');
}

Index.html

<script>
  function resizeDialog(width, height) {
    google.script.host.setWidth(width);
    google.script.host.setHeight(height);
  }
</script>
<input type="button" value="Resize dialog"
  onclick="resizeDialog(450, 300)" />

参数

名称类型说明
widthInteger新宽度(以像素为单位)