Created
October 4, 2024 17:30
-
-
Save dpaluy/415a0607930d20fd57b3fddd5bb3cfcb to your computer and use it in GitHub Desktop.
Dynamic retrieval of meta values into property Current
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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()); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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