Title: [293921] trunk
Revision
293921
Author
[email protected]
Date
2022-05-06 13:26:03 -0700 (Fri, 06 May 2022)

Log Message

Add support for Notification objects with custom data
https://bugs.webkit.org/show_bug.cgi?id=240153

Reviewed by Chris Dumez.

This adds support for the data attribute in Notification. This holds an arbitrary structured
cloneable object passed through the constructor. The accessor is marked SameObject, which we
implement via CachedAttribute. The wire form of the data is serialized and deserialized in
NotificationData so that persistent notifications properly support this property.

* Modules/notifications/Notification.cpp:
(WebCore::createSerializedNotificationData):
(WebCore::Notification::create):
(WebCore::Notification::createForServiceWorker):
(WebCore::Notification::Notification):
(WebCore::Notification::dataForBindings):
* Modules/notifications/Notification.h:
* Modules/notifications/Notification.idl:
* Modules/notifications/NotificationData.cpp:
(WebCore::NotificationData::isolatedCopy const):
(WebCore::NotificationData::isolatedCopy):
* Modules/notifications/NotificationData.h:
(WebCore::NotificationData::encode const):
(WebCore::NotificationData::decode):
* Modules/notifications/NotificationDataCocoa.mm:
(WebCore::NotificationData::fromDictionary):
(WebCore::NotificationData::dictionaryRepresentation const):
* Modules/notifications/NotificationOptions.idl:
* workers/service/ServiceWorkerRegistration.cpp:
(WebCore::ServiceWorkerRegistration::showNotification):

LayoutTests/imported/w3c:

* web-platform-tests/notifications/idlharness.https.any-expected.txt:
* web-platform-tests/notifications/idlharness.https.any.serviceworker-expected.txt:
* web-platform-tests/wasm/serialization/module/serialization-via-notifications-api.any-expected.txt:

LayoutTests:

* http/tests/notifications/notification-expected.txt:
* http/tests/notifications/notification.html:
* http/tests/workers/service/getnotifications-expected.txt:
* http/tests/workers/service/getnotifications-stop-expected.txt:
* http/tests/workers/service/getnotifications-stop.html:
* http/tests/workers/service/getnotifications.html:
* http/tests/workers/service/openwindow-from-notification-click.html:
* http/tests/workers/service/resources/shownotification-openwindow-worker.js:
(async tryShow):
(async getNotes):
* http/tests/workers/service/resources/shownotification-worker.js:
(async event):
(async tryShow):
(async tryShowInvalidData.try.data):
(async tryShowInvalidData):
(async getNotes):
* http/tests/workers/service/shownotification-allowed-document-expected.txt:
* http/tests/workers/service/shownotification-allowed-document.html:
* http/tests/workers/service/shownotification-allowed.html:
* http/tests/workers/service/shownotification-invalid-data-expected.txt: Added.
* http/tests/workers/service/shownotification-invalid-data.html:

Canonical link: https://commits.webkit.org/250368@main

Modified Paths

Added Paths

Diff

Modified: trunk/LayoutTests/ChangeLog (293920 => 293921)


--- trunk/LayoutTests/ChangeLog	2022-05-06 19:55:27 UTC (rev 293920)
+++ trunk/LayoutTests/ChangeLog	2022-05-06 20:26:03 UTC (rev 293921)
@@ -1,3 +1,35 @@
+2022-05-05  Ben Nham  <[email protected]>
+
+        Add support for Notification objects with custom data
+        https://bugs.webkit.org/show_bug.cgi?id=240153
+
+        Reviewed by Chris Dumez.
+
+        Test that Notification objects with custom data can be created and shown by both documents
+        and service workers.
+
+        * http/tests/notifications/notification-expected.txt:
+        * http/tests/notifications/notification.html:
+        * http/tests/workers/service/getnotifications-expected.txt:
+        * http/tests/workers/service/getnotifications-stop-expected.txt:
+        * http/tests/workers/service/getnotifications-stop.html:
+        * http/tests/workers/service/getnotifications.html:
+        * http/tests/workers/service/openwindow-from-notification-click.html:
+        * http/tests/workers/service/resources/shownotification-openwindow-worker.js:
+        (async tryShow):
+        (async getNotes):
+        * http/tests/workers/service/resources/shownotification-worker.js:
+        (async event):
+        (async tryShow):
+        (async tryShowInvalidData.try.data):
+        (async tryShowInvalidData):
+        (async getNotes):
+        * http/tests/workers/service/shownotification-allowed-document-expected.txt:
+        * http/tests/workers/service/shownotification-allowed-document.html:
+        * http/tests/workers/service/shownotification-allowed.html:
+        * http/tests/workers/service/shownotification-invalid-data-expected.txt: Added.
+        * http/tests/workers/service/shownotification-invalid-data.html: Added.
+
 2022-05-06  Brent Fulgham  <[email protected]>
 
         Remove the viewportFitEnabled WKPreference now that it is always on 

Modified: trunk/LayoutTests/http/tests/notifications/notification-expected.txt (293920 => 293921)


--- trunk/LayoutTests/http/tests/notifications/notification-expected.txt	2022-05-06 19:55:27 UTC (rev 293920)
+++ trunk/LayoutTests/http/tests/notifications/notification-expected.txt	2022-05-06 20:26:03 UTC (rev 293921)
@@ -2,5 +2,7 @@
 PASS The Notification constructor requires at least one argument.
 PASS The Notification object initializes its properties to their default values from the NotificationOptions dictionary if it is not provided.
 PASS The Notification object initializes its properties to the values from NotificationOptions dictionary if it is provided.
+PASS The Notification constructor should throw if it is passed a non-cloneable data option.
 PASS The NotificationOptions dictionary only accepts valid NotificationDirection values.
+PASS The Notification data property returns the same object after GC.
 

Modified: trunk/LayoutTests/http/tests/notifications/notification.html (293920 => 293921)


--- trunk/LayoutTests/http/tests/notifications/notification.html	2022-05-06 19:55:27 UTC (rev 293920)
+++ trunk/LayoutTests/http/tests/notifications/notification.html	2022-05-06 20:26:03 UTC (rev 293921)
@@ -2,6 +2,7 @@
 <html>
 <head>
     <meta charset="utf-8">
+    <script src=""
     <script src=""
     <script src=""
 </head>
