This feature has been shipped since v95 in Chrome browser. This tool allows picking a color from the screen.
It can be done by checking this property in the window
object:
if('EyeDropper' in window) {
console.log('This browser has EyeDropper')
}
First of all, we need to create an instance of EyeDroper
:
const eyeDropperInstance = new window.EyeDropper()
Then, we need to call an open
method of this instance. It returns a Promise
, so we need to use then
with a callback or call open
within async
block with the await
keyword.
eyeDropperInstance.open().then((color) => {
// color = { sRGBHex: "#<some-hex>" }
})
You will see the picker on the screen. If you click in Eyedropper Mode you will get the color selection result. It’s an object with one field - sRGBHex
and it contains a HEX-color as a string
:
One interesting thing about the eyedropper is you can go outside the browser and pick any color:
To exit from the eyedropper mode you need to press the Esc
button. You will see the error message in the Chrome console:
Uncaught (in promise) DOMException: The user canceled the selection.
To handle this message (other errors as well) we can use catch
method:
eyeDropperInstance.open()
.then((res) => console.log(res))
.catch((err) => console.log(`we have this, ${err}`))