Please check the build logs for more information.
See Builds for ideas on how to fix a failed build, or Metadata for how to configure docs.rs builds.
If you believe this is docs.rs' fault, open an issue.
A standard library for the client-side Web
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.
Donate
Patrons
This software was brought to you thanks to these wonderful people:
- Daniel Norman
- Ben Berman
- Stephen Sugden
Thank you!
Examples
You can directly embed JavaScript code into Rust:
let message = "Hello, 世界!";
let result = js! ;
println!;
Closures are also supported:
let print_hello = ;
js!
You can also pass arbitrary structures thanks to serde:
js_serializable!;
js! ;
This crate also exposes a number of Web APIs, for example:
let button = document.query_selector.unwrap.unwrap;
button.add_event_listener;
Exposing Rust functions to JavaScript is supported too:
Then you can do this from Node.js:
var hasher = require; // Where `hasher.js` is generated from Rust code.
console.log;
Or you can take the same .js file and use it in a web browser:
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:
import hasher from "./hasher/Cargo.toml";
console.log;
Design goals
- Expose a full suite of Web APIs as exposed by web browsers.
- Try to follow the original JavaScript conventions and structure as much as possible, except in cases where doing otherwise results in a clearly superior design.
- Be a building block from which higher level frameworks and libraries can be built.
- Make it convenient and easy to embed JavaScript code directly into Rust and to marshal data between the two.
- Integrate with the wider Rust ecosystem, e.g. support marshaling of structs which implement serde's Serializable.
- Put Rust in the driver's seat where a non-trivial Web application can be written without touching JavaScript at all.
- Allow Rust to take part in the upcoming WebAssembly (re)volution.
- Make it possible to trivially create standalone libraries which are easily callable from JavaScript.
Getting started
Take a look at some of the examples:
examples/minimal- a totally minimal example which calls alertexamples/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 here
Running the examples
-
Install cargo-web:
$ cargo install -f cargo-web -
Go into
examples/todomvcand 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:8000with 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!
Changelog
-
0.4.3- Objects which cannot be used as keys in a
WeakMapshould be supported now (e.g. some of the WebGL-related objects under Firefox) - New methods:
Element::get_bounding_client_rectElement::scroll_topElement::scroll_leftWindow::page_x_offsetWindow::page_y_offsetNodeList::itemDocument::bodyDocument::headDocument::titleDocument::set_titleIMouseEvent::offset_xIMouseEvent::offset_y
- Expose more canvas related types:
CompositeOperationLineCapLineJoinRepetitionTextAlignTextBaseline
- Expose canvas related error types:
AddColorStopError,DrawImageError,GetImageDataError - New events:
MouseOverEventMouseOutEventPointerOverEventPointerEnterEventPointerDownEventPointerMoveEventPointerUpEventPointerCancelEventPointerOutEventPointerLeaveEventGotPointerCaptureEventLostPointerCaptureEvent
- New interface for pointer events:
IPointerEvent
- Objects which cannot be used as keys in a
-
0.4.2- Fixed a leak when deserializing references
- Fixed
CanvasRenderingContext2d::get_canvas - Exposed
FillRuleandSocketReadyState - New attribute related methods added to
IElement - New
Datebindings
-
0.4.1- Support for newest nightly Rust on
wasm32-unknown-unknown - Exposed
SocketBinaryTypeenum - New canvas APIs:
- Numerous new methods for
CanvasRenderingContext2d - New types:
CanvasGradient,CanvasPattern,CanvasStyle,ImageData,TextMetrics
- Numerous new methods for
- New error types:
IndexSizeError,NotSupportedError,TypeError
- Support for newest nightly Rust on
-
0.4- (breaking change) Removed
ArrayandObjectvariants fromValue; these are now treated asReferences - (breaking change) The
Valuehas an extra variant:Symbol - (breaking change) Removed:
InputElement::set_kindInputElement::files
- (breaking change) Renamed:
KeydownEvent->KeyDownEventKeyupEvent->KeyUpEventKeypressEvent->KeyPressEventReadyState->FileReaderReadyStateInputElement::value->InputElement::raw_valueInputElement::set_value->InputElement::set_raw_value
- (breaking change)
ArrayBuffer::newnow takes anu64argument - (breaking change)
InputElement::set_raw_valuenow takes&strinstead ofInto< Value > - (breaking change) Changed return types:
- Every method which returned
usizenow returnsu32 INode::remove_childnow returnsNodein theOkcase- The following now return an
u64:ArrayBuffer::len
- The following now return an
i32instead off64:IMouseEvent::client_xIMouseEvent::client_yIMouseEvent::movement_xIMouseEvent::movement_yIMouseEvent::screen_xIMouseEvent::screen_y
- The following now return a
Result:INode::insert_beforeINode::replace_childINode::clone_nodeStringMap::insertTokenList::addTokenList::removeDocument::create_elementIEventTarget::dispatch_eventFileReader::read_as_textFileReader::read_as_array_bufferFileReader::read_as_textHistory::replace_stateHistory::goHistory::backHistory::forwardLocation::hrefLocation::hashCanvasElement::to_data_urlCanvasElement::to_blobArrayBuffer::new
INode::base_urinow returns aStringinstead ofOption< String >InputElement::raw_valuenow returns aStringinstead ofValue
- Every method which returned
- (breaking change)
INode::inner_textwas moved toIHtmlElement::inner_text - (breaking change)
Document::query_selectorandDocument::query_selector_allwere moved toIParentNode - (breaking change)
IElement::query_selectorandIElement::query_selector_allwere moved toIParentNode - (breaking change)
Document::get_element_by_idwas moved toINonElementParentNode - (breaking change) A blanket impl for converting between arbitrary reference-like objects using
TryFrom/TryIntohas been removed - When building using a recent
cargo-webit's not necessary to callstdweb::initializenorstdweb::event_loopanymore - Support for
cdylibcrates onwasm32-unknown-unknown - New bindings:
XmlHttpRequestWebSocketMutationObserverHistoryTextAreaElementCanvasElement
- New event types:
MouseDownEventMouseUpEventMouseMoveEventPopStateEventResizeEventReadyStateChangeSocketCloseEventSocketErrorEventSocketOpenEventSocketMessageEvent
- Initial support for the Canvas APIs
- New traits:
ReferenceTypeandInstanceOf - Add
#[derive(ReferenceType)]instdweb-derivecrate; it's now possible to define custom API bindings outside ofstdweb - Add
#[js_export]procedural attribute (wasm32-unknown-unknownonly) - Add
DomExceptionand subtypes for passing around JavaScript exceptions IElementnow inherits fromINode- Every interface now inherits from
ReferenceType - Add
stdweb::traitsmodule to act as a prelude foruse-ing all of our interface traits - Add
console!macro - Most types now implement
PartialEqandEq
- (breaking change) Removed
-
0.3- (breaking change) Deleted
ErrorEventmethods - (breaking change) Renamed:
LoadEvent->ResourceLoadEventAbortEvent->ResourceAbortEventErrorEvent->ResourceErrorEvent
- Add
UnsafeTypedArrayfor zero cost slice passing tojs! - Add
Oncefor passingFnOnceclosures tojs!
- (breaking change) Deleted
License
Licensed under either of
- Apache License, Version 2.0, (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.
Snippets of documentation which come from Mozilla Developer Network are covered under the CC-BY-SA, version 2.5 or later.
Contributing
See CONTRIBUTING.md
