DOMException on calling navigator.clipboard.readText()

33,104

Solution 1

This seems to happen when executing code from the devtools console or snippets.

Workaround:

You can execute the code below and focus on the window within 3 seconds, by clicking somewhere, or just by pressing <tab>.

e.g. from snippets

Ctrl-Enter
<Tab>

e.g. from console

Enter
<Tab>

setTimeout(async()=>console.log(
     await window.navigator.clipboard.readText()), 3000)

Solution 2

As Kaiido said, your DOM need to be focused. I had the same problem during my development when i put a breakpoint in the code... The console developper took the focused and the error appear. With the same code and same browser, all work fine if F12 is closed

Solution 3

Problem

It's a security risk, clearly. :)

Solution

I assume you face this when you are trying to call it from the dev tools. Well, to make life easier, I am taking Jannis's answer, to a less adrenaline-oriented way. :)

I am adding a one-time focus listener to window to do the things magically after hitting "tab" from the Devtools.

function readClipboardFromDevTools() {
    return new Promise((resolve, reject) => {
        const _asyncCopyFn = (async () => {
            try {
                const value = await navigator.clipboard.readText();
                console.log(`${value} is read!`);
                resolve(value);
            } catch (e) {
                reject(e);
            }
            window.removeEventListener("focus", _asyncCopyFn);
        });
    
        window.addEventListener("focus", _asyncCopyFn);
        console.log("Hit <Tab> to give focus back to document (or we will face a DOMException);");
    });
}

// To call:
readClipboardFromDevTools().then((r) => console.log("Returned value: ", r));

Note: The return value is a Promise as it's an asynchronous call.

Solution 4

if you want to debug a and play around to view result. also can hide this <p></p>.

async function readClipboard () {
  if (!navigator.clipboard) {
    // Clipboard API not available
    return
  }

  try {
    const text = await navigator.clipboard.readText();
    document.querySelector('.clipboard-content').innerText = text;
  } catch (err) {
    console.error('Failed to copy!', err)
  }
}

function updateClipboard() {
  // Here You Can Debug without DomException
  debugger
  const clipboard = document.querySelector('.clipboard-content').innerText;
  document.querySelector('.clipboard-content').innerText = 'Updated => ' + clipboard;
}
<button onclick="readClipboard()">Paste</button>
<p class="clipboard-content"></p>
<button onclick="updateClipboard()">Edit</button>

Solution 5

As the exception message says, you need to have the Document actively focused in order to use this API.

Share:
33,104
frosty
Author by

frosty

I suffer fools gladly, as I myself try to clear my mind of unknown. In that process I do especially of down vote trolls:)

Updated on January 13, 2022

Comments

  • frosty
    frosty over 2 years

    Following lines of code used to work and stopped working after chrome upgrade to Version 74.0.3729.169 (Official Build) (64-bit). Now I get DOMException even though permission is set correctly. Appreciate if you can explain what is the bug and workaround. Exception details:

    message:Document is not focused name:NotAllowedError code:0

    navigator.permissions.query({ name: 'clipboard-read' }).then(result => {
    // If permission to read the clipboard is granted or if the user will
    // be prompted to allow it, we proceed.
        if (result.state === 'granted' || result.state === 'prompt') {
            navigator.clipboard.readText()
                .then(text => {
                    //my code to handle paste
                 })
                 .catch(err => {
                     console.error('Failed to read clipboard contents: ', err);
                 });
         }
    }
    
  • vir us
    vir us over 4 years
    This is what the exception says but how to actually fix that? Is there a programmatic way?
  • Kaiido
    Kaiido over 4 years
    @virus you could make the request while handling a click event.
  • Aidin
    Aidin over 2 years
    Great answer! I posted a time-insensitive answer based on this: stackoverflow.com/a/70386674
  • Aidin
    Aidin over 2 years
    Fun fact: The first time you copy/paste this and hit <enter> in dev-tools, you will see these lines printed again. That means it works -- that's the content of your clipboard. ;D
  • Jannis Ioannou
    Jannis Ioannou over 2 years
    Could this be a candidate for the quine programs hall of fame :) ?
  • Admin
    Admin over 2 years
    As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
  • PYK
    PYK almost 2 years
    Very good Workaround \o/