Last active
July 3, 2022 01:49
-
-
Save duduindo/2096bdd5a0131b48e98b5c42a8b0a0eb to your computer and use it in GitHub Desktop.
Example Rust + WebAssembly + localStorage.getItem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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" | |
] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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