Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

navigator.clipboard is undefined

Why is navigator.clipboard always undefined in the following snippet?

var clipboard = navigator.clipboard; if (clipboard == undefined) {     console.log('clipboard is undefined'); } else {     clipboard.writeText('stuff to write').then(function() {         console.log('Copied to clipboard successfully!');     }, function() {         console.error('Unable to write to clipboard. :-(');     }); } 

More on the clipboard API can be found here.

Chrome Version: 68.0.3440.106.

I'm sure this was working at some point, but no longer is. It's confusing because this table suggests that the Clipboard API is implemented in Chrome (has been for some time), but this table of specific API methods suggests that none of the methods of the API is supported??

like image 762
drmrbrewer Avatar asked Aug 12 '18 03:08

drmrbrewer


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 async clipboard API?

Safari 13.1 adds support for the async Clipboard API. This API allows you, as web developers, to write and read data to and from the system clipboard, and offers several advantages over the current state of the art for reading and writing clipboard data via DataTransfer.


1 Answers

This requires a secure origin — either HTTPS or localhost (or disabled by running Chrome with a flag). Just like for ServiceWorker, this state is indicated by the presence or absence of the property on the navigator object.

https://developers.google.com/web/updates/2018/03/clipboardapi

This is noted in the spec with [SecureContext] on the interface: https://w3c.github.io/clipboard-apis/#dom-navigator-clipboard

You can check the state of window.isSecureContext to learn if that's the reason a feature is unavailable. Secure contexts | MDN

And yes, you should set up HSTS to make sure HTTP redirects to HTTPS.

like image 135
Josh Lee Avatar answered Sep 21 '22 09:09

Josh Lee