Skip to content

Commit bab0d04

Browse files
authored
fix(desktop): keep sites in the browser off the taskbar badge (#65646)
1 parent 361bed5 commit bab0d04

4 files changed

Lines changed: 139 additions & 2 deletions

File tree

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
import { createServer } from "node:http"
2+
import electron from "electron"
3+
import { createExtensionHost } from "./profile/extension-api/host"
4+
import { createManifests } from "./profile/extension-api/manifest"
5+
6+
// The Electron main process of `electron-app-badge.test.ts`, bundled and run by the pinned Electron. A page of a
7+
// partition without the profile's preload sets the app's badge to 7. Then a page of a partition with it, a child
8+
// frame of that page and its service worker each ask for another number, and the page clears the badge. It prints
9+
// the app's badge count after each as one JSON line.
10+
11+
const child = `<!doctype html><script>navigator.setAppBadge(4).then(() => parent.postMessage("frame", "*"))</script>`
12+
13+
const script = `onmessage = (event) => navigator.setAppBadge(5).then(() => event.source.postMessage("worker"))`
14+
15+
const page = `<!doctype html><title>page</title><body><script>
16+
const heard = (target) => new Promise((resolve) => target.addEventListener("message", (event) => resolve(event.data), { once: true }))
17+
const frame = () => {
18+
const reply = heard(window)
19+
document.body.append(Object.assign(document.createElement("iframe"), { src: "/frame" }))
20+
return reply
21+
}
22+
const worker = async () => {
23+
await navigator.serviceWorker.register("/worker.js")
24+
const registration = await navigator.serviceWorker.ready
25+
const reply = heard(navigator.serviceWorker)
26+
registration.active.postMessage("badge")
27+
return reply
28+
}
29+
</script>`
30+
31+
const server = createServer((request, response) => {
32+
const worker = request.url === "/worker.js"
33+
response.writeHead(200, { "content-type": worker ? "text/javascript" : "text/html" })
34+
response.end(worker ? script : request.url === "/frame" ? child : page)
35+
})
36+
37+
void electron.app.whenReady().then(async () => {
38+
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve))
39+
const address = server.address()
40+
const origin = `http://127.0.0.1:${address instanceof Object ? address.port : 0}`
41+
const win = new electron.BrowserWindow({ show: false })
42+
43+
// A page as the pane opens one for a server on this machine (`createBrowserPage`), in a partition kept on disk as
44+
// the profile's is: Electron answers the badge calls of no other kind of partition.
45+
const open = async (partition: string) => {
46+
const view = new electron.WebContentsView({
47+
webPreferences: { partition, sandbox: true, contextIsolation: true, nodeIntegrationInSubFrames: true },
48+
})
49+
50+
win.contentView.addChildView(view)
51+
await view.webContents.loadURL(origin)
52+
53+
return view.webContents
54+
}
55+
56+
const host = await createExtensionHost({
57+
session: electron.session.fromPartition("persist:profile"),
58+
directory: electron.app.getPath("userData"),
59+
modules: [],
60+
log: { write: () => undefined },
61+
manifest: createManifests(),
62+
})
63+
64+
const plain = await open("persist:plain")
65+
await plain.executeJavaScript("navigator.setAppBadge(7)")
66+
// Main hears of a badge a moment after the page hears its call resolve.
67+
const deadline = Date.now() + 10_000
68+
69+
while (electron.app.getBadgeCount() !== 7 && Date.now() < deadline)
70+
await new Promise((resolve) => setTimeout(resolve, 20))
71+
72+
const unguarded = electron.app.getBadgeCount()
73+
const profile = await open("persist:profile")
74+
75+
// The app's count once the profile's page, frame or worker heard its own call resolve. The page's answer can
76+
// overtake a badge on its way to main, so one more round trip to the page goes first. A frame's badge can take
77+
// longer still, and then shows in the next count.
78+
const after = async (call: string) => {
79+
await profile.executeJavaScript(call)
80+
await profile.executeJavaScript("0")
81+
82+
return electron.app.getBadgeCount()
83+
}
84+
85+
const result = {
86+
unguarded,
87+
page: await after("navigator.setAppBadge(3)"),
88+
frame: await after("frame()"),
89+
worker: await after("worker()"),
90+
cleared: await after("navigator.clearAppBadge()"),
91+
}
92+
93+
console.log(JSON.stringify(result))
94+
host.dispose()
95+
server.close()
96+
electron.app.exit(0)
97+
})
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import { expect, test } from "bun:test"
2+
import path from "node:path"
3+
import { runElectronFixture } from "./electron-run"
4+
5+
// Electron draws what a page asks of `navigator.setAppBadge` on the app's taskbar button, Dock icon or launcher entry,
6+
// where the app shows its own count, and Chromium has no switch for it. The profile's preload keeps a site off it
7+
// (`profile/extension-api/app-badge.js`). This runs that preload in the pinned Electron: a page without it sets the
8+
// app's count to 7, and then a page, a child frame and a service worker of the profile neither move nor clear it.
9+
test(
10+
"a page, frame or service worker of the profile cannot set or clear the app's badge",
11+
async () => {
12+
const line = await runElectronFixture({ fixture: path.join(import.meta.dir, "electron-app-badge.fixture.ts") })
13+
14+
expect(JSON.parse(line)).toEqual({ unguarded: 7, page: 7, frame: 7, worker: 7, cleared: 7 })
15+
},
16+
// Starting Electron takes seconds on a loaded runner.
17+
60_000,
18+
)
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// Runs in every frame and service worker of the profile's partition, before the page's own script. Chromium gives
2+
// each of them `navigator.setAppBadge` and `clearAppBadge`, and Electron draws what they ask for on the app's
3+
// taskbar button, Dock icon or launcher entry without telling main, over the count the app shows there. A site is not
4+
// the app, so here both resolve and draw nothing, as they do in a browser tab. A frame's initial empty document gets
5+
// no preload (Electron has nothing to run one with), so a page that reaches into such a frame for its `navigator`
6+
// still draws.
7+
{
8+
// Runs in the page's own world, so it must not use anything from this file's scope.
9+
const ignore = () => {
10+
const prototype = Object.getPrototypeOf(globalThis.navigator)
11+
12+
// Only a secure context has the badge.
13+
if (prototype.setAppBadge) Object.assign(prototype, { async setAppBadge() {}, async clearAppBadge() {} })
14+
}
15+
16+
// Manifest V2 background pages run without context isolation, so this shares their world.
17+
if (process.contextIsolated === false) ignore()
18+
else require("electron").contextBridge.executeInMainWorld({ func: ignore })
19+
}

