An error is triggered by the EyeDropper API stating that 'EyeDropper' has not been defined

I am trying to utilize EyeDropper for an eyedropper function in my project that uses Vue2 + Ts. Here is the code snippet:

<div
  v-if="haveEyeDropper"
  @click="handleClickPick"
>
  <i class="iconfont icon-xiguan"></i>
</div>

handleClickPick(): void {
  const eyeDropper = new EyeDropper();
  // ...
}

However, I am encountering errors stating "Cannot find name 'EyeDropper'. Did you mean 'eyeDropper'? -Vetur" and "'EyeDropper' is not defined -eslint". Interestingly, when I copied the example code from MDN documentation (https://developer.mozilla.org/en-US/docs/Web/API/EyeDropper) into an index.html file, it worked without any issues.

(Using Chrome version 105.0.5195.52)

Answer №1

Could you verify if your application is running on a Secure Context? (Likely within local development)

window.isSecureContext

If it's not running in a secure context, you won't be able to access the EyeDropper API (as per MDN):

https://i.stack.imgur.com/dGmX8.png

In that scenario, you might want to consider accessing your application over HTTPS using ngnix or similar methods.

Answer №2

I devised a innovative plan that may not be considered traditional.

Here is the code snippet I implemented in index.html:

<script>
  if (!!window.EyeDropper) {
    window.EyeDropperTarget = new EyeDropper();
  }
</script>

I am checking if window.EyeDropper exists, and if it does, I initialize an instance of EyeDropper() on window.

Subsequently, I utilize it in my application logic like so:

handleClickPick(): void {
  const picker = window.EyeDropperTarget;

  picker.open().then((result: any) => {
    const color = result?.sRGBHex;
    // ...
  });
}

Answer №3

My team leader provided me with a conventional approach using the following code:

const sample = (window as any).ColorPicker()

An error is being flagged by Vetur because: Esline does not recognize the new window Api.

Answer №4

To use that variable/type, you must declare it on the Window object. This means creating a new variable (not default) on the "window" object.

declare global {
    interface Window {
        EyeDropper?: any;
    }
}

For more information, refer to this thread:

Answer №5

Give this a shot:

const colorPicker = new window.ColorPicker();

Keep in mind that if you are using Ubuntu, you might encounter the error message: "AbortError: Failed to execute 'open' on 'ColorPicker': The user canceled the selection.". However, rest assured this code/ColorPicker will function properly on Windows Chrome/Edge versions >= 95.

Take a look at this article for more information:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can I access the component attributes in Vuetify using Typescript?

For example, within a v-data-table component, the headers object contains a specific structure in the API: https://i.stack.imgur.com/4m8WA.png Is there a way to access this headers type in Typescript for reusability? Or do I have to define my own interfac ...

The Vite / Page reloading loop reaches its peak callstack size

I'm currently using Vite in conjunction with Rails to load my custom component. Take a look at how I'm doing it: main.js import { defineCustomElement } from 'vue'; import Panel from '~/components/panel_custom/Panel.ce.vue'; ...

Importing Json in Angular 8: A detailed guide

I recently came across information that you can now directly import JSON in TypeScript 2.9 and made changes to my tsconfig.json file accordingly: { "compileOnSave": false, "compilerOptions": { "baseUrl": "./", "outDir": "./dist/out-tsc", " ...

Selenium Grid: Unable to locate the DevToolsActivePort file (error: Chrome did not launch successfully and exited abnormally)

Recently, I decided to use Selenium Grid to automate some tests. To make the process more efficient, I set up VMs running on a LINUX Platform (one acting as a Selenium hub and others as Selenium nodes). The standalone server started without any issues in b ...

The Unit Test for Angular NgRx is not passing as expected

I'm facing difficulties with my unit tests failing. How can I verify that my asynchronous condition is met after a store dispatch? There are 3 specific checks I want to perform: 1/ Ensure that my component is truthy after the dispatch (when the cond ...

The field '_id' is not present in the type Pick

I'm working on a project using Next.js and attempting to query MongoDB with TypeScript and mongoose, but I keep encountering a type error. types.d.ts type dbPost = { _id: string user: { uid: string name: string avatar: string } po ...

Discovering all words enclosed by '#' in a string using React TypeScript

Trying to figure out how to extract words between '#' in a given string... For example: const str = `<Table striped bordered hover> <thead> <tr> <th>#project name#</th> <th>#First Name#& ...

Troubleshooting compilation issues when using RxJS with TypeScript

Having trouble resolving tsc errors in the code snippet below. This code is using rxjs 5.0.3 with tsc 2.1.5 import { Observable } from 'rxjs/Observable'; import { Subject } from 'rxjs/Subject'; import 'rxjs/Rx'; let subject ...

Vue's watch feature will not execute if the watched property remains unchanged during a page reload

<template> <!-- The navbar has a property for gender, the color of the navbar will change depending on the gender --> <!-- pass the props gender through a form submission and event --> <div class="nav-main" :class="{f ...

Mapping JSON objects to TypeScript Class Objects

I am in the process of transitioning my AngularJS application to Angular 6, and I'm encountering difficulties converting a JSON object into a TypeScript object list. In my Angular 6 application, I utilize this.http.get(Url) to retrieve data from an AP ...

"Trouble with Typescript's 'keyof' not recognizing 'any' as a constraint

These are the current definitions I have on hand: interface Action<T extends string, P> { type: T; payload: P; } type ActionDefinitions = { setNumber: number; setString: string; } type ActionCreator<A extends keyof ActionDefinitions> ...

Observing the completion of a subscriber function

Is there a more streamlined way to determine if the subscriber has finished executing or return something and catch it up-stream? Consider the following code snippets: this._subscriptions.push(this._client .getCommandStream(this._command) // R ...

Restricted inclusive collection utilizing embedded identifier

Attempting to segregate a discriminated union array into separate arrays of its union types has presented some challenges. I came across this particular question that provides generic discriminators. Unfortunately, the dataset I am working with doesn&apos ...

Error: Undefined object trying to access 'vibrate' property

Good day, I apologize for my poor English. I am encountering an issue with Ionic Capacitor while attempting to utilize the Vibration plugin. The documentation lacks detailed information, and when checking the Android Studio terminal, I found the following ...

The external typing file encounters an issue when trying to locate the relative path to its own index.d.ts file

While working on my project and using react-color as a dependency, I encountered an issue with the tsc import failing. The error message displayed: node_modules/@types/react-color/lib/components/sketch/Sketch.d.ts(2,41): error TS2307: Cannot find module & ...

Function in nodejs throwing an error: Return type missing

I am facing an issue with this code snippet while trying to compile the application. public async test(options?: { engine?: Config }): Promise<any> { const hostel = new Service({ list: this.servicesList, createService ...

Displaying a segment of information extracted from a JSON array

I'm currently tackling a project that involves using React, Redux, and TypeScript. Within the JSON file, there is a key-value pair: "data_start": "2022-09-02" Is there a way to display this date in a different format, specifical ...

Ways to implement a package designed for non-framework usage in Vue

Alert This may not be the appropriate place to pose such inquiries, but I am in need of some guidance. It's more about seeking direction rather than a definitive answer as this question seems quite open-ended. Overview I've created a package th ...

What are some ways to detect TypeScript type errors in the data of a Vue component?

Recently, I delved into Typescript development using Nuxt-ts and Vue 2. My goal was to steer clear of class-style components so I opted for the following approach. I created my Interfaces in a folder named /types. Whenever I needed to declare a type in a ...

Utilizing Angular 10 to Transform a JSON Data into a Custom String for HTML Rendering

I have received a JSON response from my backend built using Spring Boot. The "category" field in the response can either be 1 or 2, where 1 represents Notifications and 2 represents FAQs. { "pageNumber": 0, "size": 5, "totalPages&q ...