Skip to content

Instantly share code, notes, and snippets.

@petems
Created July 22, 2025 02:29
Show Gist options
  • Select an option

  • Save petems/2d8750a4061646b93f08fd5bd343704d to your computer and use it in GitHub Desktop.

Select an option

Save petems/2d8750a4061646b93f08fd5bd343704d to your computer and use it in GitHub Desktop.
Google Sheets Hyperlink Shortener Extension - Using Google Apps Scripts

πŸ“Ž Google Sheets Hyperlink Shortener App Script

A step-by-step guide to get the "Google Sheets Hyperlink Shortener App Script" up and running in any new Google Sheet πŸ‘‡


1️⃣ Create a New Google Sheet

  • Go to Google Sheets or type sheets.new in your browser's address bar.
  • This creates a brand new, blank spreadsheet.

2️⃣ Open the Apps Script Editor

  • In the top menu of your Sheet, click Extensions > Apps Script.
  • A new tab will open with the Apps Script editor.

3️⃣ Paste the Script Code

  • In the editor, you'll see a file like Code.gs or possibly Untitled project.
  • Delete any default code (function myFunction() {} etc.).
  • Copy the code from the Canvas document titled β€œGoogle Sheets Hyperlink Shortener App Script” and paste it into this file.

4️⃣ Save the Script πŸ’Ύ

  • Click the floppy disk icon or press:
    • Ctrl + S (Windows/Linux) or Cmd + S (Mac).
  • Give your project a name (e.g., Hyperlink Shortener) and confirm.

5️⃣ Authorize the Script (First-Time Only) βœ…

This allows your script to access the spreadsheet.

  • In the Apps Script toolbar:
    • Select onOpen from the dropdown next to the ▢️ Run button.
    • Click ▢️ Run.
  • A dialog will prompt you to review permissions:
    • Click Review permissions, choose your account.
    • Click Advanced, then Go to [Your Project Name] (unsafe).
    • Finally, click Allow.

The onOpen function will now run and create a custom menu in your Sheet.


6️⃣ Go Back to Your Sheet & Refresh πŸ”„

  • Return to your Google Sheet tab.
  • Refresh the page (F5, Ctrl+R, or Cmd+R).
  • You should now see a new menu called Hyperlink Tools between Extensions and Help.

7️⃣ Use the Extension! πŸš€

  • Enter URLs in a column (e.g., Column A).
    • These can be plain text or existing HYPERLINK() formulas.
  • Select a cell in that column.
  • Go to the Hyperlink Tools menu β†’ choose Create Short Hyperlink (Column).
  • The script will shorten all URLs in that column and output the shortened links to the column on the right.

You’ll see a message confirming success at the bottom of your screen πŸŽ‰

