Skip to content

Truly independent web browser

LibWeb: Resolve SVG use instances through their corresponding element

Shannon Boothbbbe30fdfe45
diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.h
index 87c12b03514..8613e49e91c 100644
--- a/Libraries/LibWeb/Forward.h
+++ b/Libraries/LibWeb/Forward.h
@@ -1143,6 +1143,7 @@ class SVGSwitchElement;
class SVGSymbolElement;
class SVGTitleElement;
class SVGTransformList;
+class SVGUseElement;
class SVGViewElement;
class TimeEvent;
diff --git a/Libraries/LibWeb/HTML/SharedResourceRequest.cpp b/Libraries/LibWeb/HTML/SharedResourceRequest.cpp
index e3f5738d1b9..ffc8bba7530 100644
--- a/Libraries/LibWeb/HTML/SharedResourceRequest.cpp
+++ b/Libraries/LibWeb/HTML/SharedResourceRequest.cpp
@@ -190,7 +190,7 @@ void SharedResourceRequest::fetch_resource(NonnullRefPtr<Fetch::Infrastructure::
: request->url().basename().ends_with(".svg"sv);
if (extracted_mime_type.has_value())
self->m_image_mime_type = extracted_mime_type->essence();
- self->handle_successful_fetch(request->url(), is_svg_image ? IsSVGImage::Yes : IsSVGImage::No, move(data), image_data_is_cors_cross_origin);
+ self->handle_successful_fetch(response->url().value_or(request->url()), is_svg_image ? IsSVGImage::Yes : IsSVGImage::No, move(data), image_data_is_cors_cross_origin);
});
auto process_body_error = GC::create_function(GC::Heap::the(), [weak_this](JS::Value) {
auto self = weak_this.ptr();
diff --git a/Libraries/LibWeb/SVG/SVGElement.cpp b/Libraries/LibWeb/SVG/SVGElement.cpp
index 39e58b06015..a88bbb88a23 100644
--- a/Libraries/LibWeb/SVG/SVGElement.cpp
+++ b/Libraries/LibWeb/SVG/SVGElement.cpp
@@ -14,6 +14,7 @@
#include <LibWeb/CSS/StyleValues/KeywordStyleValue.h>
#include <LibWeb/CSS/StyleValues/NumberStyleValue.h>
#include <LibWeb/DOM/Document.h>
+#include <LibWeb/DOM/ElementRareData.h>
#include <LibWeb/DOM/ShadowRoot.h>
#include <LibWeb/Layout/LayoutRustBridge.h>
#include <LibWeb/Layout/Node.h>
@@ -37,6 +38,37 @@ namespace Web::SVG {
GC_DEFINE_ALLOCATOR(SVGElement);
+struct SVGElement::RareData final : DOM::Element::RareData {
+ AK_ALLOC_WITH_KMALLOC;
+
+ virtual void visit_edges(Cell::Visitor& visitor) override
+ {
+ DOM::Element::RareData::visit_edges(visitor);
+ visitor.visit(corresponding_element);
+ }
+
+ GC::Ptr<SVGElement const> corresponding_element;
+};
+
+OwnPtr<DOM::Node::RareData> SVGElement::create_rare_data() const
+{
+ return make<RareData>();
+}
+
+// https://svgwg.org/svg2-draft/struct.html#TermCorrespondingElement
+GC::Ptr<SVGElement const> SVGElement::corresponding_element() const
+{
+ auto const* data = static_cast<RareData const*>(rare_data());
+ if (!data)
+ return nullptr;
+ return data->corresponding_element;
+}
+
+void SVGElement::set_corresponding_element(Badge<SVGUseElement>, SVGElement const& corresponding_element)
+{
+ static_cast<RareData&>(ensure_rare_data()).corresponding_element = corresponding_element;
+}
+
SVGElement::SVGElement(DOM::Document& document, DOM::QualifiedName qualified_name)
: Element(document, move(qualified_name))
{
diff --git a/Libraries/LibWeb/SVG/SVGElement.h b/Libraries/LibWeb/SVG/SVGElement.h
index 95e5742279f..37155ede8c4 100644
--- a/Libraries/LibWeb/SVG/SVGElement.h
+++ b/Libraries/LibWeb/SVG/SVGElement.h
@@ -42,6 +42,8 @@ public:
bool is_in_never_rendered_subtree() const;
GC::Ref<SVGAnimatedString> class_name();
+ GC::Ptr<SVGElement const> corresponding_element() const;
+ void set_corresponding_element(Badge<SVGUseElement>, SVGElement const&);
GC::Ptr<SVGSVGElement> owner_svg_element();
GC::Ptr<SVGSVGElement> outermost_svg_element();
GC::Ptr<SVGElement> viewport_element();
@@ -91,6 +93,9 @@ protected:
void mark_resource_box_referencing_elements_for_layout_update();
private:
+ struct RareData;
+ virtual OwnPtr<DOM::Node::RareData> create_rare_data() const override;
+
// ^HTML::GlobalEventHandlers
virtual GC::Ptr<DOM::EventTarget> global_event_handlers_to_event_target(Utf16FlyString const&) override { return *this; }
diff --git a/Libraries/LibWeb/SVG/SVGUseElement.cpp b/Libraries/LibWeb/SVG/SVGUseElement.cpp
index d49122a3b9f..f3f34ce0e41 100644
--- a/Libraries/LibWeb/SVG/SVGUseElement.cpp
+++ b/Libraries/LibWeb/SVG/SVGUseElement.cpp
@@ -70,38 +70,19 @@ void SVGUseElement::adopted_from(DOM::Document& old_document)
{
Base::adopted_from(old_document);
- if (m_load_event_delayer.has_value())
- m_load_event_delayer.emplace(document());
-
m_document_observer->retarget_for_adoption(document());
// Adoption removed us from our tree, so nothing of ours renders, and our shadow tree is a clone made for the old
// document; our href may resolve to something else in this one. Drop it, and leave the new clone to inserted(),
// once we're in a document tree again. A clone made here would join the tree being adopted — so a nested use
// element in it would then run the adopting steps as if it had come from the old document.
- clone_element_tree_as_our_shadow_tree(nullptr);
-
- auto href = href_value();
- if (!href.has_value())
- return;
-
- m_href = document().encoding_parse_url(*href);
- if (!m_href.has_value())
- return;
-
- if (!is_referenced_element_same_document())
- fetch_the_document(*m_href);
+ discard_the_url();
}
void SVGUseElement::inserted()
{
Base::inserted();
- // A use element inside another use element's shadow tree is itself part of a clone, so it's left alone.
- auto* containing_shadow_root = as_if<DOM::ShadowRoot>(root());
- if (containing_shadow_root && containing_shadow_root->is_user_agent_internal())
- return;
-
// Only use elements in the document's node tree react to changes of the elements they reference, mirroring the
// document-wide traversal this registry replaced.
if (root().is_document())
@@ -114,6 +95,12 @@ void SVGUseElement::inserted()
// resolving the reference again.
if (!is_connected() || instance_root())
return;
+
+ if (!m_href.has_value()) {
+ process_the_url(href_value());
+ return;
+ }
+
if (auto to_clone = referenced_element())
clone_element_tree_as_our_shadow_tree(to_clone);
}
@@ -124,6 +111,13 @@ void SVGUseElement::removed_from(IsSubtreeRoot is_subtree_root, Node* old_ancest
if (old_root.is_document())
unregister_for_referenced_element_changes();
+
+ // NB: The request of a disconnected use element must not delay the load event, which matters for an instance in a
+ // shadow tree that is being discarded. inserted() processes the URL again.
+ if (!is_connected() && m_load_event_delayer.has_value()) {
+ stop_using_resource_request();
+ m_href = {};
+ }
}
void SVGUseElement::moved_from(IsSubtreeRoot is_subtree_root, GC::Ptr<Node> old_ancestor)
@@ -179,6 +173,12 @@ void SVGUseElement::attribute_changed(Utf16FlyString const& name, Optional<Utf16
Base::attribute_changed(name, old_value, value, namespace_);
if (name == SVG::AttributeNames::href || name == SVG::AttributeNames::xlink_href) {
+ // AD-HOC: A disconnected use element processes the URL once it is inserted. By then, an instance is linked to
+ // its corresponding element, and cycle checks can see its enclosing instances.
+ if (!is_connected()) {
+ discard_the_url();
+ return;
+ }
// When the ‘href’ attribute is set (or, in the absence of an ‘href’ attribute, an ‘xlink:href’ attribute), the user agent must process the URL.
process_the_url(value);
}
@@ -191,6 +191,13 @@ Optional<Utf16String> SVGUseElement::href_value() const
return get_attribute_ns(Namespace::XLink, AttributeNames::href);
}
+DOM::Document const& SVGUseElement::document_containing_reference() const
+{
+ if (auto source = corresponding_element())
+ return source->document();
+ return document();
+}
+
// https://www.w3.org/TR/SVG2/linking.html#processingURL
void SVGUseElement::process_the_url(Optional<Utf16String> const& href)
{
@@ -203,7 +210,7 @@ void SVGUseElement::process_the_url(Optional<Utf16String> const& href)
// it with the document base URL. If all parts other than the target fragment are equal, this is
// a same-document URL reference, and processing the URL must continue as indicated in Identifying
// the target element with the current document as the referenced document.
- m_href = document().encoding_parse_url(href.value_or({}));
+ m_href = document_containing_reference().encoding_parse_url(href.value_or({}));
if (m_href.has_value() && is_referenced_element_same_document()) {
clone_element_tree_as_our_shadow_tree(referenced_element());
return;
@@ -219,7 +226,7 @@ void SVGUseElement::process_the_url(Optional<Utf16String> const& href)
bool SVGUseElement::is_referenced_element_same_document() const
{
- return m_href->equals(document().base_url(), URL::ExcludeFragment::Yes);
+ return m_href->equals(document_containing_reference().base_url(), URL::ExcludeFragment::Yes);
}
void SVGUseElement::svg_element_changed(SVGElement& svg_element)
@@ -269,7 +276,7 @@ GC::Ptr<DOM::Element> SVGUseElement::referenced_element() const
if (is_referenced_element_same_document()) {
auto id = decode_fragment_identifier(*m_href->fragment());
- return document().get_element_by_id(id);
+ return document_containing_reference().get_element_by_id(id);
}
if (!m_resource_request)
@@ -282,6 +289,13 @@ GC::Ptr<DOM::Element> SVGUseElement::referenced_element() const
return as<SVG::SVGDecodedImageData>(*data).svg_document().get_element_by_id(decode_fragment_identifier(*m_href->fragment()));
}
+void SVGUseElement::discard_the_url()
+{
+ clone_element_tree_as_our_shadow_tree(nullptr);
+ stop_using_resource_request();
+ m_href = {};
+}
+
void SVGUseElement::stop_using_resource_request()
{
if (m_resource_request && m_resource_request_callbacks_id.has_value())
@@ -296,7 +310,7 @@ void SVGUseElement::fetch_the_document(URL::URL const& url)
{
// AD-HOC: An element in a temporary document for fragment parsing does not fetch anything, so that markup parsed
// into such a document, for example by the Sanitizer API, causes no network requests for elements that
- // are never inserted anywhere. The document is fetched once the element is adopted into another document.
+ // are never inserted anywhere. The document is fetched once the element is inserted into another document.
if (document().is_temporary_document_for_fragment_parsing())
return;
@@ -324,8 +338,7 @@ void SVGUseElement::fetch_the_document(URL::URL const& url)
m_resource_request = HTML::SharedResourceRequest::get_or_create(document(), *request);
m_resource_request_callbacks_id = m_resource_request->add_removable_callbacks(
[this] {
- // A request that already finished calls back right away, which from adopted_from() is in the middle of the
- // adoption. Only a connected use element builds its shadow tree; inserted() builds it otherwise.
+ // Only a connected use element builds its shadow tree; inserted() builds it otherwise.
if (is_connected())
clone_element_tree_as_our_shadow_tree(referenced_element());
m_load_event_delayer.clear();
@@ -349,11 +362,17 @@ void SVGUseElement::clone_element_tree_as_our_shadow_tree(GC::Ptr<Element> to_cl
// https://svgwg.org/svg2-draft/struct.html#UseStyleInheritance
// When the referenced element is from the same document as the ‘use’ element, the same document stylesheets will
// apply in both the original document and the shadow tree document fragment.
- shadow_root()->set_uses_document_style_sheets(to_clone && is_referenced_element_same_document());
+ shadow_root()->set_uses_document_style_sheets(to_clone && &to_clone->document() == &document());
if (to_clone && is_valid_reference_element(*to_clone)) {
// The ‘use’ element references another element, a copy of which is rendered in place of the ‘use’ in the document.
+ // Each node in the shadow tree is an instance of a corresponding node from the referenced document subtree.
+ // FIXME: If the referenced element is in an external file, then all URL references in attributes and style
+ // properties must be made absolute as described in Generating the absolute URL, before copying the value
+ // to the element instances. The shadow tree itself uses the same document base URL as the document that
+ // includes it.
auto cloned_reference_node = MUST(to_clone->clone_node(&document(), true));
+ link_to_corresponding_elements(as<SVGElement>(*cloned_reference_node), as<SVGElement>(*to_clone));
if (is<SVGSVGElement>(cloned_reference_node.ptr()) || is<SVGSymbolElement>(cloned_reference_node.ptr())) {
auto& cloned_element = as<SVGElement>(*cloned_reference_node);
@@ -372,6 +391,20 @@ void SVGUseElement::clone_element_tree_as_our_shadow_tree(GC::Ptr<Element> to_cl
}
}
+// https://svgwg.org/svg2-draft/struct.html#TermCorrespondingElement
+void SVGUseElement::link_to_corresponding_elements(SVGElement& instance, SVGElement const& original)
+{
+ instance.set_corresponding_element({}, original);
+
+ // NB: Only SVG children are paired up. Inserting a clone's HTML content can change it, for example when an option
+ // element updates a selectedcontent element.
+ auto* instance_child = instance.first_child_of_type<SVGElement>();
+ for (auto const* original_child = original.first_child_of_type<SVGElement>(); original_child && instance_child; original_child = original_child->next_sibling_of_type<SVGElement>()) {
+ link_to_corresponding_elements(*instance_child, *original_child);
+ instance_child = instance_child->next_sibling_of_type<SVGElement>();
+ }
+}
+
bool SVGUseElement::is_valid_reference_element(Element const& reference_element) const
{
// If the referenced element that results from resolving the URL is not an SVG element, then the reference is invalid and the ‘use’ element is in error.
@@ -390,6 +423,14 @@ bool SVGUseElement::is_valid_reference_element(Element const& reference_element)
bool SVGUseElement::would_create_circular_reference(Element const& target) const
{
auto visited = GC::Heap::the().allocate<GC::HeapHashTable<GC::Ref<Element const>>>();
+ for (auto* shadow_root = as_if<DOM::ShadowRoot>(root()); shadow_root && shadow_root->host(); shadow_root = as_if<DOM::ShadowRoot>(shadow_root->host()->root())) {
+ if (auto const* use = as_if<SVGUseElement>(*shadow_root->host())) {
+ if (auto instance = use->instance_root()) {
+ if (auto source = instance->corresponding_element())
+ visited->table().set(*source);
+ }
+ }
+ }
return would_create_circular_reference_impl(target, visited);
}
diff --git a/Libraries/LibWeb/SVG/SVGUseElement.h b/Libraries/LibWeb/SVG/SVGUseElement.h
index b5c2a84a0dc..1d748e0942d 100644
--- a/Libraries/LibWeb/SVG/SVGUseElement.h
+++ b/Libraries/LibWeb/SVG/SVGUseElement.h
@@ -65,14 +65,17 @@ private:
void process_the_url(Optional<Utf16String> const& href);
Optional<Utf16String> href_value() const;
+ DOM::Document const& document_containing_reference() const;
GC::Ptr<DOM::Element> referenced_element() const;
void fetch_the_document(URL::URL const& url);
+ void discard_the_url();
void stop_using_resource_request();
bool is_referenced_element_same_document() const;
void clone_element_tree_as_our_shadow_tree(GC::Ptr<Element> to_clone);
+ static void link_to_corresponding_elements(SVGElement& instance, SVGElement const& original);
bool is_valid_reference_element(Element const& reference_element) const;
bool would_create_circular_reference(Element const& target) const;
bool would_create_circular_reference_impl(Element const& target, GC::HeapHashTable<GC::Ref<Element const>>& visited) const;
diff --git a/Tests/LibWeb/Crash/SVG/use-element-clone-with-selectedcontent.html b/Tests/LibWeb/Crash/SVG/use-element-clone-with-selectedcontent.html
new file mode 100644
index 00000000000..ac905584329
--- /dev/null
+++ b/Tests/LibWeb/Crash/SVG/use-element-clone-with-selectedcontent.html
@@ -0,0 +1,5 @@
+<!DOCTYPE html>
+<!-- Cloning the option element empties the cloned selectedcontent element, so the instance tree has fewer nodes than
+ the element it was cloned from. -->
+<svg><g id="a"><foreignObject><select><button><selectedcontent></selectedcontent></button><option>One</option></select></foreignObject><rect/></g></svg>
+<svg><use href="#a"/></svg>
diff --git a/Tests/LibWeb/Crash/SVG/use-element-fetch-in-collected-document.html b/Tests/LibWeb/Crash/SVG/use-element-fetch-in-collected-document.html
index d02697ef9f2..a6d01634ffc 100644
--- a/Tests/LibWeb/Crash/SVG/use-element-fetch-in-collected-document.html
+++ b/Tests/LibWeb/Crash/SVG/use-element-fetch-in-collected-document.html
@@ -7,6 +7,7 @@
const doc = document.implementation.createHTMLDocument();
const use = doc.createElementNS("http://www.w3.org/2000/svg", "use");
use.setAttribute("href", new URL("../../Assets/120.png#target", document.baseURI).href);
+ doc.body.append(use);
}
startFetchInUnreachableDocument();
diff --git a/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.ini
index 63b8e4b287e..c1ce7a9ae29 100644
--- a/Tests/LibWeb/TestConfig.ini
+++ b/Tests/LibWeb/TestConfig.ini
@@ -1240,8 +1240,12 @@ Crash/SVG/use-element-with-cached-external-reference-adopted.html
Layout/input/svg/svg-use-element-crashtest.html
Text/input/HTML/Element-setHTMLUnsafe-removed-elements-do-not-fetch.html
Text/input/SVG/use-element-blocks-cross-origin-requests.html
+Text/input/SVG/use-element-discarded-instance-stops-delaying-load.html
Text/input/SVG/use-element-external-fragments-share-one-fetch.html
Text/input/SVG/use-element-external-reference-after-adoption.html
+Text/input/SVG/use-element-fetches-once-connected.html
+Text/input/SVG/use-element-nested-external-fragment.html
+Text/input/SVG/use-element-nested-external-fragment-after-redirect.html
Text/input/SVG/use-element-relative-external-reference-after-adoption.html
Text/input/SVG/use-element-repeated-href-changes-on-stalled-sprite.html
Text/input/SVG/use-element-same-document-href-stops-delaying-load.html
diff --git a/Tests/LibWeb/Text/data/svg-use-nested-fragment.svg b/Tests/LibWeb/Text/data/svg-use-nested-fragment.svg
new file mode 100644
index 00000000000..53ebcd6d08c
--- /dev/null
+++ b/Tests/LibWeb/Text/data/svg-use-nested-fragment.svg
@@ -0,0 +1,4 @@
+<svg xmlns="http://www.w3.org/2000/svg">
+ <rect id="leaf" width="10" height="20"/>
+ <g id="icon"><use href="#leaf"/></g>
+</svg>
diff --git a/Tests/LibWeb/Text/expected/SVG/use-element-discarded-instance-stops-delaying-load.txt b/Tests/LibWeb/Text/expected/SVG/use-element-discarded-instance-stops-delaying-load.txt
new file mode 100644
index 00000000000..ef983288d5a
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/SVG/use-element-discarded-instance-stops-delaying-load.txt
@@ -0,0 +1 @@
+loaded while the discarded instance's request is pending
diff --git a/Tests/LibWeb/Text/expected/SVG/use-element-fetches-once-connected.txt b/Tests/LibWeb/Text/expected/SVG/use-element-fetches-once-connected.txt
new file mode 100644
index 00000000000..43354dec2b2
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/SVG/use-element-fetches-once-connected.txt
@@ -0,0 +1,3 @@
+requests while disconnected: 0
+requests once connected: 1
+width once connected: 20
diff --git a/Tests/LibWeb/Text/expected/SVG/use-element-nested-external-fragment-after-redirect.txt b/Tests/LibWeb/Text/expected/SVG/use-element-nested-external-fragment-after-redirect.txt
new file mode 100644
index 00000000000..65fc8f975df
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/SVG/use-element-nested-external-fragment-after-redirect.txt
@@ -0,0 +1,2 @@
+nested fragment: 10x20
+sprite requests: 1
diff --git a/Tests/LibWeb/Text/expected/SVG/use-element-nested-external-fragment.txt b/Tests/LibWeb/Text/expected/SVG/use-element-nested-external-fragment.txt
new file mode 100644
index 00000000000..131d973401c
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/SVG/use-element-nested-external-fragment.txt
@@ -0,0 +1 @@
+10x20
diff --git a/Tests/LibWeb/Text/input/SVG/use-element-discarded-instance-stops-delaying-load.html b/Tests/LibWeb/Text/input/SVG/use-element-discarded-instance-stops-delaying-load.html
new file mode 100644
index 00000000000..6bff037135d
--- /dev/null
+++ b/Tests/LibWeb/Text/input/SVG/use-element-discarded-instance-stops-delaying-load.html
@@ -0,0 +1,40 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ promiseTest(async () => {
+ const server = httpTestServer();
+ const stalledToken = `stalled-${uniqueID()}`;
+ const blockerToken = `blocker-${uniqueID()}`;
+ const stalledSprite = await server.createEcho("GET", "/stalled.svg", {
+ status: 200,
+ headers: { "Content-Type": "image/svg+xml" },
+ body: '<svg xmlns="http://www.w3.org/2000/svg"><rect id="rect" width="20" height="20"/></svg>',
+ wait_for_unblock: stalledToken,
+ });
+ const sprite = await server.createEcho("GET", "/sprite.svg", {
+ status: 200,
+ headers: { "Content-Type": "image/svg+xml" },
+ body: `<svg xmlns="http://www.w3.org/2000/svg"><g id="a"><use href="${stalledSprite}#rect"/></g></svg>`,
+ });
+ const blocker = await server.createEcho("GET", "/blocker.js", {
+ status: 200,
+ headers: { "Content-Type": "text/javascript" },
+ body: "",
+ wait_for_unblock: blockerToken,
+ });
+
+ const frame = document.createElement("iframe");
+ const loaded = new Promise(resolve => frame.onload = resolve);
+ frame.srcdoc = `<svg><use id="outer" href="${sprite}#a"/></svg>
+ <script src="${blocker}"><\/script>
+ <script>document.getElementById("outer").setAttribute("href", "#missing");<\/script>`;
+ document.body.append(frame);
+
+ // NB: The parser waits for the blocker script until the outer use element's instance has requested its sprite.
+ await server.waitForRequest(stalledSprite);
+ await fetch(`${server.baseURL}/unblock/${blockerToken}`);
+ await loaded;
+ println("loaded while the discarded instance's request is pending");
+ await fetch(`${server.baseURL}/unblock/${stalledToken}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/SVG/use-element-fetches-once-connected.html b/Tests/LibWeb/Text/input/SVG/use-element-fetches-once-connected.html
new file mode 100644
index 00000000000..4e74a23a734
--- /dev/null
+++ b/Tests/LibWeb/Text/input/SVG/use-element-fetches-once-connected.html
@@ -0,0 +1,34 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ promiseTest(async () => {
+ const server = httpTestServer();
+ const createSprite = path => server.createEcho("GET", path, {
+ status: 200,
+ headers: { "Content-Type": "image/svg+xml" },
+ body: '<svg xmlns="http://www.w3.org/2000/svg"><rect id="rect" width="20" height="20"/></svg>',
+ });
+ const requestCount = async url => (await fetch(server.recordedRequestCountURL(url))).json();
+ const createUse = sprite => `const use = document.createElementNS("http://www.w3.org/2000/svg", "use");
+ use.setAttribute("href", "${sprite}#rect");`;
+
+ // NB: A fetch started by the frame's use element delays the frame's load event.
+ const loadFrame = async script => {
+ const frame = document.createElement("iframe");
+ const loaded = new Promise(resolve => frame.onload = resolve);
+ frame.srcdoc = `<svg></svg><script>${script}<\/script>`;
+ document.body.append(frame);
+ await loaded;
+ return frame.contentDocument;
+ };
+
+ const disconnectedSprite = await createSprite("/disconnected.svg");
+ await loadFrame(createUse(disconnectedSprite));
+ println(`requests while disconnected: ${await requestCount(disconnectedSprite)}`);
+
+ const connectedSprite = await createSprite("/connected.svg");
+ const frameDocument = await loadFrame(`${createUse(connectedSprite)} document.querySelector("svg").append(use);`);
+ println(`requests once connected: ${await requestCount(connectedSprite)}`);
+ println(`width once connected: ${frameDocument.querySelector("use").getBBox().width}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/SVG/use-element-nested-external-fragment-after-redirect.html b/Tests/LibWeb/Text/input/SVG/use-element-nested-external-fragment-after-redirect.html
new file mode 100644
index 00000000000..97c7875c67d
--- /dev/null
+++ b/Tests/LibWeb/Text/input/SVG/use-element-nested-external-fragment-after-redirect.html
@@ -0,0 +1,35 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ asyncTest(async done => {
+ const server = httpTestServer();
+ const sprite = await server.createEcho("GET", "/sprites/icon.svg", {
+ status: 200,
+ headers: { "Content-Type": "image/svg+xml", "Cache-Control": "no-store" },
+ body: `<svg xmlns="http://www.w3.org/2000/svg">
+ <rect id="leaf" width="10" height="20"/>
+ <g id="icon"><use href="icon.svg#leaf"/></g>
+ </svg>`,
+ });
+ const redirect = await server.createEcho("GET", "/redirect", {
+ status: 302,
+ headers: { Location: sprite, "Cache-Control": "no-store" },
+ body: "",
+ });
+
+ const frame = document.createElement("iframe");
+ const loaded = new Promise(resolve => frame.onload = resolve);
+ frame.srcdoc = `<svg>
+ <defs><rect id="leaf" width="40" height="40"/></defs>
+ <use id="instance" href="${redirect}#icon"/>
+ </svg>`;
+ document.body.append(frame);
+ await loaded;
+
+ const { width, height } = frame.contentDocument.getElementById("instance").getBBox();
+ const requests = await (await fetch(server.recordedRequestCountURL(sprite))).json();
+ println(`nested fragment: ${width}x${height}`);
+ println(`sprite requests: ${requests}`);
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/SVG/use-element-nested-external-fragment.html b/Tests/LibWeb/Text/input/SVG/use-element-nested-external-fragment.html
new file mode 100644
index 00000000000..e4d88a6fff0
--- /dev/null
+++ b/Tests/LibWeb/Text/input/SVG/use-element-nested-external-fragment.html
@@ -0,0 +1,15 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<svg>
+ <defs><rect id="leaf" width="40" height="40"/></defs>
+ <use id="instance" href="../../data/svg-use-nested-fragment.svg#icon"/>
+</svg>
+<script>
+ asyncTest(done => {
+ window.addEventListener("load", () => {
+ const { width, height } = document.getElementById("instance").getBBox();
+ println(`${width}x${height}`);
+ done();
+ });
+ });
+</script>