@@ -24,6 +25,7 @@
     assert_equals(notification.body, "");
     assert_equals(notification.tag, "");
     assert_equals(notification.icon, "");
+    assert_equals(notification.data, null);
 }, "The Notification object initializes its properties to their default values from the NotificationOptions dictionary if it is not provided.");
 
 test(function() {
@@ -32,7 +34,8 @@
         lang: "en",
         body: "test body",
         tag: "test tag",
-        icon: "foo.png"
+        icon: "foo.png",
+        data: {foo: 'bar'}
     });
 
     assert_equals(notification.title, "test title");
@@ -41,9 +44,14 @@
     assert_equals(notification.body, "test body");
     assert_equals(notification.tag, "test tag");
     assert_equals(notification.icon, "http://127.0.0.1:8000/notifications/foo.png");
+    assert_equals(JSON.stringify(notification.data), '{"foo":"bar"}')
 }, "The Notification object initializes its properties to the values from NotificationOptions dictionary if it is provided.");
 
 test(function() {
+    assert_throws_dom('DataCloneError', function() { new Notification("title", { data: function() { } }); });
+}, "The Notification constructor should throw if it is passed a non-cloneable data option.");
+
+test(function() {
     let notification1 = new Notification("test title", { dir: "auto" });
     assert_equals(notification1.dir, "auto");
 
@@ -56,6 +64,17 @@
     assert_throws_js(TypeError, function() { new Notification("test title", { dir: "foo" }) });
 }, "The NotificationOptions dictionary only accepts valid NotificationDirection values.");
 
+promise_test(async function() {
+    let notification = new Notification("test title", { data: { foo: 'bar' } });
+    let data = ""
+    assert_equals(JSON.stringify(data), '{"foo":"bar"}')
+    gc();
+    await new Promise(resolve => setTimeout(resolve, 10));
+    gc();
+    await new Promise(resolve => setTimeout(resolve, 10));
+    assert_equals(data, notification.data);
+}, "The Notification data property returns the same object after GC.");
+
 </script>
 </body>
 </html>

Modified: trunk/LayoutTests/http/tests/workers/service/getnotifications-expected.txt (293920 => 293921)


--- trunk/LayoutTests/http/tests/workers/service/getnotifications-expected.txt	2022-05-06 19:55:27 UTC (rev 293920)
+++ trunk/LayoutTests/http/tests/workers/service/getnotifications-expected.txt	2022-05-06 20:26:03 UTC (rev 293921)
@@ -15,12 +15,15 @@
 Title: Hello
 Body: Body1
 Tag: tag-a
+Data: null
 Title: There
 Body: Body2
 Tag: tag-b
+Data: null
 Title: Buddy
 Body: Body3
 Tag: tag-b
+Data: Data3
 
 Got notifications
 There are 1 notifications
@@ -27,6 +30,7 @@
 Title: Hello
 Body: Body1
 Tag: tag-a
+Data: null
 
 Got notifications
 There are 2 notifications
@@ -33,14 +37,16 @@
 Title: There
 Body: Body2
 Tag: tag-b
+Data: null
 Title: Buddy
 Body: Body3
 Tag: tag-b
+Data: Data3
 
 Retrieving notifications from page registration object - 3
-Notification: Hello / Body1 / tag-a
-Notification: There / Body2 / tag-b
-Notification: Buddy / Body3 / tag-b
+Notification: Hello / Body1 / tag-a / null
+Notification: There / Body2 / tag-b / null
+Notification: Buddy / Body3 / tag-b / Data3
 Retrieving notifications from page registration object - end
 PASS successfullyParsed is true
 

Modified: trunk/LayoutTests/http/tests/workers/service/getnotifications-stop-expected.txt (293920 => 293921)


--- trunk/LayoutTests/http/tests/workers/service/getnotifications-stop-expected.txt	2022-05-06 19:55:27 UTC (rev 293920)
+++ trunk/LayoutTests/http/tests/workers/service/getnotifications-stop-expected.txt	2022-05-06 20:26:03 UTC (rev 293921)
@@ -15,12 +15,15 @@
 Title: Hello
 Body: Body1
 Tag: tag-a
+Data: null
 Title: There
 Body: Body2
 Tag: tag-b
+Data: null
 Title: Buddy
 Body: Body3
 Tag: tag-b
+Data: Data3
 
 Got notifications
 There are 1 notifications
@@ -27,6 +30,7 @@
 Title: Hello
 Body: Body1
 Tag: tag-a
+Data: null
 
 Got notifications
 There are 2 notifications
@@ -33,17 +37,19 @@
 Title: There
 Body: Body2
 Tag: tag-b
+Data: null
 Title: Buddy
 Body: Body3
 Tag: tag-b
+Data: Data3
 
 Loading iframe
 Get notifications from iframe
 Remove iframes to stop notifications
 Retrieving notifications from page registration object - 3
-Notification: Hello / Body1 / tag-a
-Notification: There / Body2 / tag-b
-Notification: Buddy / Body3 / tag-b
+Notification: Hello / Body1 / tag-a / null
+Notification: There / Body2 / tag-b / null
+Notification: Buddy / Body3 / tag-b / Data3
 Retrieving notifications from page registration object - end
 PASS successfullyParsed is true
 

Modified: trunk/LayoutTests/http/tests/workers/service/getnotifications-stop.html (293920 => 293921)


--- trunk/LayoutTests/http/tests/workers/service/getnotifications-stop.html	2022-05-06 19:55:27 UTC (rev 293920)
+++ trunk/LayoutTests/http/tests/workers/service/getnotifications-stop.html	2022-05-06 20:26:03 UTC (rev 293921)
@@ -66,7 +66,7 @@
     if (numberGot == 1) {
         event.source.postMessage("tryshow|Hello|Body1|tag-a");
         event.source.postMessage("tryshow|There|Body2|tag-b");
-        event.source.postMessage("tryshow|Buddy|Body3|tag-b");
+        event.source.postMessage("tryshow|Buddy|Body3|tag-b|Data3");
     } else if (numberGot == 4) {
         debug("Loading iframe");
         const frame = await with_iframe("resources/getNotifications-iframe.html");
@@ -79,7 +79,7 @@
 
         debug("Retrieving notifications from page registration object - " + notifications.length);
         notifications.forEach(notification => {
-            debug("Notification: " + notification.title + " / " + notification.body + " / " + notification.tag);
+            debug("Notification: " + notification.title + " / " + notification.body + " / " + notification.tag + " / " + notification.data);
         });    
         debug("Retrieving notifications from page registration object - end");
 

Modified: trunk/LayoutTests/http/tests/workers/service/getnotifications.html (293920 => 293921)


--- trunk/LayoutTests/http/tests/workers/service/getnotifications.html	2022-05-06 19:55:27 UTC (rev 293920)
+++ trunk/LayoutTests/http/tests/workers/service/getnotifications.html	2022-05-06 20:26:03 UTC (rev 293921)
@@ -56,12 +56,12 @@
     if (numberGot == 1) {
         event.source.postMessage("tryshow|Hello|Body1|tag-a");
         event.source.postMessage("tryshow|There|Body2|tag-b");
-        event.source.postMessage("tryshow|Buddy|Body3|tag-b");
+        event.source.postMessage("tryshow|Buddy|Body3|tag-b|Data3");
     } else if (numberGot == 4) {
         const notifications = await registration.getNotifications({ tag: "" });
         debug("Retrieving notifications from page registration object - " + notifications.length);
         notifications.forEach(notification => {
-            debug("Notification: " + notification.title + " / " + notification.body + " / " + notification.tag);
+            debug("Notification: " + notification.title + " / " + notification.body + " / " + notification.tag + " / " + notification.data);
         });    
         debug("Retrieving notifications from page registration object - end");
 

Modified: trunk/LayoutTests/http/tests/workers/service/openwindow-from-notification-click.html (293920 => 293921)


--- trunk/LayoutTests/http/tests/workers/service/openwindow-from-notification-click.html	2022-05-06 19:55:27 UTC (rev 293920)
+++ trunk/LayoutTests/http/tests/workers/service/openwindow-from-notification-click.html	2022-05-06 20:26:03 UTC (rev 293921)
@@ -37,7 +37,7 @@
 
     installingWorker.addEventListener("statechange", () => {
         if (installingWorker.state === "activated") {
-            installingWorker.postMessage("tryshow");
+            installingWorker.postMessage("tryshow|title|body|tag|foobar");
         }
     });
 }
@@ -55,7 +55,7 @@
     } else if (event.data == "shown") {
         if (testRunner)
             testRunner.simulateWebNotificationClickForServiceWorkerNotifications();
-    } else if (event.data == "clicked") {
+    } else if (event.data == "clicked|data:foobar") {
         shouldBeFalse("gotClicked");
         shouldBeFalse("gotClosed");
         gotClicked = true;

Modified: trunk/LayoutTests/http/tests/workers/service/resources/shownotification-openwindow-worker.js (293920 => 293921)


--- trunk/LayoutTests/http/tests/workers/service/resources/shownotification-openwindow-worker.js	2022-05-06 19:55:27 UTC (rev 293920)
+++ trunk/LayoutTests/http/tests/workers/service/resources/shownotification-openwindow-worker.js	2022-05-06 20:26:03 UTC (rev 293921)
@@ -17,7 +17,7 @@
 });
 
 self.addEventListener('notificationclick', async function(event) {
-    await messageClients("clicked");
+    await messageClients("clicked|data:" + event.notification.data);
     event.notification.close();
 
     // Should fail because about:blank is not an allowable URL
@@ -49,21 +49,22 @@
 
 async function tryShow(message)
 {
-    var title, body, tag;
+    var command, title, body, tag, data;
     var components = message.split('|');
 
     if (components.length == 1) {
         title = "This is a notification";        
-    } else {
-        title = components[1];
-        body = components[2];
-        tag = components[3];
+    } else if (components.length == 4) {
+        [command, title, body, tag] = components;
+    } else if (components.length == 5) {
+        [command, title, body, tag, data] = components;
     }
     
     try {
         await registration.showNotification(title, {
             body: body,
-            tag: tag
+            tag: tag,
+            data: data
         });
     } catch(error) {
         await messageClients("showFailed");
@@ -93,6 +94,7 @@
         reply += "Title: " + notification.title + "|";
         reply += "Body: " + notification.body + "|";
         reply += "Tag: " + notification.tag + "|";
+        reply += "Data: " + notification.data + "|";
     }
     await messageClients(reply);
 }

Modified: trunk/LayoutTests/http/tests/workers/service/resources/shownotification-worker.js (293920 => 293921)


--- trunk/LayoutTests/http/tests/workers/service/resources/shownotification-worker.js	2022-05-06 19:55:27 UTC (rev 293920)
+++ trunk/LayoutTests/http/tests/workers/service/resources/shownotification-worker.js	2022-05-06 20:26:03 UTC (rev 293921)
@@ -9,7 +9,7 @@
 }
 
 self.addEventListener('notificationclick', async function(event) {
-    await messageClients("clicked");
+    await messageClients("clicked|data:" + event.notification.data);
     event.notification.close();
 });
 
@@ -19,15 +19,15 @@
 
 async function tryShow(message)
 {
-    var title, body, tag;
+    var command, title, body, tag, data;
     var components = message.split('|');
 
     if (components.length == 1) {
         title = "This is a notification";        
-    } else {
-        title = components[1];
-        body = components[2];
-        tag = components[3];
+    } else if (components.length == 4) {
+        [command, title, body, tag] = components;
+    } else if (components.length == 5) {
+        [command, title, body, tag, data] = components;
     }
 
     if (!self.Notification) {
@@ -37,7 +37,8 @@
     try {
          new Notification(title, {
             body: body,
-            tag: tag
+            tag: tag,
+            data: data
         });
         await messageClients("showFailed due to Notification created from constructor");
         return;
@@ -51,7 +52,8 @@
     try {
         await registration.showNotification(title, {
             body: body,
-            tag: tag
+            tag: tag,
+            data: data
         });
     } catch(error) {
         await messageClients("showFailed");
@@ -61,6 +63,21 @@
     await messageClients("shown");
 }
 
+async function tryShowInvalidData()
+{
+    let error = null;
+    try {
+        await registration.showNotification("Invalid notification", { data: function() { } });
+    } catch (e) {
+        error = e;
+    }
+
+    if (error)
+        await messageClients("showFailed: threw " + error.name);
+    else if (error0)
+        await messageClients("shown");
+}
+
 var seenNotes = new Set();
 
 async function getNotes(message)
@@ -81,6 +98,7 @@
         reply += "Title: " + notification.title + "|";
         reply += "Body: " + notification.body + "|";
         reply += "Tag: " + notification.tag + "|";
+        reply += "Data: " + notification.data + "|";
     }
     await messageClients(reply);
 }
@@ -89,6 +107,8 @@
     var messageName = event.data.split('|')[0];
     if (messageName == "tryshow")
         await tryShow(event.data);
+    if (messageName == "tryshowinvaliddata")
+        await tryShowInvalidData();
     if (messageName == "getnotes")
         await getNotes(event.data);
 });

