我相信您的目标如下。
- 当单击 Google 文档上的超链接文本时,您希望打开一个对话框作为警报。
- 您希望使用 Google Apps 脚本来实现此目的。
问题和解决方法:
不幸的是,在现阶段,OnSelectionChange 和 OnEdit 触发器不能用于 Google 文档。因此,需要使用解决方法。这时,我想起了我最近的帖子 https://tanaikech.github.io/2021/12/01/pseudo-onedit-trigger-for-google-document-using-google-apps-script/。我认为当使用这个解决方法时,你的目标也许能够间接实现。在这个答案中,我想提出一个解决方法。
此解决方法使用 Javascript。并且,伪 OnEdit 触发器是使用 Javascript 实现的。因此,此解决方法使用侧边栏。
示例脚本:
Google Apps 脚本端:Code.gs
请将此脚本作为脚本文件复制并粘贴到 Google 文档的脚本编辑器中。
function openDialog() {
const doc = DocumentApp.getActiveDocument();
const cursor = doc.getCursor();
if (!cursor) return;
const ps = cursor.getElement();
if (ps.getType() != DocumentApp.ElementType.TEXT) return;
const link = ps.asText().getLinkUrl();
if (!link) return;
const text = `<p>This is a text with a hyperlink.</p><p>The link is <a href="${link}" target="_blank">${link}</a></p>`;
DocumentApp.getUi().showModalDialog(HtmlService.createHtmlOutput(text).setWidth(350).setHeight(100), "sample");
Utilities.sleep(5000); // Please adjust this value for your actual situation.
}
// Please run this function.
function openSidebar() {
DocumentApp.getUi().showSidebar(HtmlService.createHtmlOutputFromFile("index").setTitle("Sample"));
}
JavaScript 和 HTML 方面:index.html
请将此脚本作为 HTML 文件复制并粘贴到 Google 文档的脚本编辑器中。
<input type="button" onclick="start()" id="b1" value="start" />
<input type="button" onclick="stop()" id="b2" value="stop" disabled />
<script>
let run;
const runGoogleScript = (_) => new Promise((resolve, reject) => google.script.run.withFailureHandler(reject).withSuccessHandler(resolve).openDialog());
const main = (_) => new Promise((resolve, reject) => setTimeout(async () => await runGoogleScript().then(resolve).catch(reject), 1000));
const start = async () => {
const b1 = document.getElementById("b1");
const b2 = document.getElementById("b2");
b1.disabled = true;
b2.disabled = false;
run = true;
console.log("Start.");
while (run) console.log(await main());
console.log("End.");
b1.disabled = false;
b2.disabled = true;
};
const stop = (_) => (run = false);
</script>
Testing:
请跑openSidebar
。这样,侧边栏就打开了。您可以通过单击“开始”按钮来使用该脚本。演示影片可以在下面的 GIF 图片中看到。
参考:
- Google Workspace 文档中的对话框和侧边栏 https://developers.google.com/apps-script/guides/dialogs
- Related thread.
- 使用 Google App Script 从一个电子表格跳转到另一个电子表格 https://stackoverflow.com/q/70165584/7108653
- 使用 Google Apps 脚本对 Google 文档进行伪 OnEdit 触发器 https://tanaikech.github.io/2021/12/01/pseudo-onedit-trigger-for-google-document-using-google-apps-script/