How to Access Meta Tags in PureScript

by|inArticles||2 min read
PureScript
PureScript

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
main = do
  mContentValue <- getMetaTag "description"
  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)
getMetaTag identifier = do
    doc <- map toParentNode $ document =<< window
    mMetaTag <- querySelector (QuerySelector ("meta[name=" <> identifier <> "]")) doc
    case mMetaTag of
      Just element -> do
        mContent <- getAttribute "content" element
        pure mContent
      Nothing -> do
        pure Nothing

Accessing Meta Tags in Halogen

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:

handleAction SomeButtonClicked = do
   doc <- map toParentNode $ document =<< window
    mMetaTag <- querySelector (QuerySelector ("meta[name=" <> identifier <> "]")) doc
    case mMetaTag of
      Just element -> do
        mContent <- getAttribute "content" element
        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.

Related Articles

© Copyright 2024 - ersocon.net - All rights reservedVer. 415