The APIConcepto de API¿Qué es una API?Una API, siglas de Application Programming Interface o Interfaz de Programación de Apps, es un recopilatorio de código que se puede emplear para que varias apps se comuniquen entre ellas. Es algo que realiza una tarea equivalente a la interfaz de usuario al momento de promover la interacción entre persona y programa, solo que aplicado única y exclusivamente dentro del entorno del software.Aún cuando suene plus de WebHID posibilita que los sitios web accedan a teclados auxiliares alternativos y gamepads exóticos.
The WebHID API is part of the Capabilities project and is currently under development. This post will be updated as implementation progresses.
Existe una larga lista de dispositivos de interfaz humana (HID), como teclados alternativos o gamepads exóticos, que son demasiado nuevos, demasiado antiguos o poco comunes para que los controladores de dispositivos de los sistemas puedan ingresar a ellos. La API WebHID resuelve esto proporcionando una forma de poner en práctica la lógica específica del dispositivo en JavaScriptJavaScript es un lenguaje de programación que funciona en el lado del cliente y con el que las webs pueden ser más funcionales. Incorporación en código HTML El código JavaScript puede ser incrustado en las páginas HTML, para que adquieran funcionalidad. Existen varias opciones. Puede estar entre las etiquetas <SCRIPT> y </SCRIPT>, puede estar contenido en un archivo externo, puede ser un parámetro de las etiquetas HTML, y puede estar plus.
Suggested use cases
An HID device takes input from humans or provides them with an output. Examples of devices include keyboards, pointing devices (mice, touchscreens, etc.), and gamepads. the HID protocol makes it feasible to access these devices on desktop computers using operating system drivers. The web platform supports HID devices based on these drivers.
The inability to access rare HID devices is particularly painful when it consists of alternative helper keyboards (eg. Elgato Stream cover, Jabra Headphones, X-keys) y soporte exótico para gamepad. Los gamepads diseñados para el escritorio a menudo utilizan HID para las entradas del gamepad (botones, joysticks, disparadores) y salidas (LED, rumble). Desafortunadamente, las entradas y salidas del gamepad no están bien estandarizadas y los browsersConcepto de Navegadores¿Qué son los Navegadores?Los Navegadores son herramientas informáticas que utilizamos para, normalmente, navegar por Internet y visitar cualquier página web, al mismo tiempo de para hacer otras tareas como ver documentos, observar vídeos o reproducir contenido multimedia de cualquier tipo. Son un tipo de software sencillamente usual y bastante utilizado hoy en día.Insistimos en que es algo que se utiliza con mucha frecuencia, puesto que moverse por Internet plus web a menudo requieren una lógica personalizada para dispositivos específicos. Esto es insostenible y da como consecuencia un soporte deficiente para la larga cola de dispositivos más antiguos y poco comunes. Además hace que el browserUn navegador (además: browser) es una herramienta informática que te permite ver documentos y datos y navegar por la red. Los navegadores pueden mostrar distintos tipos de recursos de información; principalmente documentos HTML, a pesar de todo, además son posibles otros tipos de archivos y contenido multimedia, como PDF, JPEG, MPEG, GIF o el lenguaje de meta marcado. A través el uso de complementos especiales y la configuración respectivo, los plus dependa de peculiaridades en el comportamiento de dispositivos específicos.
Actual state
Terminology
HID consta de dos conceptos fundamentales: informes y descriptores de informes. Los informes son los datos que se intercambian entre un dispositivo y un cliente de softwareConcepto de Software¿Qué es el Software y cuál es su función?Un Software es la parte lógica, o más bien el soporte lógico, de cualquier sistema de tipo informático. Sea un PC, un teléfono teléfono celular o inclusive una tablet, es todo aquel programa que se ejecuta en él gracias a la coordinación de la parte física, es decir, el hardware, para llevar adelante alguna tarea concretamente o un recopilatorio de plus. El descriptor de reporte describe el formato y el significado de los datos que admite el dispositivo.
Un HID (Dispositivo de interfaz humana) es un tipo de dispositivo que recibe entradas de personsLas personas son personalidades imaginarias que representan a un determinado grupo objetivo. En el marketing online, las personas ayudan a entender mejor a los usuarios de un portal web o a los clientes de una tienda online. Concepto de personas Para que las personas puedan ejercer su efecto positivo, deben ser lo más detalladas viable. Esto conlleva un término exhaustiva de los grupos destinatarios para conseguir datos empíricos. La próxima plus o proporciona salidas a ellas. Además se refiere al protocolo HID, un estándar para la comunicación bidireccional entre un host y un dispositivo que está diseñado para simplificar el proceso de instalación. El protocolo HID se desarrolló originalmente para dispositivos USB, pero desde entonces se ha implementado en muchos otros protocolos, incluido Bluetooth.
HID devices and applications exchange binary data through three types of reports:
| report type | Description |
|---|---|
| input report | Data that is sent from the device to the application (for example, a button is pressed). |
| output report | Data that is sent from the application to the device (for example, a request to turn on the keyboard backlight). |
| Functions report | Data that can be sent to any address. The format is device specific. |
A report descriptor describes the binary format of the reports supported by the device. Its structure is hierarchical, and you can group reports as distinct collections within the top-level collection. the Format The descriptor is defined by the HID specification.
An HID usage is a numeric value that refers to a standardized input or output. Usage values enable a device to describe the intended usage of the device and the purpose of each field in its reports. As an example, one is set for the left button of a mouse. Usages are further organized into usage pages, which provide an indication of the high-level category of the device or report.
Using the WebHID API
Enabling via chrome: // flags
To experiment with the WebHID API locally on all desktop platforms, without a proof of origin token, enable the #experimental-web-platform-features flag on
chrome://flags.
Enable support during origin testing stage
The WebHID API is available on all desktop platforms (Chrome OS, Linux, macOS, and Windows) as a source test in Chrome 86. The source test is expected to end just before Chrome 89 goes live in February 2021. The API can also be enabled via a flag.
Origin testing allows you to test new features and provide feedback on their usability, practicality, and effectiveness to the web standards community. For more information, see the Origin testing guide for web developers. To enroll in this or any other proof of origin, visit the registration page.
Register for proof of origin
- Request a token by your origin.
- Add the token to your pages. There are two ways to do it:
- Add a
origin-trialtag to the header of each page. As an example, this might look like this: - Si puede configurar su serverLos servidores son ordenadores centrales y potentes dentro del campo de la tecnología de la información que procesan y proporcionan software y archivos en una red. Desde el punto de vista de un cliente, varios ordenadores en una red pueden ponerse en contacto con el servidor central para conseguir la información solicitada. En la arquitectura cliente-servidor, el servidor puede ser un software que proporciona un servicio y se ejecuta en plus, además puede agregar el token utilizando un
Origin-TrialEncabezado HTTPEl HTTP (Hyper Text Transfer Protocol) es un protocolo que se usa para transmitir datos en redes. HTTP es un estándar técnico generalmente aceptado que establece cómo un cliente web se comunica con un servidor para que los datos solicitados por el cliente puedan ser cargados y mostrados. Información general Junto con el URL y el HTML, HTTP es uno de los conceptos más importantes de Internet (www). Fue desarrollado plus. El encabezado de respuesta resultante debería verse así:Origin-Trial: TOKEN_GOES_HERE
- Add a
Feature detection
To check if the WebHID API is supported, use:
if ("hid" in navigator) {
}
Open a HID connection
La API de WebHID es asincrónica por diseño para evitar que la user interface Una interfaz de usuario es un medio por medio de del cual una persona puede controlar un software o hardware específico. Lo ideal es que las interfaces de usuario sean fáciles de utilizar para que la interacción sea lo más instintiva e intuitiva factible. En el caso de los programas informáticos, esto se denomina interfaz gráfica de usuario. Desarrollo y tipos de interfaces de usuario A diferencia de la plus del portal web se bloquee cuando se espera una entrada. Esto es esencial debido a que los datos HID se pueden recibir en cualquier momento, lo que necesita una forma de escucharlos.
To open an HID connection, first access a HIDDevice object. For this, you can ask the user to select a device by calling
navigator.hid.requestDevice ()or choose one of navigator.hid.getDevices ()
which returns a list of devices previously accessed by the web portal.
the navigator.hid.requestDevice () La función toma un objeto obligatorio que establece filtersConcepto de Filtros¿Qué son los Filtros?Los Filtros son unos mecanismos que, sea en el campo de la informática o en el de las páginas web, se usan para establecer qué tipo de contenidos se deben visualizar o mostrar por pantalla, o cuáles no deben aparecer. Es algo que se emplea en numerosos lugares con fines muy distintos, pero que siempre tiene como objetivo perfilar la búsqueda para acertar mejor con plus. Se usan para hacer coincidir cualquier dispositivo conectado con un identificador de proveedor USB (vendorId), a USB product identifier (productId), a usage page value (usagePage) and a use value (usage). You can get them from the USB ID repository and the HID Usage Tables Document.
The multiple HIDDevice The objects returned by this function represent multiple HID interfaces on the same physical device.
const filters = [
{
vendorId: 0x057e,
productId: 0x2006
},
{
vendorId: 0x057e,
productId: 0x2007
}
];
const [device] = await navigator.hid.requestDevice({ filters });
const devices = await navigator.hid.getDevices();

