Safari clipboard writeText NotAllowedError after await fetch()
Our Copy share link button worked in Chrome but threw NotAllowedError in Safari. The await fetch() before writeText() consumed the user gesture. Passing a Promise into ClipboardItem fixed it in every engine.
Support tickets arrived from Mac and iPhone users with the same complaint: the Copy share link button on our report page did nothing. No toast, no link in the clipboard. Chrome and Edge users were fine. Our frontend error tracker had the answer within minutes, all from Safari user agents:
NotAllowedError: The request is not allowed by the user agent or the platform in the current
context, possibly because the user denied permission.
The button handler had changed two weeks earlier. Before, the share URL was already in the page. After a privacy review, we started minting a short-lived signed link on demand, so the handler now called our API first and copied the result second.
Reproducing it
The smallest version that failed every time in Safari 26 on macOS and iOS:
copyButton.addEventListener('click', async () => {
const res = await fetch('/api/reports/42/share-link', { method: 'POST' });
const { url } = await res.json();
await navigator.clipboard.writeText(url); // rejects in Safari
showToast('Link copied');
});
Remove the fetch and copy a constant string, and Safari copies it without complaint. Put the fetch back and it fails, even when the API answers in 40 ms.
What we ruled out
Permissions. Safari has no site-level clipboard-write permission to grant. There was no prompt and nothing to toggle in Settings for Websites.
Insecure context. The Clipboard API only exists on HTTPS pages. We were on HTTPS, and
navigator.clipboardwas defined, so the API was present and was refusing the call.Slow API. We suspected a timeout like Chrome's transient activation window, which lasts a few seconds. Making the endpoint answer instantly did not help in Safari, so it was not about elapsed time.
Focus loss. Chrome can reject clipboard calls when the document is not focused. The page kept focus the whole time in our tests.
Root cause
Safari only allows clipboard writes while the page handles a user gesture, and it ties that permission to the synchronous part of the event handler. Once our code awaited the network request, the call to writeText() happened in a later task, outside the gesture, so WebKit rejected it. Chrome gives a short grace period after a click, which is why the same code passed there. The fix was not to make the request faster but to start the clipboard write inside the click and hand it the data later.
What is happening under the hood
Browsers gate powerful features behind user activation. The HTML standard defines transient activation: a short-lived flag set when the user clicks, taps or presses a key. Chromium keeps that flag for a few seconds and lets clipboard writes use it, so an await that finishes quickly still counts.
WebKit takes a stricter line for the clipboard. A write must start while the gesture is being handled. The Async Clipboard API gives a clean way to do that: navigator.clipboard.write() takes ClipboardItem objects, and a ClipboardItem can hold a Promise that resolves to a Blob or a string. You call write() synchronously in the click handler, which satisfies the gesture check, and the browser waits for your Promise before it puts data on the clipboard. WebKit's engineers described this design when they shipped the API in Safari 13.1.
writeText() has no such option. It takes a string, so you must already have the string when you call it, and you only have it after the await.
Environment
Component | Version / value |
|---|---|
Safari (macOS) | 26.1 on macOS Tahoe 26.1 |
Safari (iOS) | iOS 26.1, iPhone 15 |
Chrome | 142, macOS and Android |
Firefox | 145, macOS |
Frontend | Vanilla TypeScript, bundled with Vite 7 |
API |
|
Minimal reproduction
<button id="copy">Copy share link</button>
<script type="module">
const button = document.getElementById('copy');
button.addEventListener('click', async () => {
try {
const res = await fetch('/share-link.json');
const { url } = await res.json();
await navigator.clipboard.writeText(url);
console.log('copied', url);
} catch (err) {
console.error(err.name, err.message);
}
});
</script>
Serve it over HTTPS (or localhost, which counts as a secure context), click in Safari, and the console shows NotAllowedError.
Who is affected
Any Safari version with the Async Clipboard API (13.1 and later) on macOS, iOS and iPadOS, plus every iOS browser, since they all use WebKit.
Code that does any
awaitbefore the copy: a fetch, a dynamicimport(), reading a file, waiting for a modal to close, or asetTimeoutused to debounce the button.Chrome and Firefox users are usually fine, which is why this bug survives review when the team tests mainly in Chromium.
The fix
Start the clipboard write in the click handler and pass a Promise that resolves to the data.
copyButton.addEventListener('click', async () => {
- const res = await fetch('/api/reports/42/share-link', { method: 'POST' });
- const { url } = await res.json();
- await navigator.clipboard.writeText(url);
+ const urlPromise = fetch('/api/reports/42/share-link', { method: 'POST' })
+ .then((res) => {
+ if (!res.ok) throw new Error(`share-link ${res.status}`);
+ return res.json();
+ })
+ .then(({ url }) => new Blob([url], { type: 'text/plain' }));
+
+ await navigator.clipboard.write([
+ new ClipboardItem({ 'text/plain': urlPromise }),
+ ]);
showToast('Link copied');
});
Two details matter. First, nothing may be awaited before navigator.clipboard.write() runs. The fetch starts first, but we do not await it. Second, the Promise resolves to a Blob with a MIME type that matches the key. Current engines also accept a plain string as the resolved value, but a Blob works across more versions.
We wrapped it in a helper so the rest of the code base cannot get it wrong:
export async function copyFromPromise(text: Promise<string>): Promise<void> {
if (typeof ClipboardItem !== 'undefined' && navigator.clipboard?.write) {
const blob = text.then((t) => new Blob([t], { type: 'text/plain' }));
await navigator.clipboard.write([new ClipboardItem({ 'text/plain': blob })]);
return;
}
// Older engines without ClipboardItem: fall back to writeText after the data arrives.
await navigator.clipboard.writeText(await text);
}
Alternatives and trade-offs
Fetch ahead of time. Mint the link when the share dialog opens, store it, and call
writeText()synchronously on click. This is the simplest option when the data is cheap to produce, but it creates links nobody uses and they may expire before the click.Two-step UI. Show the link in a read-only field once it arrives, with a second Copy click. It always works, but costs the user an extra tap.
document.execCommand('copy'). Deprecated, needs a selected text node, and is also bound to the gesture. We did not keep it.
How to test the fix
Manual checks in each engine:
Open the page in Safari on macOS, click Copy share link, paste into a text editor.
Repeat on an iPhone in Safari and in Chrome for iOS (both WebKit).
Throttle the network to Slow 3G in Chrome DevTools and confirm the copy still lands.
Make the API return 500 and confirm the error toast shows and the clipboard is unchanged.
Our Playwright suite covers Chromium and WebKit. Clipboard permissions differ per engine, so the test reads the clipboard back through the page rather than the OS:
test('copies share link', async ({ page, context, browserName }) => {
if (browserName === 'chromium') {
await context.grantPermissions(['clipboard-read', 'clipboard-write']);
}
await page.goto('/reports/42');
await page.getByRole('button', { name: 'Copy share link' }).click();
await expect(page.getByText('Link copied')).toBeVisible();
if (browserName === 'chromium') {
const text = await page.evaluate(() => navigator.clipboard.readText());
expect(text).toMatch(/^https:\/\/example\.com\/s\//);
}
});
WebKit in Playwright is not Safari, so we still do the real-device pass before release.
Confirming in production
We added two counters to our frontend telemetry: share_link.copy_ok and share_link.copy_failed with err.name attached. Before the fix, Safari sessions showed about 60 percent failures on this button. After the deploy, failures dropped to a handful per day, all TypeError from the API being unreachable on flaky mobile networks, which is the expected residue.
share_link.copy_failed{browser="Safari", error="NotAllowedError"} before: 412/day after: 0/day
Regression guard
A lint rule in our custom ESLint plugin flags
navigator.clipboard.writeTextinside anasyncfunction when anyawaitappears before it in the same function body.The helper
copyFromPromiseis the only clipboard entry point allowed in feature code.The WebKit Playwright project runs on every pull request, not only nightly.
Security implications
None beyond the existing design. The fix does not widen access: the browser still requires a real user gesture, and pages cannot write to the clipboard in the background. Do not try to bypass the gesture rule with synthetic events. element.click() from script does not grant activation, and attempts to get around it are what clipboard hijacking abuse looks like. Keep the share link short-lived and scoped, because users paste clipboard contents into chats where other people see them.
Prevention checklist
Call clipboard writes synchronously inside the gesture handler; await nothing before them.
Use
ClipboardItemwith a Promise when the data comes from the network.Test copy buttons in WebKit, not only Chromium.
Log clipboard failures with the error name so engine-specific breakage shows up quickly.
References
MDN, Clipboard.write(): https://developer.mozilla.org/en-US/docs/Web/API/Clipboard/write
MDN, ClipboardItem: https://developer.mozilla.org/en-US/docs/Web/API/ClipboardItem
MDN, User activation: https://developer.mozilla.org/en-US/docs/Web/Security/User_activation
WebKit blog, Async Clipboard API: https://webkit.org/blog/10855/async-clipboard-api/
HTML Standard, user activation: https://html.spec.whatwg.org/multipage/interaction.html#tracking-user-activation
Add a label
Embed this post
<iframe src="https://hibug.me/safari-clipboard-writetext-notallowederror-after-await" width="700" height="420" frameborder="0" loading="lazy"></iframe>
I build and maintain public and partner APIs, currently for a logistics platform with web, mobile and third-party clients all calling the same endpoints. Before that I worked on identity: login, sessions, OAuth integrations and the long tail of edge cases they create. The bugs I care about sit at the contract between client and server. A PUT that wiped fields the client never sent, a cache that served one user's page to another, a field removal that broke app versions still in the wild, a refresh flow that logged people out when two tabs raced. None of these show up in a happy-path demo. My posts walk through how each one surfaced, what the HTTP or auth spec actually says, the fix we shipped and the tests we added so the next change to the API does not repeat it.
Related Stories
forEach with an async callback reported success before any email was sent
Comments
0No comments yet. Be the first to comment!
Sign In to post a comment.