Skip to content

Instantly share code, notes, and snippets.

@dpaluy
Created October 4, 2024 17:30
Show Gist options
  • Save dpaluy/415a0607930d20fd57b3fddd5bb3cfcb to your computer and use it in GitHub Desktop.
Save dpaluy/415a0607930d20fd57b3fddd5bb3cfcb to your computer and use it in GitHub Desktop.
Dynamic retrieval of meta values into property Current
// On-demand JavaScript objects from "current" HTML <meta> elements. Example:
//
// <meta name="current-identity-id" content="123">
// <meta name="current-identity-time-zone-name" content="Central Time (US & Canada)">
//
// >> Current.identity
// => { id: "123", timeZoneName: "Central Time (US & Canada)" }
//
// >> Current.foo
// => {}
export const Current = new Proxy({}, {
get(_target, propertyName) {
const result = {};
const prefix = `current-${propertyName}-`;
for (const { name, content } of document.head.querySelectorAll(`meta[name^=${prefix}]`)) {
const key = camelize(name.slice(prefix.length));
result[key] = content;
}
return result;
}
});
function camelize(string) {
return string.replace(/(?:[_-])([a-z0-9])/g, (_, char) => char.toUpperCase());
}
<html>
<head>
<meta name="current-identity-id" content="123">
<meta name="current-identity-time-zone-name" content="Central Time (US & Canada)">
</head>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment