Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DOMException on calling navigator.clipboard.readText()

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);              });      } } 
like image 554
frosty Avatar asked May 25 '19 15:05

frosty


People also ask

What is navigator clipboard?

clipboard. The Clipboard API adds to the Navigator interface the read-only clipboard property, which returns the Clipboard object used to read and write the clipboard's contents. The Clipboard API can be used to implement cut, copy, and paste features within a web application.

Can I use clipboard write?

The Clipboard method write() writes arbitrary data, such as images, to the clipboard. This can be used to implement cut and copy functionality. The "clipboard-write" permission of the Permissions API, is granted automatically to pages when they are in the active tab.

What is clipboard API?

The Clipboard API provides the ability to respond to clipboard commands (cut, copy, and paste) as well as to asynchronously read from and write to the system clipboard. Note: This API is not available in Web Workers (not exposed via WorkerNavigator ).

What is async clipboard API?

The async clipboard API is a powerful web API, capable of both writing arbitrary data to the clipboard, as well as reading from the system clipboard.


2 Answers

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) 
like image 147
Jannis Ioannou Avatar answered Oct 13 '22 22:10

Jannis Ioannou


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

like image 25
Guy Baillon Rafart Avatar answered Oct 13 '22 22:10

Guy Baillon Rafart