getPenId()
Signature
Section titled “Signature”SaltyKeys.getPenId(): string | nullReturns
Section titled “Returns”| Value | Meaning |
|---|---|
string | The captured ID from the URL (first capture group of urlPattern). |
null | The URL did not match the pattern and no canonical <link> was found, or caching is disabled and no ID was extractable. |
Behavior
Section titled “Behavior”getPenId() uses a two-step strategy to find the pen ID:
- URL match — tests
window.location.hrefagainstSaltyKeys.config.urlPattern - Canonical link fallback — if the direct URL match fails (common in embedded iframes), looks for
<link rel="canonical">in the document<head>and tests itshrefattribute
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.
Examples
Section titled “Examples”Basic usage
Section titled “Basic usage”const penId = SaltyKeys.getPenId();
if (penId) { console.log('Pen ID:', penId); // e.g. "XWbpNvY"} else { console.warn('Not running in a recognised CodePen context.');}Testing from the browser console
Section titled “Testing from the browser console”Navigate to a CodePen pen, open the console, and run:
SaltyKeys.getPenId(); // → "AbCdEf" (the pen's slug)Resetting the cache
Section titled “Resetting the cache”If you need to force a re-extraction (for example, after navigating in a single-page app):
// Disable and re-enable caching or reconfigureSaltyKeys.configure({ cacheEnabled: false });const id = SaltyKeys.getPenId();SaltyKeys.configure({ cacheEnabled: true });User-facing warnings
Section titled “User-facing warnings”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:
| Situation | Banner 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 all | Configure 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 bothgenerateSaltedKey()andgetApiKey(). You rarely need to call it directly.