如何通过Chrome扩展运行Google Apps Script为Google Docs添加自定义菜单
解决Chrome扩展调用Google Apps Script为Docs添加自定义菜单的问题
核心问题:你写的Apps Script代码依赖Google Docs专属运行环境(比如DocumentApp、DocumentApp.getUi()),这些对象在Chrome扩展的浏览器环境中不存在,所以直接把代码贴到扩展脚本里无法运行。下面是具体的结合方案:
步骤1:调整并绑定Apps Script到Google Docs
- 打开目标Google Docs,点击「工具」>「脚本编辑器」。
- 替换原有代码为以下内容(把自动触发的
onOpen改成可手动调用的函数):
function createInsertToolMenu() { const ui = DocumentApp.getUi(); // 避免重复创建菜单,捕获已存在的错误 try { ui.createMenu('Insert Tool') .addItem('Insert Rickroll', 'insertRickroll') .addToUi(); } catch (e) {} } function insertRickroll() { const cursor = DocumentApp.getActiveDocument().getCursor(); if (cursor) { cursor.insertText('https://www.youtube.com/watch?v=dQw4w9WgXcQ'); } else { DocumentApp.getUi().alert('请先将光标定位到文档中'); } }
- 点击脚本编辑器的「运行」按钮,执行
createInsertToolMenu,首次运行会弹出授权提示,按步骤允许脚本访问你的文档即可。 - 保存脚本项目(比如命名为「Insert Tool Script」)。
步骤2:配置Chrome扩展的Manifest文件
在你的扩展manifest.json中添加内容脚本配置,指定只在Google Docs页面运行:
{ "manifest_version": 3, "name": "Docs Insert Tool", "version": "1.0", "content_scripts": [ { "matches": ["https://docs.google.com/document/*"], "js": ["content.js"], "run_at": "document_idle" } ] }
步骤3:编写扩展的内容脚本(content.js)
在扩展目录下创建content.js文件,写入以下代码——它会等待Google Docs的客户端API加载完成,然后调用绑定的Apps Script函数创建菜单:
// 等待Google Docs的客户端API加载就绪 function waitForGoogleScriptAPI(callback) { if (typeof google !== 'undefined' && google.script) { callback(); } else { setTimeout(() => waitForGoogleScriptAPI(callback), 100); } } // 调用Apps Script函数创建自定义菜单 waitForGoogleScriptAPI(() => { google.script.run .withSuccessHandler(() => console.log('自定义菜单创建成功')) .withFailureHandler(error => console.error('菜单创建失败:', error)) .createInsertToolMenu(); });
原理说明
- Google Docs页面内置了
google.script客户端API,它可以直接调用绑定到当前文档的Apps Script函数。 - Chrome扩展的内容脚本会注入到Docs页面的上下文,通过这个API间接触发Apps Script代码的执行,绕开了环境不兼容的问题。
- 当用户点击菜单中的「Insert Rickroll」时,Docs会自动调用绑定的
insertRickroll函数,无需扩展额外处理。
内容的提问来源于stack exchange,提问作者Gibson DeGroot
相关产品推荐
相关产品推荐

