You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Google Sheets中通过Google Apps Script自定义函数还原短链接

Google Sheets 短链接还原自定义函数修复方案

修复后可直接使用的代码

function ExpandURL(url) {
  try {
    // 补全协议头,处理不带http/https的短链输入
    if (!/^https?:\/\//i.test(url)) {
      url = 'https://' + url;
    }
    let currentUrl = url;
    // 最多追踪5次重定向,避免死循环触发脚本执行超时
    const maxRedirects = 5;
    for (let i = 0; i < maxRedirects; i++) {
      const response = UrlFetchApp.fetch(currentUrl, {
        followRedirects: false,
        muteHttpExceptions: true
      });
      const responseCode = response.getResponseCode();
      // 判断是否为重定向状态码
      if (responseCode >= 300 && responseCode < 400) {
        const location = response.getHeaders()['Location'];
        if (location && !/^https?:\/\//i.test(location)) {
          // 处理相对路径的Location响应头
          const baseUrl = new URL(currentUrl).origin;
          currentUrl = baseUrl + location;
        } else if (location) {
          currentUrl = location;
        } else {
          break;
        }
      } else {
        break;
      }
    }
    return decodeURIComponent(currentUrl);
  } catch (e) {
    return "无效链接/短链已过期";
  }
}

原代码问题排查

  • 缺少协议头补全逻辑:表格内输入的短链通常不带https://前缀,UrlFetchApp要求请求地址必须携带完整协议,否则直接触发请求错误。
  • 未处理多层重定向:部分短链接服务会设置2次及以上跳转,仅读取一次Location头只能获取中间跳转地址,无法拿到最终落地页链接。
  • 无异常捕获逻辑:输入无效链接、短链已过期等异常场景时,原代码会直接抛出错误,表格内显示#ERROR异常值,无友好反馈。

使用方法

  1. 打开目标Google Sheets,点击顶部菜单栏「扩展程序」-「Apps Script」进入脚本编辑器
  2. 删除编辑器内默认代码,粘贴上述修复后的代码,点击「保存」按钮
  3. 回到表格页面,在空白单元格输入=ExpandURL(短链所在单元格)即可调用,例如短链存放在A1单元格,就输入=ExpandURL(A1)

内容的提问来源于stack exchange,提问作者antonietta171

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 13:24:00