如何在Google Apps Script客户端获取HtmlOutput.setTitle设置的标题
问题原因
你通过setTitle()设置的是Google Workspace侧边栏容器的头部标题,并不是你嵌入的HTML页面本身的文档标题。你的HTML代码是被放在侧边栏内部的iframe中加载的,因此document.title读取的是iframe内页面的标题,自然返回空值。
解决方案1:模板注入标题(推荐)
该方案稳定性最高,不依赖Google界面结构,不会因为官方更新前端结构失效。
调整Main.gs代码
改用HTML模板注入参数,把标题同时传给模板和侧边栏容器:
function onOpen() { var spreadsheet = SpreadsheetApp.getActive(); var menuItems = [ {name: 'Build Form...', functionName: 'buildForm_'}, ]; spreadsheet.addMenu('Test', menuItems); } function buildForm_(){ const reportTitle = "Some Title" // 加载HTML模板而非直接读取静态文件 const htmlTemplate = HtmlService.createTemplateFromFile('HTML_Sidebar') // 给模板绑定标题参数 htmlTemplate.reportTitle = reportTitle // 渲染模板后设置侧边栏标题 const htmlForm = htmlTemplate.evaluate() .setTitle(reportTitle); SpreadsheetApp.getUi() .showSidebar(htmlForm) }
调整HTML_Sidebar.html代码
在页面中直接使用注入的标题变量:
<!DOCTYPE html> <html> <head> <base target="_top"> <script> // 把服务端注入的标题存为全局变量,随时调用 const SIDEBAR_TITLE = <?= reportTitle ?> </script> </head> <body> <button onmouseup="seeTitle()" id="seeTitleButton">See title</button> <script> function seeTitle() { document.getElementById("seeTitleButton").textContent = "(" + SIDEBAR_TITLE + ")" } </script> </body> </html>
解决方案2:前端直接读取容器标题
如果你不方便修改服务端代码,可以直接通过DOM查询父级页面的侧边栏标题元素,注意该方案依赖Google当前的前端结构,后续如果官方更新类名可能失效:
仅需修改HTML_Sidebar.html中的seeTitle方法即可:
function seeTitle() { // 查询父级页面的侧边栏标题元素 const titleEle = window.parent.document.querySelector(".script-app-dialog-title") const sidebarTitle = titleEle ? titleEle.textContent.trim() : "" document.getElementById("seeTitleButton").textContent = "(" + sidebarTitle + ")" }
内容的提问来源于stack exchange,提问作者madarez
相关产品推荐
相关产品推荐