A HIDDevice The object contains USB vendor and product identifiers for device identification. Their collections The attributeAtributo es una definición que se usa en varios campos de IT. Generalmente, un atributo se usa para describir un fichero o un campo de datos con más detalle. En la programación orientada a objetos, los atributos son una propiedad o característica que se puede asignar a un objeto (elemento). A través el uso de atributos se pueden asignar valores específicos a ciertos items. Áreas de aplicación Las tres áreas plus se inicializa con una descripción jerárquica de los formatos de reporte del dispositivo.
for (let collection of device.collections) {
console.log(`Usage: ${collection.usage}`);
console.log(`Usage page: ${collection.usagePage}`);for (let inputReport of collection.inputReports) {
console.log(`Input report: ${inputReport.reportId}`);
}
for (let outputReport of collection.outputReports) {
console.log(`Output report: ${outputReport.reportId}`);
}
for (let featureReport of collection.featureReports) {
console.log(`Feature report: ${featureReport.reportId}`);
}
}
the HIDDevice devices are returned by default in a "closed" state and must be opened by calling open () before data can be sent or received.
await device.open();
Receive input reports
Once the HID connection has been established, you can handle incoming incoming reports by listening "inputreport" device events. Those events contain the HID data like DataView objectdata), the HID device to which it belongs (device) and the 8-bit report ID associated with the input report (reportId).

