Skip to content

Commit 4efcea1

Browse files
steipetecodex
andauthored
feat(browser): send pages to OpenClaw from the Chrome extension (#111158)
* feat(browser): send pages to the main session from the Chrome extension One-click page share in the OpenClaw Chrome extension: toolbar popup with an optional note, page/selection context menu, and Alt+Shift+S. Capture is selection-first with a readability heuristic, X/Twitter thread extraction, and Google Docs plain-text export via the user's session cookies. Payloads ride the existing paired relay WebSocket as a new pageShare message; the gateway-only page-share sink wraps page text in the external-content safety boundary, then enqueues a main-session system event and requests an immediate heartbeat (hooks/wake semantics). Node-hosted relays report a clear unsupported error. Capture heuristics adapted from Nat Eliason's MIT-licensed send-to-openclaw. Co-authored-by: Codex <[email protected]> * fix(browser): keep page-controlled metadata inside the share safety boundary Review findings: move title/URL inside wrapExternalContent (a hostile <title> must not become trusted header text), prefer the user's selection over the full Google Docs export, and pass the context-menu selectionText through so iframe selections and selections cleared during relay reconnect still win. * fix(browser): bind context-menu shares to the click-time document Selection shares from the context menu now send the click snapshot directly (no recapture), so navigations during relay reconnect cannot mislabel the source and iframe selections are preserved. The Google Docs selection probe scans all accessible frames before falling back to the full-document export. * test(browser): expect the page-share handler in relay server args * fix(browser): probe only the main frame for Google Docs selections All-frame injection rejects wholesale when one frame is inaccessible and returns child frames in nondeterministic order, so the probe now reads the main frame only. Child-frame selections still share correctly through the context menu's click-time selectionText; toolbar/shortcut entry sends the full page for that case (named tradeoff in the code comment). * fix(browser): satisfy page-share CI gates --------- Co-authored-by: Codex <[email protected]>
1 parent 0f95e66 commit 4efcea1

24 files changed

Lines changed: 1047 additions & 14 deletions

‎docs/.generated/plugin-sdk-api-baseline.sha256‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -296,7 +296,7 @@ ff35f9f74d35d37a2eb6126b57f3dc5a4d580b6222fe3a34c9368779ad32eab7 module/state-p
296296
c5ff317bb7957d0870cb806e7989c1d48877e3bed583c173ce2f8e9cfe57ee36 module/status-helpers
297297
537047854c21ad20ea0572f8019503cbda3bbafece8194a28c30b0639bde2fde module/string-coerce-runtime
298298
eb9a25321eaa2bbea1721f7d4b8b218bed398379494e09a21a621f264435b39a module/string-normalization-runtime
299-
f2fffad58593eff358c47937ec90c34953be64ed0138010cf6c82c55b1fda3c7 module/system-event-runtime
299+
32f031eb75c887b24b8eaa693cd0aa1a4648dca85eab7bfdfb3d08136861c274 module/system-event-runtime
300300
65361dc9a23578787c1ccf98f7df99e443574614e7ce95889f9a295725e12fae module/talk-config-runtime
301301
9efd666b8c2cc8a9abf816751fd9420f3c048d158e48570cae8b7a4cbc52a83f module/target-resolver-runtime
302302
cb77f0dcdd4f360cbc5efbb657f57f8ed5840e66adc903a23385ba6d42ca0101 module/telegram-account

‎docs/docs_map.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9738,6 +9738,7 @@ Do not edit it by hand; run `pnpm docs:map:gen`.
97389738
- H2: Install and pair
97399739
- H2: Use it
97409740
- H3: Tab copilot side panel
9741+
- H2: Send a page to OpenClaw
97419742
- H2: Remote / cross-machine
97429743
- H2: Diagnostics
97439744
- H2: Security model

‎docs/tools/chrome-extension.md‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,30 @@ direct remote Gateway relay. A loopback relay on a browser node cannot yet
141141
provide the node route required by the typed tab binding, so the panel denies
142142
that topology instead of falling back to browser-wide routing.
143143

144+
## Send a page to OpenClaw
145+
146+
Use **Send page to OpenClaw** in the toolbar popup to share readable page text
147+
with your main OpenClaw session. You can add an optional note, use the page or
148+
selection right-click menu, or press `Alt+Shift+S`. OpenClaw prefers your current
149+
selection when one exists, enqueues the share as a system event, and wakes the
150+
main session immediately.
151+
152+
The tab does not need to be in the OpenClaw tab group. This is a one-shot,
153+
explicit share: nothing else on the page is exposed, and it grants no ongoing
154+
access. Google Docs are exported as plain text with your signed-in browser
155+
session, without Google API setup. X and Twitter threads are extracted without
156+
the surrounding interface chrome.
157+
158+
Page text is wrapped in OpenClaw's external-content safety boundary. Your
159+
optional note stays outside that boundary as your own instruction. Page text
160+
and selections are capped at about 120,000 characters and include a truncation
161+
marker when shortened.
162+
163+
Page sharing works when the extension relay is hosted by the Gateway, using
164+
same-host pairing or direct `wss://` Gateway pairing. Node-hosted relays return
165+
a clear error for now. To remap the keyboard shortcut, open
166+
`chrome://extensions/shortcuts`.
167+
144168
## Remote / cross-machine
145169

146170
Chrome does not have to run on the Gateway host. Three topologies work:

‎extensions/browser/chrome-extension/background.js‎

Lines changed: 158 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
11
import { createCopilotController } from "./modules/copilot-background.js";
2+
import {
3+
buildPageSharePayload,
4+
capturePageShare,
5+
waitForCondition,
6+
} from "./modules/page-share-core.js";
27
// OpenClaw extension service worker.
38
//
49
// Thin transport between the OpenClaw extension relay (loopback WebSocket) and
@@ -50,6 +55,10 @@ const attachingTabs = new Map();
5055
const copilotRevocations = new Map();
5156
/** Debounce handle for tab-list refreshes. */
5257
let tabsSyncTimer = null;
58+
let nextPageShareRequestId = 1;
59+
let pageShareBadgeTimer = null;
60+
/** @type {Map<number, {resolve: (value: void) => void, reject: (error: Error) => void, timer: ReturnType<typeof setTimeout>}>} */
61+
const pendingPageShares = new Map();
5362

5463
function setBadge(kind) {
5564
relayState = kind;
@@ -62,6 +71,21 @@ function setBadge(kind) {
6271
});
6372
}
6473

74+
function flashPageShareBadge(ok) {
75+
if (pageShareBadgeTimer) {
76+
clearTimeout(pageShareBadgeTimer);
77+
}
78+
void chrome.action.setBadgeText({ text: ok ? "✓" : "!" });
79+
void chrome.action.setBadgeBackgroundColor({ color: ok ? "#0F9D58" : "#B91C1C" });
80+
pageShareBadgeTimer = setTimeout(
81+
() => {
82+
pageShareBadgeTimer = null;
83+
setBadge(relayState);
84+
},
85+
ok ? 2_000 : 3_000,
86+
);
87+
}
88+
6589
async function getConfig() {
6690
const stored = await chrome.storage.local.get(["relayUrl", "token", "groupColor"]);
6791
return {
@@ -431,6 +455,19 @@ async function connectRelay() {
431455
} catch {
432456
return;
433457
}
458+
if (msg?.type === "pageShareResult") {
459+
const pending = pendingPageShares.get(msg.requestId);
460+
if (pending) {
461+
pendingPageShares.delete(msg.requestId);
462+
clearTimeout(pending.timer);
463+
if (msg.ok) {
464+
pending.resolve();
465+
} else {
466+
pending.reject(new Error(msg.error || "Page share failed."));
467+
}
468+
}
469+
return;
470+
}
434471
void handleRelayCommand(msg);
435472
});
436473
ws.addEventListener("close", () => {
@@ -444,6 +481,86 @@ async function connectRelay() {
444481
// onclose follows onerror and drives the reconnect, so no error handler needed.
445482
}
446483

484+
async function sendPageShareRequest(payload) {
485+
if (!relayWs || relayWs.readyState !== WebSocket.OPEN) {
486+
throw new Error("Relay not connected.");
487+
}
488+
const requestId = nextPageShareRequestId++;
489+
return await new Promise((resolve, reject) => {
490+
const timer = setTimeout(() => {
491+
pendingPageShares.delete(requestId);
492+
reject(new Error("Timed out waiting for OpenClaw."));
493+
}, 10_000);
494+
pendingPageShares.set(requestId, { resolve, reject, timer });
495+
try {
496+
relayWs.send(JSON.stringify({ type: "pageShare", requestId, payload }));
497+
} catch (error) {
498+
pendingPageShares.delete(requestId);
499+
clearTimeout(timer);
500+
reject(error instanceof Error ? error : new Error(String(error)));
501+
}
502+
});
503+
}
504+
505+
async function ensureRelayReady() {
506+
const config = await getConfig();
507+
if (!config.relayUrl || !config.token) {
508+
throw new Error("Pair the extension first.");
509+
}
510+
if (!relayWs || relayWs.readyState !== WebSocket.OPEN) {
511+
await connectRelay();
512+
if (!(await waitForCondition(() => relayWs?.readyState === WebSocket.OPEN, 3_000))) {
513+
throw new Error("Relay not connected.");
514+
}
515+
}
516+
}
517+
518+
async function sendPageToOpenClaw(tabId, note) {
519+
await ensureRelayReady();
520+
const tab = await chrome.tabs.get(tabId);
521+
const capture = await capturePageShare(tab);
522+
const payload = buildPageSharePayload({ ...capture, note });
523+
if (!payload.content && !payload.selection) {
524+
throw new Error("Nothing to send on this page.");
525+
}
526+
await sendPageShareRequest(payload);
527+
}
528+
529+
// Context-menu selections bind to the click-time document: the relay-connect
530+
// delay can outlive a navigation, and recapture cannot see iframe selections,
531+
// so the payload is built from the click snapshot without touching the tab.
532+
async function sendSelectionSnapshot(tab, selection) {
533+
await ensureRelayReady();
534+
const payload = buildPageSharePayload({
535+
url: tab.url ?? "",
536+
title: tab.title ?? "",
537+
content: "",
538+
selection,
539+
note: "",
540+
});
541+
await sendPageShareRequest(payload);
542+
}
543+
544+
function withShareBadge(promise) {
545+
return promise.then(
546+
() => flashPageShareBadge(true),
547+
() => flashPageShareBadge(false),
548+
);
549+
}
550+
551+
function sendPageFromChromeEntry(tabId) {
552+
return withShareBadge(sendPageToOpenClaw(tabId, ""));
553+
}
554+
555+
async function installPageShareContextMenu() {
556+
await chrome.contextMenus.removeAll();
557+
chrome.contextMenus.create({
558+
id: "openclaw-send-page",
559+
title: "Send page to OpenClaw",
560+
contexts: ["page", "selection"],
561+
});
562+
}
563+
447564
copilot = createCopilotController({
448565
getConfig: getCopilotConfig,
449566
isTabShared,
@@ -572,6 +689,22 @@ chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {
572689
sendResponse({ shared: await isTabShared(msg.tabId) });
573690
return;
574691
}
692+
case "sendPageToOpenClaw": {
693+
if (typeof msg.tabId !== "number") {
694+
sendResponse({ ok: false, error: "No tab." });
695+
return;
696+
}
697+
try {
698+
await sendPageToOpenClaw(msg.tabId, msg.note);
699+
sendResponse({ ok: true });
700+
} catch (error) {
701+
sendResponse({
702+
ok: false,
703+
error: error instanceof Error ? error.message : String(error),
704+
});
705+
}
706+
return;
707+
}
575708
case "prepareCopilotPanel": {
576709
const options = await copilot.preparePanel(msg.tabId);
577710
sendResponse({ ok: true, ...options });
@@ -612,6 +745,26 @@ chrome.tabGroups.onRemoved.addListener(() => {
612745
void copilot.onConsentChanged();
613746
});
614747

748+
chrome.commands.onCommand.addListener((command) => {
749+
if (command !== "send-page") {
750+
return;
751+
}
752+
void chrome.tabs
753+
.query({ active: true, lastFocusedWindow: true })
754+
.then(([tab]) => (typeof tab?.id === "number" ? sendPageFromChromeEntry(tab.id) : undefined));
755+
});
756+
chrome.contextMenus.onClicked.addListener((info, tab) => {
757+
if (info.menuItemId !== "openclaw-send-page" || typeof tab?.id !== "number") {
758+
return;
759+
}
760+
const selection = info.selectionText?.trim() ?? "";
761+
if (selection) {
762+
void withShareBadge(sendSelectionSnapshot(tab, selection));
763+
return;
764+
}
765+
void sendPageFromChromeEntry(tab.id);
766+
});
767+
615768
// Watchdog: MV3 can stop this worker; the alarm revives it and re-connects.
616769
chrome.alarms.create(RELAY_WATCHDOG_ALARM, { periodInMinutes: 0.5 });
617770
chrome.alarms.onAlarm.addListener((alarm) => {
@@ -625,6 +778,8 @@ chrome.alarms.onAlarm.addListener((alarm) => {
625778
}
626779
});
627780
chrome.runtime.onStartup.addListener(() => void connectRelay());
628-
chrome.runtime.onInstalled.addListener(() => void connectRelay());
629-
void connectRelay();
630-
void copilotReady;
781+
chrome.runtime.onInstalled.addListener(() => {
782+
void installPageShareContextMenu();
783+
void connectRelay();
784+
});
785+
void [connectRelay(), copilotReady];

‎extensions/browser/chrome-extension/background.test.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,12 @@ async function loadBackground() {
5757
const setBadgeBackgroundColor = vi.fn(async () => undefined);
5858
const chromeMock = {
5959
action: { setBadgeText, setBadgeBackgroundColor },
60+
commands: { onCommand: { addListener } },
61+
contextMenus: {
62+
create: vi.fn(),
63+
removeAll: vi.fn(async () => undefined),
64+
onClicked: { addListener },
65+
},
6066
alarms: {
6167
create: createAlarm,
6268
clear: clearAlarm,
@@ -96,6 +102,7 @@ async function loadBackground() {
96102
set: vi.fn(async () => undefined),
97103
},
98104
},
105+
scripting: { executeScript: vi.fn(async () => []) },
99106
tabGroups: {
100107
query: vi.fn(async () => []),
101108
update: vi.fn(async () => undefined),

‎extensions/browser/chrome-extension/manifest.json‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,31 @@
11
{
22
"manifest_version": 3,
33
"name": "OpenClaw",
4-
"version": "2.0.0",
4+
"version": "2.1.0",
55
"description": "Let OpenClaw agents browse with you. Tabs shared with OpenClaw live in a colored tab group; drag a tab out to revoke access.",
66
"icons": {
77
"16": "icons/icon16.png",
88
"32": "icons/icon32.png",
99
"48": "icons/icon48.png",
1010
"128": "icons/icon128.png"
1111
},
12-
"permissions": ["debugger", "tabs", "tabGroups", "storage", "alarms", "sidePanel"],
12+
"permissions": [
13+
"debugger",
14+
"tabs",
15+
"tabGroups",
16+
"storage",
17+
"alarms",
18+
"sidePanel",
19+
"contextMenus",
20+
"scripting",
21+
"activeTab"
22+
],
23+
"commands": {
24+
"send-page": {
25+
"suggested_key": { "default": "Alt+Shift+S" },
26+
"description": "Send this page to OpenClaw"
27+
}
28+
},
1329
"background": { "service_worker": "background.js", "type": "module" },
1430
"action": {
1531
"default_title": "OpenClaw",
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
export type PageSharePayload = {
2+
url: string;
3+
title: string;
4+
content: string;
5+
selection?: string;
6+
note?: string;
7+
};
8+
9+
export type PageCapture = {
10+
url: string;
11+
title: string;
12+
selection: string;
13+
content: string;
14+
};
15+
16+
export function waitForCondition(condition: () => boolean, timeoutMs: number): Promise<boolean>;
17+
export function buildPageSharePayload(params: {
18+
url: string;
19+
title: string;
20+
content: string;
21+
selection?: string;
22+
note?: string;
23+
}): PageSharePayload;
24+
export function capturePageShare(tab: {
25+
id?: number;
26+
url?: string;
27+
title?: string;
28+
}): Promise<PageCapture>;

0 commit comments

Comments
 (0)