Skip to content

Truly independent web browser

LibWeb: Fetch and process rel=prefetch links

Shannon Booth5e3cfdfa0e9d
diff --git a/Libraries/LibWeb/HTML/HTMLLinkElement.cpp b/Libraries/LibWeb/HTML/HTMLLinkElement.cpp
index 140f5050024..89e1561bf07 100644
--- a/Libraries/LibWeb/HTML/HTMLLinkElement.cpp
+++ b/Libraries/LibWeb/HTML/HTMLLinkElement.cpp
@@ -235,6 +235,8 @@ void HTMLLinkElement::attribute_changed(Utf16FlyString const& name, Optional<Utf
m_relationship |= Relationship::Preconnect;
else if (token.equals_ignoring_ascii_case(u"icon"sv))
m_relationship |= Relationship::Icon;
+ else if (token.equals_ignoring_ascii_case(u"prefetch"sv))
+ m_relationship |= Relationship::Prefetch;
}
start = i + 1;
@@ -263,7 +265,7 @@ void HTMLLinkElement::attribute_changed(Utf16FlyString const& name, Optional<Utf
// - When the href attribute of the link element of an external resource link that is already browsing-context connected is changed.
auto fetch = name == AttributeNames::href;
- if (!fetch && (m_relationship & (Relationship::Preconnect | Relationship::Stylesheet))) {
+ if (!fetch && (m_relationship & (Relationship::Preconnect | Relationship::Prefetch | Relationship::Stylesheet))) {
// - When the crossorigin attribute of the link element of an external resource link that is already browsing-context connected is set, changed, or removed.
fetch = name == AttributeNames::crossorigin;
}
@@ -283,6 +285,11 @@ void HTMLLinkElement::attribute_changed(Utf16FlyString const& name, Optional<Utf
fetch = name == AttributeNames::rel && !(old_relationship & Relationship::ModulePreload);
}
+ if (!fetch && (m_relationship & Relationship::Prefetch)) {
+ // - When the external resource link is created on a link element that is already browsing-context connected.
+ fetch = name == AttributeNames::rel && !(old_relationship & Relationship::Prefetch);
+ }
+
if (!fetch && (m_relationship & Relationship::Stylesheet)) {
fetch =
// - When the disabled attribute of the link element of an external resource link that is already browsing-context connected is set, changed, or removed.
@@ -458,12 +465,14 @@ void HTMLLinkElement::fetch_and_process_linked_resource()
document().remove_from_script_blocking_style_sheet_set(*this);
}
- if (m_relationship & ~(Relationship::DNSPrefetch | Relationship::Preconnect | Relationship::Preload | Relationship::ModulePreload))
+ if (m_relationship & ~(Relationship::DNSPrefetch | Relationship::Preconnect | Relationship::Preload | Relationship::ModulePreload | Relationship::Prefetch))
default_fetch_and_process_linked_resource(fetch_generation);
else if (m_relationship & Relationship::ModulePreload)
fetch_and_process_linked_modulepreload_resource();
else if (m_relationship & Relationship::Preload)
fetch_and_process_linked_preload_resource();
+ else if (m_relationship & Relationship::Prefetch)
+ fetch_and_process_linked_prefetch_resource();
else if (m_relationship & Relationship::Preconnect)
fetch_and_process_linked_preconnect_resource();
else if (m_relationship & Relationship::DNSPrefetch)
@@ -742,6 +751,50 @@ void HTMLLinkElement::fetch_and_process_linked_modulepreload_resource()
fetch_modulepreload_module_script_graph(relevant_realm(*this), *url, *destination, settings_object, options, on_complete);
}
+// https://html.spec.whatwg.org/multipage/links.html#link-type-prefetch:fetch-and-process-the-linked-resource-2
+void HTMLLinkElement::fetch_and_process_linked_prefetch_resource()
+{
+ // 1. If el's href attribute's value is the empty string, then return.
+ if (attribute(AttributeNames::href).value_or({}).is_empty())
+ return;
+
+ // 2. Let options be the result of creating link options from el.
+ auto options = create_link_options();
+
+ // 3. Let request be the result of creating a link request given options.
+ auto request = create_link_request(options);
+
+ // 4. If request is null, then return.
+ if (!request)
+ return;
+
+ // 5. Set request's initiator to "prefetch".
+ request->set_initiator(Fetch::Infrastructure::Request::Initiator::Prefetch);
+
+ // 6. Let processPrefetchResponse be the following steps given a response response and null, failure, or a byte
+ // sequence bytesOrNull:
+ Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input {};
+ fetch_algorithms_input.process_response_consume_body = [this, fetch_generation = m_current_fetch_generation](auto response, auto) {
+ if (fetch_generation != m_current_fetch_generation)
+ return;
+ m_fetch_controller = nullptr;
+
+ // 1. If response is a network error, fire an event named error at el.
+ if (response->is_network_error()) {
+ dispatch_event(create_event_for_element(*this, HTML::EventNames::error));
+ }
+ // 2. Otherwise, fire an event named load at el.
+ else {
+ dispatch_event(create_event_for_element(*this, HTML::EventNames::load));
+ }
+ };
+
+ // 7. The user agent should fetch request, with processResponseConsumeBody set to processPrefetchResponse. User
+ // agents may delay the fetching of request to prioritize other requests that are necessary for the current
+ // document.
+ m_fetch_controller = Fetch::Fetching::fetch(HTML::relevant_realm(*this), *request, Fetch::Infrastructure::FetchAlgorithms::create(move(fetch_algorithms_input)));
+}
+
// https://html.spec.whatwg.org/multipage/semantics.html#linked-resource-fetch-setup-steps
bool HTMLLinkElement::linked_resource_fetch_setup_steps(Fetch::Infrastructure::Request& request)
{
@@ -1331,7 +1384,8 @@ bool HTMLLinkElement::should_fetch_and_process_resource_type() const
// https://html.spec.whatwg.org/multipage/links.html#link-type-preload:fetch-and-process-the-linked-resource
// https://html.spec.whatwg.org/multipage/links.html#link-type-stylesheet:fetch-and-process-the-linked-resource
// https://html.spec.whatwg.org/multipage/links.html#link-type-modulepreload:fetch-and-process-the-linked-resource
- if (m_relationship & (Relationship::DNSPrefetch | Relationship::Preconnect | Relationship::Preload | Relationship::ModulePreload | Relationship::Stylesheet))
+ // https://html.spec.whatwg.org/multipage/links.html#link-type-prefetch:fetch-and-process-the-linked-resource
+ if (m_relationship & (Relationship::DNSPrefetch | Relationship::Preconnect | Relationship::Preload | Relationship::ModulePreload | Relationship::Prefetch | Relationship::Stylesheet))
return true;
// AD-HOC: The spec is underspecified for fetching and processing rel="icon". See:
diff --git a/Libraries/LibWeb/HTML/HTMLLinkElement.h b/Libraries/LibWeb/HTML/HTMLLinkElement.h
index 48858a972fd..64bc7fde8c6 100644
--- a/Libraries/LibWeb/HTML/HTMLLinkElement.h
+++ b/Libraries/LibWeb/HTML/HTMLLinkElement.h
@@ -165,6 +165,7 @@ private:
void fetch_and_process_linked_preconnect_resource();
void fetch_and_process_linked_preload_resource();
void fetch_and_process_linked_modulepreload_resource();
+ void fetch_and_process_linked_prefetch_resource();
bool linked_resource_fetch_setup_steps(Fetch::Infrastructure::Request&);
bool icon_linked_resource_fetch_setup_steps(Fetch::Infrastructure::Request&);
@@ -192,6 +193,7 @@ private:
Preconnect = 1 << 4,
Icon = 1 << 5,
ModulePreload = 1 << 6,
+ Prefetch = 1 << 7,
};
};
diff --git a/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.ini
index d6bf124ffe6..6e44477cda2 100644
--- a/Tests/LibWeb/TestConfig.ini
+++ b/Tests/LibWeb/TestConfig.ini
@@ -568,6 +568,8 @@ Text/input/wpt-import/scroll-to-text-fragment/scroll-to-text-fragment.html
Text/input/wpt-import/scroll-to-text-fragment/text-directive-mime-type-parameter.html
Text/input/wpt-import/worklets/audio-worklet-import.https.html
Text/input/wpt-import/streams/transferable/audioworklet.https.html
+Text/input/wpt-import/preload/prefetch-load-event.html
+Text/input/wpt-import/preload/prefetch-events.html
[Skipped]
; Needs vertical-rl inline geometry fidelity beyond the binary transpose
diff --git a/Tests/LibWeb/Text/expected/wpt-import/preload/prefetch-events.txt b/Tests/LibWeb/Text/expected/wpt-import/preload/prefetch-events.txt
new file mode 100644
index 00000000000..f7985ca0dab
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/preload/prefetch-events.txt
@@ -0,0 +1,14 @@
+Harness status: OK
+
+Found 9 tests
+
+9 Pass
+Pass Prefetch should fire the load event
+Pass Cross-origin prefetch should fire the load event
+Pass Prefetch should fire the load event for 404
+Pass Prefetch should fire the load event for 404 (cross-origin)
+Pass Prefetch should fire the load event for 500
+Pass Cross-origin prefetch should fire the load event for 500
+Pass Prefetch should fire the error event for network errors
+Pass Prefetch should do nothing with an empty href
+Pass Prefetch should do nothing with an invalid href
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/preload/prefetch-load-event.txt b/Tests/LibWeb/Text/expected/wpt-import/preload/prefetch-load-event.txt
new file mode 100644
index 00000000000..172ace7fc23
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/preload/prefetch-load-event.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass Prefetch should not block the load event
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/input/wpt-import/preload/prefetch-events.html b/Tests/LibWeb/Text/input/wpt-import/preload/prefetch-events.html
new file mode 100644
index 00000000000..b29edb7e200
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/preload/prefetch-events.html
@@ -0,0 +1,97 @@
+<!DOCTYPE html>
+<title>Ensures that prefetch respects HTTP cache semantics</title>
+<meta name="timeout" content="long">
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="../common/utils.js"></script>
+<script src="resources/prefetch-helper.js"></script>
+<script src="../common/get-host-info.sub.js"></script>
+<body>
+<script>
+const {REMOTE_ORIGIN} = get_host_info();
+async function prefetch(link, uid, t) {
+ link.rel = "prefetch";
+ document.head.appendChild(link);
+ const event = new Promise(resolve => {
+ link.addEventListener("error", () => resolve("error"));
+ link.addEventListener("load", () => resolve("load"));
+ t.step_timeout(() => resolve("timeout"), 1000);
+ });
+ return await event;
+}
+
+promise_test(async t => {
+ const uid = token();
+ const link = document.createElement("link");
+ link.href = `/preload/resources/prefetch-info.py?key=${uid}`;
+ const event = await prefetch(link, uid, t);
+ assert_equals(event, "load");
+}, "Prefetch should fire the load event");
+
+promise_test(async t => {
+ const uid = token();
+ const link = document.createElement("link");
+ link.href = `${REMOTE_ORIGIN}/preload/resources/prefetch-info.py?key=${uid}`;
+ const event = await prefetch(link, uid, t);
+ assert_equals(event, "load");
+}, "Cross-origin prefetch should fire the load event");
+
+promise_test(async t => {
+ const uid = token();
+ const link = document.createElement("link");
+ link.href = `/preload/resources/prefetch-info.py?key=${uid}&status=404`;
+ const event = await prefetch(link, uid, t);
+ assert_equals(event, "load");
+}, "Prefetch should fire the load event for 404");
+
+promise_test(async t => {
+ const uid = token();
+ const link = document.createElement("link");
+ link.href = `${REMOTE_ORIGIN}/preload/resources/prefetch-info.py?key=${uid}&status=404`;
+ const event = await prefetch(link, uid, t);
+ assert_equals(event, "load");
+}, "Prefetch should fire the load event for 404 (cross-origin)");
+
+promise_test(async t => {
+ const uid = token();
+ const link = document.createElement("link");
+ link.href = `/preload/resources/prefetch-info.py?key=${uid}&status=500`;
+ const event = await prefetch(link, uid, t);
+ assert_equals(event, "load");
+}, "Prefetch should fire the load event for 500");
+
+promise_test(async t => {
+ const uid = token();
+ const link = document.createElement("link");
+ link.href = `${REMOTE_ORIGIN}/preload/resources/prefetch-info.py?key=${uid}&status=500`;
+ const event = await prefetch(link, uid, t);
+ assert_equals(event, "load");
+}, "Cross-origin prefetch should fire the load event for 500");
+
+promise_test(async t => {
+ const uid = token();
+ const link = document.createElement("link");
+ link.crossOrigin = "anonymous";
+ link.href = `${REMOTE_ORIGIN}/preload/resources/prefetch-info.py?key=${uid}&cors=false`;
+ const event = await prefetch(link, uid, t);
+ assert_equals(event, "error");
+}, "Prefetch should fire the error event for network errors");
+
+promise_test(async t => {
+ const uid = token();
+ const link = document.createElement("link");
+ link.crossOrigin = "anonymous";
+ const event = await prefetch(link, uid, t);
+ assert_equals(event, "timeout");
+}, "Prefetch should do nothing with an empty href");
+
+promise_test(async t => {
+ const uid = token();
+ const link = document.createElement("link");
+ link.href = "https://example.com\u0000mozilla.org";
+ link.crossOrigin = "anonymous";
+ const event = await prefetch(link, uid, t);
+ assert_equals(event, "timeout");
+}, "Prefetch should do nothing with an invalid href");
+</script>
+</body>
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/input/wpt-import/preload/prefetch-load-event.html b/Tests/LibWeb/Text/input/wpt-import/preload/prefetch-load-event.html
new file mode 100644
index 00000000000..62e80cba761
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/preload/prefetch-load-event.html
@@ -0,0 +1,13 @@
+<!DOCTYPE html>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="../common/utils.js"></script>
+<link rel="prefetch" href="/xhr/resources/delay.py?ms=100000">
+<body>
+<script>
+
+promise_test(() => new Promise(resolve => window.addEventListener("load", resolve)),
+ "Prefetch should not block the load event");
+
+</script>
+</body>
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/input/wpt-import/preload/resources/prefetch-helper.js b/Tests/LibWeb/Text/input/wpt-import/preload/resources/prefetch-helper.js
new file mode 100644
index 00000000000..367d4824c41
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/preload/resources/prefetch-helper.js
@@ -0,0 +1,22 @@
+async function get_prefetch_info(href) {
+ const response = await fetch(`${href}&mode=info`, {mode: "cors"});
+ return await response.json();
+}
+
+async function prefetch(p = {}, t) {
+ const link = document.createElement("link");
+ link.rel = "prefetch";
+ link.as = p.as;
+ if (p.crossOrigin)
+ link.setAttribute("crossorigin", p.crossOrigin);
+ const uid = token();
+ const params = new URLSearchParams();
+ params.set("key", uid);
+ for (const key in p)
+ params.set(key, p[key]);
+ const origin = p.origin || '';
+ link.href = `${origin}/preload/resources/prefetch-info.py?${params.toString()}`;
+ document.head.appendChild(link);
+ while (!(await get_prefetch_info(link.href)).length) { }
+ return {href: link.href, uid};
+}
diff --git a/Tests/LibWeb/Text/input/wpt-import/preload/resources/prefetch-info.py b/Tests/LibWeb/Text/input/wpt-import/preload/resources/prefetch-info.py
new file mode 100644
index 00000000000..04d942ba05e
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/preload/resources/prefetch-info.py
@@ -0,0 +1,37 @@
+import os
+from wptserve.utils import isomorphic_encode
+from json import dumps, loads
+
+def main(request, response):
+ key = request.GET.first(b"key").decode("utf8")
+ mode = request.GET.first(b"mode", "content")
+ status = int(request.GET.first(b"status", b"200"))
+ stash = request.server.stash
+ cors = request.GET.first(b"cors", "true")
+ if cors == "true" or mode == b"info":
+ response.headers.set(b"Access-Control-Allow-Origin", b"*")
+
+ response.status = status
+ with stash.lock:
+ requests = loads(stash.take(key) or '[]')
+ if mode == b"info":
+ response.headers.set(b"Content-Type", "application/json")
+ json_reqs = dumps(requests)
+ response.content = json_reqs
+ stash.put(key, json_reqs)
+ return
+ else:
+ headers = {}
+ for header, value in request.headers.items():
+ headers[header.decode("utf8")] = value[0].decode("utf8")
+ path = request.url
+ requests.append({"headers": headers, "url": request.url})
+ stash.put(key, dumps(requests))
+
+ response.headers.set(b"Content-Type", request.GET.first(b"type", "text/plain"))
+ response.headers.set(b"Cache-Control", request.GET.first(b"cache-control", b"max-age: 604800"))
+ if b"file" in request.GET:
+ path = os.path.join(os.path.dirname(isomorphic_encode(__file__)), os.path.basename(request.GET.first(b"file")))
+ response.content = open(path, mode=u'rb').read()
+ else:
+ return request.GET.first(b"content", "123")
diff --git a/Tests/LibWeb/Text/input/wpt-import/xhr/resources/delay.py b/Tests/LibWeb/Text/input/wpt-import/xhr/resources/delay.py
new file mode 100644
index 00000000000..61a0ed26884
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/xhr/resources/delay.py
@@ -0,0 +1,7 @@
+import time
+
+def main(request, response):
+ delay = float(request.GET.first(b"ms", 500))
+ time.sleep(delay / 1E3)
+
+ return [(b"Access-Control-Allow-Origin", b"*"), (b"Access-Control-Allow-Methods", b"YO"), (b"Content-type", b"text/plain")], b"TEST_DELAY"