Home > OS >  How to get the content from clipboard on Firefox in Javascript
How to get the content from clipboard on Firefox in Javascript

Time:09-06

I am very frustrated to make Paste from the clipboard on my React app.

I used navigator.clipboard.readText(), which works perfectly on Chrome browser. But it doesn't work on my latest Firefox browser.

I tried to search SO and there are few posts related to it. But all of them don't make me happy.

According to MDN documentation, it says:

Blockquote Firefox only supports reading the clipboard in browser extensions, using the "clipboardRead" extension permission.

But I really don't know how to enable it.

Could you help me out with this issue? Is there any good library for it?

Thanks in advance.

CodePudding user response:

Based on Can I use, Firefox only supports reading the clipboard in browser extensions.

This article's selected answer says that Firefox currently doesn't allow web pages to access the clipboard via JavaScript, so your only option would be to use the keyboard.

CodePudding user response:

What I did in one of my projects is to register an eventListener for the document to handle the paste event in a useEffect hook.

  useEffect(() => {
    const pasteFn = (event) => {
      const data = event.clipboardData.items;
      for (let i = 0; i < data.length; i  = 1) {
        if (data[i].kind === 'string' && data[i].type.match('^text/plain')) {
          data[i].getAsString((str) => console.log('text/plain', str));
        } else if (data[i].kind === 'string' && data[i].type.match('^text/html')) {
          data[i].getAsString((str) => console.log('html', str));
        } else if (data[i].kind === 'string' && data[i].type.match('^text/uri-list')) {
          data[i].getAsString((str) => console.log('uri', str));
        } else if (data[i].kind === 'file' && data[i].type.match('^image/')) {
          const f = data[i].getAsFile();
          console.log('File', f);
        }
      }
    };
    document.addEventListener('paste', pasteFn);
    return () => {
      document.removeEventListener('paste', pasteFn); // clean up
    };
  }, []);

CodePudding user response:

navigator.clipboard is an API that works only on secure environments. It could be just that you are running your React app on localhost, a non-secure env and it doesn't have access to the clipboard object from the browser.

You could have a check to see if navigator.clipboard is available on the environment and then use it.

if (navigator.clipboard !== undefined) {
  // make use of clipboard functions here
}
  • Related