snehan kekre

Writing to a Google Sheet from a script that only has a browser

I keep a work queue in a Google Sheet: what is waiting on me, what I promised and by when, and what other teams owe. A script rebuilds it every hour from my email and chats. Other people can see the sheet, and I tick items off in it, so the script has to write to it without losing anything a person typed.

The job runs unattended under macOS’s launchd. It has no Google API credentials for the account. What it has is a Chrome profile signed in to that account, which Playwright can drive headless. Every write goes through the same web interface a person uses, and that interface can put data in the wrong place without showing an error.

How a tab got wiped

On 5 November an earlier script imported a CSV into a tab with File > Import > “Replace current sheet”. It opened the sheet at the target tab’s URL, which ends in #gid=<tab id>, and ran the import.

The target tab was hidden. Sheets can’t open a hidden tab by URL, so the page stayed on another tab without any error, and “Replace current sheet” replaced that one. It was the Change log, the tab where we record every change made to the sheet. I restored it from a local copy the same afternoon. The script never checked which tab was open before it wrote, and every write since then checks first.

Checks before writing

The hourly script writes five tabs: Queue, Promises, Other teams, Requests and Backlog. The spreadsheet id and the five tab ids are constants in the script. It refuses any other file and any other tab, and two tabs in that spreadsheet (a dashboard and an About page) are never written.

Before writing a tab, the script runs three checks:

  1. The page title starts with the spreadsheet’s name, so a redirect to a sign-in page or a different file stops it.
  2. The name of the active tab, read from the tab bar in the page, equals the tab it means to write. This check would have stopped the 5 November import.
  3. Cell A1 of the tab, fetched through the CSV export URL, is either empty or holds the header that tab’s data always starts with. The Queue’s first column is “Done”, the Requests tab starts with “Key”, and so on. Anything else in A1 means the tab holds data this script didn’t write.

The CSV export is a plain GET request that the signed-in browser context can make:

const r = await ctx.request.get(
  `https://docs.google.com/spreadsheets/d/${ID}/export?format=csv&gid=${gid}`);

It is the script’s only way to read the sheet, and it is rate-limited. Several exports in a row return HTTP 429, so the script retries up to three times, waiting 20, 40 and then 60 seconds.

Writing through the clipboard

The data goes in through the clipboard. The script writes the tab’s contents to the clipboard as tab-separated text, selects A1 through the Name box, and presses Cmd+V. Sheets splits pasted tab-separated text into cells, and a plain-text paste keeps the tab’s existing formatting, checkboxes and dropdowns.

await page.click('#t-name-box');
await page.keyboard.type('A1');
await page.keyboard.press('Enter');
await page.evaluate(t => navigator.clipboard.writeText(t), tsv);
await page.keyboard.press('Meta+v');

The script pastes the new data over the old, confirms through an export that the paste landed, and only then deletes whatever is left below the new last row. If the paste fails, the old data is still there. Clearing first would leave an empty tab whenever the paste failed.

The range it clears is closed: from the row after the new data, through two columns past its width, down to 50 rows past the larger of the old and new row counts. An earlier version used an open-ended range, and on 25 November a tab that had shrunk kept old rows at the bottom.

Reading every cell back

After the paste and the clear, the script exports the tab again and compares it with what it sent, cell by cell. If any cell differs, it tries the whole write once more, and if it still differs it reports which cell:

read-back mismatch: row 14 col 3: sent "chase on Tuesday", sheet has ""

A plain string comparison fails on almost every run, because Sheets reformats values as they arrive. 2026-11-17 comes back as 11/17/2026, 1,500 as 1500, true as TRUE, and a leading apostrophe that forced a value to stay text disappears. Both sides go through a normaliser first, which converts dates, times, numbers and booleans to one format.

Checkboxes need their own rule. An unticked checkbox exports as FALSE, so a tab with a checkbox column has a FALSE in every row down to the bottom of the grid, and the export looks like hundreds of rows of data. A row containing nothing but empty cells and FALSE counts as empty.

Saving edits made in the sheet

I edit three things in the Queue tab: I tick Done, set a priority, or type a next step. The hourly rewrite would erase all three, so the script reads them from the sheet before it writes.

Each run starts by exporting the editable tabs and reading those columns. A ticked box or a set priority is an edit. For the next-step column, which the script also fills in, an edit is a value that differs from what the script pasted last time, so the script keeps a copy of every tab it pushed. The edits are saved to the local files the queue is built from, and only then is the tab rebuilt with them applied.

If the script finds an edit in the sheet that has not been saved yet, it refuses to write that tab at all:

{"tab":"Queue","ok":false,"error":"2 edits in the sheet not saved yet (run tools/triage.py first); not writing"}

Other guards

A tab whose data hasn’t changed since the last verified write is skipped. The script stores a SHA-1 of what it sent, so most hourly runs touch nothing.

Only one machine may write. A Windows test machine runs the same code with an environment variable that turns every sheet write into an error before the browser starts.

When anything fails, the script saves a screenshot of the page and prints one JSON line for that tab with the reason, then moves on to the next tab, so a failure on one tab doesn’t stop the other four.

With API credentials

With a service account and the Sheets API, most of these checks would be unnecessary. A values.update call names the tab and range explicitly, so there is no active tab to get wrong, and the response says what was written. I would keep the read-back and the edit round trip, because they also catch edits other people make in the sheet.