Skip to content

Instantly share code, notes, and snippets.

@duduindo
Last active July 3, 2022 01:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save duduindo/2096bdd5a0131b48e98b5c42a8b0a0eb to your computer and use it in GitHub Desktop.
Save duduindo/2096bdd5a0131b48e98b5c42a8b0a0eb to your computer and use it in GitHub Desktop.
Example Rust + WebAssembly + localStorage.getItem
[package]
name = "hello_world_storage"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ["cdylib"]
[dependencies]
wasm-bindgen = "0.2.81"
[dependencies.web-sys]
version = "0.3.58"
features = [
"Storage",
"Window"
]
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<script type="module">
import init, { get_value_from_storage } from './hello_world_storage.js'
await init()
console.log(get_value_from_storage())
</script>
</body>
</html>
/**
* Documentation:
* - https://rustwasm.github.io/wasm-bindgen/api/src/web_sys/features/gen_Storage.rs.html
* - https://rustwasm.github.io/wasm-bindgen/api/src/web_sys/features/gen_Window.rs.html
*/
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn get_value_from_storage() -> Result<Option<String>, JsValue> {
let window = web_sys::window().unwrap();
let storage = window.local_storage().unwrap();
let local = storage.unwrap();
let key: &'static str = "KEY_TEST";
// Example in JS: localStorage.getItem('KEY_TEST')
local.get_item(key)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment