The goal of this crate is to provide Rust bindings to the Web APIs and to allow a high degree of interoperability between Rust and JavaScript.
This software was brought to you thanks to these wonderful people: * Daniel Norman * Ben Berman * Stephen Sugden
Thank you!
You can directly embed JavaScript code into Rust:
```rust let message = "Hello, 世界!"; let result = js! { alert( @{message} ); return 2 + 2 * 2; };
println!( "2 + 2 * 2 = {:?}", result ); ```
Closures are also supported:
```rust let print_hello = |name: String| { println!( "Hello, {}!", name ); };
js! { var printhello = @{printhello}; printhello( "Bob" ); printhello.drop(); // Necessary to clean up the closure on Rust's side. } ```
You can also pass arbitrary structures thanks to [serde]:
```rust
struct Person { name: String, age: i32 }
js_serializable!( Person );
js! { var person = @{person}; console.log( person.name + " is " + person.age + " years old." ); }; ```
This crate also exposes a number of Web APIs, for example:
rust
let button = document().query_selector( "#hide-button" ).unwrap().unwrap();
button.add_event_listener( move |_: ClickEvent| {
for anchor in document().query_selector_all( "#main a" ) {
js!( @{anchor}.style = "display: none;"; );
}
});
Exposing Rust functions to JavaScript is supported too:
```rust
fn hash( string: String ) -> String { let mut hasher = Sha1::new(); hasher.update( string.asbytes() ); hasher.digest().tostring() } ```
Then you can do this from Node.js:
js
var hasher = require( "hasher.js" ); // Where `hasher.js` is generated from Rust code.
console.log( hasher.hash( "Hello world!" ) );
Or you can take the same .js
file and use it in a web browser:
```html
```
If you're using [Parcel] you can also use our [experimental Parcel plugin]; first do this in your existing Parcel project:
$ npm install --save parcel-plugin-cargo-web
And then simply:
js
import hasher from "./hasher/Cargo.toml";
console.log( hasher.hash( "Hello world!" ) );
Take a look at some of the examples:
examples/minimal
- a totally minimal example which calls [alert]examples/todomvc
- a naively implemented [TodoMVC] application; shows how to call into the DOMexamples/hasher
- shows how to export Rust functions to JavaScript and how to call them from
a vanilla web browser environment or from Nodejsexamples/hasher-parcel
- shows how to import and call exported Rust functions in a [Parcel] projectpinky-web
] - an NES emulator; you can play with the precompiled version hereInstall [cargo-web]:
$ cargo install -f cargo-web
Go into examples/todomvc
and start the example using one of these commands:
Compile to [WebAssembly] using Rust's native WebAssembly backend (requires Rust nightly!):
$ cargo web start --target=wasm32-unknown-unknown
Compile to [asm.js] using Emscripten:
$ cargo web start --target=asmjs-unknown-emscripten
Compile to [WebAssembly] using Emscripten:
$ cargo web start --target=wasm32-unknown-emscripten
Visit http://localhost:8000
with your browser.
For the *-emscripten
targets cargo-web
is not necessary, however
the native wasm32-unknown-unknown
which doesn't need Emscripten
requires cargo-web
to work!
0.4.4
docs.rs
(hopefully).Location::origin
Location::protocol
Location::host
Location::hostname
Location::port
Location::pathname
Location::search
SecurityError
in the error case:
Location::hash
Location::href
0.4.3
WeakMap
should be supported now (e.g. some of the WebGL-related objects under Firefox)Element::get_bounding_client_rect
Element::scroll_top
Element::scroll_left
Window::page_x_offset
Window::page_y_offset
NodeList::item
Document::body
Document::head
Document::title
Document::set_title
IMouseEvent::offset_x
IMouseEvent::offset_y
CompositeOperation
LineCap
LineJoin
Repetition
TextAlign
TextBaseline
AddColorStopError
, DrawImageError
, GetImageDataError
MouseOverEvent
MouseOutEvent
PointerOverEvent
PointerEnterEvent
PointerDownEvent
PointerMoveEvent
PointerUpEvent
PointerCancelEvent
PointerOutEvent
PointerLeaveEvent
GotPointerCaptureEvent
LostPointerCaptureEvent
IPointerEvent
0.4.2
CanvasRenderingContext2d::get_canvas
FillRule
and SocketReadyState
IElement
Date
bindings0.4.1
wasm32-unknown-unknown
SocketBinaryType
enumCanvasRenderingContext2d
CanvasGradient
, CanvasPattern
, CanvasStyle
, ImageData
, TextMetrics
IndexSizeError
, NotSupportedError
, TypeError
0.4
Array
and Object
variants from Value
; these are now treated as Reference
sValue
has an extra variant: Symbol
InputElement::set_kind
InputElement::files
KeydownEvent
-> KeyDownEvent
KeyupEvent
-> KeyUpEvent
KeypressEvent
-> KeyPressEvent
ReadyState
-> FileReaderReadyState
InputElement::value
-> InputElement::raw_value
InputElement::set_value
-> InputElement::set_raw_value
ArrayBuffer::new
now takes an u64
argumentInputElement::set_raw_value
now takes &str
instead of Into< Value >
usize
now returns u32
INode::remove_child
now returns Node
in the Ok
caseu64
:
ArrayBuffer::len
i32
instead of f64
:
IMouseEvent::client_x
IMouseEvent::client_y
IMouseEvent::movement_x
IMouseEvent::movement_y
IMouseEvent::screen_x
IMouseEvent::screen_y
Result
:
INode::insert_before
INode::replace_child
INode::clone_node
StringMap::insert
TokenList::add
TokenList::remove
Document::create_element
IEventTarget::dispatch_event
FileReader::read_as_text
FileReader::read_as_array_buffer
FileReader::read_as_text
History::replace_state
History::go
History::back
History::forward
Location::href
Location::hash
CanvasElement::to_data_url
CanvasElement::to_blob
ArrayBuffer::new
INode::base_uri
now returns a String
instead of Option< String >
InputElement::raw_value
now returns a String
instead of Value
INode::inner_text
was moved to IHtmlElement::inner_text
Document::query_selector
and Document::query_selector_all
were moved to IParentNode
IElement::query_selector
and IElement::query_selector_all
were moved to IParentNode
Document::get_element_by_id
was moved to INonElementParentNode
TryFrom
/TryInto
has been removedcargo-web
it's not necessary to call
stdweb::initialize
nor stdweb::event_loop
anymorecdylib
crates on wasm32-unknown-unknown
XmlHttpRequest
WebSocket
MutationObserver
History
TextAreaElement
CanvasElement
MouseDownEvent
MouseUpEvent
MouseMoveEvent
PopStateEvent
ResizeEvent
ReadyStateChange
SocketCloseEvent
SocketErrorEvent
SocketOpenEvent
SocketMessageEvent
ReferenceType
and InstanceOf
#[derive(ReferenceType)]
in stdweb-derive
crate; it's now possible
to define custom API bindings outside of stdweb
#[js_export]
procedural attribute (wasm32-unknown-unknown
only)DomException
and subtypes for passing around JavaScript exceptionsIElement
now inherits from INode
ReferenceType
stdweb::traits
module to act as a prelude for use
-ing all of our interface traitsconsole!
macroPartialEq
and Eq
0.3
ErrorEvent
methodsLoadEvent
-> ResourceLoadEvent
AbortEvent
-> ResourceAbortEvent
ErrorEvent
-> ResourceErrorEvent
UnsafeTypedArray
for zero cost slice passing to js!
Once
for passing FnOnce
closures to js!
Licensed under either of
at your option.
Snippets of documentation which come from [Mozilla Developer Network] are covered under the [CC-BY-SA, version 2.5] or later.
See CONTRIBUTING.md