Google 文档插件 - 通过侧边栏按钮设置文本的 setSelection() - 如何使其成为活动选择?

Google document add-on - setSelection() of text by sidebar button - how to make it an active selection?

背景:

我正在 google 市场附加组件中使用 setSelection() method google 文档。

单击插件侧边栏上的相关按钮时,文本会按预期 select 编辑。 但是,此 selection 未激活 - 即 selected 文本以浅灰色而不是浅蓝色突出显示(参见下面的示例)。

现在:

我需要:

这是因为浏览器选项卡的最后活动部分是边栏(单击按钮后),而不是实际文档。

问题:

有没有办法让按钮单击 select 文本 使文档保持活动部分?

目标:

这个 selection 的全部目的是通过键盘上的 Ctrl + C 复制 selected 文本,当 selection 是未激活。

现在用户需要使用鼠标右键单击并从菜单中 select Copy...

解决方案

由于您的目标是复制所选文本,我想提出一个替代解决方案:

任务现在将直接包含复制功能,除了单击按钮外,无需其他用户输入。并且会这样发展:

文本选择

通过单击按钮触发的 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 我们可以将 text-to-copy 变量传递给 Client-Side 接口。

处理 Server-Side return 值

我们可以通过以下方式将文本传回 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>

我们现在可以利用本机 client-side 功能将该文本直接复制到用户剪贴板,而无需 her/him 到 Ctrl+C 一旦你的脚本完成。

在这种情况下,一个好的做法是在复制过程完成后向您的用户提供视觉反馈。

参考

withSuccessHandler(function)

在您的 client-side 代码中使用 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));
}

来自https://developers.google.com/apps-script/guides/html/communication#moving_browser_focus_in

Moving browser focus in Google Workspace

To switch focus in the user's browser from a dialog or sidebar back to the Google Docs, Sheets, or Forms editor, simply call the method google.script.host.editor.focus(). This method is particularly useful in combination with the Document service methods Document.setCursor(position) and Document.setSelection(range).