Modified: trunk/LayoutTests/http/tests/workers/service/shownotification-allowed-document-expected.txt (293920 => 293921)


--- trunk/LayoutTests/http/tests/workers/service/shownotification-allowed-document-expected.txt	2022-05-06 19:55:27 UTC (rev 293920)
+++ trunk/LayoutTests/http/tests/workers/service/shownotification-allowed-document-expected.txt	2022-05-06 20:26:03 UTC (rev 293921)
@@ -4,6 +4,7 @@
 
 
 PASS Notification.permission is "granted"
+PASS threwDataCloneError is true
 PASS gotClicked is false
 PASS gotClosed is false
 PASS gotClicked is true

Modified: trunk/LayoutTests/http/tests/workers/service/shownotification-allowed-document.html (293920 => 293921)


--- trunk/LayoutTests/http/tests/workers/service/shownotification-allowed-document.html	2022-05-06 19:55:27 UTC (rev 293920)
+++ trunk/LayoutTests/http/tests/workers/service/shownotification-allowed-document.html	2022-05-06 20:26:03 UTC (rev 293921)
@@ -20,6 +20,8 @@
 
 shouldBeEqualToString("Notification.permission", "granted");
 
+var threwDataCloneError = false;
+
 async function registerServiceWorker() {
     var registration = await navigator.serviceWorker.register('resources/shownotification-worker.js');
 
@@ -37,7 +39,14 @@
 
     installingWorker.addEventListener("statechange", async () => {
         if (installingWorker.state === "activated") {
-            await registration.showNotification("This is a notification", { body: "body", tag: "tag" });
+            try {
+                await registration.showNotification("Invalid notification", { data: function() { } });
+            } catch (error) {
+                threwDataCloneError = error.name == 'DataCloneError';
+            }
+            shouldBeTrue('threwDataCloneError');
+
+            await registration.showNotification("This is a notification", { body: "body", tag: "tag", data: "foobar" });
             if (window.testRunner)
                 testRunner.simulateWebNotificationClickForServiceWorkerNotifications();
         }
@@ -50,7 +59,7 @@
 navigator.serviceWorker.addEventListener('message', async event => {
     if (event.data == "showFailed") {
         failTheTest("Unexpectedly received the failed-to-show message");
-    } else if (event.data == "clicked") {
+    } else if (event.data == "clicked|data:foobar") {
         shouldBeFalse("gotClicked");
         shouldBeFalse("gotClosed");
         gotClicked = true;

Modified: trunk/LayoutTests/http/tests/workers/service/shownotification-allowed.html (293920 => 293921)


--- trunk/LayoutTests/http/tests/workers/service/shownotification-allowed.html	2022-05-06 19:55:27 UTC (rev 293920)
+++ trunk/LayoutTests/http/tests/workers/service/shownotification-allowed.html	2022-05-06 20:26:03 UTC (rev 293921)
@@ -37,7 +37,7 @@
 
     installingWorker.addEventListener("statechange", () => {
         if (installingWorker.state === "activated") {
-            installingWorker.postMessage("tryshow");
+            installingWorker.postMessage("tryshow|title|body|tag|foobar");
         }
     });
 }
@@ -57,7 +57,7 @@
 
         if (testRunner)
             testRunner.simulateWebNotificationClickForServiceWorkerNotifications();
-    } else if (event.data == "clicked") {
+    } else if (event.data == "clicked|data:foobar") {
         shouldBeFalse("gotClicked");
         shouldBeFalse("gotClosed");
         gotClicked = true;

Added: trunk/LayoutTests/http/tests/workers/service/shownotification-invalid-data-expected.txt (0 => 293921)


--- trunk/LayoutTests/http/tests/workers/service/shownotification-invalid-data-expected.txt	                        (rev 0)
+++ trunk/LayoutTests/http/tests/workers/service/shownotification-invalid-data-expected.txt	2022-05-06 20:26:03 UTC (rev 293921)
@@ -0,0 +1,11 @@
+This tests that a notification shown by a service worker fails if it is passed an invalid data option
+
+On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
+
+
+PASS Notification.permission is "granted"
+PASS Notification constructor failed with DataCloneError
+PASS successfullyParsed is true
+
+TEST COMPLETE
+

Added: trunk/LayoutTests/http/tests/workers/service/shownotification-invalid-data.html (0 => 293921)


--- trunk/LayoutTests/http/tests/workers/service/shownotification-invalid-data.html	                        (rev 0)
+++ trunk/LayoutTests/http/tests/workers/service/shownotification-invalid-data.html	2022-05-06 20:26:03 UTC (rev 293921)
@@ -0,0 +1,52 @@
+<head>
+<script src=""
+<script src=""
+<script>
+description("This tests that a notification shown by a service worker fails if it is passed an invalid data option");
+jsTestIsAsync = true;
+
+function failTheTest(msg)
+{
+    testFailed(msg);
+    finishJSTest();
+}
+
+if (window.testRunner)
+    testRunner.grantWebNotificationPermission(testURL);
+
+shouldBeEqualToString("Notification.permission", "granted");
+
+async function registerServiceWorker() {
+    var registration = await navigator.serviceWorker.register('resources/shownotification-worker.js');
+    
+    if (!registration)
+        return testFailed("No registration");
+    
+    if (registration.active) {
+        registration.active.postMessage("tryshowinvaliddata");
+        return;
+    }
+
+    var installingWorker = registration.installing;
+    if (!installingWorker)
+        failTheTest("No active *or* installing worker");
+
+    installingWorker.addEventListener("statechange", () => {
+        if (installingWorker.state === "activated") {
+            installingWorker.postMessage("tryshowinvaliddata");
+        }
+    });
+}
+
+navigator.serviceWorker.addEventListener('message', event => {
+    if (event.data == "showFailed: threw DataCloneError") {
+        testPassed("Notification constructor failed with DataCloneError");
+    } else {
+        testFailed("Message received: " + event.data);
+    }
+    finishJSTest();
+});
+</script>
+</head>
+<body _onload_="registerServiceWorker()">
+</body>

Modified: trunk/LayoutTests/imported/w3c/ChangeLog (293920 => 293921)


--- trunk/LayoutTests/imported/w3c/ChangeLog	2022-05-06 19:55:27 UTC (rev 293920)
+++ trunk/LayoutTests/imported/w3c/ChangeLog	2022-05-06 20:26:03 UTC (rev 293921)
@@ -1,3 +1,14 @@
+2022-05-05  Ben Nham  <[email protected]>
+        
+        Add support for Notification objects with custom data
+        https://bugs.webkit.org/show_bug.cgi?id=240153
+
+        Reviewed by Chris Dumez.
+
+        * web-platform-tests/notifications/idlharness.https.any-expected.txt:
+        * web-platform-tests/notifications/idlharness.https.any.serviceworker-expected.txt:
+        * web-platform-tests/wasm/serialization/module/serialization-via-notifications-api.any-expected.txt:
+
 2022-05-05  Manuel Rego Casasnovas  <[email protected]>
 
         ARIA reflection for Element attributes

Modified: trunk/LayoutTests/imported/w3c/web-platform-tests/notifications/idlharness.https.any-expected.txt (293920 => 293921)


--- trunk/LayoutTests/imported/w3c/web-platform-tests/notifications/idlharness.https.any-expected.txt	2022-05-06 19:55:27 UTC (rev 293920)
+++ trunk/LayoutTests/imported/w3c/web-platform-tests/notifications/idlharness.https.any-expected.txt	2022-05-06 20:26:03 UTC (rev 293921)
@@ -32,7 +32,7 @@
 FAIL Notification interface: attribute renotify assert_true: The prototype object must have a property "renotify" expected true got false
 FAIL Notification interface: attribute silent assert_true: The prototype object must have a property "silent" expected true got false
 FAIL Notification interface: attribute requireInteraction assert_true: The prototype object must have a property "requireInteraction" expected true got false
-FAIL Notification interface: attribute data assert_true: The prototype object must have a property "data" expected true got false
+PASS Notification interface: attribute data
 FAIL Notification interface: attribute actions assert_true: The prototype object must have a property "actions" expected true got false
 PASS Notification interface: operation close()
 PASS Notification must be primary interface of notification
@@ -58,7 +58,7 @@
 FAIL Notification interface: notification must inherit property "renotify" with the proper type assert_inherits: property "renotify" not found in prototype chain
 FAIL Notification interface: notification must inherit property "silent" with the proper type assert_inherits: property "silent" not found in prototype chain
 FAIL Notification interface: notification must inherit property "requireInteraction" with the proper type assert_inherits: property "requireInteraction" not found in prototype chain
-FAIL Notification interface: notification must inherit property "data" with the proper type assert_inherits: property "data" not found in prototype chain
+PASS Notification interface: notification must inherit property "data" with the proper type
 FAIL Notification interface: notification must inherit property "actions" with the proper type assert_inherits: property "actions" not found in prototype chain
 PASS Notification interface: notification must inherit property "close()" with the proper type
 PASS NotificationEvent interface: existence and properties of interface object

Modified: trunk/LayoutTests/imported/w3c/web-platform-tests/notifications/idlharness.https.any.serviceworker-expected.txt (293920 => 293921)


--- trunk/LayoutTests/imported/w3c/web-platform-tests/notifications/idlharness.https.any.serviceworker-expected.txt	2022-05-06 19:55:27 UTC (rev 293920)
+++ trunk/LayoutTests/imported/w3c/web-platform-tests/notifications/idlharness.https.any.serviceworker-expected.txt	2022-05-06 20:26:03 UTC (rev 293921)
@@ -32,7 +32,7 @@
 FAIL Notification interface: attribute renotify assert_true: The prototype object must have a property "renotify" expected true got false
 FAIL Notification interface: attribute silent assert_true: The prototype object must have a property "silent" expected true got false
 FAIL Notification interface: attribute requireInteraction assert_true: The prototype object must have a property "requireInteraction" expected true got false
-FAIL Notification interface: attribute data assert_true: The prototype object must have a property "data" expected true got false
+PASS Notification interface: attribute data
 FAIL Notification interface: attribute actions assert_true: The prototype object must have a property "actions" expected true got false
 PASS Notification interface: operation close()
 PASS NotificationEvent interface: existence and properties of interface object

Modified: trunk/LayoutTests/imported/w3c/web-platform-tests/wasm/serialization/module/serialization-via-notifications-api.any-expected.txt (293920 => 293921)


--- trunk/LayoutTests/imported/w3c/web-platform-tests/wasm/serialization/module/serialization-via-notifications-api.any-expected.txt	2022-05-06 19:55:27 UTC (rev 293920)
+++ trunk/LayoutTests/imported/w3c/web-platform-tests/wasm/serialization/module/serialization-via-notifications-api.any-expected.txt	2022-05-06 20:26:03 UTC (rev 293921)
@@ -1,12 +1,4 @@
 
-FAIL WebAssembly.Module cloning via the Notifications API's data member: basic case assert_throws_dom: function "() => {
-    new Notification("Bob: Hi", { data: createEmptyWasmModule() });
-  }" did not throw
-FAIL WebAssembly.Module cloning via the Notifications API's data member: is interleaved correctly assert_throws_dom: function "() => {
-    new Notification("Bob: Hi", { data: [
-      { get x() { getter1Called = true; return 5; } },
-      createEmptyWasmModule(),
-      { get x() { getter2Called = true; return 5; } }
-    ]});
-  }" did not throw
+PASS WebAssembly.Module cloning via the Notifications API's data member: basic case
+PASS WebAssembly.Module cloning via the Notifications API's data member: is interleaved correctly
 

Modified: trunk/Source/WebCore/ChangeLog (293920 => 293921)


--- trunk/Source/WebCore/ChangeLog	2022-05-06 19:55:27 UTC (rev 293920)
+++ trunk/Source/WebCore/ChangeLog	2022-05-06 20:26:03 UTC (rev 293921)
@@ -1,3 +1,38 @@
+2022-05-05  Ben Nham  <[email protected]>
+        
+        Add support for Notification objects with custom data
+        https://bugs.webkit.org/show_bug.cgi?id=240153
+
+        Reviewed by Chris Dumez.
+
+        This adds support for the data attribute in Notification. This holds an arbitrary structured
+        cloneable object passed through the constructor. The accessor is marked SameObject, which we
+        implement via CachedAttribute. The wire form of the data is serialized and deserialized in
+        NotificationData so that persistent notifications properly support this property.
+
+        Covered by new and existing layout tests.
+
+        * Modules/notifications/Notification.cpp:
+        (WebCore::createSerializedNotificationData):
+        (WebCore::Notification::create):
+        (WebCore::Notification::createForServiceWorker):
+        (WebCore::Notification::Notification):
+        (WebCore::Notification::dataForBindings):
+        * Modules/notifications/Notification.h:
+        * Modules/notifications/Notification.idl:
+        * Modules/notifications/NotificationData.cpp:
+        (WebCore::NotificationData::isolatedCopy const):
+        (WebCore::NotificationData::isolatedCopy):
+        * Modules/notifications/NotificationData.h:
+        (WebCore::NotificationData::encode const):
+        (WebCore::NotificationData::decode):
+        * Modules/notifications/NotificationDataCocoa.mm:
+        (WebCore::NotificationData::fromDictionary):
+        (WebCore::NotificationData::dictionaryRepresentation const):
+        * Modules/notifications/NotificationOptions.idl:
+        * workers/service/ServiceWorkerRegistration.cpp:
+        (WebCore::ServiceWorkerRegistration::showNotification):
+
 2022-05-06  Brent Fulgham  <[email protected]>
 
         Remove internal WKPreference for non-iTunesAVOutput now that all platform support it 

Modified: trunk/Source/WebCore/Modules/notifications/Notification.cpp (293920 => 293921)


--- trunk/Source/WebCore/Modules/notifications/Notification.cpp	2022-05-06 19:55:27 UTC (rev 293920)
+++ trunk/Source/WebCore/Modules/notifications/Notification.cpp	2022-05-06 20:26:03 UTC (rev 293921)
@@ -39,6 +39,7 @@
 #include "Event.h"
 #include "EventNames.h"
 #include "JSDOMPromiseDeferred.h"
+#include "MessagePort.h"
 #include "NotificationClient.h"
 #include "NotificationData.h"
 #include "NotificationEvent.h"
@@ -53,20 +54,38 @@
 
 WTF_MAKE_ISO_ALLOCATED_IMPL(Notification);
 
+static ExceptionOr<Ref<SerializedScriptValue>> createSerializedScriptValue(ScriptExecutionContext& context, JSC::JSValue value)
+{
+    auto globalObject = context.globalObject();
+    if (!globalObject)
+        return Exception { TypeError, "Notification cannot be created without a global object"_s };
+
+    Vector<RefPtr<MessagePort>> dummyPorts;
+    return SerializedScriptValue::create(*globalObject, value, { }, dummyPorts);
+}
+
 ExceptionOr<Ref<Notification>> Notification::create(ScriptExecutionContext& context, String&& title, Options&& options)
 {
     if (context.isServiceWorkerGlobalScope())
         return Exception { TypeError, "Notification cannot be directly created in a ServiceWorkerGlobalScope"_s };
 
-    auto notification = adoptRef(*new Notification(context, UUID::createVersion4(), WTFMove(title), WTFMove(options)));
+    auto dataResult = createSerializedScriptValue(context, options.data);
+    if (dataResult.hasException())
+        return dataResult.releaseException();
+
+    auto notification = adoptRef(*new Notification(context, UUID::createVersion4(), WTFMove(title), WTFMove(options), dataResult.releaseReturnValue()));
     notification->suspendIfNeeded();
     notification->showSoon();
     return notification;
 }
 
-Ref<Notification> Notification::createForServiceWorker(ScriptExecutionContext& context, String&& title, Options&& options, const URL& serviceWorkerRegistrationURL)
+ExceptionOr<Ref<Notification>> Notification::createForServiceWorker(ScriptExecutionContext& context, String&& title, Options&& options, const URL& serviceWorkerRegistrationURL)
 {
-    auto notification = adoptRef(*new Notification(context, UUID::createVersion4(), WTFMove(title), WTFMove(options)));
+    auto dataResult = createSerializedScriptValue(context, options.data);
+    if (dataResult.hasException())
+        return dataResult.releaseException();
+
+    auto notification = adoptRef(*new Notification(context, UUID::createVersion4(), WTFMove(title), WTFMove(options), dataResult.releaseReturnValue()));
     notification->m_serviceWorkerRegistrationURL = serviceWorkerRegistrationURL;
     notification->suspendIfNeeded();
     return notification;
@@ -74,14 +93,15 @@
 
 Ref<Notification> Notification::create(ScriptExecutionContext& context, NotificationData&& data)
 {
-    Options options { data.direction, WTFMove(data.language), WTFMove(data.body), WTFMove(data.tag), WTFMove(data.iconURL) };
-    auto notification = adoptRef(*new Notification(context, data.notificationID, WTFMove(data.title), WTFMove(options)));
+    Options options { data.direction, WTFMove(data.language), WTFMove(data.body), WTFMove(data.tag), WTFMove(data.iconURL), JSC::jsNull() };
+
+    auto notification = adoptRef(*new Notification(context, data.notificationID, WTFMove(data.title), WTFMove(options), SerializedScriptValue::createFromWireBytes(WTFMove(data.data))));
     notification->suspendIfNeeded();
     notification->m_serviceWorkerRegistrationURL = WTFMove(data.serviceWorkerRegistrationURL);
     return notification;
 }
 
-Notification::Notification(ScriptExecutionContext& context, UUID identifier, String&& title, Options&& options)
+Notification::Notification(ScriptExecutionContext& context, UUID identifier, String&& title, Options&& options, Ref<SerializedScriptValue>&& dataForBindings)
     : ActiveDOMObject(&context)
     , m_identifier(identifier)
     , m_title(WTFMove(title).isolatedCopy())
@@ -89,6 +109,7 @@
     , m_lang(WTFMove(options.lang).isolatedCopy())
     , m_body(WTFMove(options.body).isolatedCopy())
     , m_tag(WTFMove(options.tag).isolatedCopy())
+    , m_dataForBindings(WTFMove(dataForBindings))
     , m_state(Idle)
     , m_contextIdentifier(context.identifier())
 {
@@ -241,6 +262,11 @@
     queueTaskToDispatchEvent(*this, TaskSource::UserInteraction, Event::create(eventNames().errorEvent, Event::CanBubble::No, Event::IsCancelable::No));
 }
 
+JSC::JSValue Notification::dataForBindings(JSC::JSGlobalObject& globalObject)
+{
+    return m_dataForBindings->deserialize(globalObject, &globalObject, SerializationErrorMode::NonThrowing);
+}
+
 auto Notification::permission(ScriptExecutionContext& context) -> Permission
 {
     auto* client = context.notificationClient();
@@ -314,7 +340,8 @@
         m_serviceWorkerRegistrationURL.isolatedCopy(),
         identifier(),
         *sessionID,
-        MonotonicTime::now()
+        MonotonicTime::now(),
+        m_dataForBindings->wireBytes()
     };
 }
 

Modified: trunk/Source/WebCore/Modules/notifications/Notification.h (293920 => 293921)


--- trunk/Source/WebCore/Modules/notifications/Notification.h	2022-05-06 19:55:27 UTC (rev 293920)
+++ trunk/Source/WebCore/Modules/notifications/Notification.h	2022-05-06 20:26:03 UTC (rev 293921)
@@ -38,6 +38,7 @@
 #include "NotificationDirection.h"
 #include "NotificationPermission.h"
 #include "ScriptExecutionContextIdentifier.h"
+#include "SerializedScriptValue.h"
 #include <wtf/URL.h>
 #include <wtf/UUID.h>
 #include "WritingMode.h"
@@ -63,11 +64,12 @@
         String body;
         String tag;
         String icon;
+        JSC::JSValue data;
     };
     // For JS constructor only.
     static ExceptionOr<Ref<Notification>> create(ScriptExecutionContext&, String&& title, Options&&);
 
-    static Ref<Notification> createForServiceWorker(ScriptExecutionContext&, String&& title, Options&&, const URL&);
+    static ExceptionOr<Ref<Notification>> createForServiceWorker(ScriptExecutionContext&, String&& title, Options&&, const URL&);
     static Ref<Notification> create(ScriptExecutionContext&, NotificationData&&);
 
     WEBCORE_EXPORT virtual ~Notification();
@@ -81,6 +83,7 @@
     const String& lang() const { return m_lang; }
     const String& tag() const { return m_tag; }
     const URL& icon() const { return m_icon; }
+    JSC::JSValue dataForBindings(JSC::JSGlobalObject&);
 
     TextDirection direction() const { return m_direction == Direction::Rtl ? TextDirection::RTL : TextDirection::LTR; }
 
@@ -109,7 +112,7 @@
     bool isPersistent() const { return !m_serviceWorkerRegistrationURL.isNull(); }
 
 private:
-    Notification(ScriptExecutionContext&, UUID, String&& title, Options&&);
+    Notification(ScriptExecutionContext&, UUID, String&& title, Options&&, Ref<SerializedScriptValue>&&);
 
     NotificationClient* clientFromContext();
     EventTargetInterface eventTargetInterface() const final { return NotificationEventTargetInterfaceType; }
@@ -133,6 +136,7 @@
     String m_body;
     String m_tag;
     URL m_icon;
+    Ref<SerializedScriptValue> m_dataForBindings;
 
     enum State { Idle, Showing, Closed };
     State m_state { Idle };

Modified: trunk/Source/WebCore/Modules/notifications/Notification.idl (293920 => 293921)


--- trunk/Source/WebCore/Modules/notifications/Notification.idl	2022-05-06 19:55:27 UTC (rev 293920)
+++ trunk/Source/WebCore/Modules/notifications/Notification.idl	2022-05-06 20:26:03 UTC (rev 293921)
@@ -62,7 +62,7 @@
     // readonly attribute boolean renotify;
     // readonly attribute boolean silent;
     // readonly attribute boolean requireInteraction;
-    // [SameObject] readonly attribute any data;
+    [CallWith=CurrentGlobalObject, CachedAttribute, ImplementedAs=dataForBindings] readonly attribute any data;
     // [SameObject] readonly attribute FrozenArray<NotificationAction> actions;
 
     undefined close();

Modified: trunk/Source/WebCore/Modules/notifications/NotificationData.cpp (293920 => 293921)


--- trunk/Source/WebCore/Modules/notifications/NotificationData.cpp	2022-05-06 19:55:27 UTC (rev 293920)
+++ trunk/Source/WebCore/Modules/notifications/NotificationData.cpp	2022-05-06 20:26:03 UTC (rev 293921)
@@ -30,12 +30,12 @@
 
 NotificationData NotificationData::isolatedCopy() const &
 {
-    return { title.isolatedCopy(), body.isolatedCopy(), iconURL.isolatedCopy(), tag.isolatedCopy(), language.isolatedCopy(), direction, originString.isolatedCopy(), serviceWorkerRegistrationURL.isolatedCopy(), notificationID, sourceSession, creationTime };
+    return { title.isolatedCopy(), body.isolatedCopy(), iconURL.isolatedCopy(), tag.isolatedCopy(), language.isolatedCopy(), direction, originString.isolatedCopy(), serviceWorkerRegistrationURL.isolatedCopy(), notificationID, sourceSession, creationTime, data };
 }
 
 NotificationData NotificationData::isolatedCopy() &&
 {
-    return { WTFMove(title).isolatedCopy(), WTFMove(body).isolatedCopy(), WTFMove(iconURL).isolatedCopy(), WTFMove(tag).isolatedCopy(), WTFMove(language).isolatedCopy(), direction, WTFMove(originString).isolatedCopy(), WTFMove(serviceWorkerRegistrationURL).isolatedCopy(), notificationID, sourceSession, creationTime };
+    return { WTFMove(title).isolatedCopy(), WTFMove(body).isolatedCopy(), WTFMove(iconURL).isolatedCopy(), WTFMove(tag).isolatedCopy(), WTFMove(language).isolatedCopy(), direction, WTFMove(originString).isolatedCopy(), WTFMove(serviceWorkerRegistrationURL).isolatedCopy(), notificationID, sourceSession, creationTime, WTFMove(data) };
 }
 
 } // namespace WebCore

Modified: trunk/Source/WebCore/Modules/notifications/NotificationData.h (293920 => 293921)


--- trunk/Source/WebCore/Modules/notifications/NotificationData.h	2022-05-06 19:55:27 UTC (rev 293920)
+++ trunk/Source/WebCore/Modules/notifications/NotificationData.h	2022-05-06 20:26:03 UTC (rev 293921)
@@ -61,12 +61,13 @@
     UUID notificationID;
     PAL::SessionID sourceSession;
     MonotonicTime creationTime;
+    Vector<uint8_t> data;
 };
 
 template<class Encoder>
 void NotificationData::encode(Encoder& encoder) const
 {
-    encoder << title << body << iconURL << tag << language << direction << originString << serviceWorkerRegistrationURL << notificationID << sourceSession << creationTime;
+    encoder << title << body << iconURL << tag << language << direction << originString << serviceWorkerRegistrationURL << notificationID << sourceSession << creationTime << data;
 }
 
 template<class Decoder>
