google.script.host 類別 (用戶端 API)

google.script.host 是非同步的用戶端 JavaScript API,可與包含 HTML 服務頁面的 Google 文件、試算表或表單中的對話方塊或側欄互動。如要從用戶端程式碼執行伺服器端函式,請使用 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新寬度 (以像素為單位)