Skip to content

getPenId()

SaltyKeys.getPenId(): string | null
ValueMeaning
stringThe captured ID from the URL (first capture group of urlPattern).
nullThe URL did not match the pattern and no canonical <link> was found, or caching is disabled and no ID was extractable.

getPenId() uses a two-step strategy to find the pen ID:

  1. URL match — tests window.location.href against SaltyKeys.config.urlPattern
  2. Canonical link fallback — if the direct URL match fails (common in embedded iframes), looks for <link rel="canonical"> in the document <head> and tests its href attribute

If cacheEnabled is true (the default), the result is stored in a private field after the first successful extraction and returned immediately on subsequent calls.

const penId = SaltyKeys.getPenId();
if (penId) {
console.log('Pen ID:', penId); // e.g. "XWbpNvY"
} else {
console.warn('Not running in a recognised CodePen context.');
}

Navigate to a CodePen pen, open the console, and run:

SaltyKeys.getPenId(); // → "AbCdEf" (the pen's slug)

If you need to force a re-extraction (for example, after navigating in a single-page app):

// Disable and re-enable caching or reconfigure
SaltyKeys.configure({ cacheEnabled: false });
const id = SaltyKeys.getPenId();
SaltyKeys.configure({ cacheEnabled: true });

When getPenId() cannot find an ID and environment is 'codepen' (the default), a dismissable in-page banner is shown at the top of the page. The message differs by situation:

SituationBanner message
On codepen.io but pen has no saved ID (e.g. new/unsaved pen at /pen?editors=1010)Save the pen first, then regenerate the salted key
Not on codepen.io at allConfigure a custom urlPattern or override getPenId()

The warning also logs to console.warn. Each unique warning is shown at most once per page load regardless of how many times getPenId() is called.

No banner is shown when a custom environment is set, since the caller has already opted out of the default CodePen assumptions.

  • The extracted value is the first regex capture group from urlPattern. Make sure your custom pattern has exactly one capture group.
  • getPenId() is called internally by both generateSaltedKey() and getApiKey(). You rarely need to call it directly.