# EyeDropper API

The EyeDropper API provides a mechanism for creating an eyedropper tool that allows users to sample colors from their screens, including outside of the browser window.

## 1. The Concept

Traditionally, color pickers in web apps (like `<input type="color">`) are limited to the browser's implementation or canvas-based pickers restricted to the page content. The EyeDropper API allows the user to pick a pixel color from *anywhere* on their screen.

## 2. Basic Usage

To use the API, you create an instance of `EyeDropper` and call its `open()` method. This method returns a Promise that resolves to an object containing the selected color.

```javascript
const eyeDropper = new EyeDropper();

async function pickColor() {
  try {
    const result = await eyeDropper.open();
    // result is { sRGBHex: "#ff0000" }
    console.log('Selected color:', result.sRGBHex);
    
    document.body.style.backgroundColor = result.sRGBHex;
  } catch (err) {
    console.log('User canceled the selection.');
  }
}

const btn = document.getElementById('color-btn');
btn.addEventListener('click', pickColor);
```

## 3. Requirements and Limitations

*   **Secure Context:** The API is only available in secure contexts (HTTPS).
*   **User Gesture:** `open()` must be called in response to a user action (like a button click) to prevent abuse.
*   **Browser Support:** Currently supported primarily in Chromium-based desktop browsers (Chrome, Edge, Opera). It is generally not available on mobile devices.

## 4. Checking Support

You should check if the API is supported before trying to use it.

```javascript
if ('EyeDropper' in window) {
  console.log('EyeDropper API is supported');
} else {
  console.log('EyeDropper API is not supported');
}
```

## 5. Aborting the Selection

The `open()` method accepts an `AbortSignal` to programmatically cancel the eyedropper mode.

```javascript
const controller = new AbortController();
const signal = controller.signal;

eyeDropper.open({ signal }).then((result) => {
  console.log(result.sRGBHex);
}).catch((err) => {
  if (err.name === 'AbortError') {
    console.log('Selection aborted');
  }
});
```

[[programming/javascript/vanilla/javascript]]
[[programming/javascript/vanilla/promises-async-await]]
[[programming/javascript/vanilla/events]]