Skip to content

Instantly share code, notes, and snippets.

@AceofSpades5757
Created June 9, 2022 02:06
Show Gist options
  • Save AceofSpades5757/88975a727fe62a169b5fc04271500ad1 to your computer and use it in GitHub Desktop.
Save AceofSpades5757/88975a727fe62a169b5fc04271500ad1 to your computer and use it in GitHub Desktop.
In a browser, set the clipboard (WASM)
[package]
name = "set-web-clipboard"
version = "0.1.0"
edition = "2021"
[dependencies]
# JavaScript in Rust
wasm-bindgen = "0.2" # May not be needed
web-sys = { version = "0.3", features = ["Clipboard"] }
//! Reference: <https://docs.rs/web-sys/0.3.57/web_sys/struct.Clipboard.html>
#[cfg(web_sys_unstable_apis)]
fn set_clipboard(text: String) {
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_namespace = ["navigator", "clipboard"])]
fn writeText(s: &str);
}
writeText(text.as_str());
}
#[cfg(not(web_sys_unstable_apis))]
fn set_clipboard(text: String) {
// This is an unstable Web API. This package needs to be compiled as such.
console::log("Package compiled without unstable APIs.");
}
@AceofSpades5757
Copy link
Author

Thanks to the Yew community for helping with this, quickly and politely. I couldn't find a straightforward solution, so I created this Gist for others.

Feel free to leave comments to anyone with questions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment