Offline, privacy-first grammar checker. Fast, open-source, Rust-powered
Improve embedded form support in iframes (#3010)
Kacper Kuczkowskied58bb32b2e6
diff --git a/packages/chrome-plugin/src/background/index.ts b/packages/chrome-plugin/src/background/index.tsindex 0113c29d8..3725031c0 100644--- a/packages/chrome-plugin/src/background/index.ts+++ b/packages/chrome-plugin/src/background/index.ts@@ -62,8 +62,8 @@ chrome.runtime.onInstalled.addListener((details) => {}});-chrome.runtime.onMessage.addListener((request, _sender, sendResponse) => {- handleRequest(request).then(sendResponse);+chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {+ handleRequest(request, sender).then(sendResponse);return true;});@@ -141,12 +141,12 @@ async function enableDefaultDomains() {enableDefaultDomains();-function handleRequest(message: Request): Promise<Response> {+function handleRequest(message: Request, sender?: chrome.runtime.MessageSender): Promise<Response> {console.log(`Handling ${message.kind} request`);switch (message.kind) {case 'lint':- return handleLint(message);+ return handleLint(message, sender);case 'getConfig':return handleGetConfig(message);case 'setConfig':@@ -206,8 +206,16 @@ function handleRequest(message: Request): Promise<Response> {}/** Handle a request for linting. */-async function handleLint(req: LintRequest): Promise<LintResponse> {- if (!(await enabledForDomain(req.domain))) {+async function handleLint(+ req: LintRequest,+ sender?: chrome.runtime.MessageSender,+): Promise<LintResponse> {+ // Keep the content-script keepalive ping cheap; empty requests should not hit inheritance or linting.+ if (req.text.length === 0) {+ return { kind: 'lints', lints: {} };+ }++ if (!(await shouldLintForRequest(req, sender))) {return { kind: 'lints', lints: {} };}@@ -222,6 +230,39 @@ async function handleLint(req: LintRequest): Promise<LintResponse> {return { kind: 'lints', lints: unpackedBySource };}+async function shouldLintForRequest(+ req: LintRequest,+ sender?: chrome.runtime.MessageSender,+): Promise<boolean> {+ if (await enabledForDomain(req.domain)) {+ return true;+ }++ if (await isDomainSet(req.domain)) {+ return false;+ }++ const parentDomain = getParentDomain(sender);+ if (parentDomain == null || parentDomain === req.domain) {+ return false;+ }++ return await enabledForDomain(parentDomain);+}++function getParentDomain(sender?: chrome.runtime.MessageSender): string | null {+ const url = sender?.tab?.url;+ if (url == null) {+ return null;+ }++ try {+ return new URL(url).hostname;+ } catch {+ return null;+ }+}+async function handleGetConfig(_req: GetConfigRequest): Promise<GetConfigResponse> {return { kind: 'getConfig', config: await getLintConfig() };}@@ -542,12 +583,39 @@ function formatDomainKey(domain: string): string {return `domainStatus ${domain}`;}+function getDomainLookupCandidates(domain: string): string[] {+ const withoutWww = domain.replace(/^www\./, '');+ return withoutWww === domain ? [domain] : [domain, withoutWww];+}++/**+ * Looks up a domain-specific enable/disable setting in local storage.+ * The lookup is normalized through `getDomainLookupCandidates` so we can try+ * both the exact hostname and a `www.`-stripped variant when sites are stored+ * under either form. Returns `undefined` when no stored override exists.+ */+async function getStoredDomainStatus(domain: string): Promise<boolean | undefined> {+ const candidates = getDomainLookupCandidates(domain);+ const response = await chrome.storage.local.get(candidates.map(formatDomainKey));++ for (const candidate of candidates) {+ const value = response[formatDomainKey(candidate)];+ if (typeof value === 'boolean') {+ return value;+ }+ }++ return undefined;+}+/** Check if Harper has been enabled for a given domain. */async function enabledForDomain(domain: string): Promise<boolean | null> {- const req = await chrome.storage.local.get({- [formatDomainKey(domain)]: await enabledByDefault(),- });- return req[formatDomainKey(domain)];+ const stored = await getStoredDomainStatus(domain);+ if (stored !== undefined) {+ return stored;+ }++ return await enabledByDefault();}/** Set whether Harper is enabled for a given domain.@@ -579,8 +647,7 @@ async function enabledByDefault(): Promise<boolean> {/** Check whether Harper's state has been set for a given domain. */async function isDomainSet(domain: string): Promise<boolean> {- const resp = await chrome.storage.local.get(formatDomainKey(domain));- return typeof resp[formatDomainKey(domain)] == 'boolean';+ return (await getStoredDomainStatus(domain)) !== undefined;}/** Reset the persistent user dictionary. */diff --git a/packages/chrome-plugin/src/contentScript/index.ts b/packages/chrome-plugin/src/contentScript/index.tsindex a3d1b43a2..a0b43d55f 100644--- a/packages/chrome-plugin/src/contentScript/index.ts+++ b/packages/chrome-plugin/src/contentScript/index.ts@@ -56,6 +56,41 @@ const keepAliveCallback = () => {keepAliveCallback();+/**+ * Returns the reasons Harper should skip this textarea while scanning for targets.+ * An empty array means the textarea is eligible to be added.+ */+function getTextareaReasons(element: HTMLTextAreaElement, requireVisible: boolean): string[] {+ const reasons = [];++ if (requireVisible && !isVisible(element)) {+ reasons.push('not-visible');+ }++ if (element.getAttribute('data-enable-grammarly') === 'false') {+ reasons.push('grammarly-disabled');+ }++ if (element.disabled) {+ reasons.push('disabled');+ }++ if (element.readOnly) {+ reasons.push('readonly');+ }++ return reasons;+}++function maybeAddTextareaTarget(element: HTMLTextAreaElement, requireVisible: boolean) {+ const reasons = getTextareaReasons(element, requireVisible);+ if (reasons.length > 0) {+ return;+ }++ fw.addTarget(element);+}+function scan() {void syncGoogleDocsBridge();@@ -64,16 +99,7 @@ function scan() {}document.querySelectorAll<HTMLTextAreaElement>('textarea').forEach((element) => {- if (- !isVisible(element) ||- element.getAttribute('data-enable-grammarly') === 'false' ||- element.disabled ||- element.readOnly- ) {- return;- }-- fw.addTarget(element);+ maybeAddTextareaTarget(element, true);});document@@ -192,4 +218,17 @@ new MutationObserver(scan).observe(document.body, {subtree: true,});+document.addEventListener(+ 'focusin',+ (event) => {+ const target = event.target;+ if (!(target instanceof HTMLTextAreaElement)) {+ return;+ }++ maybeAddTextareaTarget(target, false);+ },+ { capture: true },+);+setTimeout(scan, 1000);diff --git a/packages/chrome-plugin/tests/iframe_domain_inheritance.spec.ts b/packages/chrome-plugin/tests/iframe_domain_inheritance.spec.tsnew file mode 100644index 000000000..b80b4eed5--- /dev/null+++ b/packages/chrome-plugin/tests/iframe_domain_inheritance.spec.ts@@ -0,0 +1,158 @@+import type { BrowserContext, Page } from '@playwright/test';+import { expect, test } from './fixtures';+import { replaceEditorContent } from './testUtils';++const PARENT_DOMAIN = 'parent.localhost';+const CHILD_DOMAIN = '127.0.0.1';+const TEST_PAGE_URL = 'http://parent.localhost:8081/iframe_parent_origin.html';+const TEST_PAGE_WWW_URL = 'http://www.parent.localhost:8081/iframe_parent_origin.html';++async function getBackground(context: BrowserContext) {+ return (+ context.serviceWorkers()[0] ??+ context.backgroundPages()[0] ??+ (await context.waitForEvent('serviceworker'))+ );+}++async function seedDomainSettings(+ context: BrowserContext,+ domains: Record<string, boolean>,+ defaultEnable = false,+) {+ const background = await getBackground(context);+ const storageEntries = Object.fromEntries(+ Object.entries(domains).map(([domain, enabled]) => [`domainStatus ${domain}`, enabled]),+ );++ await background.evaluate(+ async ({ defaultEnable, storageEntries }) => {+ await chrome.storage.local.set({ defaultEnable, ...storageEntries });+ },+ { defaultEnable, storageEntries },+ );+}++function getChildFrame(page: Page) {+ return page.frameLocator('#editor-frame');+}++function getChildTextarea(page: Page) {+ return getChildFrame(page).locator('textarea');+}++function getChildHighlights(page: Page) {+ return getChildFrame(page).locator('#harper-highlight');+}++function getChildPopup(page: Page) {+ return getChildFrame(page).locator('.harper-container');+}++async function typeLintableText(page: Page) {+ await replaceEditorContent(getChildTextarea(page), 'This is an test');+}++async function waitForChildHighlight(page: Page) {+ const highlight = getChildHighlights(page).first();+ await highlight.waitFor({ state: 'visible', timeout: 12000 });+ return highlight;+}++async function clickChildHighlight(page: Page) {+ const highlight = await waitForChildHighlight(page);+ const box = await highlight.boundingBox();++ if (box == null) {+ throw new Error('Expected iframe highlight to have a bounding box.');+ }++ await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);+}++async function expectNoChildHighlights(page: Page) {+ await page.waitForTimeout(3000);+ await expect(getChildHighlights(page)).toHaveCount(0);+}++test.describe('parent-origin inheritance', () => {+ test.skip(+ ({ browserName }) => browserName === 'firefox',+ 'Firefox MV3 background context is not exposed reliably in playwright-webextext.',+ );++ test('inherits the parent enabled state when the iframe host is unset', async ({+ context,+ page,+ }) => {+ test.slow();+ await seedDomainSettings(context, { [PARENT_DOMAIN]: true });++ await page.goto(TEST_PAGE_URL);+ await typeLintableText(page);+ await clickChildHighlight(page);++ await expect(getChildPopup(page)).toBeVisible();+ });++ test('inherits when the parent is `www.` but the stored key follows the popup pattern', async ({+ context,+ page,+ }) => {+ test.slow();+ await seedDomainSettings(context, { [PARENT_DOMAIN]: true });++ await page.goto(TEST_PAGE_WWW_URL);+ await typeLintableText(page);+ await clickChildHighlight(page);++ await expect(getChildPopup(page)).toBeVisible();+ });++ test('preserves an explicit iframe opt-out when the parent is enabled', async ({+ context,+ page,+ }) => {+ await seedDomainSettings(context, {+ [PARENT_DOMAIN]: true,+ [CHILD_DOMAIN]: false,+ });++ await page.goto(TEST_PAGE_URL);+ await typeLintableText(page);++ await expectNoChildHighlights(page);+ });++ test('does not inherit when the parent is disabled and the iframe host is unset', async ({+ context,+ page,+ }) => {+ await seedDomainSettings(context, { [PARENT_DOMAIN]: false });++ await page.goto(TEST_PAGE_URL);+ await typeLintableText(page);++ await expectNoChildHighlights(page);+ });++ test('preserves an explicit iframe opt-in even when the parent is disabled', async ({+ context,+ page,+ }) => {+ test.slow();+ await seedDomainSettings(context, {+ [PARENT_DOMAIN]: false,+ [CHILD_DOMAIN]: true,+ });++ await page.goto(TEST_PAGE_URL);+ await typeLintableText(page);++ // This precedence is intentional for now because explicit user overrides should win.+ // Confirm it with maintainers if the project wants parent-level disablement to dominate.+ await clickChildHighlight(page);++ await expect(getChildPopup(page)).toBeVisible();+ });+});diff --git a/packages/chrome-plugin/tests/iframe_dynamic_textarea.spec.ts b/packages/chrome-plugin/tests/iframe_dynamic_textarea.spec.tsnew file mode 100644index 000000000..77ee4e34c--- /dev/null+++ b/packages/chrome-plugin/tests/iframe_dynamic_textarea.spec.ts@@ -0,0 +1,80 @@+import type { BrowserContext, Page } from '@playwright/test';+import { expect, test } from './fixtures';+import { replaceEditorContent } from './testUtils';++const PARENT_DOMAIN = 'localhost';+const TEST_PAGE_URL = 'http://localhost:8081/iframe_dynamic_textarea_parent.html';++async function getBackground(context: BrowserContext) {+ return (+ context.serviceWorkers()[0] ??+ context.backgroundPages()[0] ??+ (await context.waitForEvent('serviceworker'))+ );+}++async function seedDomainSettings(+ context: BrowserContext,+ domains: Record<string, boolean>,+ defaultEnable = false,+) {+ const background = await getBackground(context);+ const storageEntries = Object.fromEntries(+ Object.entries(domains).map(([domain, enabled]) => [`domainStatus ${domain}`, enabled]),+ );++ await background.evaluate(+ async ({ defaultEnable, storageEntries }) => {+ await chrome.storage.local.set({ defaultEnable, ...storageEntries });+ },+ { defaultEnable, storageEntries },+ );+}++test.skip(+ ({ browserName }) => browserName === 'firefox',+ 'Firefox MV3 background context is not exposed reliably in playwright-webextext.',+);++function getChildFrame(page: Page) {+ return page.frameLocator('#editor-frame');+}++function getRevealButton(page: Page) {+ return getChildFrame(page).getByRole('button', { name: 'Enter manually' });+}++function getChildTextarea(page: Page) {+ return getChildFrame(page).locator('#editor');+}++function getChildHighlights(page: Page) {+ return getChildFrame(page).locator('#harper-highlight');+}++async function clickChildHighlight(page: Page) {+ const highlight = getChildHighlights(page).first();+ await highlight.waitFor({ state: 'visible', timeout: 12000 });++ const box = await highlight.boundingBox();+ if (box == null) {+ throw new Error('Expected iframe highlight to have a bounding box.');+ }++ await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);+}++test('attaches to a dynamically revealed iframe textarea on focus', async ({ context, page }) => {+ test.slow();+ await seedDomainSettings(context, { [PARENT_DOMAIN]: true });++ await page.goto(TEST_PAGE_URL);+ await getRevealButton(page).click();++ const editor = getChildTextarea(page);+ await editor.waitFor({ state: 'visible', timeout: 5000 });+ await replaceEditorContent(editor, 'This is an test');++ await clickChildHighlight(page);+ await expect(getChildFrame(page).locator('.harper-container')).toBeVisible();+});diff --git a/packages/chrome-plugin/tests/pages/iframe_dynamic_textarea_child.html b/packages/chrome-plugin/tests/pages/iframe_dynamic_textarea_child.htmlnew file mode 100644index 000000000..226f9499e--- /dev/null+++ b/packages/chrome-plugin/tests/pages/iframe_dynamic_textarea_child.html@@ -0,0 +1,61 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Dynamic child editor</title>+ <style>+ body {+ margin: 0;+ padding: 24px;+ font-family: sans-serif;+ background: white;+ }++ button {+ margin-bottom: 16px;+ padding: 10px 18px;+ border: 1px solid #6a3be5;+ border-radius: 999px;+ background: white;+ color: #6a3be5;+ cursor: pointer;+ }++ textarea {+ width: 100%;+ min-height: 120px;+ padding: 12px;+ font: 16px/1.4 sans-serif;+ border: 1px solid #a1a1aa;+ box-sizing: border-box;+ opacity: 0;+ }+ </style>+ </head>+ <body>+ <button id="reveal" type="button">Enter manually</button>+ <div id="editor-root"></div>+ <script>+ const revealButton = document.getElementById('reveal');+ const editorRoot = document.getElementById('editor-root');++ revealButton.addEventListener('click', () => {+ if (document.getElementById('editor') != null) {+ return;+ }++ const textarea = document.createElement('textarea');+ textarea.id = 'editor';+ textarea.spellcheck = true;++ editorRoot.appendChild(textarea);++ // Reveal after Harper's one-shot delayed scan so focus is what triggers attachment.+ window.setTimeout(() => {+ textarea.style.opacity = '1';+ }, 1500);+ });+ </script>+ </body>+</html>diff --git a/packages/chrome-plugin/tests/pages/iframe_dynamic_textarea_parent.html b/packages/chrome-plugin/tests/pages/iframe_dynamic_textarea_parent.htmlnew file mode 100644index 000000000..35bfad069--- /dev/null+++ b/packages/chrome-plugin/tests/pages/iframe_dynamic_textarea_parent.html@@ -0,0 +1,38 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Dynamic iframe textarea parent</title>+ <style>+ body {+ margin: 0;+ font-family: sans-serif;+ background: #f4f4f5;+ }++ main {+ max-width: 960px;+ margin: 32px auto;+ padding: 24px;+ }++ iframe {+ width: 100%;+ height: 320px;+ border: 1px solid #d4d4d8;+ background: white;+ }+ </style>+ </head>+ <body>+ <main>+ <h1>Dynamic iframe textarea test</h1>+ <iframe+ id="editor-frame"+ title="Cross-origin child editor"+ src="http://127.0.0.1:8081/iframe_dynamic_textarea_child.html"+ ></iframe>+ </main>+ </body>+</html>diff --git a/packages/chrome-plugin/tests/pages/iframe_parent_origin.html b/packages/chrome-plugin/tests/pages/iframe_parent_origin.htmlnew file mode 100644index 000000000..88956110a--- /dev/null+++ b/packages/chrome-plugin/tests/pages/iframe_parent_origin.html@@ -0,0 +1,38 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Parent Origin Inheritance</title>+ <style>+ body {+ margin: 0;+ font-family: sans-serif;+ background: #f4f4f5;+ }++ main {+ max-width: 960px;+ margin: 32px auto;+ padding: 24px;+ }++ iframe {+ width: 100%;+ height: 240px;+ border: 1px solid #d4d4d8;+ background: white;+ }+ </style>+ </head>+ <body>+ <main>+ <h1>Parent origin inheritance test</h1>+ <iframe+ id="editor-frame"+ title="Cross-origin child editor"+ src="http://127.0.0.1:8081/iframe_parent_origin_child.html"+ ></iframe>+ </main>+ </body>+</html>diff --git a/packages/chrome-plugin/tests/pages/iframe_parent_origin_child.html b/packages/chrome-plugin/tests/pages/iframe_parent_origin_child.htmlnew file mode 100644index 000000000..7e033cfbf--- /dev/null+++ b/packages/chrome-plugin/tests/pages/iframe_parent_origin_child.html@@ -0,0 +1,29 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Child Editor</title>+ <style>+ body {+ margin: 0;+ padding: 24px;+ font-family: sans-serif;+ background: white;+ }++ textarea {+ width: 100%;+ min-height: 120px;+ padding: 12px;+ font: 16px/1.4 sans-serif;+ border: 1px solid #a1a1aa;+ box-sizing: border-box;+ }+ </style>+ </head>+ <body>+ <label for="editor">Cross-origin editor</label>+ <textarea id="editor" autofocus spellcheck="true"></textarea>+ </body>+</html>