{
"timeZone": "Europe/London",
"dependencies": {},
"exceptionLogging": "STACKDRIVER",
"runtimeVersion": "V8"
}
/**
* @file Google Sheets Hyperlink Shortener
* @description This script provides a Google Sheets App Script extension
* to create shorter hyperlinks from existing URLs in cells. It can process
* an entire column, skipping non-URL cells gracefully.
*/
/**
* onOpen function runs automatically when the Google Sheet is opened.
* It creates a custom menu to make the script easily accessible.
*/
function onOpen() {
// Get the active spreadsheet UI.
const ui = SpreadsheetApp.getUi();
// Create a custom menu named "Hyperlink Tools".
ui.createMenu('Hyperlink Tools')
// Add a menu item "Create Short Hyperlink (Column)" that calls the 'createShortHyperlinksInColumn' function.
.addItem('Create Short Hyperlink (Column)', 'createShortHyperlinksInColumn')
// Add the menu to the UI.
.addToUi();
}
/**
* createShortHyperlinksInColumn function processes all cells in the active column
* to create new hyperlinks with shorter display text in the adjacent column.
* It gracefully handles cells that are not valid URLs.
*/
function createShortHyperlinksInColumn() {
// Get the active spreadsheet.
const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
// Get the currently active sheet.
const sheet = spreadsheet.getActiveSheet();
// Get the currently selected cell to determine the active column.
const activeCell = sheet.getActiveCell();
// Get the index of the column where the active cell is located.
const activeColumnIndex = activeCell.getColumn();
// Determine the last row with content in the sheet.
const lastRow = sheet.getLastRow();
// If there are no rows with content, exit.
if (lastRow === 0) {
spreadsheet.toast('The sheet is empty.', 'Info', 3);
return;
}
// Get the entire range of the active column from row 1 to the last row.
// The range is (startRow, startColumn, numRows, numColumns).
const columnRange = sheet.getRange(1, activeColumnIndex, lastRow, 1);
// Get all formulas and display values from the selected column for efficient processing.
const cellFormulas = columnRange.getFormulas();
const cellValues = columnRange.getDisplayValues();
// Initialize an array to hold the new formulas for the target column.
// This will be a 2D array, where each inner array represents a row.
const newFormulasForTargetColumn = [];
let processedCount = 0; // Counter for successfully created hyperlinks.
try {
// Iterate through each row in the collected data.
// 'i' represents the row index (0-based for arrays, 1-based for sheet rows).
for (let i = 0; i < lastRow; i++) {
const currentCellFormula = cellFormulas[i][0]; // [0] because getFormulas returns a 2D array for a single column.
const currentCellValue = cellValues[i][0]; // [0] because getDisplayValues returns a 2D array for a single column.
let url = '';
const shortDisplayText = 'Go to Link'; // Define the short display text for the new hyperlink.
// Check if the cell contains a HYPERLINK formula.
if (currentCellFormula.startsWith('=HYPERLINK(')) {
// Use a regular expression to extract the URL from the HYPERLINK formula.
const urlMatch = currentCellFormula.match(/^=HYPERLINK\("([^"]*)",/);
if (urlMatch && urlMatch[1]) {
url = urlMatch[1];
}
} else if (currentCellValue.startsWith('http://') || currentCellValue.startsWith('https://')) {
// If it's not a HYPERLINK formula, check if the cell value itself is a URL.
url = currentCellValue;
}
// If a valid URL was extracted or found for the current cell.
if (url) {
// Construct the new HYPERLINK formula.
const newHyperlinkFormula = `=HYPERLINK("${url}", "${shortDisplayText}")`;
// Add the new formula to the array for this row.
newFormulasForTargetColumn.push([newHyperlinkFormula]);
processedCount++;
} else {
// If no valid URL was found, add an empty string to the array for this row.
// This ensures the target column maintains its row count and doesn't shift.
newFormulasForTargetColumn.push(['']);
}
}
// Get the target range one column to the right of the active column.
// The range is (startRow, startColumn, numRows, numColumns).
const targetColumnRange = sheet.getRange(1, activeColumnIndex + 1, lastRow, 1);
// Set all the new formulas to the target column in one go for efficiency.
targetColumnRange.setFormulas(newFormulasForTargetColumn);
// Provide feedback to the user.
if (processedCount > 0) {
spreadsheet.toast(`Created ${processedCount} short hyperlinks in column ${String.fromCharCode(64 + activeColumnIndex + 1)}.`, 'Success', 5);
} else {
spreadsheet.toast('No valid URLs found in the selected column to create hyperlinks.', 'Info', 5);
}
} catch (e) {
// Catch any errors that occur during the process and show a toast message.
spreadsheet.toast('An error occurred: ' + e.message, 'Error', 5);
}
}

TBD - Maybe Some Day When I CBA πŸ˜…

🧠 Google Apps Script Integration Overview


πŸ“ 1. Google Cloud Project (Implicit for Bound Scripts)

βœ… No Manual Setup Required

You don’t need to manually create or configure a Google Cloud Project for your script.
Google Apps Script automatically provisions a hidden project for each script, especially for container-bound scripts (like those attached to a Google Sheet).

🎯 Purpose of the Implicit Project

  • Manages the script’s metadata, versions, and API scopes.
  • Powers services like UrlFetchApp (if used).
  • All permissions and configurations are abstracted away by Google.

πŸ› οΈ When Manual Setup Is Needed

Create and link a Google Cloud Project only if:

  • 🌐 You're deploying a Web App or API Executable.
  • πŸ§ͺ You need advanced Google Cloud APIs (e.g., ML or Vision APIs).
  • 🧩 You're building a Google Workspace Add-on for public distribution.

πŸ’‘ Since your script is just a utility within a Google Sheet, you don’t need any of this complexity.


πŸ” 2. OAuth Permissions (Authorization Flow)

🚦 How It Works

  1. πŸ›« First Run: The first time the script uses services like SpreadsheetApp.getUi() or getActiveSpreadsheet(), it triggers an auth check.
  2. πŸ”“ Authorization Dialog: A pop-up appears prompting the user to grant permissions.
    • Example scopes shown:
      • "View and manage your Google Drive files"
      • "Edit your Google Sheets"
  3. πŸ™‹ User Consent: The user clicks β€œAllow” to proceed.
  4. πŸ”‘ Token Issuance: Google securely issues an OAuth token for the script to act on behalf of the user.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment