Storage.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. /*
  2. * Copyright (c) 2022, Andreas Kling <andreas@ladybird.org>
  3. * Copyright (c) 2023, Luke Wilde <lukew@serenityos.org>
  4. * Copyright (c) 2024-2025, Shannon Booth <shannon@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/String.h>
  9. #include <LibGC/RootVector.h>
  10. #include <LibWeb/Bindings/Intrinsics.h>
  11. #include <LibWeb/Bindings/StoragePrototype.h>
  12. #include <LibWeb/HTML/Storage.h>
  13. #include <LibWeb/HTML/StorageEvent.h>
  14. #include <LibWeb/HTML/Window.h>
  15. namespace Web::HTML {
  16. GC_DEFINE_ALLOCATOR(Storage);
  17. static HashTable<GC::RawRef<Storage>>& all_storages()
  18. {
  19. // FIXME: This needs to be stored at the user agent level.
  20. static HashTable<GC::RawRef<Storage>> storages;
  21. return storages;
  22. }
  23. GC::Ref<Storage> Storage::create(JS::Realm& realm, Type type, NonnullRefPtr<StorageAPI::StorageBottle> storage_bottle)
  24. {
  25. return realm.create<Storage>(realm, type, move(storage_bottle));
  26. }
  27. Storage::Storage(JS::Realm& realm, Type type, NonnullRefPtr<StorageAPI::StorageBottle> storage_bottle)
  28. : Bindings::PlatformObject(realm)
  29. , m_type(type)
  30. , m_storage_bottle(move(storage_bottle))
  31. {
  32. m_legacy_platform_object_flags = LegacyPlatformObjectFlags {
  33. .supports_indexed_properties = true,
  34. .supports_named_properties = true,
  35. .has_indexed_property_setter = true,
  36. .has_named_property_setter = true,
  37. .has_named_property_deleter = true,
  38. .indexed_property_setter_has_identifier = true,
  39. .named_property_setter_has_identifier = true,
  40. .named_property_deleter_has_identifier = true,
  41. };
  42. all_storages().set(*this);
  43. }
  44. Storage::~Storage() = default;
  45. void Storage::initialize(JS::Realm& realm)
  46. {
  47. Base::initialize(realm);
  48. WEB_SET_PROTOTYPE_FOR_INTERFACE(Storage);
  49. }
  50. void Storage::finalize()
  51. {
  52. all_storages().remove(*this);
  53. }
  54. // https://html.spec.whatwg.org/multipage/webstorage.html#dom-storage-length
  55. size_t Storage::length() const
  56. {
  57. // The length getter steps are to return this's map's size.
  58. return map().size();
  59. }
  60. // https://html.spec.whatwg.org/multipage/webstorage.html#dom-storage-key
  61. Optional<String> Storage::key(size_t index)
  62. {
  63. // 1. If index is greater than or equal to this's map's size, then return null.
  64. if (index >= map().size())
  65. return {};
  66. // 2. Let keys be the result of running get the keys on this's map.
  67. auto keys = map().keys();
  68. // 3. Return keys[index].
  69. return keys[index];
  70. }
  71. // https://html.spec.whatwg.org/multipage/webstorage.html#dom-storage-getitem
  72. Optional<String> Storage::get_item(StringView key) const
  73. {
  74. // 1. If this's map[key] does not exist, then return null.
  75. auto it = map().find(key);
  76. if (it == map().end())
  77. return {};
  78. // 2. Return this's map[key].
  79. return it->value;
  80. }
  81. // https://html.spec.whatwg.org/multipage/webstorage.html#dom-storage-setitem
  82. WebIDL::ExceptionOr<void> Storage::set_item(String const& key, String const& value)
  83. {
  84. auto& realm = this->realm();
  85. // 1. Let oldValue be null.
  86. Optional<String> old_value;
  87. // 2. Let reorder be true.
  88. bool reorder = true;
  89. // 3. If this's map[key] exists:
  90. auto new_size = m_stored_bytes;
  91. if (auto it = map().find(key); it != map().end()) {
  92. // 1. Set oldValue to this's map[key].
  93. old_value = it->value;
  94. // 2. If oldValue is value, then return.
  95. if (old_value == value)
  96. return {};
  97. // 3. Set reorder to false.
  98. reorder = false;
  99. } else {
  100. new_size += key.bytes().size();
  101. }
  102. // 4. If value cannot be stored, then throw a "QuotaExceededError" DOMException exception.
  103. new_size += value.bytes().size() - old_value.value_or(String {}).bytes().size();
  104. if (m_storage_bottle->quota.has_value() && new_size > *m_storage_bottle->quota)
  105. return WebIDL::QuotaExceededError::create(realm, MUST(String::formatted("Unable to store more than {} bytes in storage"sv, *m_storage_bottle->quota)));
  106. // 5. Set this's map[key] to value.
  107. map().set(key, value);
  108. m_stored_bytes = new_size;
  109. // 6. If reorder is true, then reorder this.
  110. if (reorder)
  111. this->reorder();
  112. // 7. Broadcast this with key, oldValue, and value.
  113. broadcast(key, old_value, value);
  114. return {};
  115. }
  116. // https://html.spec.whatwg.org/multipage/webstorage.html#dom-storage-removeitem
  117. void Storage::remove_item(String const& key)
  118. {
  119. // 1. If this's map[key] does not exist, then return null.
  120. // FIXME: Return null?
  121. auto it = map().find(key);
  122. if (it == map().end())
  123. return;
  124. // 2. Set oldValue to this's map[key].
  125. auto old_value = it->value;
  126. // 3. Remove this's map[key].
  127. map().remove(it);
  128. m_stored_bytes = m_stored_bytes - key.bytes().size() - old_value.bytes().size();
  129. // 4. Reorder this.
  130. reorder();
  131. // 5. Broadcast this with key, oldValue, and null.
  132. broadcast(key, old_value, {});
  133. }
  134. // https://html.spec.whatwg.org/multipage/webstorage.html#dom-storage-clear
  135. void Storage::clear()
  136. {
  137. // 1. Clear this's map.
  138. map().clear();
  139. // 2. Broadcast this with null, null, and null.
  140. broadcast({}, {}, {});
  141. }
  142. // https://html.spec.whatwg.org/multipage/webstorage.html#concept-storage-reorder
  143. void Storage::reorder()
  144. {
  145. // To reorder a Storage object storage, reorder storage's map's entries in an implementation-defined manner.
  146. // NOTE: This basically means that we're not required to maintain any particular iteration order.
  147. }
  148. // https://html.spec.whatwg.org/multipage/webstorage.html#concept-storage-broadcast
  149. void Storage::broadcast(Optional<String> const& key, Optional<String> const& old_value, Optional<String> const& new_value)
  150. {
  151. auto& realm = this->realm();
  152. // 1. Let thisDocument be storage's relevant global object's associated Document.
  153. auto& relevant_global = relevant_global_object(*this);
  154. auto const& this_document = verify_cast<Window>(relevant_global).associated_document();
  155. // 2. Let url be thisDocument's URL.
  156. auto url = this_document.url().to_string();
  157. // 3. Let remoteStorages be all Storage objects excluding storage whose:
  158. GC::RootVector<GC::Ref<Storage>> remote_storages(heap());
  159. for (auto storage : all_storages()) {
  160. if (storage == this)
  161. continue;
  162. // * type is storage's type
  163. if (storage->type() != type())
  164. continue;
  165. // * relevant settings object's origin is same origin with storage's relevant settings object's origin.
  166. if (!relevant_settings_object(*this).origin().is_same_origin(relevant_settings_object(storage).origin()))
  167. continue;
  168. // * and, if type is "session", whose relevant settings object's associated Document's node navigable's traversable navigable
  169. // is thisDocument's node navigable's traversable navigable.
  170. if (type() == Type::Session) {
  171. auto& storage_document = *relevant_settings_object(storage).responsible_document();
  172. // NOTE: It is possible the remote storage may have not been fully teared down immediately at the point it's document is made inactive.
  173. if (!storage_document.navigable())
  174. continue;
  175. VERIFY(this_document.navigable());
  176. if (storage_document.navigable()->traversable_navigable() != this_document.navigable()->traversable_navigable())
  177. continue;
  178. }
  179. remote_storages.append(storage);
  180. }
  181. // 4. For each remoteStorage of remoteStorages: queue a global task on the DOM manipulation task source given remoteStorage's relevant
  182. // global object to fire an event named storage at remoteStorage's relevant global object, using StorageEvent, with key initialized
  183. // to key, oldValue initialized to oldValue, newValue initialized to newValue, url initialized to url, and storageArea initialized to
  184. // remoteStorage.
  185. for (auto remote_storage : remote_storages) {
  186. queue_global_task(Task::Source::DOMManipulation, relevant_global, GC::create_function(heap(), [&realm, key, old_value, new_value, url, remote_storage] {
  187. StorageEventInit init;
  188. init.key = move(key);
  189. init.old_value = move(old_value);
  190. init.new_value = move(new_value);
  191. init.url = move(url);
  192. init.storage_area = remote_storage;
  193. verify_cast<Window>(relevant_global_object(remote_storage)).dispatch_event(StorageEvent::create(realm, EventNames::storage, init));
  194. }));
  195. }
  196. }
  197. Vector<FlyString> Storage::supported_property_names() const
  198. {
  199. // The supported property names on a Storage object storage are the result of running get the keys on storage's map.
  200. Vector<FlyString> names;
  201. names.ensure_capacity(map().size());
  202. for (auto const& key : map().keys())
  203. names.unchecked_append(key);
  204. return names;
  205. }
  206. Optional<JS::Value> Storage::item_value(size_t index) const
  207. {
  208. // Handle index as a string since that's our key type
  209. auto key = String::number(index);
  210. auto value = get_item(key);
  211. if (!value.has_value())
  212. return {};
  213. return JS::PrimitiveString::create(vm(), value.release_value());
  214. }
  215. JS::Value Storage::named_item_value(FlyString const& name) const
  216. {
  217. auto value = get_item(name);
  218. if (!value.has_value())
  219. // AD-HOC: Spec leaves open to a description at: https://html.spec.whatwg.org/multipage/webstorage.html#the-storage-interface
  220. // However correct behavior expected here: https://github.com/whatwg/html/issues/8684
  221. return JS::js_undefined();
  222. return JS::PrimitiveString::create(vm(), value.release_value());
  223. }
  224. WebIDL::ExceptionOr<Bindings::PlatformObject::DidDeletionFail> Storage::delete_value(String const& name)
  225. {
  226. remove_item(name);
  227. return DidDeletionFail::NotRelevant;
  228. }
  229. WebIDL::ExceptionOr<void> Storage::set_value_of_indexed_property(u32 index, JS::Value unconverted_value)
  230. {
  231. // Handle index as a string since that's our key type
  232. auto key = String::number(index);
  233. return set_value_of_named_property(key, unconverted_value);
  234. }
  235. WebIDL::ExceptionOr<void> Storage::set_value_of_named_property(String const& key, JS::Value unconverted_value)
  236. {
  237. // NOTE: Since PlatformObject does not know the type of value, we must convert it ourselves.
  238. // The type of `value` is `DOMString`.
  239. auto value = TRY(unconverted_value.to_string(vm()));
  240. return set_item(key, value);
  241. }
  242. void Storage::dump() const
  243. {
  244. dbgln("Storage ({} key(s))", map().size());
  245. size_t i = 0;
  246. for (auto const& it : map()) {
  247. dbgln("[{}] \"{}\": \"{}\"", i, it.key, it.value);
  248. ++i;
  249. }
  250. }
  251. }