Skip to content

Truly independent web browser

LibWeb: Implement Storage and StorageEvent in Rust

Shannon Boothf08a79423204
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/event_target.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/event_target.rs
index a776ec6e68c..ac6039ab142 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/event_target.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/event_target.rs
@@ -89,6 +89,8 @@ unsafe extern "C" {
event: *mut c_void,
) -> bool;
fn web_bindings_event_canceled(event: *mut c_void) -> bool;
+ fn web_bindings_event_dispatched(event: *mut c_void) -> bool;
+ fn web_bindings_initialize_event(event: *mut c_void, r#type: usize, bubbles: bool, cancelable: bool);
}
/// The EventTarget that an object owns.
@@ -317,6 +319,18 @@ impl CppEvent {
// SAFETY: The event is live.
unsafe { web_bindings_event_canceled(self.as_ptr()) }
}
+
+ /// https://dom.spec.whatwg.org/#dispatch-flag
+ pub(crate) fn dispatched(&self) -> bool {
+ // SAFETY: The event is live.
+ unsafe { web_bindings_event_dispatched(self.as_ptr()) }
+ }
+
+ /// https://dom.spec.whatwg.org/#concept-event-initialize
+ pub(crate) fn initialize_event(&self, r#type: &Utf16String, bubbles: bool, cancelable: bool) {
+ // SAFETY: The event is live, and the type is lent for the call.
+ unsafe { web_bindings_initialize_event(self.as_ptr(), r#type.raw_identity(), bubbles, cancelable) };
+ }
}
/// The data attribute of a MessageEvent, which the value is a wrapper of.
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/global_object.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/global_object.rs
index 0eef7cda409..d30be250b10 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/global_object.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/global_object.rs
@@ -9,15 +9,20 @@
use core::ffi::c_void;
use core::ptr::NonNull;
-use libjs_rust::api::{Gc, Object, Trace};
+use libjs_rust::api::{Gc, MarkedVec, Object, Trace, Vm};
use liburl_rust::Url;
use crate::bindings::cpp_cell::CppCell;
+use crate::bindings::event_target::CppEventTarget;
use crate::bindings::interface::Wrappable;
unsafe extern "C" {
fn web_bindings_window_from_global_object(global_object: *mut c_void) -> *mut c_void;
+ fn web_bindings_for_each_active_window(ctx: *mut c_void, on_window: unsafe extern "C" fn(*mut c_void, *mut c_void));
fn web_bindings_window_associated_document(window: *mut c_void) -> *mut c_void;
+ fn web_bindings_window_page_id(window: *mut c_void) -> u64;
+ fn web_bindings_window_as_event_target(window: *mut c_void) -> *mut c_void;
+ fn web_bindings_document_has_navigable(document: *mut c_void) -> bool;
fn web_bindings_document_is_fully_active(document: *mut c_void) -> bool;
fn web_bindings_document_url(document: *mut c_void) -> liburl_rust::RustUrl;
fn web_bindings_worker_global_scope_from_global_object(global_object: *mut c_void) -> *mut c_void;
@@ -74,7 +79,36 @@ pub(crate) fn worker_global_scope_from_global_object(global_object: Gc<Object>)
.map(CppWorkerGlobalScope)
}
+unsafe extern "C" fn on_active_window(windows: *mut c_void, window: *mut c_void) {
+ // SAFETY: windows is the list of the caller, and LibWeb passes a live Window.
+ unsafe { &*windows.cast::<MarkedVec<'_, CppWindow>>() }.push(CppWindow(unsafe { CppCell::from_raw(window) }));
+}
+
+/// Every Window of this process whose associated Document is fully active.
+pub(crate) fn active_windows(vm: &Vm) -> MarkedVec<'_, CppWindow> {
+ let windows = MarkedVec::new(vm);
+ // SAFETY: The list outlives the call.
+ unsafe { web_bindings_for_each_active_window((&raw const windows).cast_mut().cast(), on_active_window) };
+ windows
+}
+
impl CppWindow {
+ pub(crate) fn as_ptr(&self) -> *mut c_void {
+ self.0.as_ptr()
+ }
+
+ /// The Window as an EventTarget.
+ pub(crate) fn as_event_target(&self) -> CppEventTarget {
+ // SAFETY: The Window is live, and LibWeb returns it as an EventTarget.
+ unsafe { CppEventTarget::from_raw(web_bindings_window_as_event_target(self.0.as_ptr())) }
+ }
+
+ /// The id of the page whose traversable navigable the Window's navigable belongs to.
+ pub(crate) fn page_id(&self) -> u64 {
+ // SAFETY: The Window is live.
+ unsafe { web_bindings_window_page_id(self.0.as_ptr()) }
+ }
+
/// https://html.spec.whatwg.org/multipage/nav-history-apis.html#concept-document-window
pub(crate) fn associated_document(&self) -> CppDocument {
// SAFETY: The Window is live, and LibWeb returns its live associated Document.
@@ -89,6 +123,12 @@ impl CppDocument {
unsafe { web_bindings_document_is_fully_active(self.0.as_ptr()) }
}
+ /// Whether the Document's node navigable is not null, https://html.spec.whatwg.org/multipage/document-sequences.html#node-navigable
+ pub(crate) fn has_navigable(&self) -> bool {
+ // SAFETY: The Document is live.
+ unsafe { web_bindings_document_has_navigable(self.0.as_ptr()) }
+ }
+
/// https://dom.spec.whatwg.org/#concept-document-url
pub(crate) fn url(&self) -> Url {
// SAFETY: The Document is live, and LibWeb lends its URL, which this copies before the Document can change it.
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs
index c91c7af5d20..682924551aa 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs
@@ -22,10 +22,15 @@ use super::broadcast_channel::{BROADCAST_CHANNEL_MESSAGE_CLASS, BroadcastChannel
use super::image_bitmap::ImageBitmap;
use super::image_data::ImageData;
use super::message_port::MessagePort;
+use super::storage::{Storage, StorageType, dispatch_storage_events};
+use super::storage_event::{StorageEvent, StorageEventInit};
use crate::bindings::CallContext;
+use crate::bindings::conversions::UsvString;
use crate::bindings::event_target::CppEventTarget;
use crate::bindings::interface::{Interface, Ref, cell_from_abi, cell_into_abi, realm_arguments};
+use crate::dom::event::EventInit;
use crate::html::structured_serialize::message_record::MessageRecord;
+use crate::storage_api::storage_bottle::StorageBottle;
use crate::storage_api::storage_key::StorageKey;
/// The implementation of the object whose cell C++ lends, for as long as C++ keeps the cell alive.
@@ -390,3 +395,104 @@ pub unsafe extern "C" fn web_rust_broadcast_channel_deliver_message_locally(
});
BroadcastChannel::deliver_message_locally(vm, message, None);
}
+
+/// A new Storage object of the type, 0 for "local" and 1 for "session", whose map is the bottle, in the realm of the
+/// Window it is for.
+///
+/// # Safety
+///
+/// The pointers must be the live VM, a live realm and a live StorageAPI::StorageBottle.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_html_create_storage(
+ vm: *mut c_void,
+ realm: *mut c_void,
+ storage_type: u8,
+ map: *mut c_void,
+) -> *mut c_void {
+ // SAFETY: The caller passes the live VM, a live realm and a live bottle.
+ let ((vm, realm), map) = unsafe { (realm_arguments(vm, realm), StorageBottle::from_raw(map)) };
+ cell_into_abi(Storage::create(vm, realm, StorageType::from_abi(storage_type), map))
+}
+
+/// The StorageAPI::StorageBottle that is the map of the Storage object.
+///
+/// # Safety
+///
+/// `storage` must be the live cell of a Storage object.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_html_storage_map(storage: *mut c_void) -> *mut c_void {
+ // SAFETY: The caller passes a live Storage object, which keeps its map alive.
+ unsafe { object_from_abi::<Storage>(storage) }.map().as_ptr()
+}
+
+/// The Event of a new StorageEvent in the realm whose type is the empty string and whose attributes are their
+/// defaults, for createEvent().
+///
+/// # Safety
+///
+/// The pointers must be the live VM and a live realm.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_html_create_storage_event(vm: *mut c_void, realm: *mut c_void) -> *mut c_void {
+ // SAFETY: The caller passes the live VM and a live realm.
+ let (vm, realm) = unsafe { realm_arguments(vm, realm) };
+ let event_init = StorageEventInit {
+ parent: EventInit {
+ bubbles: false,
+ cancelable: false,
+ composed: false,
+ },
+ key: None,
+ old_value: None,
+ new_value: None,
+ url: UsvString::from_utf8(""),
+ storage_area: None,
+ };
+ StorageEvent::create(vm, realm, &Utf16String::from_utf8(""), event_init)
+ .event()
+ .as_ptr()
+}
+
+/// Fires the storage events for a change that another process made to a storage area of the type whose storage key
+/// has the origin, which C++ lends, with the page of its traversable navigable, for a "session" type, the strings, raw
+/// AK::Utf16Strings that C++ hands over, and the URL, which C++ lends.
+///
+/// # Safety
+///
+/// The VM must be live, the origin must be one that C++ lends, and every string that the flag next to it says is
+/// there must be one that C++ hands over.
+#[unsafe(no_mangle)]
+#[allow(clippy::too_many_arguments, reason = "a change has these parts")]
+pub unsafe extern "C" fn web_rust_html_dispatch_storage_events_for_remote_change(
+ vm: *mut c_void,
+ storage_type: u8,
+ origin: *const FfiOrigin,
+ has_session_page: bool,
+ session_page: u64,
+ has_key: bool,
+ key: usize,
+ has_old_value: bool,
+ old_value: usize,
+ has_new_value: bool,
+ new_value: usize,
+ url: ak::Span<'_, u8>,
+) {
+ // SAFETY: The caller passes the live VM.
+ let vm = unsafe { &*vm.cast::<Vm>() };
+ // SAFETY: The caller lends the origin for the call.
+ let storage_key = StorageKey {
+ origin: unsafe { (*origin).to_origin() },
+ };
+ // SAFETY: The caller hands over the strings that the flags say are there.
+ let string = |is_there: bool, raw: usize| is_there.then(|| unsafe { Utf16String::from_raw_owned(raw) });
+ dispatch_storage_events(
+ vm,
+ StorageType::from_abi(storage_type),
+ &storage_key,
+ has_session_page.then_some(session_page),
+ string(has_key, key),
+ string(has_old_value, old_value),
+ string(has_new_value, new_value),
+ &String::from_utf8_lossy(url.as_slice()),
+ None,
+ );
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs
index 131866d4aaa..229aa35cca2 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs
@@ -7,7 +7,7 @@
//! The 2D canvas contexts, with the attributes and operations of each of their mixins in the module of its IDL file,
//! the objects that they draw with, the images that they and WebGL read and write the pixels of, and the operations of
//! a path that Path2D and the contexts share. The state that the contexts share is in crate::canvas_2d. The message
-//! ports and channels of web messaging and the broadcast channels are here as well.
+//! ports and channels of web messaging, the broadcast channels and Web Storage are here as well.
pub(crate) mod canvas_path;
pub(crate) mod color_stops;
@@ -69,6 +69,10 @@ pub(crate) mod offscreen_canvas_rendering_context2d;
#[cfg(not(test))]
pub(crate) mod path2d;
#[cfg(not(test))]
+pub(crate) mod storage;
+#[cfg(not(test))]
+pub(crate) mod storage_event;
+#[cfg(not(test))]
pub(crate) mod structured_serialize;
#[cfg(not(test))]
pub(crate) mod text_metrics;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/storage.rs b/Libraries/LibWeb/Bindings/Rust/src/html/storage.rs
new file mode 100644
index 00000000000..a437d8f3968
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/storage.rs
@@ -0,0 +1,402 @@
+/*
+ * Copyright (c) 2022, Andreas Kling <[email protected]>
+ * Copyright (c) 2023, Luke Wilde <[email protected]>
+ * Copyright (c) 2024-2026, Shannon Booth <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Storage, https://html.spec.whatwg.org/multipage/webstorage.html#storage-2
+
+use core::ffi::c_void;
+
+use ak::Utf16String;
+use libjs_rust::api::{EmbedderClass, EmbedderValue, Gc, MarkedVec, Realm, Throw, Trace, Value, Visitor, Vm};
+use liburl_rust::url::ExcludeFragment;
+
+use crate::bindings::conversions::UsvString;
+use crate::bindings::global_object::{CppWindow, active_windows, relevant_global_object, window_from_global_object};
+use crate::bindings::interface::{Ref, Wrappable, allocate, cell_from_abi};
+use crate::bindings::promise::{TaskSource, queue_a_global_task};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+use crate::dom::event::EventInit;
+use crate::html::storage_event::{StorageEvent, StorageEventInit};
+use crate::storage_api::storage_bottle::StorageBottle;
+use crate::storage_api::storage_key::{StorageKey, obtain_a_storage_key};
+use crate::webidl::dom_exception::DOMExceptionFields;
+use crate::webidl::quota_exceeded_error::{self, QuotaExceededErrorFields};
+
+unsafe extern "C" {
+ fn web_html_window_storage(window: *mut c_void, storage_type: u8) -> *mut c_void;
+}
+
+/// https://html.spec.whatwg.org/multipage/webstorage.html#concept-storage-type
+#[derive(Clone, Copy, PartialEq, Eq)]
+#[repr(u8)]
+pub(crate) enum StorageType {
+ Local = 0,
+ Session = 1,
+}
+
+impl StorageType {
+ /// The storage type that LibWeb passes, an HTML::Storage::Type.
+ pub(crate) fn from_abi(value: u8) -> Self {
+ match value {
+ 0 => StorageType::Local,
+ 1 => StorageType::Session,
+ _ => panic!("LibWeb passes a storage type"),
+ }
+ }
+}
+
+// SAFETY: A storage type holds no cells.
+unsafe impl Trace for StorageType {
+ fn trace(&self, _: &mut Visitor) {}
+}
+
+// https://html.spec.whatwg.org/multipage/webstorage.html#storage-2
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct Storage {
+ realm: Gc<Realm>,
+ storage_type: StorageType,
+ map: StorageBottle,
+}
+
+impl Wrappable for Storage {
+ fn relevant_realm(&self) -> Option<Gc<Realm>> {
+ Some(self.realm)
+ }
+}
+
+/// The key, values and URL of a change to a storage area, which the storage events for it carry.
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+struct StorageChange {
+ key: Option<Utf16String>,
+ old_value: Option<Utf16String>,
+ new_value: Option<Utf16String>,
+ #[gc(untraced)]
+ url: UsvString,
+}
+
+static STORAGE_CHANGE_CLASS: EmbedderClass<StorageChange> = EmbedderClass::new("StorageChange");
+
+impl EmbedderValue for StorageChange {
+ const CLASS: &'static EmbedderClass<Self> = &STORAGE_CHANGE_CLASS;
+}
+
+/// The Storage object that the Window's localStorage or sessionStorage getter returns, if it does not throw.
+fn window_storage(window: &CppWindow, storage_type: StorageType) -> Option<Ref<Storage>> {
+ // SAFETY: The Window is live, and LibWeb returns null or the live cell of a Storage object.
+ let storage = unsafe { web_html_window_storage(window.as_ptr(), storage_type as u8) };
+ // SAFETY: A non-null pointer is the live cell of a Storage object.
+ (!storage.is_null()).then(|| unsafe { cell_from_abi::<Storage>(storage) })
+}
+
+/// Fires the storage events for a change to a storage area of the type with the storage key, made by the script of
+/// excluded_storage when the change was made in this process: steps 3 and 4 of broadcast.
+///
+/// NB: The map lives in the browser process and is mirrored here; the mirror tells the browser of a change made here,
+/// and the browser relays it to every other process mirroring the map, where these steps run with no
+/// excluded_storage. session_page is the page of the change's traversable navigable, for a "session" type.
+#[allow(clippy::too_many_arguments, reason = "a change has these parts")]
+pub(crate) fn dispatch_storage_events(
+ vm: &Vm,
+ storage_type: StorageType,
+ storage_key: &StorageKey,
+ session_page: Option<u64>,
+ key: Option<Utf16String>,
+ old_value: Option<Utf16String>,
+ new_value: Option<Utf16String>,
+ url: &str,
+ excluded_storage: Option<Ref<Storage>>,
+) {
+ // 3. Let remoteStorages be all Storage objects excluding storage whose:
+ let remote_storages = MarkedVec::new(vm);
+
+ // AD-HOC: The specification defines this by iterating over created Storage objects. However, Storage objects are
+ // created lazily when accessed through window.localStorage or window.sessionStorage. This means that events
+ // will not be fired to Windows who have not had these properties accessed - which is not expected.
+ // See: https://github.com/whatwg/html/issues/10135. To solve this, we instead iterate over all active
+ // windows, and initialize any storage objects as part of this loop.
+ let windows = active_windows(vm);
+ for window in windows.values().iter() {
+ // * type is storage's type
+ let Some(storage) = window_storage(window, storage_type) else {
+ continue;
+ };
+
+ // "excluding storage"
+ if Some(storage) == excluded_storage {
+ continue;
+ }
+
+ // * relevant settings object's origin is same origin with storage's relevant settings object's origin
+ // NB: A storage key is an origin, and two keys are equal when their origins are same origin. Compared as the
+ // keys the bottles are kept under, so the file: documents that share one bottle hear each other.
+ if obtain_a_storage_key(storage.realm).as_ref() != Some(storage_key) {
+ continue;
+ }
+
+ // * and, if type is "session", whose relevant settings object's associated Document's node navigable's
+ // traversable navigable is thisDocument's node navigable's traversable navigable.
+ // NB: A page's documents all belong to one traversable, so the page stands for the traversable here.
+ if storage_type == StorageType::Session {
+ // NB: It is possible the remote storage may have not been fully teared down immediately at the point it's
+ // document is made inactive.
+ if !window.associated_document().has_navigable() {
+ continue;
+ }
+
+ if session_page != Some(window.page_id()) {
+ continue;
+ }
+ }
+
+ remote_storages.push(storage);
+ }
+
+ if remote_storages.is_empty() {
+ return;
+ }
+
+ let change = STORAGE_CHANGE_CLASS.allocate(vm, |_| StorageChange {
+ key,
+ old_value,
+ new_value,
+ url: UsvString::from_utf8(url),
+ });
+
+ // 4. For each remoteStorage of remoteStorages: queue a global task on the DOM manipulation task source given
+ // remoteStorage's relevant global object to fire an event named storage at remoteStorage's relevant global
+ // object, using StorageEvent, with key initialized to key, oldValue initialized to oldValue, newValue
+ // initialized to newValue, url initialized to url, and storageArea initialized to remoteStorage.
+ for &remote_storage in remote_storages.values().iter() {
+ let global: &Storage = &remote_storage;
+ queue_a_global_task(
+ vm,
+ relevant_global_object(global),
+ TaskSource::DOMManipulation,
+ (remote_storage, change),
+ |vm, (remote_storage, change)| {
+ let event_init = StorageEventInit {
+ parent: EventInit {
+ bubbles: false,
+ cancelable: false,
+ composed: false,
+ },
+ key: change.key.clone(),
+ old_value: change.old_value.clone(),
+ new_value: change.new_value.clone(),
+ url: change.url.clone(),
+ storage_area: Some(remote_storage),
+ };
+ let event =
+ StorageEvent::create(vm, remote_storage.realm, &Utf16String::from_utf8("storage"), event_init);
+ event.event().set_is_trusted(true);
+ remote_storage.window().as_event_target().dispatch_event(event.event());
+ },
+ );
+ }
+}
+
+impl Storage {
+ pub(crate) fn create(vm: &Vm, realm: Gc<Realm>, storage_type: StorageType, map: StorageBottle) -> Ref<Storage> {
+ allocate(vm, |_| Storage {
+ realm,
+ storage_type,
+ map,
+ })
+ }
+
+ pub(crate) fn map(&self) -> &StorageBottle {
+ &self.map
+ }
+
+ /// The Window that is the relevant global object.
+ fn window(&self) -> CppWindow {
+ window_from_global_object(relevant_global_object(self)).expect("a Storage belongs to a Window")
+ }
+
+ /// The serialization of the URL of the associated Document of the relevant global object.
+ fn document_url(&self) -> String {
+ self.window()
+ .associated_document()
+ .url()
+ .serialize(ExcludeFragment::No)
+ .to_owned()
+ }
+
+ // https://html.spec.whatwg.org/multipage/webstorage.html#dom-storage-length
+ pub(crate) fn length(&self, _: &mut CallContext) -> WebIdlResult<u32> {
+ // The length getter steps are to return this's map's size.
+ Ok(u32::try_from(self.map.size()).expect("the quota keeps a map below 2^32 entries"))
+ }
+
+ // https://html.spec.whatwg.org/multipage/webstorage.html#dom-storage-key
+ pub(crate) fn key(&self, _: &mut CallContext, index: u32) -> WebIdlResult<Option<Utf16String>> {
+ // 1. If index is greater than or equal to this's map's size, then return null.
+ // 2. Let keys be the result of running get the keys on this's map.
+ // NB: We combine these steps so we don't have to do two IPC calls and cause a race condition if the storage bottle
+ // changes size between them.
+ let keys = self.map.keys();
+
+ // 3. Return keys[index].
+ Ok(keys.into_iter().nth(index as usize))
+ }
+
+ // https://html.spec.whatwg.org/multipage/webstorage.html#dom-storage-getitem
+ pub(crate) fn get_item(&self, _: &mut CallContext, key: Utf16String) -> WebIdlResult<Option<Utf16String>> {
+ // 1. If this's map[key] does not exist, then return null.
+ // 2. Return this's map[key].
+ Ok(self.map.get(&key))
+ }
+
+ // https://html.spec.whatwg.org/multipage/webstorage.html#dom-storage-setitem
+ pub(crate) fn set_item(
+ this: &Ref<Self>,
+ cx: &mut CallContext,
+ key: Utf16String,
+ value: Utf16String,
+ ) -> WebIdlResult<()> {
+ // 1. Let oldValue be null.
+ // 2. Let reorder be true.
+ let mut reorder = true;
+
+ // 3. If this's map[key] exists:
+ // 1. Set oldValue to this's map[key].
+ // 2. If oldValue is value, then return.
+ // 3. Set reorder to false.
+ // 4. If value cannot be stored, then throw a "QuotaExceededError" DOMException.
+ // 5. Set this's map[key] to value.
+
+ let url = this.document_url();
+ let Ok(old_value) = this.map.set(&key, &value, &url) else {
+ return Err(this.quota_exceeded_error(cx));
+ };
+
+ if let Some(old_value) = &old_value {
+ if *old_value == value {
+ return Ok(());
+ }
+
+ reorder = false;
+ }
+
+ // 6. If reorder is true, then reorder this.
+ if reorder {
+ this.reorder();
+ }
+
+ // 7. Broadcast this with key, oldValue, and value.
+ Self::broadcast(this, cx.vm(), Some(key), old_value, Some(value), &url);
+
+ Ok(())
+ }
+
+ fn quota_exceeded_error(&self, cx: &CallContext) -> Exception {
+ let quota = self.map.quota().expect("a bottle that refuses a value has a quota");
+ let fields = QuotaExceededErrorFields {
+ dom_exception: DOMExceptionFields {
+ name: Utf16String::from_utf8("QuotaExceededError"),
+ message: Utf16String::from_utf8(&format!("Unable to store more than {quota} bytes in storage")),
+ },
+ quota: None,
+ requested: None,
+ };
+ Exception::Thrown(Throw::new(Value::from_object(quota_exceeded_error::create(
+ cx.realm(),
+ &fields,
+ ))))
+ }
+
+ // https://html.spec.whatwg.org/multipage/webstorage.html#dom-storage-removeitem
+ pub(crate) fn remove_item(this: &Ref<Self>, cx: &mut CallContext, key: Utf16String) -> WebIdlResult<()> {
+ // 1. If this's map[key] does not exist, then return.
+ // 2. Set oldValue to this's map[key].
+ let Some(old_value) = this.map.get(&key) else {
+ return Ok(());
+ };
+
+ // 3. Remove this's map[key].
+ let url = this.document_url();
+ this.map.remove(&key, &url);
+
+ // 4. Reorder this.
+ this.reorder();
+
+ // 5. Broadcast this with key, oldValue, and null.
+ Self::broadcast(this, cx.vm(), Some(key), Some(old_value), None, &url);
+
+ Ok(())
+ }
+
+ // https://html.spec.whatwg.org/multipage/webstorage.html#dom-storage-clear
+ pub(crate) fn clear(this: &Ref<Self>, cx: &mut CallContext) -> WebIdlResult<()> {
+ // 1. If this's map is empty, then return.
+ if this.map.size() == 0 {
+ return Ok(());
+ }
+
+ // 2. Clear this's map.
+ let url = this.document_url();
+ this.map.clear(&url);
+
+ // 3. Broadcast this with null, null, and null.
+ Self::broadcast(this, cx.vm(), None, None, None, &url);
+
+ Ok(())
+ }
+
+ // https://html.spec.whatwg.org/multipage/webstorage.html#concept-storage-reorder
+ #[allow(
+ clippy::unused_self,
+ reason = "reordering is implementation-defined, and does nothing here"
+ )]
+ fn reorder(&self) {
+ // To reorder a Storage object storage, reorder storage's map's entries in an implementation-defined manner.
+ // NOTE: This basically means that we're not required to maintain any particular iteration order.
+ }
+
+ // https://html.spec.whatwg.org/multipage/webstorage.html#concept-storage-broadcast
+ fn broadcast(
+ this: &Ref<Self>,
+ vm: &Vm,
+ key: Option<Utf16String>,
+ old_value: Option<Utf16String>,
+ new_value: Option<Utf16String>,
+ url: &str,
+ ) {
+ // 1. Let thisDocument be storage's relevant global object's associated Document.
+ // 2. Let url be the serialization of thisDocument's URL.
+ // NB: The caller serialized it, for the bottle; it is the same document's URL.
+
+ // NB: The key the bottle is kept under, not the bare origin: Every file: document shares one bottle (see "obtain
+ // a storage key"), so each hears the others' changes. A window that has no key has no bottle to have written.
+ let Some(storage_key) = obtain_a_storage_key(this.realm) else {
+ return;
+ };
+ let session_page = (this.storage_type == StorageType::Session).then(|| this.window().page_id());
+
+ // Steps 3 and 4.
+ dispatch_storage_events(
+ vm,
+ this.storage_type,
+ &storage_key,
+ session_page,
+ key,
+ old_value,
+ new_value,
+ url,
+ Some(*this),
+ );
+ }
+
+ pub(crate) fn supported_property_names(&self, _: &mut CallContext) -> Vec<Utf16String> {
+ // The supported property names on a Storage object storage are the result of running get the keys on storage's
+ // map.
+ self.map.keys()
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/storage_event.rs b/Libraries/LibWeb/Bindings/Rust/src/html/storage_event.rs
new file mode 100644
index 00000000000..0cd53398385
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/storage_event.rs
@@ -0,0 +1,148 @@
+/*
+ * Copyright (c) 2024, Shannon Booth <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! StorageEvent, https://html.spec.whatwg.org/multipage/webstorage.html#storageevent
+
+use core::ffi::c_void;
+use core::ptr::NonNull;
+
+use ak::Utf16String;
+use libjs_rust::api::{Gc, GcRefCell, Realm, Trace, Vm};
+
+use crate::bindings::conversions::UsvString;
+use crate::bindings::event_target::CppEvent;
+use crate::bindings::interface::{Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, WebIdlResult};
+use crate::dom::event::EventInit;
+use crate::html::storage::Storage;
+
+/// The dictionary StorageEventInit of HTML/StorageEvent.idl.
+pub(crate) struct StorageEventInit {
+ pub(crate) parent: EventInit,
+ pub(crate) key: Option<Utf16String>,
+ pub(crate) old_value: Option<Utf16String>,
+ pub(crate) new_value: Option<Utf16String>,
+ pub(crate) url: UsvString,
+ pub(crate) storage_area: Option<Ref<Storage>>,
+}
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+struct StorageEventState {
+ key: Option<Utf16String>,
+ old_value: Option<Utf16String>,
+ new_value: Option<Utf16String>,
+ #[gc(untraced)]
+ url: UsvString,
+ storage_area: Option<Ref<Storage>>,
+}
+
+// https://html.spec.whatwg.org/multipage/webstorage.html#storageevent
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct StorageEvent {
+ event: CppEvent,
+ state: GcRefCell<StorageEventState>,
+}
+
+impl Wrappable for StorageEvent {
+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {
+ self.event.as_cpp_parent()
+ }
+}
+
+impl StorageEvent {
+ pub(crate) fn create(
+ vm: &Vm,
+ realm: Gc<Realm>,
+ event_name: &Utf16String,
+ event_init: StorageEventInit,
+ ) -> Ref<StorageEvent> {
+ let event = CppEvent::create_for_owner(
+ realm,
+ event_name,
+ event_init.parent.bubbles,
+ event_init.parent.cancelable,
+ event_init.parent.composed,
+ );
+ let object = allocate(vm, |_| StorageEvent {
+ event,
+ state: GcRefCell::new(StorageEventState {
+ key: event_init.key,
+ old_value: event_init.old_value,
+ new_value: event_init.new_value,
+ url: event_init.url,
+ storage_area: event_init.storage_area,
+ }),
+ });
+ object.event.set_owner(object);
+ object
+ }
+
+ pub(crate) fn construct(
+ cx: &mut CallContext,
+ r#type: Utf16String,
+ event_init_dict: StorageEventInit,
+ ) -> WebIdlResult<Ref<StorageEvent>> {
+ Ok(Self::create(cx.vm(), cx.realm(), &r#type, event_init_dict))
+ }
+
+ pub(crate) fn event(&self) -> &CppEvent {
+ &self.event
+ }
+
+ pub(crate) fn key(&self, _: &mut CallContext) -> WebIdlResult<Option<Utf16String>> {
+ Ok(self.state.borrow().key.clone())
+ }
+
+ pub(crate) fn old_value(&self, _: &mut CallContext) -> WebIdlResult<Option<Utf16String>> {
+ Ok(self.state.borrow().old_value.clone())
+ }
+
+ pub(crate) fn new_value(&self, _: &mut CallContext) -> WebIdlResult<Option<Utf16String>> {
+ Ok(self.state.borrow().new_value.clone())
+ }
+
+ pub(crate) fn url(&self, _: &mut CallContext) -> WebIdlResult<UsvString> {
+ Ok(self.state.borrow().url.clone())
+ }
+
+ pub(crate) fn storage_area(&self, _: &mut CallContext) -> WebIdlResult<Option<Ref<Storage>>> {
+ Ok(self.state.borrow().storage_area)
+ }
+
+ // https://html.spec.whatwg.org/multipage/webstorage.html#dom-storageevent-initstorageevent
+ #[allow(clippy::too_many_arguments, reason = "the operation has these arguments")]
+ pub(crate) fn init_storage_event(
+ &self,
+ cx: &mut CallContext,
+ r#type: Utf16String,
+ bubbles: bool,
+ cancelable: bool,
+ key: Option<Utf16String>,
+ old_value: Option<Utf16String>,
+ new_value: Option<Utf16String>,
+ url: UsvString,
+ storage_area: Option<Ref<Storage>>,
+ ) -> WebIdlResult<()> {
+ // The initStorageEvent(type, bubbles, cancelable, key, oldValue, newValue, url, storageArea) method must initialize
+ // the event in a manner analogous to the similarly-named initEvent() method. [DOM]
+ if self.event.dispatched() {
+ return Ok(());
+ }
+
+ self.event.initialize_event(&r#type, bubbles, cancelable);
+ *self.state.borrow_mut(cx.vm()) = StorageEventState {
+ key,
+ old_value,
+ new_value,
+ url,
+ storage_area,
+ };
+ Ok(())
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/storage_api/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/storage_api/mod.rs
index 56cdf15aa72..f3b52eaae1b 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/storage_api/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/storage_api/mod.rs
@@ -6,4 +6,5 @@
//! The Storage Standard, https://storage.spec.whatwg.org/
+pub(crate) mod storage_bottle;
pub(crate) mod storage_key;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/storage_api/storage_bottle.rs b/Libraries/LibWeb/Bindings/Rust/src/storage_api/storage_bottle.rs
new file mode 100644
index 00000000000..546c236acaf
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/storage_api/storage_bottle.rs
@@ -0,0 +1,133 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Storage bottles, https://storage.spec.whatwg.org/#storage-bottle
+
+use core::ffi::c_void;
+
+use ak::Utf16String;
+use libjs_rust::api::Trace;
+
+use crate::bindings::cpp_cell::CppCell;
+
+unsafe extern "C" {
+ fn web_storage_api_storage_bottle_size(bottle: *mut c_void) -> usize;
+ fn web_storage_api_storage_bottle_keys(
+ bottle: *mut c_void,
+ keys: *mut c_void,
+ append: unsafe extern "C" fn(*mut c_void, usize),
+ );
+ fn web_storage_api_storage_bottle_get(bottle: *mut c_void, key: usize, value: *mut usize) -> bool;
+ /// 0 when the quota refuses the value, 1 for a new key, and 2 for a key that had the old value.
+ fn web_storage_api_storage_bottle_set(
+ bottle: *mut c_void,
+ key: usize,
+ value: usize,
+ document_url: ak::Span<'_, u8>,
+ old_value: *mut usize,
+ ) -> u8;
+ fn web_storage_api_storage_bottle_remove(bottle: *mut c_void, key: usize, document_url: ak::Span<'_, u8>);
+ fn web_storage_api_storage_bottle_clear(bottle: *mut c_void, document_url: ak::Span<'_, u8>);
+ fn web_storage_api_storage_bottle_quota(bottle: *mut c_void, quota: *mut u64) -> bool;
+}
+
+/// The value cannot be stored, as the bottle's quota does not leave room for it.
+pub(crate) struct QuotaExceeded;
+
+/// A storage bottle of LibWeb's C++ code, StorageAPI::StorageBottle. Its map is this process's mirror of the one the
+/// browser process keeps.
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct StorageBottle(CppCell);
+
+unsafe extern "C" fn append_key(keys: *mut c_void, key: usize) {
+ // SAFETY: keys is the list of the caller, and LibWeb hands over the key.
+ unsafe { (*keys.cast::<Vec<Utf16String>>()).push(Utf16String::from_raw_owned(key)) };
+}
+
+impl StorageBottle {
+ /// # Safety
+ ///
+ /// `bottle` must be a live StorageAPI::StorageBottle.
+ pub(crate) unsafe fn from_raw(bottle: *mut c_void) -> Self {
+ // SAFETY: The caller passes a live bottle.
+ Self(unsafe { CppCell::from_raw(bottle) })
+ }
+
+ pub(crate) fn as_ptr(&self) -> *mut c_void {
+ self.0.as_ptr()
+ }
+
+ pub(crate) fn size(&self) -> usize {
+ // SAFETY: The bottle is live.
+ unsafe { web_storage_api_storage_bottle_size(self.as_ptr()) }
+ }
+
+ /// https://infra.spec.whatwg.org/#map-getting-the-keys
+ pub(crate) fn keys(&self) -> Vec<Utf16String> {
+ let mut keys: Vec<Utf16String> = Vec::new();
+ // SAFETY: The bottle is live, and the keys outlive the call.
+ unsafe { web_storage_api_storage_bottle_keys(self.as_ptr(), (&raw mut keys).cast(), append_key) };
+ keys
+ }
+
+ pub(crate) fn get(&self, key: &Utf16String) -> Option<Utf16String> {
+ let mut value = 0;
+ // SAFETY: The bottle is live, and the key and the value outlive the call.
+ let exists = unsafe { web_storage_api_storage_bottle_get(self.as_ptr(), key.raw_identity(), &raw mut value) };
+ // SAFETY: LibWeb hands over the value it found.
+ exists.then(|| unsafe { Utf16String::from_raw_owned(value) })
+ }
+
+ /// The value the key had, if it existed, or the refusal of the bottle's quota.
+ pub(crate) fn set(
+ &self,
+ key: &Utf16String,
+ value: &Utf16String,
+ document_url: &str,
+ ) -> Result<Option<Utf16String>, QuotaExceeded> {
+ let mut old_value = 0;
+ // SAFETY: The bottle is live, and the strings and the old value outlive the call.
+ let result = unsafe {
+ web_storage_api_storage_bottle_set(
+ self.as_ptr(),
+ key.raw_identity(),
+ value.raw_identity(),
+ ak::Span::new(document_url.as_bytes()),
+ &raw mut old_value,
+ )
+ };
+ match result {
+ 0 => Err(QuotaExceeded),
+ 1 => Ok(None),
+ // SAFETY: LibWeb hands over the old value.
+ _ => Ok(Some(unsafe { Utf16String::from_raw_owned(old_value) })),
+ }
+ }
+
+ pub(crate) fn remove(&self, key: &Utf16String, document_url: &str) {
+ // SAFETY: The bottle is live, and the strings outlive the call.
+ unsafe {
+ web_storage_api_storage_bottle_remove(
+ self.as_ptr(),
+ key.raw_identity(),
+ ak::Span::new(document_url.as_bytes()),
+ );
+ }
+ }
+
+ pub(crate) fn clear(&self, document_url: &str) {
+ // SAFETY: The bottle is live, and the URL outlives the call.
+ unsafe { web_storage_api_storage_bottle_clear(self.as_ptr(), ak::Span::new(document_url.as_bytes())) };
+ }
+
+ /// https://storage.spec.whatwg.org/#storage-bottle-quota
+ pub(crate) fn quota(&self) -> Option<u64> {
+ let mut quota = 0;
+ // SAFETY: The bottle is live, and the quota outlives the call.
+ unsafe { web_storage_api_storage_bottle_quota(self.as_ptr(), &raw mut quota) }.then_some(quota)
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
index 29ad194c045..3c0b2ae59ab 100644
--- a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
+++ b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
@@ -27,6 +27,7 @@
#include <LibWeb/HTML/Window.h>
#include <LibWeb/HTML/WindowProxy.h>
#include <LibWeb/HTML/WorkerGlobalScope.h>
+#include <LibWeb/Page/Page.h>
#include <LibWeb/Platform/EventLoopPlugin.h>
#include <LibWeb/WebIDL/AbstractOperations.h>
#include <LibWeb/WebIDL/CallbackType.h>
@@ -114,7 +115,11 @@ void web_bindings_pop_element_queue_and_invoke_reactions();
bool web_bindings_realm_is_window(void* realm);
bool web_bindings_realm_is_secure_context(void* realm);
HTML::Window* web_bindings_window_from_global_object(JSObject* global_object);
+void web_bindings_for_each_active_window(void* ctx, void (*on_window)(void*, HTML::Window*));
DOM::Document* web_bindings_window_associated_document(HTML::Window*);
+u64 web_bindings_window_page_id(HTML::Window*);
+DOM::EventTarget* web_bindings_window_as_event_target(HTML::Window*);
+bool web_bindings_document_has_navigable(DOM::Document*);
bool web_bindings_document_is_fully_active(DOM::Document*);
URL::FFI::RustUrl web_bindings_document_url(DOM::Document*);
HTML::WorkerGlobalScope* web_bindings_worker_global_scope_from_global_object(JSObject* global_object);
@@ -205,11 +210,34 @@ HTML::Window* web_bindings_window_from_global_object(JSObject* global_object)
return HTML::window_from_global_object(*JS::HostABI::object_from_abi(global_object));
}
+void web_bindings_for_each_active_window(void* ctx, void (*on_window)(void*, HTML::Window*))
+{
+ HTML::Window::for_each_active([&](HTML::Window& window) {
+ on_window(ctx, &window);
+ return IterationDecision::Continue;
+ });
+}
+
DOM::Document* web_bindings_window_associated_document(HTML::Window* window)
{
return &window->associated_document();
}
+u64 web_bindings_window_page_id(HTML::Window* window)
+{
+ return window->page().client().id().value();
+}
+
+DOM::EventTarget* web_bindings_window_as_event_target(HTML::Window* window)
+{
+ return window;
+}
+
+bool web_bindings_document_has_navigable(DOM::Document* document)
+{
+ return document->navigable() != nullptr;
+}
+
bool web_bindings_document_is_fully_active(DOM::Document* document)
{
return document->is_fully_active();
diff --git a/Libraries/LibWeb/Bindings/RustEventTarget.cpp b/Libraries/LibWeb/Bindings/RustEventTarget.cpp
index 1610d7996c1..3c6d7fc68f4 100644
--- a/Libraries/LibWeb/Bindings/RustEventTarget.cpp
+++ b/Libraries/LibWeb/Bindings/RustEventTarget.cpp
@@ -125,6 +125,8 @@ void web_bindings_event_set_is_trusted(DOM::Event*, bool is_trusted);
bool web_bindings_dispatch_event(DOM::EventTarget*, DOM::Event*);
bool web_bindings_dispatch_event_with_legacy_output_did_listeners_throw_flag(DOM::EventTarget*, DOM::Event*);
bool web_bindings_event_canceled(DOM::Event*);
+bool web_bindings_event_dispatched(DOM::Event*);
+void web_bindings_initialize_event(RustEvent*, FlatPtr type, bool bubbles, bool cancelable);
}
RustEventTarget* web_bindings_create_event_target()
@@ -254,3 +256,14 @@ bool web_bindings_event_canceled(DOM::Event* event)
{
return event->cancelled();
}
+
+bool web_bindings_event_dispatched(DOM::Event* event)
+{
+ return event->dispatched();
+}
+
+void web_bindings_initialize_event(RustEvent* event, FlatPtr type, bool bubbles, bool cancelable)
+{
+ auto type_string = Utf16String::from_raw(type);
+ event->initialize_event(Utf16FlyString::from_utf16(type_string.utf16_view()), bubbles, cancelable);
+}
diff --git a/Libraries/LibWeb/Bindings/RustEventTarget.h b/Libraries/LibWeb/Bindings/RustEventTarget.h
index 440c91f0622..c28c9edfbd4 100644
--- a/Libraries/LibWeb/Bindings/RustEventTarget.h
+++ b/Libraries/LibWeb/Bindings/RustEventTarget.h
@@ -53,6 +53,9 @@ public:
void set_owner(InterfaceName, RustInterfaceCell&);
+ // For the init*Event() operations of its owner.
+ using DOM::Event::initialize_event;
+
private:
RustEvent(Utf16FlyString const& type, DOM::EventInit const&, HighResolutionTime::DOMHighResTimeStamp);
diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cpp
index 06df110018d..9e034925099 100644
--- a/Libraries/LibWeb/DOM/Document.cpp
+++ b/Libraries/LibWeb/DOM/Document.cpp
@@ -3979,7 +3979,7 @@ WebIDL::ExceptionOr<GC::Ref<Event>> Document::create_event(Utf16FlyString const&
|| interface.equals_ignoring_ascii_case("mouseevents"sv)) {
event = UIEvents::MouseEvent::create(FlyString {}, UIEvents::MouseEventOptions {}, 0, 0, 0, 0, time_stamp);
} else if (interface.equals_ignoring_ascii_case("storageevent"sv)) {
- event = HTML::StorageEvent::create(Utf16FlyString {}, {}, time_stamp);
+ event = HTML::create_storage_event(realm);
} else if (interface.equals_ignoring_ascii_case("svgevents"sv)) {
event = Event::create(FlyString {}, time_stamp);
} else if (interface.equals_ignoring_ascii_case("textevent"sv)) {
diff --git a/Libraries/LibWeb/HTML/Storage.cpp b/Libraries/LibWeb/HTML/Storage.cpp
index 59cc1bc9852..c732c1a4783 100644
--- a/Libraries/LibWeb/HTML/Storage.cpp
+++ b/Libraries/LibWeb/HTML/Storage.cpp
@@ -2,300 +2,75 @@
* Copyright (c) 2022, Andreas Kling <[email protected]>
* Copyright (c) 2023, Luke Wilde <[email protected]>
* Copyright (c) 2024-2026, Shannon Booth <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/String.h>
-#include <LibGC/Heap.h>
-#include <LibGC/RootVector.h>
-#include <LibWeb/DOM/Document.h>
-#include <LibWeb/HTML/LocalNavigable.h>
-#include <LibWeb/HTML/Navigable.h>
+#include <LibJS/HostClassBuilder.h>
+#include <LibJS/Runtime/Realm.h>
+#include <LibURL/RustIntegration.h>
+#include <LibWeb/Bindings/MainThreadVM.h>
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/HTML/Storage.h>
-#include <LibWeb/HTML/StorageEvent.h>
#include <LibWeb/HTML/Window.h>
-#include <LibWeb/Infra/SerializedURL.h>
-#include <LibWeb/Page/Page.h>
-#include <LibWeb/StorageAPI/StorageKey.h>
-#include <LibWeb/WebIDL/QuotaExceededError.h>
+#include <LibWebCommon/StorageAPI/StorageKey.h>
namespace Web::HTML {
-GC_DEFINE_ALLOCATOR(Storage);
+extern "C" {
-GC::Ref<Storage> Storage::create(Window& window, Type type, GC::Ref<StorageAPI::StorageBottle> storage_bottle)
-{
- return GC::Heap::the().allocate<Storage>(window, type, move(storage_bottle));
-}
-
-Storage::Storage(Window& window, Type type, GC::Ref<StorageAPI::StorageBottle> storage_bottle)
- : m_window(window)
- , m_type(type)
- , m_storage_bottle(move(storage_bottle))
-{
-}
-
-GC::Ptr<Bindings::Wrappable> Storage::relevant_global_impl() const
-{
- return m_window;
-}
-
-Storage::~Storage() = default;
-
-void Storage::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_window);
- visitor.visit(m_storage_bottle);
-}
-
-// https://html.spec.whatwg.org/multipage/webstorage.html#dom-storage-length
-size_t Storage::length() const
-{
- // The length getter steps are to return this's map's size.
- return m_storage_bottle->size();
-}
-
-// https://html.spec.whatwg.org/multipage/webstorage.html#dom-storage-key
-Optional<Utf16String> Storage::key(size_t index)
-{
- // 1. If index is greater than or equal to this's map's size, then return null.
- // 2. Let keys be the result of running get the keys on this's map.
- // NB: We combine these steps so we don't have to do two IPC calls and cause a race condition if the storage bottle
- // changes size between them.
- auto keys = m_storage_bottle->keys();
- if (index >= keys.size())
- return {};
-
- // 3. Return keys[index].
- return keys[index];
-}
+// Defined in Bindings/Rust/src/html/exports.rs.
+void* web_rust_html_create_storage(JSVM*, void* realm, u8 type, StorageAPI::StorageBottle* map);
+StorageAPI::StorageBottle* web_rust_html_storage_map(Storage*);
+void web_rust_html_dispatch_storage_events_for_remote_change(JSVM*, u8 type, URL::FFI::FfiOrigin const* origin, bool has_session_page, u64 session_page, bool has_key, FlatPtr key, bool has_old_value, FlatPtr old_value, bool has_new_value, FlatPtr new_value, ReadonlyBytes url);
-// https://html.spec.whatwg.org/multipage/webstorage.html#dom-storage-getitem
-Optional<Utf16String> Storage::get_item(Utf16View key) const
-{
- // 1. If this's map[key] does not exist, then return null.
- // 2. Return this's map[key].
- return m_storage_bottle->get(key);
+// Declared on the Rust side in Bindings/Rust/src/html/storage.rs.
+Storage* web_html_window_storage(Window*, u8 type);
}
-// https://html.spec.whatwg.org/multipage/webstorage.html#dom-storage-setitem
-WebIDL::ExceptionOr<void> Storage::set_item(Utf16View key, Utf16View value)
-{
- // 1. Let oldValue be null.
- // 2. Let reorder be true.
- bool reorder = true;
-
- // 3. If this's map[key] exists:
- // 1. Set oldValue to this's map[key].
- // 2. If oldValue is value, then return.
- // 3. Set reorder to false.
- // 4. If value cannot be stored, then throw a "QuotaExceededError" DOMException.
- // 5. Set this's map[key] to value.
-
- auto url = m_window->associated_document().url().serialize();
- auto result = m_storage_bottle->set(key, value, url);
-
- if (result.has<WebView::StorageOperationError>())
- return WebIDL::QuotaExceededError::create(Utf16String::formatted("Unable to store more than {} bytes in storage", *m_storage_bottle->quota()));
-
- auto old_value = result.get<Optional<Utf16String>>();
-
- if (old_value.has_value()) {
- if (old_value.value() == value)
- return {};
-
- reorder = false;
- }
-
- // 6. If reorder is true, then reorder this.
- if (reorder)
- this->reorder();
-
- // 7. Broadcast this with key, oldValue, and value.
- Optional<Utf16View> old_value_view;
- if (old_value.has_value())
- old_value_view = old_value->utf16_view();
- broadcast(key, old_value_view, value, url);
-
- return {};
-}
-
-// https://html.spec.whatwg.org/multipage/webstorage.html#dom-storage-removeitem
-void Storage::remove_item(Utf16View key)
-{
- // 1. If this's map[key] does not exist, then return.
- // 2. Set oldValue to this's map[key].
- auto old_value = m_storage_bottle->get(key);
- if (!old_value.has_value())
- return;
-
- // 3. Remove this's map[key].
- auto url = m_window->associated_document().url().serialize();
- m_storage_bottle->remove(key, url);
-
- // 4. Reorder this.
- reorder();
-
- // 5. Broadcast this with key, oldValue, and null.
- broadcast(key, old_value->utf16_view(), {}, url);
-}
-
-// https://html.spec.whatwg.org/multipage/webstorage.html#dom-storage-clear
-void Storage::clear()
+GC::Ref<Storage> Storage::create(Window& window, Type type, GC::Ref<StorageAPI::StorageBottle> storage_bottle)
{
- // 1. If this's map is empty, then return.
- if (m_storage_bottle->size() == 0)
- return;
-
- // 2. Clear this's map.
- auto url = m_window->associated_document().url().serialize();
- m_storage_bottle->clear(url);
-
- // 3. Broadcast this with null, null, and null.
- broadcast({}, {}, {}, url);
+ auto& realm = relevant_realm(window);
+ return *static_cast<Storage*>(web_rust_html_create_storage(JS::HostABI::vm_to_abi(realm.vm()), &realm, to_underlying(type), storage_bottle.ptr()));
}
-// https://html.spec.whatwg.org/multipage/webstorage.html#concept-storage-reorder
-void Storage::reorder()
+StorageAPI::StorageBottle& Storage::map()
{
- // To reorder a Storage object storage, reorder storage's map's entries in an implementation-defined manner.
- // NOTE: This basically means that we're not required to maintain any particular iteration order.
+ return *web_rust_html_storage_map(this);
}
-static GC::Ptr<Storage> obtain_storage_for_window(Window& window, Storage::Type type)
+void Storage::dump()
{
- if (type == Storage::Type::Local) {
- auto storage = window.local_storage();
- if (storage.is_exception())
- return {};
- return storage.release_value();
+ auto keys = map().keys();
+ dbgln("Storage ({} key(s))", keys.size());
+ size_t i = 0;
+ for (auto const& key : keys) {
+ auto value = map().get(key);
+ dbgln("[{}] \"{}\": \"{}\"", i, key, value.value());
+ ++i;
}
-
- auto storage = window.session_storage();
- if (storage.is_exception())
- return {};
- return storage.release_value();
}
-// https://html.spec.whatwg.org/multipage/webstorage.html#concept-storage-broadcast
-void Storage::broadcast(Optional<Utf16View> key, Optional<Utf16View> old_value, Optional<Utf16View> new_value, String const& url)
+void Storage::dispatch_storage_events_for_remote_change(Type type, StorageAPI::StorageKey const& storage_key, Optional<PageId> session_page, Optional<Utf16String> const& key, Optional<Utf16String> const& old_value, Optional<Utf16String> const& new_value, String const& url)
{
- // 1. Let thisDocument be storage's relevant global object's associated Document.
- // 2. Let url be the serialization of thisDocument's URL.
- // NB: The caller serialized it, for the bottle; it is the same document's URL.
-
- // NB: The map lives in the browser process and is mirrored here; the mirror told the browser of this change
- // before this runs, and the browser relays it to every other process mirroring the map, where steps 3 and 4
- // run for the Storage objects there. Here they run for this process's, excluding this one.
- auto to_utf16_string = [](Optional<Utf16View> value) -> Optional<Utf16String> {
- if (!value.has_value())
- return {};
- return Utf16String::from_utf16(*value);
+ auto raw = [](Optional<Utf16String> const& string) -> FlatPtr {
+ if (!string.has_value())
+ return 0;
+ return Utf16String { *string }.into_raw();
};
- // NB: The key the bottle is kept under, not the bare origin: Every file: document shares one bottle (see "obtain
- // a storage key"), so each hears the others' changes. A window that has no key has no bottle to have written.
- auto storage_key = StorageAPI::obtain_a_storage_key(relevant_settings_object(*m_window));
- if (!storage_key.has_value())
- return;
- Optional<PageId> session_page;
- if (type() == Type::Session)
- session_page = m_window->page().client().id();
- dispatch_storage_events_for_remote_change(type(), *storage_key, session_page, to_utf16_string(key), to_utf16_string(old_value), to_utf16_string(new_value), url, this);
-}
-
-void Storage::dispatch_storage_events_for_remote_change(Type type, StorageAPI::StorageKey const& storage_key, Optional<PageId> session_page, Optional<Utf16String> const& key, Optional<Utf16String> const& old_value, Optional<Utf16String> const& new_value, String const& url_string, GC::Ptr<Storage> excluded_storage)
-{
- auto url = utf16_string_from_url_ascii(url_string);
-
- // 3. Let remoteStorages be all Storage objects excluding storage whose:
- GC::RootVector<GC::Ref<Storage>> remote_storages;
-
- // AD-HOC: The specification defines this by iterating over created Storage objects. However, Storage objects are
- // created lazily when accessed through window.localStorage or window.sessionStorage. This means that events
- // will not be fired to Windows who have not had these properties accessed - which is not expected.
- // See: https://github.com/whatwg/html/issues/10135. To solve this, we instead iterate over all active
- // windows, and initialize any storage objects as part of this loop.
- Window::for_each_active([&](auto& window) {
- // * type is storage's type
- auto storage = obtain_storage_for_window(window, type);
- if (!storage)
- return IterationDecision::Continue;
-
- // "excluding storage"
- if (storage == excluded_storage)
- return IterationDecision::Continue;
-
- // * relevant settings object's origin is same origin with storage's relevant settings object's origin
- // NB: A storage key is an origin, and two keys are equal when their origins are same origin. Compared as the
- // keys the bottles are kept under, so the file: documents that share one bottle hear each other.
- auto window_storage_key = StorageAPI::obtain_a_storage_key(relevant_settings_object(window));
- if (!window_storage_key.has_value() || *window_storage_key != storage_key)
- return IterationDecision::Continue;
-
- // * and, if type is "session", whose relevant settings object's associated Document's node navigable's traversable navigable
- // is thisDocument's node navigable's traversable navigable.
- // NB: A page's documents all belong to one traversable, so the page stands for the traversable here.
- if (type == Type::Session) {
- auto& storage_document = storage->m_window->associated_document();
-
- // NB: It is possible the remote storage may have not been fully teared down immediately at the point it's
- // document is made inactive.
- if (!storage_document.navigable())
- return IterationDecision::Continue;
-
- if (!session_page.has_value() || window.page().client().id() != *session_page)
- return IterationDecision::Continue;
- }
-
- remote_storages.append(*storage);
- return IterationDecision::Continue;
+ URL::RustIntegration::lend_origin_to_ffi(storage_key.origin, [&](URL::FFI::FfiOrigin const& origin) {
+ web_rust_html_dispatch_storage_events_for_remote_change(JS::HostABI::vm_to_abi(Bindings::main_thread_vm()), to_underlying(type), &origin, session_page.has_value(), session_page.has_value() ? session_page->value() : 0, key.has_value(), raw(key), old_value.has_value(), raw(old_value), new_value.has_value(), raw(new_value), url.bytes());
});
-
- if (remote_storages.is_empty())
- return;
-
- // 4. For each remoteStorage of remoteStorages: queue a global task on the DOM manipulation task source given remoteStorage's relevant
- // global object to fire an event named storage at remoteStorage's relevant global object, using StorageEvent, with key initialized
- // to key, oldValue initialized to oldValue, newValue initialized to newValue, url initialized to url, and storageArea initialized to
- // remoteStorage.
- for (auto remote_storage : remote_storages) {
- auto& remote_window = remote_storage->m_window;
- queue_global_task(Task::Source::DOMManipulation, relevant_global_object(*remote_window), GC::create_function(GC::Heap::the(), [key, old_value, new_value, url, remote_storage, remote_window] {
- StorageEventInit init;
- init.key = key;
- init.old_value = old_value;
- init.new_value = new_value;
- init.url = move(url);
- init.storage_area = remote_storage;
- remote_window->dispatch_event(StorageEvent::create(EventNames::storage, init, HighResolutionTime::current_high_resolution_time(relevant_global_object(*remote_window))));
- }));
- }
-}
-
-Vector<Utf16FlyString> Storage::supported_property_names() const
-{
- // The supported property names on a Storage object storage are the result of running get the keys on storage's map.
- Vector<Utf16FlyString> names;
- auto keys = m_storage_bottle->keys();
- names.ensure_capacity(keys.size());
- for (auto const& key : keys)
- names.unchecked_append(key);
- return names;
}
-void Storage::dump() const
+Storage* web_html_window_storage(Window* window, u8 type)
{
- auto keys = m_storage_bottle->keys();
- dbgln("Storage ({} key(s))", keys.size());
- size_t i = 0;
- for (auto const& key : keys) {
- auto value = m_storage_bottle->get(key);
- dbgln("[{}] \"{}\": \"{}\"", i, key, value.value());
- ++i;
- }
+ auto storage = static_cast<Storage::Type>(type) == Storage::Type::Local ? window->local_storage() : window->session_storage();
+ if (storage.is_exception())
+ return nullptr;
+ return storage.release_value().ptr();
}
}
diff --git a/Libraries/LibWeb/HTML/Storage.h b/Libraries/LibWeb/HTML/Storage.h
index 9a0a45ce71f..a5d16f6dfa6 100644
--- a/Libraries/LibWeb/HTML/Storage.h
+++ b/Libraries/LibWeb/HTML/Storage.h
@@ -2,76 +2,49 @@
* Copyright (c) 2022, Andreas Kling <[email protected]>
* Copyright (c) 2023, Luke Wilde <[email protected]>
* Copyright (c) 2024-2025, Shannon Booth <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
-#include <AK/FlyString.h>
#include <AK/Optional.h>
#include <AK/String.h>
-#include <LibWeb/Bindings/Wrappable.h>
+#include <AK/Utf16String.h>
+#include <LibWeb/Bindings/RustInterface.h>
+#include <LibWeb/Bindings/Storage.h>
#include <LibWeb/Export.h>
#include <LibWeb/StorageAPI/StorageBottle.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
namespace Web::HTML {
class Window;
// https://html.spec.whatwg.org/multipage/webstorage.html#storage-2
-class WEB_API Storage : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(Storage, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(Storage);
+class WEB_API Storage : public Bindings::RustInterfaceCell {
+ WEB_RUST_INTERFACE(Storage, storage)
public:
// https://html.spec.whatwg.org/multipage/webstorage.html#concept-storage-type
- enum class Type {
+ enum class Type : u8 {
Local,
Session,
};
[[nodiscard]] static GC::Ref<Storage> create(Window&, Type, GC::Ref<StorageAPI::StorageBottle>);
- ~Storage();
+ StorageAPI::StorageBottle& map();
- Window& window() { return m_window; }
- Window const& window() const { return m_window; }
-
- size_t length() const;
- Optional<Utf16String> key(size_t index);
- Optional<Utf16String> get_item(Utf16View key) const;
- WebIDL::ExceptionOr<void> set_item(Utf16View key, Utf16View value);
- void remove_item(Utf16View key);
- void clear();
- Type type() const { return m_type; }
-
- void dump() const;
+ void dump();
// A window listening for storage events has its storage connected so that changes made in other processes reach
// it; a map is otherwise only loaded on first access.
- void connect() const { m_storage_bottle->connect(); }
-
- // Fires the storage events a change calls for on every Storage object in this process that shares the changed
- // map, except excluded_storage: that is the one whose script made the change, when the change was made here.
- // A change another process made has no such object, and every Storage here gets the event.
- static void dispatch_storage_events_for_remote_change(Type, StorageAPI::StorageKey const&, Optional<PageId> session_page, Optional<Utf16String> const& key, Optional<Utf16String> const& old_value, Optional<Utf16String> const& new_value, String const& url, GC::Ptr<Storage> excluded_storage);
-
-private:
- Storage(Window&, Type, GC::Ref<StorageAPI::StorageBottle>);
-
- virtual void visit_edges(GC::Cell::Visitor&) override;
- virtual GC::Ptr<Bindings::Wrappable> relevant_global_impl() const override;
-
- // ^Wrappable
- virtual Vector<Utf16FlyString> supported_property_names() const override;
- void reorder();
- void broadcast(Optional<Utf16View> key, Optional<Utf16View> old_value, Optional<Utf16View> new_value, String const& url);
+ void connect() { map().connect(); }
- GC::Ref<Window> m_window;
- Type m_type {};
- GC::Ref<StorageAPI::StorageBottle> m_storage_bottle;
+ // Fires the storage events that a change another process made calls for on every Storage object in this process
+ // that shares the changed map.
+ static void dispatch_storage_events_for_remote_change(Type, StorageAPI::StorageKey const&, Optional<PageId> session_page, Optional<Utf16String> const& key, Optional<Utf16String> const& old_value, Optional<Utf16String> const& new_value, String const& url);
};
}
diff --git a/Libraries/LibWeb/HTML/Storage.idl b/Libraries/LibWeb/HTML/Storage.idl
index 9bae30af5b9..8c96d16371a 100644
--- a/Libraries/LibWeb/HTML/Storage.idl
+++ b/Libraries/LibWeb/HTML/Storage.idl
@@ -1,5 +1,5 @@
// https://html.spec.whatwg.org/multipage/webstorage.html#storage-2
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface Storage {
readonly attribute unsigned long length;
diff --git a/Libraries/LibWeb/HTML/StorageEvent.cpp b/Libraries/LibWeb/HTML/StorageEvent.cpp
index 6ef907be542..2210700fe4d 100644
--- a/Libraries/LibWeb/HTML/StorageEvent.cpp
+++ b/Libraries/LibWeb/HTML/StorageEvent.cpp
@@ -1,64 +1,25 @@
/*
* Copyright (c) 2024, Shannon Booth <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <LibGC/Heap.h>
-#include <LibWeb/HTML/Storage.h>
+#include <LibJS/HostClassBuilder.h>
+#include <LibJS/Runtime/Realm.h>
+#include <LibWeb/DOM/Event.h>
#include <LibWeb/HTML/StorageEvent.h>
namespace Web::HTML {
-GC_DEFINE_ALLOCATOR(StorageEvent);
-
-GC::Ref<StorageEvent> StorageEvent::create(Utf16FlyString const& event_name, StorageEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp time_stamp)
-{
- auto event = GC::Heap::the().allocate<StorageEvent>(event_name, event_init, time_stamp);
- event->set_is_trusted(true);
- return event;
-}
-
-StorageEvent::~StorageEvent() = default;
-
-// https://html.spec.whatwg.org/multipage/webstorage.html#dom-storageevent-initstorageevent
-void StorageEvent::init_storage_event(
- Utf16FlyString const& type,
- bool bubbles,
- bool cancelable,
- Optional<Utf16String> const& key,
- Optional<Utf16String> const& old_value,
- Optional<Utf16String> const& new_value,
- Utf16View url,
- GC::Ptr<Storage> storage_area)
-{
- // The initStorageEvent(type, bubbles, cancelable, key, oldValue, newValue, url, storageArea) method must initialize
- // the event in a manner analogous to the similarly-named initEvent() method. [DOM]
- if (dispatched())
- return;
-
- initialize_event(type, bubbles, cancelable);
- m_key = key;
- m_old_value = old_value;
- m_new_value = new_value;
- m_url = Utf16String::from_utf16(url);
- m_storage_area = storage_area;
-}
-
-StorageEvent::StorageEvent(Utf16FlyString const& event_name, StorageEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp time_stamp)
- : DOM::Event(event_name, event_init, time_stamp)
- , m_key(event_init.key)
- , m_old_value(event_init.old_value)
- , m_new_value(event_init.new_value)
- , m_url(event_init.url)
- , m_storage_area(event_init.storage_area)
-{
+extern "C" {
+// Defined in Bindings/Rust/src/html/exports.rs.
+DOM::Event* web_rust_html_create_storage_event(JSVM*, void* realm);
}
-void StorageEvent::visit_edges(Visitor& visitor)
+GC::Ref<DOM::Event> create_storage_event(JS::Realm& realm)
{
- Base::visit_edges(visitor);
- visitor.visit(m_storage_area);
+ return *web_rust_html_create_storage_event(JS::HostABI::vm_to_abi(realm.vm()), &realm);
}
}
diff --git a/Libraries/LibWeb/HTML/StorageEvent.h b/Libraries/LibWeb/HTML/StorageEvent.h
index e976bd9d003..71736f0fec0 100644
--- a/Libraries/LibWeb/HTML/StorageEvent.h
+++ b/Libraries/LibWeb/HTML/StorageEvent.h
@@ -1,64 +1,19 @@
/*
* Copyright (c) 2024, Shannon Booth <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
-#include <AK/Optional.h>
-#include <AK/Utf16FlyString.h>
-#include <AK/Utf16String.h>
-#include <AK/Utf16View.h>
#include <LibGC/Ptr.h>
#include <LibJS/Forward.h>
-#include <LibWeb/Bindings/StorageEvent.h>
-#include <LibWeb/DOM/Event.h>
-#include <LibWebCommon/HighResolutionTime/DOMHighResTimeStamp.h>
+#include <LibWeb/Forward.h>
namespace Web::HTML {
-class Storage;
-
-using StorageEventInit = Bindings::StorageEventInit;
-
-// https://html.spec.whatwg.org/multipage/webstorage.html#storageevent
-class StorageEvent : public DOM::Event {
- WEB_WRAPPABLE(StorageEvent, DOM::Event);
- GC_DECLARE_ALLOCATOR(StorageEvent);
-
-public:
- [[nodiscard]] static GC::Ref<StorageEvent> create(Utf16FlyString const& event_name, StorageEventInit const&, HighResolutionTime::DOMHighResTimeStamp);
-
- virtual ~StorageEvent() override;
-
- Optional<Utf16String> const& key() const { return m_key; }
- Optional<Utf16String> const& old_value() const { return m_old_value; }
- Optional<Utf16String> const& new_value() const { return m_new_value; }
- Utf16String const& url() const { return m_url; }
- GC::Ptr<Storage const> storage_area() const { return m_storage_area; }
- static constexpr size_t storage_area_offset() { return offsetof(StorageEvent, m_storage_area); }
-
- void init_storage_event(Utf16FlyString const& type,
- bool bubbles = false,
- bool cancelable = false,
- Optional<Utf16String> const& key = {},
- Optional<Utf16String> const& old_value = {},
- Optional<Utf16String> const& new_value = {},
- Utf16View url = {},
- GC::Ptr<Storage> storage_area = {});
-
-protected:
- virtual void visit_edges(Visitor& visitor) override;
-
-private:
- StorageEvent(Utf16FlyString const& event_name, StorageEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp);
-
- Optional<Utf16String> m_key;
- Optional<Utf16String> m_old_value;
- Optional<Utf16String> m_new_value;
- Utf16String m_url;
- GC::Ptr<Storage> m_storage_area;
-};
+// The Event of a new StorageEvent in the realm whose type is the empty string, for createEvent().
+GC::Ref<DOM::Event> create_storage_event(JS::Realm&);
}
diff --git a/Libraries/LibWeb/HTML/StorageEvent.idl b/Libraries/LibWeb/HTML/StorageEvent.idl
index af5c0fc230a..04e14dc333b 100644
--- a/Libraries/LibWeb/HTML/StorageEvent.idl
+++ b/Libraries/LibWeb/HTML/StorageEvent.idl
@@ -1,5 +1,5 @@
// https://html.spec.whatwg.org/multipage/webstorage.html#storageevent
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface StorageEvent : Event {
constructor(DOMString type, optional StorageEventInit eventInitDict = {});
@@ -7,9 +7,9 @@ interface StorageEvent : Event {
readonly attribute DOMString? oldValue;
readonly attribute DOMString? newValue;
readonly attribute USVString url;
- [DirectGetter] readonly attribute Storage? storageArea;
+ readonly attribute Storage? storageArea;
- undefined initStorageEvent([FlyString] DOMString type, optional boolean bubbles = false, optional boolean cancelable = false, optional DOMString? key = null, optional DOMString? oldValue = null, optional DOMString? newValue = null, optional USVString url = "", optional Storage? storageArea = null);
+ undefined initStorageEvent(DOMString type, optional boolean bubbles = false, optional boolean cancelable = false, optional DOMString? key = null, optional DOMString? oldValue = null, optional DOMString? newValue = null, optional USVString url = "", optional Storage? storageArea = null);
};
// https://html.spec.whatwg.org/multipage/webstorage.html#storageeventinit
diff --git a/Libraries/LibWeb/StorageAPI/StorageBottle.cpp b/Libraries/LibWeb/StorageAPI/StorageBottle.cpp
index 89dfc599e84..f86fb20f025 100644
--- a/Libraries/LibWeb/StorageAPI/StorageBottle.cpp
+++ b/Libraries/LibWeb/StorageAPI/StorageBottle.cpp
@@ -109,7 +109,7 @@ StorageBottle::StorageBottle(GC::Ref<Page> page, StorageEndpointType endpoint_ty
if (!mirror)
return;
auto type = mirror->endpoint_type() == StorageEndpointType::SessionStorage ? HTML::Storage::Type::Session : HTML::Storage::Type::Local;
- HTML::Storage::dispatch_storage_events_for_remote_change(type, mirror->storage_key(), mirror->session_page(), key, old_value, new_value, url, nullptr);
+ HTML::Storage::dispatch_storage_events_for_remote_change(type, mirror->storage_key(), mirror->session_page(), key, old_value, new_value, url);
};
}
}
@@ -160,4 +160,70 @@ void StorageBottle::remove(Utf16View key, String const& document_url)
(void)m_mirror->remove(requester(), key, document_url);
}
+// Declared on the Rust side in Libraries/LibWeb/Bindings/Rust/src/storage_api/storage_bottle.rs.
+extern "C" {
+
+size_t web_storage_api_storage_bottle_size(StorageBottle*);
+void web_storage_api_storage_bottle_keys(StorageBottle*, void* keys, void (*append)(void* keys, FlatPtr key));
+bool web_storage_api_storage_bottle_get(StorageBottle*, FlatPtr key, FlatPtr* value);
+u8 web_storage_api_storage_bottle_set(StorageBottle*, FlatPtr key, FlatPtr value, ReadonlyBytes document_url, FlatPtr* old_value);
+void web_storage_api_storage_bottle_remove(StorageBottle*, FlatPtr key, ReadonlyBytes document_url);
+void web_storage_api_storage_bottle_clear(StorageBottle*, ReadonlyBytes document_url);
+bool web_storage_api_storage_bottle_quota(StorageBottle*, u64* quota);
+}
+
+size_t web_storage_api_storage_bottle_size(StorageBottle* bottle)
+{
+ return bottle->size();
+}
+
+void web_storage_api_storage_bottle_keys(StorageBottle* bottle, void* keys, void (*append)(void* keys, FlatPtr key))
+{
+ for (auto& key : bottle->keys())
+ append(keys, move(key).into_raw());
+}
+
+bool web_storage_api_storage_bottle_get(StorageBottle* bottle, FlatPtr key, FlatPtr* value)
+{
+ auto key_string = Utf16String::from_raw(key);
+ auto found = bottle->get(key_string);
+ if (!found.has_value())
+ return false;
+ *value = found.release_value().into_raw();
+ return true;
+}
+
+u8 web_storage_api_storage_bottle_set(StorageBottle* bottle, FlatPtr key, FlatPtr value, ReadonlyBytes document_url, FlatPtr* old_value)
+{
+ auto key_string = Utf16String::from_raw(key);
+ auto value_string = Utf16String::from_raw(value);
+ auto result = bottle->set(key_string, value_string, MUST(String::from_utf8(document_url)));
+ if (result.has<WebView::StorageOperationError>())
+ return 0;
+ auto& existing = result.get<Optional<Utf16String>>();
+ if (!existing.has_value())
+ return 1;
+ *old_value = existing.release_value().into_raw();
+ return 2;
+}
+
+void web_storage_api_storage_bottle_remove(StorageBottle* bottle, FlatPtr key, ReadonlyBytes document_url)
+{
+ auto key_string = Utf16String::from_raw(key);
+ bottle->remove(key_string, MUST(String::from_utf8(document_url)));
+}
+
+void web_storage_api_storage_bottle_clear(StorageBottle* bottle, ReadonlyBytes document_url)
+{
+ bottle->clear(MUST(String::from_utf8(document_url)));
+}
+
+bool web_storage_api_storage_bottle_quota(StorageBottle* bottle, u64* quota)
+{
+ if (!bottle->quota().has_value())
+ return false;
+ *quota = *bottle->quota();
+ return true;
+}
+
}
diff --git a/Libraries/LibWeb/StorageAPI/StorageBottle.h b/Libraries/LibWeb/StorageAPI/StorageBottle.h
index 3fcbc8deeb0..066ef6cdb70 100644
--- a/Libraries/LibWeb/StorageAPI/StorageBottle.h
+++ b/Libraries/LibWeb/StorageAPI/StorageBottle.h
@@ -12,6 +12,7 @@
#include <AK/String.h>
#include <LibGC/Heap.h>
#include <LibGC/Ptr.h>
+#include <LibWeb/Export.h>
#include <LibWeb/Forward.h>
#include <LibWeb/Page/Page.h>
#include <LibWeb/StorageAPI/StorageAreaMirror.h>
@@ -28,7 +29,7 @@ using StorageSetResult = Variant<WebView::StorageOperationError, Optional<Utf16S
// https://storage.spec.whatwg.org/#storage-bottle
// NB: The bottle's map lives in the browser process; what a bottle here holds is this process's mirror of it, shared
// with every other bottle in the process for the same area. Each bottle object is one storage proxy map over it.
-class StorageBottle : public GC::Cell {
+class WEB_API StorageBottle : public GC::Cell {
GC_CELL(StorageBottle, GC::Cell);
GC_DECLARE_ALLOCATOR(StorageBottle);
diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.py
index d88ead654e0..0e09dbae42d 100755
--- a/Meta/Linters/check_libweb_realm_mentions.py
+++ b/Meta/Linters/check_libweb_realm_mentions.py
@@ -60,10 +60,11 @@ ALLOWED_REALM_MENTIONS = {
),
"FileAPI": (2, 9, "Blob glue still creates streams and buffers in selected realms"),
"HTML": (
- 61,
- 179,
+ 64,
+ 183,
"HTML algorithms still contain structured serialization, including posted-message preparation, canvas, navigation transfer/reconstruction, worker/worklet, and event realm use, and cross-origin Window/Location property functions are created in the current realm; RemoteWindow mirrors Window's postMessage; "
- "the C++ glue of the Rust structured serialization creates platform objects and SharedArrayBuffers in a given realm",
+ "the C++ glue of the Rust structured serialization creates platform objects and SharedArrayBuffers in a given realm; "
+ "the C++ glue of the Rust Storage and StorageEvent creates them in a given realm",
),
"IndexedDB": (
4,
diff --git a/Services/WebContent/ConnectionFromClient.cpp b/Services/WebContent/ConnectionFromClient.cpp
index fe152b51406..c6f2a4cf803 100644
--- a/Services/WebContent/ConnectionFromClient.cpp
+++ b/Services/WebContent/ConnectionFromClient.cpp
@@ -1387,19 +1387,15 @@ void ConnectionFromClient::inspect_storage(Web::PageId page_id, Web::StorageAPI:
return;
}
- auto storage = storage_or_error.release_value();
+ auto& map = storage_or_error.value()->map();
JsonArray storage_items;
- for (auto i = 0uz; i < storage->length(); ++i) {
- auto name = storage->key(i);
- if (!name.has_value())
- continue;
-
- auto value = storage->get_item(*name);
+ for (auto const& name : map.keys()) {
+ auto value = map.get(name);
if (!value.has_value())
continue;
JsonObject item;
- item.set("name"sv, name.release_value().to_utf8());
+ item.set("name"sv, name.to_utf8());
item.set("value"sv, value.release_value().to_utf8());
storage_items.must_append(move(item));
}