@@ -127,6 +128,11 @@
     if (!creationTime)
         return std::nullopt;
 
+    std::optional<Vector<uint8_t>> data;
+    decoder >> data;
+    if (!data)
+        return std::nullopt;
+
     return { {
         WTFMove(*title),
         WTFMove(*body),
@@ -138,7 +144,8 @@
         WTFMove(*serviceWorkerRegistrationURL),
         WTFMove(*notificationID),
         WTFMove(*sourceSession),
-        WTFMove(*creationTime)
+        WTFMove(*creationTime),
+        WTFMove(*data)
     } };
 }
 

Modified: trunk/Source/WebCore/Modules/notifications/NotificationDataCocoa.mm (293920 => 293921)


--- trunk/Source/WebCore/Modules/notifications/NotificationDataCocoa.mm	2022-05-06 19:55:27 UTC (rev 293920)
+++ trunk/Source/WebCore/Modules/notifications/NotificationDataCocoa.mm	2022-05-06 20:26:03 UTC (rev 293921)
@@ -38,6 +38,7 @@
 static NSString * const WebNotificationServiceWorkerRegistrationURLKey = @"WebNotificationServiceWorkerRegistrationURLKey";
 static NSString * const WebNotificationUUIDStringKey = @"WebNotificationUUIDStringKey";
 static NSString * const WebNotificationSessionIDKey = @"WebNotificationSessionIDKey";