Continuing with the previous example, the following code shows you how to detect which button the user has pressed on a Joy-Con Right device so that you can hopefully test it at home.
device.addEventListener("inputreport", event => {
const { data, device, reportId } = event;
if (device.productId !== 0x2007 &Concepto de AMP¿Qué es el AMP o Accelerated Mobile Pages?El AMP, abreviatura de Accelerated Mobile Pages, es una propuesta que empezó a tomar forma en el año 2016 con la finalidad de mejorar la usabilidad, lectura y, en general, la experiencia de los usuarios de teléfono celular dentro de cualquier página web. Emprendida por Google con un aperturismo total (es de código abierto), lleva en activo desde entonces para facilitar más;& reportId !== 0x3f) return;
const value = data.getUint8(0);
if (value === 0) return;
const someButtons = { 1: "A", 2: "X", 4: "B", 8: "Y" };
console.log(`User pressed button ${someButtons[value]}.`);
});
Send outbound reports
To send an output report to an HID device, pass the 8-bit report ID associated with the output report (reportId) and bytes like BufferSource (data) to
device.sendReport (). The returned promise is resolved after the report has been sent. If the HID device does not use reporting ID, configure reportId to 0.
The following example applies to a Joy-Con device and shows you how to make it vibrate with the output reports.
const enableVibrationData = [1, 0, 1, 64, 64, 0, 1, 64, 64, 0x48, 0x01];
await device.sendReport(0x01, new Uint8Array(enableVibrationData));
const rumbleData = [ ];
await device.sendReport(0x10, new Uint8Array(rumbleData));
Send and receive function reports
Feature reports are the only type of HID data reports that can travel in both directions. They enable HID devices and applications to exchange non-standardized HID data. Unlike input and output reports, the application does not receive or send feature reports on a regular basis.

