0.5.3 - This version may not be safe as it has not been updated for a long time. Find out if your coding project uses this component and get notified of any reported security vulnerabilities with Meterian-X Open Source Security Platform
Maintain your licence declarations and avoid unwanted licences to protect your IP the way you intended.
Apache-2.0 - Apache License 2.0The 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:
Thank you!
You can directly embed JavaScript code into Rust:
let message = "Hello, 世界!";
let result = js! {
alert( @{message} );
return 2 + 2 * 2;
};
println!( "2 + 2 * 2 = {:?}", result );Closures are also supported:
let print_hello = |name: String| {
println!( "Hello, {}!", name );
};
js! {
var print_hello = @{print_hello};
print_hello( "Bob" );
print_hello.drop(); // Necessary to clean up the closure on Rust's side.
}You can also pass arbitrary structures thanks to serde:
#[derive(Serialize)]
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:
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:
#[js_export]
fn hash( string: String ) -> String {
let mut hasher = Sha1::new();
hasher.update( string.as_bytes() );
hasher.digest().to_string()
}Then you can do this from Node.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:
<script src="hasher.js"></script>
<script>
Rust.hasher.then( function( hasher ) {
console.log( hasher.hash( "Hello world!" ) );
});
</script>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( 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 here
The API documentation is also available for you to look at.
Install 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:
$ 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!
stdweb 0.4.20
wasm-bindgen
FullscreenChangeEventstdweb 0.4.19
Document::fullscreen_enabledDocument::fullscreen_elementInputElement::selection_startInputElement::selection_endInputElement::set_selection_startInputElement::set_selection_endObject::to_iterWindow::confirm&Arrays can now be converted to Vecs through TryFrom
futures-related APIs were updated to work with the latest nightliessyn dependency was updated to version 1stdweb 0.4.18
js! macro can now be imported with an use
BeforeUnloadEventUnloadEventIBlob::sliceIBlob::slice_with_content_typeIWindowOrWorker::set_clearable_timeoutstdweb 0.4.17
futures-related APIs were updated to work with the latest nightliesstdweb 0.4.16
wasm-bindgen compatibility; you can now use stdweb in projects
using wasm-bindgen
cargo-web version is now 0.6.24stdweb 0.4.15
futures-related APIs were updated to work with the latest nightliesFormDataFormDataEntryMouseButtonsStateBlob::newstdweb 0.4.14
js! macro now generates slightly more efficient code
if you're not returning anything from your JS snippet. This makes
it unnecessary to add the @(no_return) annotation in the vast
majority of cases.Filestdweb 0.4.13
js! macro's whitespace handlingITouchEventTouchTouchTypeTouchEventTouchMoveTouchLeaveTouchEnterTouchEndTouchCancelTouchStartXmlHttpRequest::set_response_typestdweb 0.4.12
wasm32-unknown-unknown target without cargo-web
stdweb 0.4.11
cargo-web version is now 0.6.22wasm32-unknown-unknown is now officially supported on stable Rustwasm32-unknown-unknown are now supportedjs! macro is now partially implemented using a procedural macroDocument::import_nodeIElement::slotIElement::attach_shadowIElement::shadow_rootISlotableShadowRootShadowRootModeTemplateElementSlotElementSlotChangeEventIParentNode::query_selector and IParentNode::query_selector_all now return a proper error typestdweb 0.4.10, stdweb-derive 0.5.1
IElement::insert_adjacent_htmlIElement::insert_html_beforeIElement::insert_html_afterIElement::prepend_htmlIElement::append_htmlIElement::namespace_uriIElement::closestDocument::create_element_nsWindow::get_selectionAbortErrorSelectionTypeSelectionRange.try_into()/.try_from()) is now convertible into a TypeError
DrawImageError) are now serializable through the js! macroTypeError is now fixed (it was incorrectly treated as a DOMException)Number can now be converted into f64 with .into()/.from()
Mut, which is a new wrapper type for safely passing FnMut closures into the js! macro;
it is optional for now, however the usage of this wrapper type will be mandatory in the future!FnMut closures cannot be called recursively anymore#[derive(ReferenceType)] now supports a limited subset of generic types#[async_test] attribute macro (nightly only)futures 0.3 (nightly only)stdweb 0.4.9, stdweb-derive 0.5.0
ScrollEventDragRelatedEventDragEventDragStartEventDragEndEventDragEnterEventDragLeaveEventDragOverEventDragExitEventDragDropEventDataTransferEffectAllowedDropEffectDataTransferItemListDataTransferItemDataTransferItemKindIDragEventValues can now be converted to Option< Serde< T > > with try_into
i32 and f64 to be usedkeyup event
as a KeyDownEvent since only the event's JS type was checked
and both keyup and keydown share the same JS type (KeyboardEvent).
From now on the type field of the event is also checked, so
such conversions are not allowed anymore.0.4.8
wasm32-unknown-unknown
PointerLockChangeEventPointerLockErrorEventMouseWheelEventMouseWheelDeltaModeXhrResponseTypeXmlHttpRequest::raw_responseWindow::device_pixel_ratioDocument::pointer_lock_elementDocument::exit_pointer_lock0.4.7
AuxClickEventMouseEnterEventMouseLeaveEventContextMenuEventSelectionChangeEventFileListFileReaderReadyStateGamepadGamepadButtonGamepadButtonMappingGamepadEventCanvasRenderingContext2d::clear_rect
TypedArrays from
Vecs and ArrayBuffers.0.4.6
docs.rs againSubmitEventIChildNodeCanvasElement::to_data_url
0.4.5
DocumentFragmentSelectElementOptionElementHtmlCollectionNode::from_htmlValue::is_nullSocketMessageDataNodeTypefutures 0.20.4.4
docs.rs (hopefully).Location::originLocation::protocolLocation::hostLocation::hostnameLocation::portLocation::pathnameLocation::searchSecurityError in the error case:
Location::hashLocation::href0.4.3
WeakMap
should be supported now (e.g. some of the WebGL-related objects under Firefox)Element::get_bounding_client_rectElement::scroll_topElement::scroll_leftWindow::page_x_offsetWindow::page_y_offsetNodeList::itemDocument::bodyDocument::headDocument::titleDocument::set_titleIMouseEvent::offset_xIMouseEvent::offset_yCompositeOperationLineCapLineJoinRepetitionTextAlignTextBaselineAddColorStopError, DrawImageError, GetImageDataError
MouseOverEventMouseOutEventPointerOverEventPointerEnterEventPointerDownEventPointerMoveEventPointerUpEventPointerCancelEventPointerOutEventPointerLeaveEventGotPointerCaptureEventLostPointerCaptureEventIPointerEvent
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 ReferencesValue has an extra variant: Symbol
InputElement::set_kindInputElement::filesKeydownEvent -> 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::leni32 instead of f64:
IMouseEvent::client_xIMouseEvent::client_yIMouseEvent::movement_xIMouseEvent::movement_yIMouseEvent::screen_xIMouseEvent::screen_yResult:
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::newINode::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
XmlHttpRequestWebSocketMutationObserverHistoryTextAreaElementCanvasElementMouseDownEventMouseUpEventMouseMoveEventPopStateEventResizeEventReadyStateChangeSocketCloseEventSocketErrorEventSocketOpenEventSocketMessageEventReferenceType 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