+static NSString * const WebNotificationDataKey = @"WebNotificationDataKey";
 
 namespace WebCore {
 
@@ -51,6 +52,7 @@
     NSString *originString = dictionary[WebNotificationOriginKey];
     NSString *serviceWorkerRegistrationURL = dictionary[WebNotificationServiceWorkerRegistrationURLKey];
     NSNumber *sessionID = dictionary[WebNotificationSessionIDKey];
+    NSData *notificationData = dictionary[WebNotificationDataKey];
 
     NSString *uuidString = dictionary[WebNotificationUUIDStringKey];
     auto uuid = UUID::parseVersion4(String(uuidString));
@@ -69,7 +71,7 @@
         return std::nullopt;
     }
 
-    NotificationData data { title, body, iconURL, tag, language, direction, originString, URL { String { serviceWorkerRegistrationURL } }, *uuid, PAL::SessionID { sessionID.unsignedLongLongValue }, { } };
+    NotificationData data { title, body, iconURL, tag, language, direction, originString, URL { String { serviceWorkerRegistrationURL } }, *uuid, PAL::SessionID { sessionID.unsignedLongLongValue }, { }, { static_cast<const uint8_t*>(notificationData.bytes), notificationData.length } };
     return WTFMove(data);
 }
 
@@ -85,7 +87,8 @@
         WebNotificationDirectionKey : @((unsigned long)direction),
         WebNotificationServiceWorkerRegistrationURLKey : (NSString *)serviceWorkerRegistrationURL.string(),
         WebNotificationUUIDStringKey : (NSString *)notificationID.toString(),