To send a function report to an HID device, pass the 8-bit report ID associated with the function report (reportId) and bytes like BufferSource (data) to
device.sendFeatureReport (). The returned promise is resolved after the report has been sent. If the HID device does not use reporting ID, configure reportId to 0.
The following example illustrates the use of feature reports by showing you how to order an Apple keyboard backlight device, open it, and make it blink.
const waitFor = duration => new Promise(r => setTimeout(r, duration));
const [device] = await navigator.hid.requestDevice({
filters: [{ vendorId: 0x05ac, usage: 0x0f, usagePage: 0xff00 }]
});
await device.open();
const reportId = 1;
for (let i = 0; i < 10; i++) {
await device.sendFeatureReport(reportId, Uint32Array.desde([0, 0]));
await waitFor(100);
await device.sendFeatureReport(reportId, Uint32Array.desde([512, 0]));
await waitFor(100);
}
To receive a function report from an HID device, pass the 8-bit report ID associated with the function report (reportId) to
device.receiveFeatureReport (). The returned promise is resolved with a
DataView objeto que contiene el contentsEl contenido puede ser muy difícil de definir con precisión. Es una definición que se refiere a las declaraciones contenidas en un documento o publicación de cualquier tipo y puede incluir las tecnologías de la información y la comunicación. Esto cubre todos los tipos de medios como imágenes y texto. A parte de esto, en el campo de la optimización de motores de búsqueda, los términos duplicar contenido, contenido único, plus del reporte de características. Si el dispositivo HID no usa ID de reporte, configure reportId to 0.
const dataView = await device.receiveFeatureReport( 1);
Hear the connection and disconnection
When the web portal has permission to enter an HID device, it can actively receive connection and disconnection events by listening "connect"
and "disconnect" events.
navigator.hid.addEventListener("connect", event => {
});navigator.hid.addEventListener("disconnect", event => {
});
Tips for developers
Debugging HID in Chrome is easy with the inner page, chrome://device-log
where you can see all events related to USB and HID devices in one place.

Population
Some demos of WebHID are listed at web.dev/hid-examples. Go take a look!
Security and privacy
The spec authors have designed and implemented the WebHID API using the basic principles defined in Control access to powerful features of the web platform, including user control, transparency and ergonomics. The ability to use this API is primarily controlled by a permissions model that grants access to only one HID device at a time. In response to a user message, the user must take active steps to choose a particular HID device.
For safety trade-offs, see the Security and privacy considerations section of the WebHID specification.
Apart from this, Chrome inspects the usage of each top-level collection and if a top-level collection has protected usage (.eg generic keyboard, mouse), then a web portal will not be able to send or receive any defined reports. in that collection. The full list of protected uses is publicly available.
Note that security-sensitive HID devices (such as FIDO HID devices used for stronger authentication) are also blocked in Chrome. Watch the block list proceedings.
Feedback
The Chrome team would love to hear your thoughts and experiences with the WebHID API.
Tell us about the API design
Could there be something in the API not working as expected? Or are you missing methods or properties that you require to implement your idea?
Present a specification hurdle in the WebHID API GitHub repository or add your thoughts to an existing obstacle.
Report an obstacle with the implementation
Did you find a bug with the Chrome implementation? Or is the implementation different from the specification?
File a bug in https://new.crbug.com. Be sure to include as much detail as you can, provide simple instructions for reproducing the bug, and
Components adjusted to Blink> HID. Failure works great for quick and easy sharing of reps.
Show support
Thinking of using the WebHID API? Your public support helps the Chrome team prioritize features and shows other browser vendors how important it is to support them.
Send a tweetUn tweet es un mensaje corto que puede ser enviado por medio de del servicio de microblogging Twitter. ¿Qué es un tweet? Un tweet es un mensaje de estado en Twitter que puede tener hasta 280 caracteres. Los tweets solían limitarse a 140 caracteres, pero esta cantidad se incrementó a 280 en septiembre de 2017. Debido al espacio limitado para el texto, las URLs para uso en tweets son normalmente plus to @Cromodev with #WebHID and let us know where and how you are using it.
Useful Links
Thanks
Thanks to Matt reynolds and Joe medley por sus reseñas de este postConcepto de Post¿Qué es un Post?Un Post es todo aquel contenido, sea post, opinión, noticia u otro género, que un autor publica en un blog. Este puede ser de carácter corporativo o meramente ocioso; pero siempre tiene como meta arrojar información o reflejar una idea, al mismo tiempo de facilitar que los usuarios encuentren la web donde se recoge por medio de de buscadores y demás plataformas online.Generalmente, se han plus. Hero image of Valentin Müller, red and blue nintendo switch picture of Sara kurfeß, and a black and silver laptop photo of Athul Cyriac Ajay on Unsplash.




