我正在爲Google文檔構建一個小腳本bound。該腳本創建一個菜單條目和一個側欄。側欄包含一個單擊按鈕,單擊該按鈕時,將今天的日期插入文檔中的光標處。菜單條目也是一樣的。使用Ui服務API在Google Apps中移動瀏覽器焦點
使用菜單條目插入日期時,插入日期,並且光標保持聚焦在文檔編輯區域。但是,當從側欄點擊按鈕時,焦點將丟失。
挖的文檔了一下,我發現在Moving browser focus in Google Apps這個Blurb的:
從對話框切換焦點在用戶的瀏覽器或補充工具欄返回谷歌文檔,電子表格或表格編輯器,只需調用方法google.script.host.editor.focus()。此方法與Document服務方法Document.setCursor(position)和Document.setSelection(range)結合使用時特別有用。
但在使用谷歌的文檔Ui Service時調用google.script.host.editor.focus()
從點擊處理程序中失敗。什麼是強制重點回到文件區域的等效的UI服務方法?
這是我的腳本,它是bound Google文檔。請參閱myClickHandler
函數中google.script.host.editor.focus()
的註釋掉電話。
function onOpen() {
// Add a menu with some items, some separators, and a sub-menu.
DocumentApp.getUi().createMenu('Sidebars')
.addItem('Insert Date at cursor', 'insertDateAtCursor')
.addItem('Show sidebar', 'showSidebar')
.addToUi();
}
/**
* Insert a Date at the current cursor location.
*/
function insertDateAtCursor() {
var cursor = DocumentApp.getActiveDocument().getCursor();
if (cursor) {
// Attempt to insert text at the cursor position. If insertion returns null,
// then the cursor's containing element doesn't allow text insertions.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
var today = new Date;
var element = cursor.insertText(today.getFullYear() + "-" + today.getDate() + "-" + (today.getMonth()+1));
if (!element) {
DocumentApp.getUi().alert('Cannot insert text at this cursor location.');
}
} else {
DocumentApp.getUi().alert('Cannot find a cursor in the document.');
}
}
/**
* Show the side bar:
*/
function showSidebar() {
// https://developers.google.com/apps-script/guides/ui-service
var app = UiApp.createApplication().setTitle('Utility Sidebar');
var panel = app.createVerticalPanel();
var button = app.createButton("Insert Date At Cursor");
panel.add(button);
app.add(panel);
// https://developers.google.com/apps-script/guides/ui-service#ServerHandlers
var handler = app.createServerHandler('myClickHandler');
button.addClickHandler(handler);
DocumentApp.getUi().showSidebar(app);
}
/**
* Handle the button click:
*/
function myClickHandler(e) {
var app = UiApp.getActiveApplication();
insertDateAtCursor();
// What is the UiApp equivalent of this?:
// google.script.host.editor.focus();
// Calling app.close() closes the side bar so comment this out:
// app.close();
return app;
}
非常感謝! – bgoodr 2014-10-11 20:43:45