# Testing Safari Web Push Notifications on macOS

Canonical: https://figment.so/blog/mac-safari-web-push-notification-test

Send a VAPID Web Push to a real Safari subscription on macOS, then capture the Notification Center banner with screencapture as CI evidence. It needs Safari 16.1 or later on a Mac with a logged-in desktop session and outbound access to push.apple.com.

**To test Safari Web Push end to end, generate VAPID keys, subscribe from a real Safari page, send a payload with the `web-push` library, and capture the Notification Center banner with `screencapture`.** Safari adopted the cross-browser Web Push standard in Safari 16.1 on macOS Ventura. The test needs a real macOS machine that can register with Apple's `webpushd` daemon and route APNs-backed payloads into Notification Center. This page gives a working VAPID push, a Safari subscription, and a screenshot-backed assertion you can wire into CI.

## What does Safari Web Push require?

Safari Web Push needs Safari 16.1 or later on macOS Ventura or later, a user gesture, `userVisibleOnly: true`, a secure context and outbound access to `push.apple.com`. These constraints come from WebKit's launch post, [Meet Web Push](https://webkit.org/blog/12945/meet-web-push/):

- **Safari 16.1+ on macOS Ventura or later.** On iOS and iPadOS, Web Push arrived in 16.4 only for sites added to the Home Screen. See [Web Push for Web Apps on iOS and iPadOS](https://webkit.org/blog/13878/web-push-for-web-apps-on-ios-and-ipados/).
- **Explicit user gesture.** `Notification.requestPermission()` must run inside a click or tap handler. On-load prompts are ignored.
- **`userVisibleOnly: true`.** Silent push is not permitted. Every push must render a visible notification.
- **Secure context.** Service worker registration and the Push API require HTTPS or `localhost`.
- **Egress to `*.push.apple.com`.** If your runner has outbound firewall rules, allow URLs from any subdomain of `push.apple.com`.

Pin your target Safari version against the [Safari release notes](https://developer.apple.com/documentation/safari-release-notes) before assuming newer features such as Declarative Web Push. The plain VAPID flow below works from Ventura through Sequoia.

## How do I generate VAPID keys?

Generate the pair once per application with the [web-push library](https://github.com/web-push-libs/web-push). VAPID lets your server identify itself to Apple's push service.

```bash
npm install -g web-push
web-push generate-vapid-keys --json
```

Store the private key in your CI secret manager as `VAPID_PRIVATE_KEY`. The public key is safe in client JavaScript and is passed to `pushManager.subscribe` as `applicationServerKey`.

## How do I send the push?

Use a Node script that reads a subscription JSON produced by the browser step and sends one payload. It exits non-zero on failure, so a CI step stops on delivery errors.

```javascript
// send-push.js
// Usage: node send-push.js <subscription.json> "<message>"
'use strict';

const webpush = require('web-push');
const fs = require('fs');

const [,, subscriptionFile, message = 'Hello from Safari Web Push test'] = process.argv;
if (!subscriptionFile) {
  console.error('Usage: node send-push.js <subscription.json> "<message>"');
  process.exit(1);
}

const subscription = JSON.parse(fs.readFileSync(subscriptionFile, 'utf8'));

webpush.setVapidDetails(
  'mailto:ci@example.com',
  process.env.VAPID_PUBLIC_KEY,
  process.env.VAPID_PRIVATE_KEY
);

const payload = JSON.stringify({
  title: 'Web Push Test',
  body: message,
  icon: '/icon-192.png',
});

webpush.sendNotification(subscription, payload, { TTL: 60 })
  .then((result) => {
    console.log('Push sent, status:', result.statusCode);
  })
  .catch((err) => {
    console.error('Push failed:', err.statusCode, err.body);
    process.exit(1);
  });
```

Secret values stay in `process.env`. The script never writes them to disk or logs.

## How do I subscribe from a real Safari page?

Capture the subscription from Safari itself, because Playwright's bundled WebKit build is useful for driving pages but is not Safari.app and does not talk to `webpushd`. Use AppleScript or `open -a Safari` with a test page, then let Playwright assert page-level receipt. The pattern below opens Safari, captures the subscription the page writes to disk, and hands it to the sender script.

```javascript
// safari-push.spec.js
// Prereq: Safari is open on the test page, which POSTs its subscription
// to a local writer endpoint saving <sub>.json. Permission was granted
// once interactively and is remembered in the Safari profile.
const { test, expect } = require('@playwright/test');
const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');

test('VAPID push reaches Notification Center', async () => {
  const subPath = path.join(process.env.RUNNER_TEMP || '/tmp', 'safari-sub.json');

  // The page under test wrote this file after pushManager.subscribe()
  expect(fs.existsSync(subPath), 'Safari subscription JSON present').toBe(true);

  execSync(`node send-push.js ${JSON.stringify(subPath)} "Regression test push"`, {
    stdio: 'inherit',
  });

  // Give webpushd time to route the payload and render the banner
  execSync('sleep 10');

  const evidence = `/tmp/push-evidence/banner_${Date.now()}.png`;
  fs.mkdirSync('/tmp/push-evidence', { recursive: true });
  execSync(`screencapture -x ${evidence}`);
  console.log('Banner screenshot:', evidence);
});
```

The service worker in your app can also `postMessage` the received payload to a page the test polls. That gives a second, non-visual delivery receipt independent of the screenshot.

## How do I capture banner evidence?

Run `screencapture -x`, which suppresses the shutter sound and writes a PNG of the current desktop, where Notification Center banners render on macOS. A banner needs a logged-in desktop session, so connect over remote desktop first. Keep the artifact for at least seven days. Banners disappear quickly, and the file is the durable proof that a delivery reached the screen.

```bash
#!/usr/bin/env bash
set -euo pipefail
EVIDENCE_DIR="${EVIDENCE_DIR:-/tmp/push-evidence}"
mkdir -p "$EVIDENCE_DIR"
sleep 10
screencapture -x "$EVIDENCE_DIR/banner_$(date +%Y%m%d_%H%M%S).png"
```

Upload `$EVIDENCE_DIR` as a CI artifact on failure.

## How do I clear notification state between runs?

Restart `NotificationCenter`. Stale banners accumulate and confuse triage of a failure, so run this between runs:

```bash
killall NotificationCenter 2>/dev/null || true
sleep 2
```

`launchd` relaunches `NotificationCenter`, and displayed banners are cleared. This does not drop undelivered payloads that `webpushd` has queued.

## What should I check before the first run?

- [ ] HTTPS origin reachable from the Mac (or `localhost` with mkcert)
- [ ] `VAPID_PUBLIC_KEY` and `VAPID_PRIVATE_KEY` in CI secrets, not in the repo
- [ ] Service worker registered at scope `/`, with a `push` event handler
- [ ] Outbound traffic to `*.push.apple.com` allowed on the runner
- [ ] Permission granted once in Safari and preserved in the browser profile
- [ ] `web-push` installed (`npm install web-push`)
- [ ] `screencapture` available (shipped with macOS)
- [ ] `EVIDENCE_DIR` collected as a CI artifact on failure

## Can a Mac VM run a Safari web push regression test?

The Intel Mac VM ($25 a month, $2 a day) runs macOS Sequoia and fits a single-tab Safari push regression test. The Apple Silicon Mac VM ($39 a month, $6 a day) fits if you also build with Xcode 26.4 or later. We have not run this test on either plan, so confirm Apple's push delivery from the VM yourself before you depend on it. Testing push on several macOS versions needs one Mac or VM per version. See the [Mac hosting plans](/mac-hosting).

For comparison, [CloudMac lists an M4 mini at $99.99/month](https://cloudmac.org/pricing) with a [$999/year annual rate](https://cloudmac.org/) (effectively $83.25/month) on the 256 GB tier. The 512 GB and 1 TB tiers show as fully reserved. A whole Mac mini M4 is different hardware from a Figment VM, so compare the Dedicated M4 Pro ($349 a month, whole Mac) if you need the same kind of machine.

**Related guides:**

- [Safari iframe sandbox regression test](/blog/mac-safari-iframe-sandbox-regression)
- [Accessibility keyboard navigation audit on macOS](/blog/mac-accessibility-keyboard-nav-audit)
- [Register a hosted Mac as a self-hosted GitHub Actions runner](/blog/mac-github-actions-self-hosted-runner)
