点击链接谷歌文档上的警报框

2024-01-07

我对这一切都很陌生,我只是想知道每次有人点击我的谷歌文档中的链接时是否可以有一个警报框,我有脚本,以便每次打开时都会弹出警报文档,但每次您单击链接时我都想要另一个,没有具体的,只是文档中的所有链接。


我相信您的目标如下。

  • 当单击 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/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

点击链接谷歌文档上的警报框 的相关文章

随机推荐