Skip to content

Instantly share code, notes, and snippets.

@yuler
Created March 2, 2024 15:05
Show Gist options
  • Select an option

  • Save yuler/ea8b950f61d58da91e054341e7d44559 to your computer and use it in GitHub Desktop.

Select an option

Save yuler/ea8b950f61d58da91e054341e7d44559 to your computer and use it in GitHub Desktop.
On-demand JavaScript objects from current HTML <meta> elements
// Origin from Basecamp app.hey.com
// refs: https://app.hey.com/assets/helpers/current_helpers-69434f7688aaf68b68226df19cd29426713fdcad.js
// refs: https://github.com/marcoroth/current.js
/**
* On-demand JavaScript objects from "current" HTML <meta> elements
*
* @example
* ```html
* <meta name="current-identity-id" content="123">
* <meta name="current-identity-time-zone-name" content="Central Time (US & Canada)">
* ```
*
* ```js
* current.identity // => { id: "123", timeZoneName: "Central Time (US & Canada)" }
* current.unknown // => { }
* ```
*/
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())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment