Clone in a terminal:
Commit c7ded90
Johan Mattsson - 2026-06-11T21:54:00+00:00
c7ded9097ff81aac69d59542f2572a289cbeadf6johan.mattsson.m@gmail.com

Set cookie value

Changed files (2)

Diff

diff --git a/README.md b/README.mdindex de74779..11f6773 100644--- a/README.md+++ b/README.md@@ -128,7 +128,6 @@ window.addEventListener("DOMContentLoaded", async () => { }); ``` - ## Author and Contact - Written by Johan Mattsson - johan.mattsson.m@gmail.comdiff --git a/src/lib.rs b/src/lib.rsindex 088ca5c..9c3a2b5 100644--- a/src/lib.rs+++ b/src/lib.rs@@ -218,3 +218,32 @@ pub fn get_cookie_value(name: &str) -> Option<String> {     }     None }++/// Set a cookie value+pub fn set_cookie_value(name: &str, value: &str) -> Result<()> {+    let window = web_sys::window().ok_or(Error)?;+    let document = window.document().ok_or(Error)?;+    const MAX_AGE: u64 = 60 * 60 * 24 * 365 * 10; // in seconds++    if let Ok(html_doc) = document.dyn_into::<HtmlDocument>() {+        let cookie = format!("{}={}; path=/; Max-Age={}", name, value, MAX_AGE);+        html_doc.set_cookie(&cookie).map_err(|_| Error)?;+        return Ok(());+    }++    Err(Error)+}++/// Set a session cookie, it will be deleted when the browser is closed.+pub fn set_session_cookie_value(name: &str, value: &str) -> Result<()> {+    let window = web_sys::window().ok_or(Error)?;+    let document = window.document().ok_or(Error)?;++    if let Ok(html_doc) = document.dyn_into::<HtmlDocument>() {+        let cookie = format!("{}={}; path=/", name, value);+        html_doc.set_cookie(&cookie).map_err(|_| Error)?;+        return Ok(());+    }++    Err(Error)+}

Contact

Email: johan.mattsson.m@gmail.com
Mastodon: typo.social/@birdfont
GitHub: johanmattssonm
LinkedIn: johan-mattsson-2ab324112