Open By URL Or Id

Paste a whole browser URL into SpreadsheetApp.openById and the run dies. openByUrlOrId(urlOrId) accepts a Spreadsheet URL or raw id, extracts /spreadsheets/d/<id> when present, then opens with SpreadsheetApp.openById — so operators can paste whatever the address bar gave them.

When to use

  • Menu prompts / Script Properties that store “the spreadsheet”
  • Handoffs where someone copies the full Chrome URL
  • Any helper that used to assume a clean 44-char id

How to use this snippet

/** * Open a spreadsheet from a full Sheets URL or a raw spreadsheet id. * Extracts /spreadsheets/d/<id> when present; otherwise treats input as id. * @param {string} urlOrId * @return {SpreadsheetApp.Spreadsheet} */ function openByUrlOrId(urlOrId) { var s = String(urlOrId == null ? '' : urlOrId).trim(); if (!s) { throw new Error('openByUrlOrId: empty urlOrId'); } var m = s.match(/\/spreadsheets\/d\/([a-zA-Z0-9-_]+)/); var id = m ? m[1] : s; // Guard obvious “still a URL but not a Sheets URL” pastes if (/^https?:\/\//i.test(id)) { throw new Error('openByUrlOrId: not a Google Sheets URL or id: ' + s.slice(0, 80)); } return SpreadsheetApp.openById(id); }

Example

function openTargetFromProperty_() { var raw = PropertiesService.getScriptProperties().getProperty('targetSpreadsheet'); var ss = openByUrlOrId(raw); Logger.log('Opened %s (%s)', ss.getName(), ss.getId()); return ss; } function promptAndOpen() { var ui = SpreadsheetApp.getUi(); var res = ui.prompt('Spreadsheet URL or id'); if (res.getSelectedButton() !== ui.Button.OK) return; var ss = openByUrlOrId(res.getResponseText()); ui.alert('Opened: ' + ss.getName()); }

Tips:

  • Prefer storing the id in Script Properties after the first successful open — URLs get edit/share query junk appended.
  • openById still needs the caller to have access; this helper only fixes parsing.
  • Docs / Slides URLs won’t match — fail loud instead of feeding https://… to openById.

Tip: NitroGAS Co-Pilot can swap brittle openById(Browser.inputBox(…)) calls for openByUrlOrId so pasted address-bar URLs stop blowing up mid-run.

Happy Coding!

NitroGAS Chrome Extension

Want this snippet handy inside the Apps Script editor? NitroGAS gives you free themes and snippets — plus optional Co-Pilot when you want a boost (1-week, 1-month, or yearly passes — no subscription). Happy Coding!

Get the Extension