-        WebNotificationSessionIDKey : @(sourceSession.toUInt64())
+        WebNotificationSessionIDKey : @(sourceSession.toUInt64()),
+        WebNotificationDataKey: [NSData dataWithBytes:data.data() length:data.size()]
     };
 }
 

Modified: trunk/Source/WebCore/Modules/notifications/NotificationOptions.idl (293920 => 293921)


--- trunk/Source/WebCore/Modules/notifications/NotificationOptions.idl	2022-05-06 19:55:27 UTC (rev 293920)
+++ trunk/Source/WebCore/Modules/notifications/NotificationOptions.idl	2022-05-06 20:26:03 UTC (rev 293921)
@@ -39,6 +39,6 @@
     // boolean renotify = false;
     // boolean silent = false;
     // boolean requireInteraction = false;
-    // any data = ""
+    any data = ""
     // sequence<NotificationAction> actions = [];
 };

Modified: trunk/Source/WebCore/workers/service/ServiceWorkerRegistration.cpp (293920 => 293921)


--- trunk/Source/WebCore/workers/service/ServiceWorkerRegistration.cpp	2022-05-06 19:55:27 UTC (rev 293920)
+++ trunk/Source/WebCore/workers/service/ServiceWorkerRegistration.cpp	2022-05-06 20:26:03 UTC (rev 293921)
@@ -297,7 +297,13 @@
 
     // The Notification is kept alive by virtue of being show()'n soon.
     // FIXME: When implementing getNotifications(), store this Notification in the registration's notification list.
-    auto notification = Notification::createForServiceWorker(context, WTFMove(title), WTFMove(options), m_registrationData.scopeURL);
+    auto notificationResult = Notification::createForServiceWorker(context, WTFMove(title), WTFMove(options), m_registrationData.scopeURL);
+    if (notificationResult.hasException()) {
+        promise.reject(notificationResult.releaseException());
+        return;
+    }
+
+    auto notification = notificationResult.releaseReturnValue();
     notification->showSoon();
 
     context.eventLoop().queueTask(TaskSource::DOMManipulation, [promise = WTFMove(promise)]() mutable {
_______________________________________________
webkit-changes mailing list
[email protected]
https://lists.webkit.org/mailman/listinfo/webkit-changes

Reply via email to