Skip to content

Truly independent web browser

LibWeb: Implement Notification.requestPermission()

sideshowbarker3d206d97d8ad
diff --git a/Libraries/LibWeb/NotificationsAPI/Notification.cpp b/Libraries/LibWeb/NotificationsAPI/Notification.cpp
index 6984e073f17..de8f68dd9b3 100644
--- a/Libraries/LibWeb/NotificationsAPI/Notification.cpp
+++ b/Libraries/LibWeb/NotificationsAPI/Notification.cpp
@@ -7,6 +7,8 @@
#include <AK/Math.h>
#include <AK/Time.h>
#include <LibGC/Heap.h>
+#include <LibJS/Console.h>
+#include <LibJS/Runtime/ConsoleObject.h>
#include <LibJS/Runtime/Object.h>
#include <LibJS/Runtime/VM.h>
#include <LibWeb/Compositor/CompositorHost.h>
@@ -19,6 +21,7 @@
#include <LibWeb/HTML/EventLoop/EventLoop.h>
#include <LibWeb/HTML/EventNames.h>
#include <LibWeb/HTML/Scripting/Environments.h>
+#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
#include <LibWeb/HTML/StructuredSerialize.h>
#include <LibWeb/HTML/Window.h>
#include <LibWeb/HighResolutionTime/TimeOrigin.h>
@@ -26,9 +29,13 @@
#include <LibWeb/NotificationsAPI/NotificationPermission.h>
#include <LibWeb/Page/Page.h>
#include <LibWeb/Painting/PaintingRustBridge.h>
+#include <LibWeb/PermissionsAPI/Permissions.h>
#include <LibWeb/Platform/ImageCodecPlugin.h>
#include <LibWeb/Platform/Timer.h>
#include <LibWeb/ServiceWorker/ServiceWorkerGlobalScope.h>
+#include <LibWeb/WebIDL/AbstractOperations.h>
+#include <LibWeb/WebIDL/CallbackType.h>
+#include <LibWeb/WebIDL/Promise.h>
namespace Web::NotificationsAPI {
@@ -630,14 +637,9 @@ __ENUMERATE(onerror, error)
__ENUMERATE(onclose, close)
#undef __ENUMERATE
-// https://notifications.spec.whatwg.org/#dom-notification-permission
-Bindings::NotificationPermission Notification::permission()
+static Bindings::NotificationPermission notification_permission_from(PermissionsAPI::PermissionState permission_state)
{
- // The static permission getter steps are to return the result of getting the notifications permission state.
// https://notifications.spec.whatwg.org/#permissions-integration
- // 1. Let permissionState be the result of getting the current permission state with "notifications".
- auto permission_state = get_the_notifications_permission_state(HTML::current_settings_object());
-
// 2. If permissionState is "prompt", then return "default".
// 3. Return permissionState.
switch (permission_state) {
@@ -651,6 +653,74 @@ Bindings::NotificationPermission Notification::permission()
VERIFY_NOT_REACHED();
}
+// https://notifications.spec.whatwg.org/#dom-notification-permission
+Bindings::NotificationPermission Notification::permission()
+{
+ // The static permission getter steps are to return the result of getting the notifications permission state.
+ // https://notifications.spec.whatwg.org/#permissions-integration
+ // 1. Let permissionState be the result of getting the current permission state with "notifications".
+ return notification_permission_from(get_the_notifications_permission_state(HTML::current_settings_object()));
+}
+
+// https://notifications.spec.whatwg.org/#dom-notification-requestpermission
+GC::Ref<WebIDL::Promise> Notification::request_permission(GC::Ptr<WebIDL::CallbackType> deprecated_callback)
+{
+ // 1. Let global be the current global object.
+ auto& settings = HTML::current_settings_object();
+ auto& realm = settings.realm();
+ GC::Ref<JS::Object> global = settings.global_object();
+
+ // 2. Let promise be a new promise in this's relevant Realm.
+ // NB: A static method has no "this"; the current realm is the one the call was made from.
+ auto promise = WebIDL::create_promise(realm);
+
+ // 3. Run these steps in parallel:
+ // 1. Let permissionState be the result of requesting permission to use "notifications".
+ // 2. Queue a global task on the DOM manipulation task source given global to run these steps:
+ auto settle = GC::create_function(realm.heap(), [&realm, global, promise, deprecated_callback, settings = GC::Ref(settings)](PermissionsAPI::PermissionState) {
+ // AD-HOC: "Request permission to use" reports "denied" for a prompt the user dismissed, though it stores nothing
+ // for it, and the page would then take a shrug for a refusal. The state the store holds once the
+ // answer is in is reported instead: "default" after a dismissal, so the page may ask again later.
+ auto permission_state = get_the_notifications_permission_state(settings);
+ HTML::queue_global_task(HTML::Task::Source::DOMManipulation, global, GC::create_function(realm.heap(), [&realm, promise, deprecated_callback, permission_state] {
+ HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
+ auto permission = JS::PrimitiveString::create(realm.vm(), Bindings::idl_enum_to_string(notification_permission_from(permission_state)));
+
+ // 1. If deprecatedCallback is given, then invoke deprecatedCallback with « permissionState » and "report".
+ if (deprecated_callback)
+ (void)WebIDL::invoke_callback(*deprecated_callback, {}, WebIDL::ExceptionBehavior::Report, { { permission } });
+
+ // 2. Resolve promise with permissionState.
+ WebIDL::resolve_promise(realm, promise, permission);
+ }));
+ });
+
+ // AD-HOC: "Request permission to use" asks the user whenever the state is "prompt". We ask only from a document
+ // that is its own top-level site, and only while it has transient activation, which the request consumes.
+ // Any other request resolves with the state as it is, and nothing is stored, so the page may ask again
+ // from a click. (A document that isn't a secure context already reads "denied" from the permission
+ // state algorithm, so it never gets this far.) Each refusal is explained on the console.
+ auto current_state = get_the_notifications_permission_state(settings);
+ if (current_state == PermissionsAPI::PermissionState::Prompt) {
+ auto& window = *HTML::window_from_global_object(*global);
+ auto refuse = [&](StringView message) {
+ realm.intrinsics().console_object()->console().output_debug_message(JS::Console::LogLevel::Error, Utf16String::from_utf8(message));
+ settle->function()(current_state);
+ return promise;
+ };
+ auto const& top_level_origin = settings.top_level_origin;
+ if (!top_level_origin.has_value() || !window.associated_document().origin().is_same_origin(*top_level_origin))
+ return refuse("Notification permission can only be requested from a document whose origin is the top-level origin."sv);
+ if (!window.has_transient_activation())
+ return refuse("Notification permission can only be requested while handling a user gesture."sv);
+ window.consume_user_activation();
+ }
+ PermissionsAPI::request_permission_with_user_prompt({ "notifications"_utf16 }, settings, settle);
+
+ // 4. Return promise.
+ return promise;
+}
+
// https://notifications.spec.whatwg.org/#dom-notification-actions
Vector<NotificationAction> Notification::actions() const
{
diff --git a/Libraries/LibWeb/NotificationsAPI/Notification.h b/Libraries/LibWeb/NotificationsAPI/Notification.h
index 2f934b24893..f51a281a899 100644
--- a/Libraries/LibWeb/NotificationsAPI/Notification.h
+++ b/Libraries/LibWeb/NotificationsAPI/Notification.h
@@ -115,6 +115,7 @@ public:
HighResolutionTime::EpochTimeStamp fallback_timestamp);
static Bindings::NotificationPermission permission();
+ static GC::Ref<WebIDL::Promise> request_permission(GC::Ptr<WebIDL::CallbackType> deprecated_callback);
void close();
diff --git a/Libraries/LibWeb/NotificationsAPI/Notification.idl b/Libraries/LibWeb/NotificationsAPI/Notification.idl
index a0ea97964b3..d019d3f7fb1 100644
--- a/Libraries/LibWeb/NotificationsAPI/Notification.idl
+++ b/Libraries/LibWeb/NotificationsAPI/Notification.idl
@@ -4,7 +4,7 @@ interface Notification : EventTarget {
constructor(DOMString title, optional NotificationOptions options = {});
static readonly attribute NotificationPermission permission;
- [FIXME, Exposed=Window] static Promise<NotificationPermission> requestPermission(optional NotificationPermissionCallback deprecatedCallback);
+ [Exposed=Window] static Promise<NotificationPermission> requestPermission(optional NotificationPermissionCallback deprecatedCallback);
static readonly attribute unsigned long maxActions;
@@ -73,4 +73,4 @@ dictionary NotificationAction {
USVString icon;
};
-[FIXME] callback NotificationPermissionCallback = undefined (NotificationPermission permission);
+callback NotificationPermissionCallback = undefined (NotificationPermission permission);
diff --git a/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.ini
index 08562002e1d..025854dfb19 100644
--- a/Tests/LibWeb/TestConfig.ini
+++ b/Tests/LibWeb/TestConfig.ini
@@ -1232,6 +1232,7 @@ Text/input/visual-viewport-scrollend-after-pan.html
[LoadFromInsecureOrigin]
Text/input/notifications/permission-insecure-context.html
+Text/input/notifications/request-permission-insecure.html
Text/input/wpt-import/html/browsers/origin/origin-keyed-agent-clusters/insecure-http.sub.html
Text/input/HTML/page-from-an-insecure-origin-is-not-a-secure-context.html
; Geolocation refuses a page that is not a secure context, which localhost would be.
diff --git a/Tests/LibWeb/Text/expected/notifications/request-already-decided-needs-no-gesture.txt b/Tests/LibWeb/Text/expected/notifications/request-already-decided-needs-no-gesture.txt
new file mode 100644
index 00000000000..fb09656a40a
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/notifications/request-already-decided-needs-no-gesture.txt
@@ -0,0 +1,2 @@
+granted: granted
+denied: denied
diff --git a/Tests/LibWeb/Text/expected/notifications/request-callback-order.txt b/Tests/LibWeb/Text/expected/notifications/request-callback-order.txt
new file mode 100644
index 00000000000..16dc05f0463
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/notifications/request-callback-order.txt
@@ -0,0 +1,2 @@
+callback: granted
+promise: granted
diff --git a/Tests/LibWeb/Text/expected/notifications/request-callback-throws.txt b/Tests/LibWeb/Text/expected/notifications/request-callback-throws.txt
new file mode 100644
index 00000000000..86992616e47
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/notifications/request-callback-throws.txt
@@ -0,0 +1,2 @@
+reported: boom
+promise: granted
diff --git a/Tests/LibWeb/Text/expected/notifications/request-permission-cross-origin-iframe.txt b/Tests/LibWeb/Text/expected/notifications/request-permission-cross-origin-iframe.txt
new file mode 100644
index 00000000000..ec6c6b6afbf
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/notifications/request-permission-cross-origin-iframe.txt
@@ -0,0 +1,2 @@
+cross-origin iframe: default
+top-level permission: default
diff --git a/Tests/LibWeb/Text/expected/notifications/request-permission-insecure.txt b/Tests/LibWeb/Text/expected/notifications/request-permission-insecure.txt
new file mode 100644
index 00000000000..6b5c3a356c2
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/notifications/request-permission-insecure.txt
@@ -0,0 +1,2 @@
+secure context: false
+result: denied
diff --git a/Tests/LibWeb/Text/expected/notifications/request-permission-no-gesture-is-default.txt b/Tests/LibWeb/Text/expected/notifications/request-permission-no-gesture-is-default.txt
new file mode 100644
index 00000000000..7e942c35f18
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/notifications/request-permission-no-gesture-is-default.txt
@@ -0,0 +1,2 @@
+result: default
+permission: default
diff --git a/Tests/LibWeb/Text/expected/notifications/request-permission-prompt-outcomes.txt b/Tests/LibWeb/Text/expected/notifications/request-permission-prompt-outcomes.txt
new file mode 100644
index 00000000000..932608c75a2
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/notifications/request-permission-prompt-outcomes.txt
@@ -0,0 +1,3 @@
+allow: granted / granted
+block: denied / denied
+dismiss: default / default
diff --git a/Tests/LibWeb/Text/expected/wpt-import/notifications/idlharness.https.any.txt b/Tests/LibWeb/Text/expected/wpt-import/notifications/idlharness.https.any.txt
index 9e3d2c2574a..a56ad8ce163 100644
--- a/Tests/LibWeb/Text/expected/wpt-import/notifications/idlharness.https.any.txt
+++ b/Tests/LibWeb/Text/expected/wpt-import/notifications/idlharness.https.any.txt
@@ -2,8 +2,8 @@ Harness status: OK
Found 67 tests
-61 Pass
-6 Fail
+63 Pass
+4 Fail
Pass idl_test setup
Pass idl_test validation
Pass Partial interface ServiceWorkerRegistration: original interface defined
@@ -18,7 +18,7 @@ Pass Notification interface: existence and properties of interface prototype obj
Pass Notification interface: existence and properties of interface prototype object's "constructor" property
Pass Notification interface: existence and properties of interface prototype object's @@unscopables property
Pass Notification interface: attribute permission
-Fail Notification interface: operation requestPermission(optional NotificationPermissionCallback)
+Pass Notification interface: operation requestPermission(optional NotificationPermissionCallback)
Pass Notification interface: attribute maxActions
Pass Notification interface: attribute onclick
Pass Notification interface: attribute onshow
@@ -45,7 +45,7 @@ Pass Notification must be primary interface of notification
Pass Stringification of notification
Pass Notification interface: notification must inherit property "permission" with the proper type
Pass Notification interface: notification must inherit property "requestPermission(optional NotificationPermissionCallback)" with the proper type
-Fail Notification interface: calling requestPermission(optional NotificationPermissionCallback) on notification with too few arguments must throw TypeError
+Pass Notification interface: calling requestPermission(optional NotificationPermissionCallback) on notification with too few arguments must throw TypeError
Pass Notification interface: notification must inherit property "maxActions" with the proper type
Pass Notification interface: notification must inherit property "onclick" with the proper type
Pass Notification interface: notification must inherit property "onshow" with the proper type
diff --git a/Tests/LibWeb/Text/input/notifications/request-already-decided-needs-no-gesture.html b/Tests/LibWeb/Text/input/notifications/request-already-decided-needs-no-gesture.html
new file mode 100644
index 00000000000..8f22fc16d4f
--- /dev/null
+++ b/Tests/LibWeb/Text/input/notifications/request-already-decided-needs-no-gesture.html
@@ -0,0 +1,12 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ // Once the user has decided, requestPermission() resolves with that decision without a gesture and without asking.
+ asyncTest(async done => {
+ for (const state of ["granted", "denied"]) {
+ await internals.setPermission("notifications", state);
+ println(`${state}: ${await Notification.requestPermission()}`);
+ }
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/notifications/request-callback-order.html b/Tests/LibWeb/Text/input/notifications/request-callback-order.html
new file mode 100644
index 00000000000..c50d2400b58
--- /dev/null
+++ b/Tests/LibWeb/Text/input/notifications/request-callback-order.html
@@ -0,0 +1,13 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ // The deprecated callback is invoked with the state before the promise resolves with it.
+ asyncTest(async done => {
+ await internals.setPermission("notifications", "granted");
+ const order = [];
+ const promise = Notification.requestPermission(permission => order.push(`callback: ${permission}`));
+ order.push(`promise: ${await promise}`);
+ println(order.join("\n"));
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/notifications/request-callback-throws.html b/Tests/LibWeb/Text/input/notifications/request-callback-throws.html
new file mode 100644
index 00000000000..71ca952d931
--- /dev/null
+++ b/Tests/LibWeb/Text/input/notifications/request-callback-throws.html
@@ -0,0 +1,19 @@
+<!DOCTYPE html>
+<script>
+ // Registered ahead of the harness, so the reported exception reaches this test rather than ending it.
+ addEventListener("error", event => {
+ println(`reported: ${event.error.message}`);
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ });
+</script>
+<script src="../include.js"></script>
+<script>
+ // A callback that throws is reported, and the promise still resolves.
+ asyncTest(async done => {
+ await internals.setPermission("notifications", "granted");
+ const result = await Notification.requestPermission(() => { throw new Error("boom"); });
+ println(`promise: ${result}`);
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/notifications/request-permission-cross-origin-iframe.html b/Tests/LibWeb/Text/input/notifications/request-permission-cross-origin-iframe.html
new file mode 100644
index 00000000000..b8b6c28ace1
--- /dev/null
+++ b/Tests/LibWeb/Text/input/notifications/request-permission-cross-origin-iframe.html
@@ -0,0 +1,37 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<style>iframe { position: absolute; top: 0; left: 0; width: 200px; height: 100px; border: 0; }</style>
+<script>
+ // A document whose origin isn't its top-level origin can't ask for the permission, even from a click: the request
+ // resolves with the state as it is, and no prompt is shown.
+ asyncTest(async done => {
+ const server = httpTestServer();
+ const frameURL = new URL(await server.createEcho("GET", "/notifications/request-permission-frame.html", {
+ status: 200,
+ headers: { "Content-Type": "text/html" },
+ body: `<!DOCTYPE html><script>
+ addEventListener("click", async () => parent.postMessage(await Notification.requestPermission(), "*"), { once: true });
+ parent.postMessage("ready", "*");
+ <\/script>`,
+ }));
+ frameURL.hostname = uniqueLocalhostHostname("notifications-request-cross-origin");
+
+ internals.setNextPermissionPromptOutcome("notifications", "allow");
+ const iframe = document.createElement("iframe");
+ iframe.src = frameURL.href;
+ const result = await new Promise(resolve => {
+ setTimeout(() => resolve("no answer"), 2000);
+ addEventListener("message", event => {
+ // The frame lives in its own process, so the click has to travel through the UI process to reach it.
+ if (event.data === "ready")
+ internals.clickThroughUIProcess(20, 20);
+ else
+ resolve(event.data);
+ });
+ document.body.appendChild(iframe);
+ });
+ println(`cross-origin iframe: ${result}`);
+ println(`top-level permission: ${Notification.permission}`);
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/notifications/request-permission-insecure.html b/Tests/LibWeb/Text/input/notifications/request-permission-insecure.html
new file mode 100644
index 00000000000..a6cb8950ff0
--- /dev/null
+++ b/Tests/LibWeb/Text/input/notifications/request-permission-insecure.html
@@ -0,0 +1,14 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ // A page that isn't a secure context gets "denied" from requestPermission(), gesture or not, and no prompt.
+ asyncTest(async done => {
+ internals.setNextPermissionPromptOutcome("notifications", "allow");
+ addEventListener("click", async () => {
+ println(`secure context: ${isSecureContext}`);
+ println(`result: ${await Notification.requestPermission()}`);
+ done();
+ }, { once: true });
+ internals.click(10, 10);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/notifications/request-permission-no-gesture-is-default.html b/Tests/LibWeb/Text/input/notifications/request-permission-no-gesture-is-default.html
new file mode 100644
index 00000000000..5fb6b5c56c2
--- /dev/null
+++ b/Tests/LibWeb/Text/input/notifications/request-permission-no-gesture-is-default.html
@@ -0,0 +1,11 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ // Without a user gesture, requestPermission() asks nothing and resolves with the state as it is: "default".
+ asyncTest(async done => {
+ internals.setNextPermissionPromptOutcome("notifications", "allow");
+ println(`result: ${await Notification.requestPermission()}`);
+ println(`permission: ${Notification.permission}`);
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/notifications/request-permission-prompt-outcomes.html b/Tests/LibWeb/Text/input/notifications/request-permission-prompt-outcomes.html
new file mode 100644
index 00000000000..ec0c69f3ad7
--- /dev/null
+++ b/Tests/LibWeb/Text/input/notifications/request-permission-prompt-outcomes.html
@@ -0,0 +1,18 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ // requestPermission() asks through the permission prompt while the user hasn't decided, from a click, and resolves
+ // with what the user answered: "granted", "denied", or "default" for a dismissed prompt.
+ asyncTest(async done => {
+ const requestFromClick = outcome => new Promise(resolve => {
+ internals.setNextPermissionPromptOutcome("notifications", outcome);
+ addEventListener("click", async () => resolve(await Notification.requestPermission()), { once: true });
+ internals.click(10, 10);
+ });
+ for (const outcome of ["allow", "block", "dismiss"]) {
+ await internals.setPermission("notifications", "prompt");
+ println(`${outcome}: ${await requestFromClick(outcome)} / ${Notification.permission}`);
+ }
+ done();
+ });
+</script>