Websites often have useful information stored in form of meta tags in the head part of the HTML. In this article we will explore how to access those meta tags in Purescript.
The process of accessing Meta Tags in PureScript is not much different from the method in vanilla JavaScript. We can access Meta Tags by using the querySelector of the document. The only difference in PureScript, we explicitly indicate the access to Meta Tags as an effectful function.
Recently I already wrote in detail about basics in PureScript, for instance How to set Document Title in PureScript. I encourage you to read this if you are interested about things happening behind the scenes in PureScript.
Let's assume you would like to access the description meta tag in your PureScript code. We can create a new function called "getMetaTag" and assume that it will be an effectful function, like so:
main :: Effect Unit
= do
main <- getMetaTag "description"
mContentValue pure unit
getMetaTag :: String -> Effect (Maybe String)
With this definition, we can continue to our implementation. This for we will access window and document, search for the desired meta tag by using the QuerySelector and finally extract the value of our optional Element:
getMetaTag :: String -> Effect (Maybe String)
= do
getMetaTag identifier <- map toParentNode $ document =<< window
doc <- querySelector (QuerySelector ("meta[name=" <> identifier <> "]")) doc
mMetaTag case mMetaTag of
Just element -> do
<- getAttribute "content" element
mContent pure mContent
Nothing -> do
pure Nothing
To run the same code in a Halogen App we just need to lift the effectful parts. Let's assume we have an Action that we need to handle:
SomeButtonClicked = do
handleAction <- map toParentNode $ document =<< window
doc <- querySelector (QuerySelector ("meta[name=" <> identifier <> "]")) doc
mMetaTag case mMetaTag of
Just element -> do
<- getAttribute "content" element
mContent pure mContent
Nothing -> do
pure Nothing
Thank you for reading this far! Let’s connect. You can @ me on X (@debilofant) with comments, or feel free to follow. Please like/share this article so that it reaches others as well.