How to set Document Title in PureScript

by||1 min read

Setting a document title according to the context of your SPA can improve user experience. This way the user knows what part of the application is currently open/visible when your application is not the active tab.

In PureScript we can set the document title in two ways, a quick and dirty way via FFI and a proper type-safe way.

Setting Document Title via FFI

To set the document title directly we can define a foreign import (let's say in the file DocTitle.purs

foreign import setDocumentTitle :: String -> Effect Unit

As well we can provide a JavaScript implementation according to our import (in the File DocTitle.js):

export const setDocumentTitle = (title) => {
  return () => {
    window.document.title = title;
  }
}

Setting Document Title using Web.HTML module

To set a title we need to access the document first (which I cover in depth in "How to getElementById in PureScript":

import Web.HTML.HTMLDocument (toNonElementParentNode)
import Web.HTML.Window (document)
import Web.HTML (window)
import Web.DOM.NonElementParentNode (getElementById)

main :: Effect Unit
main = do
  maybeDoc <- map toNonElementParentNode $ document =<< window

With the document we can now use the function setTitle from Web.HTML.HTMLDocument:

import Data.Foldable (for_)
import Web.HTML.HTMLDocument (toNonElementParentNode)
import Web.HTML.Window (document)
import Web.HTML (window)
import Web.DOM.NonElementParentNode (getElementById)

main :: Effect Unit
main = do
  maybeDoc <- map toNonElementParentNode $ document =<< window

Thank you for reading this far! Let’s connect. You can @ me on Twitter (@debilofant) with comments, or feel free to follow. Please like/share this article so that it reaches others as well.

© Copyright 2022 - Ersocon - All rights reservedVer. 2.3.6.9