如何在Google Docs中获取文档内选中的文本内容?
为什么
window.getSelection()无法获取Google Docs选中内容及解决方案 Google Docs未使用原生DOM节点渲染文本内容,而是自行维护了渲染层和选区状态,没有将选区同步到浏览器原生的window.getSelection()实例中,所以直接调用该API只能拿到空字符串。
可行解决方案
场景1:开发Google Docs官方插件
直接调用官方提供的Google Apps Script API即可:
function getSelectedContent() { const activeDoc = DocumentApp.getActiveDocument(); const selection = activeDoc.getSelection(); // 无选区时返回空 if (!selection) return ''; return selection.getText(); }
场景2:浏览器扩展/控制台脚本调用
可以通过访问Google Docs内部暴露的编辑器实例获取选区内容,示例代码如下:
// 获取Docs内部编辑器挂载的iframe const editorIframe = document.querySelector('.docs-texteventtarget-iframe'); const editorInstance = editorIframe.contentWindow._docs_editor_init[0]; const selection = editorInstance.getSelection(); const selectedText = selection ? selection.getText() : ''; console.log(selectedText);
注意:谷歌会不定期更新Docs的内部变量命名,如果上述代码失效,可以通过调试iframe上下文的全局变量,找到最新的编辑器实例访问路径。
内容的提问来源于stack exchange,提问作者jeribeb
相关产品推荐
相关产品推荐

