dioxus icon indicating copy to clipboard operation
dioxus copied to clipboard

How to interact with clipboard, without JS?

Open i11010520 opened this issue 3 years ago • 6 comments

I wanna fill a button "onclick" callback, to copy some element content to clipboard. Without Javascript, just by native Rust.

Could somebody give me some hints? Thanks!

i11010520 avatar Jun 01 '22 14:06 i11010520

Hi! What platforms do you need to support? For native windows/mac/linux, artboard might be what you're looking for. For wasm, I don't know. I haven't done any of this myself.

Also, take a look at other clipboard crates on lib.rs!

rMazeiks avatar Jun 01 '22 14:06 rMazeiks

Hi! What platforms do you need to support? For native windows/mac/linux, artboard might be what you're looking for. For wasm, I don't know. I haven't done any of this myself.

Also, take a look at other clipboard crates on lib.rs!

My attention is on web/wasm. Thanks anyway.

i11010520 avatar Jun 01 '22 14:06 i11010520

Searching for clipboard+wasm, I found yew-hooks – not what you need, but it has a use_clipboard hook, which we can use as reference.

They use wasm_bindgen to access the clipboard from WASM. In my understanding it generates the JS + WASM bindings automatically based on this black magic. No Javascript required.

You could copy-paste fragments of that as a starting point.

rMazeiks avatar Jun 01 '22 15:06 rMazeiks

Searching for clipboard+wasm, I found yew-hooks – not what you need, but it has a use_clipboard hook, which we can use as reference.

They use wasm_bindgen to access the clipboard from WASM. In my understanding it generates the JS + WASM bindings automatically based on this black magic. No Javascript required.

You could copy-paste fragments of that as a starting point.

That's a very good reference! Thanks! @rMazeiks

i11010520 avatar Jun 02 '22 13:06 i11010520

Welp, apparently there's an easier way

let clipboard = window()?.navigator().clipboard()?;

https://docs.rs/web-sys/latest/web_sys/struct.Clipboard.html

rMazeiks avatar Jul 09 '22 20:07 rMazeiks

Welp, apparently there's an easier way

let clipboard = window()?.navigator().clipboard()?;

https://docs.rs/web-sys/latest/web_sys/struct.Clipboard.html

As the yew-hooks' inline comment said:

//! ClipboardEvent in web-sys is unstable and
//! requires `--cfg=web_sys_unstable_apis` to be activated,
//! which is inconvenient, so copy the binding code here for now.

And based on these copied web-sys code, they build use_clipboard state handle and hook then, to make using clipboard more conveniently.

i11010520 avatar Jul 13 '22 11:07 i11010520

You can now use dioxus std to interact with the clipboard in a cross platform way! Here is the code that handles the clipboard

ealmloff avatar Aug 02 '23 16:08 ealmloff