Compare commits

...

2 Commits

Author SHA1 Message Date
Keeley Hammond
029accf70b test: fix typecheck 2026-03-17 21:07:56 -07:00
Keeley Hammond
8dbc408407 feat: add Notification.getHistory() static method (macOS)
Add `Notification.getHistory()` which returns a `Promise<Notification[]>`
of all delivered notifications still present in Notification Center.

Each returned Notification is a live object connected to the corresponding
delivered notification — interaction events (click, reply, action, close)
will fire on these objects, enabling apps to re-attach event handlers after
a restart.

Key implementation details:
- Queries UNUserNotificationCenter's getDeliveredNotifications API
- Creates live Notification objects with populated id, groupId, title,
  subtitle, and body properties from what macOS provides
- Registers each object with the presenter via Restore() so the
  NotificationCenterDelegate routes events correctly
- Restored notifications use is_restored_ flag to prevent removal from
  Notification Center when the JS object is garbage collected
- Requires code-signed builds (unsigned builds resolve with empty array)

Co-Authored-By: Claude <svc-devxp-claude@slack-corp.com>
2026-03-17 12:25:37 -07:00
14 changed files with 299 additions and 25 deletions

View File

@@ -76,6 +76,43 @@ app.whenReady().then(() => {
})
```
#### `Notification.getHistory()` _macOS_
Returns `Promise<Notification[]>` - Resolves with an array of `Notification` objects representing all delivered notifications still present in Notification Center.
Each returned `Notification` is a live object connected to the corresponding delivered notification. Interaction events (`click`, `reply`, `action`, `close`) will fire on these objects when the user interacts with the notification in Notification Center. This is useful after an app restart to re-attach event handlers to notifications from a previous session.
The returned notifications have their `id`, `groupId`, `title`, `subtitle`, and `body` properties populated from what macOS provides. Other properties (e.g., `actions`, `silent`, `icon`) are not available from delivered notifications and will have default values.
> [!NOTE]
> Like all macOS notification APIs, this method requires the application to be
> code-signed. In unsigned development builds, notifications are not delivered
> to Notification Center and this method will resolve with an empty array.
> [!NOTE]
> Unlike notifications created with `new Notification()`, notifications returned
> by `getHistory()` will remain visible in Notification Center when the object
> is garbage collected.
```js
const { Notification, app } = require('electron')
app.whenReady().then(async () => {
// Restore notifications from a previous session
const notifications = await Notification.getHistory()
for (const n of notifications) {
console.log(`Found delivered notification: ${n.id} - ${n.title}`)
n.on('click', () => {
console.log(`User clicked: ${n.id}`)
})
n.on('reply', (event) => {
console.log(`User replied to ${n.id}: ${event.reply}`)
})
}
// Keep references so events continue to fire
})
```
### `new Notification([options])`
* `options` Object (optional)

View File

@@ -2,6 +2,7 @@ const binding = process._linkedBinding('electron_browser_notification');
const ElectronNotification = binding.Notification;
ElectronNotification.isSupported = binding.isSupported;
ElectronNotification.getHistory = binding.getHistory;
if (process.platform === 'win32' && binding.handleActivation) {
ElectronNotification.handleActivation = binding.handleActivation;

View File

@@ -5,6 +5,7 @@
#include "shell/browser/api/electron_api_notification.h"
#include "base/functional/bind.h"
#include "base/strings/utf_string_conversions.h"
#include "base/uuid.h"
#include "build/build_config.h"
#include "content/public/browser/browser_task_traits.h"
@@ -13,10 +14,12 @@
#include "shell/browser/browser.h"
#include "shell/browser/electron_browser_client.h"
#include "shell/common/gin_converters/image_converter.h"
#include "shell/common/gin_converters/value_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/error_thrower.h"
#include "shell/common/gin_helper/handle.h"
#include "shell/common/gin_helper/object_template_builder.h"
#include "shell/common/gin_helper/promise.h"
#include "shell/common/node_includes.h"
#include "url/gurl.h"
@@ -72,27 +75,29 @@ Notification::Notification(gin::Arguments* args) {
presenter_ = static_cast<ElectronBrowserClient*>(ElectronBrowserClient::Get())
->GetNotificationPresenter();
gin::Dictionary opts(nullptr);
if (args->GetNext(&opts)) {
opts.Get("id", &id_);
opts.Get("groupId", &group_id_);
opts.Get("title", &title_);
opts.Get("subtitle", &subtitle_);
opts.Get("body", &body_);
opts.Get("icon", &icon_);
opts.Get("silent", &silent_);
opts.Get("replyPlaceholder", &reply_placeholder_);
opts.Get("urgency", &urgency_);
opts.Get("hasReply", &has_reply_);
opts.Get("timeoutType", &timeout_type_);
opts.Get("actions", &actions_);
opts.Get("sound", &sound_);
opts.Get("closeButtonText", &close_button_text_);
opts.Get("toastXml", &toast_xml_);
}
if (args) {
gin::Dictionary opts(nullptr);
if (args->GetNext(&opts)) {
opts.Get("id", &id_);
opts.Get("groupId", &group_id_);
opts.Get("title", &title_);
opts.Get("subtitle", &subtitle_);
opts.Get("body", &body_);
opts.Get("icon", &icon_);
opts.Get("silent", &silent_);
opts.Get("replyPlaceholder", &reply_placeholder_);
opts.Get("urgency", &urgency_);
opts.Get("hasReply", &has_reply_);
opts.Get("timeoutType", &timeout_type_);
opts.Get("actions", &actions_);
opts.Get("sound", &sound_);
opts.Get("closeButtonText", &close_button_text_);
opts.Get("toastXml", &toast_xml_);
}
if (id_.empty())
id_ = base::Uuid::GenerateRandomV4().AsLowercaseString();
if (id_.empty())
id_ = base::Uuid::GenerateRandomV4().AsLowercaseString();
}
}
Notification::~Notification() {
@@ -342,6 +347,61 @@ void Notification::HandleActivation(v8::Isolate* isolate,
}
#endif
// static
v8::Local<v8::Promise> Notification::GetHistory(v8::Isolate* isolate) {
gin_helper::Promise<v8::Local<v8::Value>> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
auto* presenter =
static_cast<ElectronBrowserClient*>(ElectronBrowserClient::Get())
->GetNotificationPresenter();
if (!presenter) {
promise.Resolve(v8::Array::New(isolate));
return handle;
}
presenter->GetDeliveredNotifications(base::BindOnce(
[](gin_helper::Promise<v8::Local<v8::Value>> promise,
electron::NotificationPresenter* presenter,
std::vector<electron::NotificationInfo> notifications) {
v8::Isolate* isolate = promise.isolate();
v8::HandleScope handle_scope(isolate);
v8::Local<v8::Array> result =
v8::Array::New(isolate, notifications.size());
for (size_t i = 0; i < notifications.size(); i++) {
const auto& info = notifications[i];
// Create a live Notification object for each delivered notification.
auto* notif = new Notification(/*args=*/nullptr);
notif->id_ = info.id;
notif->group_id_ = info.group_id;
notif->title_ = base::UTF8ToUTF16(info.title);
notif->subtitle_ = base::UTF8ToUTF16(info.subtitle);
notif->body_ = base::UTF8ToUTF16(info.body);
// Register with the presenter so click/reply events route here.
if (presenter) {
notif->notification_ =
presenter->CreateNotification(notif, notif->id_);
if (notif->notification_)
notif->notification_->Restore();
}
auto handle = gin_helper::CreateHandle(isolate, notif);
result
->Set(isolate->GetCurrentContext(), static_cast<uint32_t>(i),
handle.ToV8())
.Check();
}
promise.Resolve(result.As<v8::Value>());
},
std::move(promise), presenter));
return handle;
}
void Notification::FillObjectTemplate(v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> templ) {
gin::ObjectTemplateBuilder(isolate, GetClassName(), templ)
@@ -395,6 +455,7 @@ void Initialize(v8::Local<v8::Object> exports,
#if BUILDFLAG(IS_WIN)
dict.SetMethod("handleActivation", &Notification::HandleActivation);
#endif
dict.SetMethod("getHistory", &Notification::GetHistory);
}
} // namespace

View File

@@ -38,6 +38,7 @@ class Notification final : public gin_helper::DeprecatedWrappable<Notification>,
public NotificationDelegate {
public:
static bool IsSupported();
static v8::Local<v8::Promise> GetHistory(v8::Isolate* isolate);
#if BUILDFLAG(IS_WIN)
// Register a callback to handle all notification activations.

View File

@@ -24,6 +24,7 @@ class CocoaNotification : public Notification {
// Notification:
void Show(const NotificationOptions& options) override;
void Dismiss() override;
void Restore() override;
void NotificationDisplayed();
void NotificationReplied(const std::string& reply);
@@ -38,6 +39,7 @@ class CocoaNotification : public Notification {
void LogAction(const char* action);
void ScheduleNotification(UNMutableNotificationContent* content);
bool is_restored_ = false;
UNNotificationRequest* __strong notification_request_;
};

View File

@@ -31,7 +31,10 @@ CocoaNotification::CocoaNotification(NotificationDelegate* delegate,
: Notification(delegate, presenter) {}
CocoaNotification::~CocoaNotification() {
if (notification_request_)
// Don't remove from Notification Center if this was a restored notification.
// Restored notifications are observed, not owned — destruction should just
// disconnect the event handler, not remove the visible notification.
if (notification_request_ && !is_restored_)
[[UNUserNotificationCenter currentNotificationCenter]
removeDeliveredNotificationsWithIdentifiers:@[
notification_request_.identifier
@@ -245,6 +248,24 @@ void CocoaNotification::Dismiss() {
notification_request_ = nil;
}
void CocoaNotification::Restore() {
// Create a minimal UNNotificationRequest with just the identifier so that
// GetNotification() can match this object when the user interacts with the
// notification in Notification Center.
NSString* identifier = base::SysUTF8ToNSString(notification_id());
UNMutableNotificationContent* content =
[[UNMutableNotificationContent alloc] init];
notification_request_ =
[UNNotificationRequest requestWithIdentifier:identifier
content:content
trigger:nil];
is_restored_ = true;
if (electron::debug_notifications) {
LOG(INFO) << "Notification restored (" << [identifier UTF8String] << ")";
}
}
void CocoaNotification::NotificationDisplayed() {
if (delegate())
delegate()->NotificationDisplayed();

View File

@@ -24,6 +24,10 @@ class NotificationPresenterMac : public NotificationPresenter {
NotificationPresenterMac();
~NotificationPresenterMac() override;
// NotificationPresenter
void GetDeliveredNotifications(
GetDeliveredNotificationsCallback callback) override;
NotificationImageRetainer* image_retainer() { return image_retainer_.get(); }
scoped_refptr<base::SequencedTaskRunner> image_task_runner() {
return image_task_runner_;

View File

@@ -2,11 +2,16 @@
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "base/logging.h"
#include "base/task/thread_pool.h"
#include "shell/browser/notifications/mac/notification_presenter_mac.h"
#include <string>
#include <utility>
#include <vector>
#include "base/logging.h"
#include "base/strings/sys_string_conversions.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/thread_pool.h"
#include "shell/browser/notifications/mac/cocoa_notification.h"
#include "shell/browser/notifications/mac/notification_center_delegate.h"
@@ -80,4 +85,35 @@ Notification* NotificationPresenterMac::CreateNotificationObject(
return new CocoaNotification(delegate, this);
}
void NotificationPresenterMac::GetDeliveredNotifications(
GetDeliveredNotificationsCallback callback) {
scoped_refptr<base::SequencedTaskRunner> task_runner =
base::SequencedTaskRunner::GetCurrentDefault();
__block GetDeliveredNotificationsCallback block_callback =
std::move(callback);
[[UNUserNotificationCenter currentNotificationCenter]
getDeliveredNotificationsWithCompletionHandler:^(
NSArray<UNNotification*>* _Nonnull notifications) {
std::vector<NotificationInfo> results;
results.reserve([notifications count]);
for (UNNotification* notification in notifications) {
UNNotificationContent* content = notification.request.content;
NotificationInfo info;
info.id = base::SysNSStringToUTF8(notification.request.identifier);
info.title = base::SysNSStringToUTF8(content.title);
info.subtitle = base::SysNSStringToUTF8(content.subtitle);
info.body = base::SysNSStringToUTF8(content.body);
info.group_id = base::SysNSStringToUTF8(content.threadIdentifier);
results.push_back(std::move(info));
}
task_runner->PostTask(
FROM_HERE,
base::BindOnce(std::move(block_callback), std::move(results)));
}];
}
} // namespace electron

View File

@@ -31,6 +31,15 @@ NotificationAction::NotificationAction(NotificationAction&&) noexcept = default;
NotificationAction& NotificationAction::operator=(
NotificationAction&&) noexcept = default;
NotificationInfo::NotificationInfo() = default;
NotificationInfo::~NotificationInfo() = default;
NotificationInfo::NotificationInfo(const NotificationInfo&) = default;
NotificationInfo& NotificationInfo::operator=(const NotificationInfo&) =
default;
NotificationInfo::NotificationInfo(NotificationInfo&&) noexcept = default;
NotificationInfo& NotificationInfo::operator=(NotificationInfo&&) noexcept =
default;
Notification::Notification(NotificationDelegate* delegate,
NotificationPresenter* presenter)
: delegate_(delegate), presenter_(presenter) {}

View File

@@ -59,6 +59,21 @@ struct NotificationOptions {
~NotificationOptions();
};
struct NotificationInfo {
std::string id;
std::string title;
std::string subtitle;
std::string body;
std::string group_id;
NotificationInfo();
~NotificationInfo();
NotificationInfo(const NotificationInfo&);
NotificationInfo& operator=(const NotificationInfo&);
NotificationInfo(NotificationInfo&&) noexcept;
NotificationInfo& operator=(NotificationInfo&&) noexcept;
};
class Notification {
public:
virtual ~Notification();
@@ -75,6 +90,11 @@ class Notification {
// as can happen on some platforms including Windows.
virtual void Remove() {}
// Restores a previously delivered notification for event handling without
// re-showing it. Sets up platform state so interaction events (click, reply,
// etc.) route to this object.
virtual void Restore() {}
// Should be called by derived classes.
void NotificationClicked();
void NotificationDismissed(bool should_destroy = true,

View File

@@ -44,4 +44,10 @@ void NotificationPresenter::CloseNotificationWithId(
}
}
void NotificationPresenter::GetDeliveredNotifications(
GetDeliveredNotificationsCallback callback) {
// Default: return empty list. Overridden on macOS.
std::move(callback).Run({});
}
} // namespace electron

View File

@@ -8,12 +8,14 @@
#include <memory>
#include <set>
#include <string>
#include <vector>
#include "base/functional/callback.h"
#include "base/memory/weak_ptr.h"
#include "shell/browser/notifications/notification.h"
namespace electron {
class Notification;
class NotificationDelegate;
class NotificationPresenter {
@@ -22,11 +24,17 @@ class NotificationPresenter {
virtual ~NotificationPresenter();
using GetDeliveredNotificationsCallback =
base::OnceCallback<void(std::vector<NotificationInfo>)>;
base::WeakPtr<Notification> CreateNotification(
NotificationDelegate* delegate,
const std::string& notification_id);
void CloseNotificationWithId(const std::string& notification_id);
virtual void GetDeliveredNotifications(
GetDeliveredNotificationsCallback callback);
std::set<Notification*> notifications() const { return notifications_; }
// disable copy

View File

@@ -261,4 +261,71 @@ describe('Notification module', () => {
});
// TODO(sethlu): Find way to test init with notification icon?
describe('static methods', () => {
ifit(process.platform === 'darwin')('getHistory returns a promise that resolves to an array', async () => {
const result = Notification.getHistory();
expect(result).to.be.a('promise');
const history = await result;
expect(history).to.be.an('array');
});
ifit(process.platform === 'darwin')('getHistory returns Notification instances with correct properties', async () => {
const n = new Notification({
id: 'history-test-id',
title: 'history test',
subtitle: 'history subtitle',
body: 'history body',
groupId: 'history-group',
silent: true
});
const shown = once(n, 'show');
n.show();
await shown;
const history = await Notification.getHistory();
// getHistory requires code-signed builds to return results;
// skip the content assertions if Notification Center is empty.
if (history.length > 0) {
const found = history.find((item: any) => item.id === 'history-test-id');
if (!found) {
expect.fail('Expected to find notification with id "history-test-id" in history');
}
expect(found).to.be.an.instanceOf(Notification);
expect(found.title).to.equal('history test');
expect(found.subtitle).to.equal('history subtitle');
expect(found.body).to.equal('history body');
expect(found.groupId).to.equal('history-group');
}
n.close();
});
ifit(process.platform === 'darwin')('getHistory returned notifications can be shown and closed', async () => {
const n = new Notification({
id: 'history-show-close',
title: 'show close test',
body: 'body',
silent: true
});
const shown = once(n, 'show');
n.show();
await shown;
const history = await Notification.getHistory();
if (history.length > 0) {
const found = history.find((item: any) => item.id === 'history-show-close');
if (!found) {
expect.fail('Expected to find notification with id "history-show-close" in history');
}
// Calling show() and close() on a restored notification should not throw
expect(() => {
found.show();
found.close();
}).to.not.throw();
}
});
});
});

View File

@@ -118,6 +118,7 @@ declare namespace NodeJS {
interface NotificationBinding {
isSupported(): boolean;
getHistory(): Promise<Electron.Notification[]>;
Notification: typeof Electron.Notification;
// Windows-only callback for cold-start notification activation
handleActivation?: (callback: (details: ActivationArgumentsInternal) => void) => void;