‎packages/gui-plugins/src/browser/profile/extension-api/host.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,17 @@ import { sendBackgroundEvent, workerQueue } from "./worker-events"
88
import { eventPage } from "./event-page"
99
import preloadSource from "./preload.js?raw"
1010
import frameStyles from "./frame-styles.js?raw"
11+
import appBadge from "./app-badge.js?raw"
1112

1213
/** A context that listens to an event: a page frame, or the extension's service worker, which is started to hear it. */
1314
type Subscriber = { readonly kind: "frame"; readonly process: number; readonly routing: number } | { readonly kind: "worker" | "eventPage" }
1415

1516
/**
1617
* The bridge between extension contexts and the API modules. It writes the profile's preload, which adds each
1718
* module's namespaces to the pages and service workers of installed extensions, answers their calls and delivers
18-
* events to the contexts that listen.
19+
* events to the contexts that listen. The same file carries two scripts that are not for extensions alone: the
20+
* stylesheet receiver of pane documents (`frame-styles.js`), and what keeps every page and worker of the partition off
21+
* the app's badge (`app-badge.js`).
1922
*
2023
* Trust: a frame is answered only while its document is a `chrome-extension://` page of an extension loaded in
2124
* `session`, and a service worker only when its scope is such an extension's root; either only for a namespace its
@@ -51,7 +54,7 @@ export async function createExtensionHost(input: {
5154
// The modules already listen (to cookies, tabs); a host that cannot start lets them go again.
5255
await writeFile(
5356
file,
54-
frameStyles + "\n" + preloadSource.replace('"__NAMESPACES__"', JSON.stringify(JSON.stringify(namespaces))),
57+
[frameStyles, appBadge, preloadSource.replace('"__NAMESPACES__"', JSON.stringify(JSON.stringify(namespaces)))].join("\n"),
5558
"utf8",
5659
).catch((cause: unknown) => {
5760
input.modules.forEach((module) => module.dispose?.())

0 commit comments

Comments
 (0)