DEV Community

Cover image for Playing around with browser cookies in Scala.js
Andrew (he/him)
Andrew (he/him)

Posted on

4

Playing around with browser cookies in Scala.js

Photo by Laura James from Pexels

I spent this weekend playing around with Scala.js and learning how to manipulate browser cookies with it.

Check out the live demo at cookies.awwsmm.com.

The source is available at github.com/awwsmm/CookiesScalaJS.

There are a few cool Scala flairs here, particularly this bit which pattern matches on a regular expression

  def clearAllCookies(): Unit = {
    val Cookie = "([^=]+)=.+".r
    document.cookie.split("; ").foreach {
      case Cookie(key) => clearCookie(key)
      case other => err.println(s"Couldn't parse '$other' as a key=value cookie pair")
    }
  }
Enter fullscreen mode Exit fullscreen mode

In order to ensure that users don't include the ; or = characters in their cookie keys and values (which confuses the parser), I've also added these two little safeguards, as well

    // prevent the user from typing ';' or '=' into the input
    input.addEventListener("keypress", (e: dom.KeyboardEvent) => {
      if (e.key == ";" || e.key == "=") {
        e.preventDefault()
      }
    })

    // prevent the user from pasting ';' or '=' into the input
    input.addEventListener("paste", (e: dom.ClipboardEvent) => {
      val text = e.clipboardData.getData("text")
      if (text.contains(";") || text.contains("=")) {
        e.preventDefault()
      }
    })
Enter fullscreen mode Exit fullscreen mode

What do you think? Anyone else on DEV doing anything cool with Scala.js?

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay