2 回答

TA貢獻1851條經驗 獲得超3個贊
在客戶端代碼中,使用google.script.host.editor.focus()使編輯器上的選擇成為活動選擇。
function showSidebar(){
? var ui = DocumentApp.getUi();
? var html = '<div>Hello world!</div>'
? html += '<div><button onclick="google.script.host.editor.focus()">Click me!</button></div>';
? ui.showSidebar(HtmlService.createHtmlOutput(html));
}
在 Google Workspace 中移動瀏覽器焦點
要將用戶瀏覽器中的焦點從對話框或側邊欄切換回 Google 文檔、表格或表單編輯器,只需調用方法 google.script.host.editor.focus() 即可。此方法與文檔服務方法 Document.setCursor(position) 和 Document.setSelection(range) 結合使用特別有用。

TA貢獻1869條經驗 獲得超4個贊
解決方案
由于您的目標是復制所選文本,我想提出一個替代解決方案:
現在,任務將直接包括復制功能,除了單擊按鈕之外,無需其他用戶輸入。它將這樣開發:
文本選擇
通過單擊按鈕觸發 Apps 腳本功能來獲取所選文本:
//... Your custom logic to get the text selection
var text-to-copy = doc.setSelection(x)
.getSelection()
.getRangeElements()
.map(re => re.getElement()
.asText()
.getText())
.join(" ");
return text-to-copy;
我們無法從 Apps 腳本訪問用戶剪貼板,但successHandler可以使用 a 將text-to-copy變量傳遞到客戶端界面。
處理服務器端返回值
通過以下方式,我們可以將文本傳遞回 HTML 側邊欄。
<!-- HTML Interface Index.html -->
<button onclick="google.script.run.withSuccessHandler(copyToClipboard).setSelection()">
Click Here
</button>
<script>
function copyToClipboard(text) {
const elem = document.createElement('textarea');
elem.value = text;
document.body.appendChild(elem);
elem.select();
document.execCommand('copy');
document.body.removeChild(elem);
}
</script>
現在,我們可以利用本機客戶端功能將該文本直接復制到用戶剪貼板,而無需在Ctrl+C腳本完成后讓她/他復制。
在這種情況下,一個好的做法是在復制過程完成后向用戶提供視覺反饋。
添加回答
舉報