From 2c2df5ea01eb5cd8b9ea226b2869337e59c5fe3e Mon Sep 17 00:00:00 2001 From: Florian Merz Date: Thu, 11 Feb 2021 14:50:24 +0100 Subject: unslug pt-pt: move --- .../pt-pt/web/api/ambient_light_events/index.html | 70 + files/pt-pt/web/api/api_armazenamento/index.html | 128 - .../pt-pt/web/api/api_autenticacao_web/index.html | 149 - .../web/api/api_de_armazenamento_da_web/index.html | 156 - files/pt-pt/web/api/api_de_canvas/index.html | 247 -- .../web/api/api_de_canvas/tutorial/index.html | 60 - .../web/api/api_do_estado_da_bateria/index.html | 169 - .../index.html | 191 - .../web/api/api_transmissoes_multimedia/index.html | 211 - files/pt-pt/web/api/api_webrtc/index.html | 287 -- .../api/api_webrtc/tirar_fotografias/index.html | 222 -- files/pt-pt/web/api/battery_status_api/index.html | 169 + files/pt-pt/web/api/canvas_api/index.html | 247 ++ files/pt-pt/web/api/canvas_api/tutorial/index.html | 60 + files/pt-pt/web/api/document.dir/index.html | 71 - files/pt-pt/web/api/document/alinkcolor/index.html | 43 + files/pt-pt/web/api/document/bgcolor/index.html | 55 + files/pt-pt/web/api/document/cookie/index.html | 85 + files/pt-pt/web/api/document/dir/index.html | 71 + .../api/document/getelementsbyclassname/index.html | 69 + .../pt-pt/web/api/document_object_model/index.html | 501 +++ .../using_the_w3c_dom_level_1_core/index.html | 79 + files/pt-pt/web/api/element/clientleft/index.html | 47 + files/pt-pt/web/api/element/clienttop/index.html | 38 + files/pt-pt/web/api/element/index.html | 573 +++ .../web/api/eventos_de_luz_ambiente/index.html | 70 - .../api/file_and_directory_entries_api/index.html | 191 + files/pt-pt/web/api/filesystem/index.html | 54 + .../utilizacao_da_geolocalizacao/index.html | 242 -- files/pt-pt/web/api/geolocation_api/index.html | 242 ++ files/pt-pt/web/api/media_streams_api/index.html | 211 + files/pt-pt/web/api/metadados/index.html | 116 - files/pt-pt/web/api/metadata/index.html | 116 + .../eventos_online_e_offline/index.html | 97 - .../online_and_offline_events/index.html | 97 + files/pt-pt/web/api/node/appendchild/index.html | 31 + files/pt-pt/web/api/node/clonenode/index.html | 55 + files/pt-pt/web/api/node/insertbefore/index.html | 60 + .../using_the_notifications_api/index.html | 289 ++ .../index.html" | 289 -- files/pt-pt/web/api/selection/index.html | 76 + .../pt-pt/web/api/sistema_de_ficheiros/index.html | 54 - files/pt-pt/web/api/storage_api/index.html | 128 + .../web_audio_api/using_web_audio_api/index.html | 259 ++ .../utilizar_api_audio_web/index.html | 259 -- .../web/api/web_authentication_api/index.html | 149 + files/pt-pt/web/api/web_storage_api/index.html | 108 + .../web_workers_api/using_web_workers/index.html | 1091 ++++++ .../utilizacao_de_web_workers/index.html | 1091 ------ .../pt-pt/web/api/webgl_api/constantes/index.html | 4023 -------------------- files/pt-pt/web/api/webgl_api/constants/index.html | 4023 ++++++++++++++++++++ files/pt-pt/web/api/webgl_api/dados/index.html | 133 - files/pt-pt/web/api/webgl_api/data/index.html | 133 + files/pt-pt/web/api/webgl_api/tipos/index.html | 242 -- files/pt-pt/web/api/webgl_api/types/index.html | 242 ++ .../web/api/webgl_api/using_extensions/index.html | 718 ++++ .../utilizar_extens\303\265es/index.html" | 718 ---- files/pt-pt/web/api/webrtc_api/index.html | 287 ++ .../api/webrtc_api/taking_still_photos/index.html | 222 ++ .../index.html" | 180 - .../escrever_servidores_de_websocket/index.html | 257 -- .../escrever_um_servidor_websocket_em_c/index.html | 441 --- .../index.html | 220 -- .../writing_a_websocket_server_in_java/index.html | 220 ++ .../index.html | 180 + .../writing_websocket_server/index.html | 441 +++ .../writing_websocket_servers/index.html | 257 ++ .../pt-pt/web/api/window/barra_lateral/index.html | 60 - files/pt-pt/web/api/window/sidebar/index.html | 60 + 69 files changed, 12047 insertions(+), 10383 deletions(-) create mode 100644 files/pt-pt/web/api/ambient_light_events/index.html delete mode 100644 files/pt-pt/web/api/api_armazenamento/index.html delete mode 100644 files/pt-pt/web/api/api_autenticacao_web/index.html delete mode 100644 files/pt-pt/web/api/api_de_armazenamento_da_web/index.html delete mode 100644 files/pt-pt/web/api/api_de_canvas/index.html delete mode 100644 files/pt-pt/web/api/api_de_canvas/tutorial/index.html delete mode 100644 files/pt-pt/web/api/api_do_estado_da_bateria/index.html delete mode 100644 files/pt-pt/web/api/api_entradas_de_diretoria_e_ficheiro/index.html delete mode 100644 files/pt-pt/web/api/api_transmissoes_multimedia/index.html delete mode 100644 files/pt-pt/web/api/api_webrtc/index.html delete mode 100644 files/pt-pt/web/api/api_webrtc/tirar_fotografias/index.html create mode 100644 files/pt-pt/web/api/battery_status_api/index.html create mode 100644 files/pt-pt/web/api/canvas_api/index.html create mode 100644 files/pt-pt/web/api/canvas_api/tutorial/index.html delete mode 100644 files/pt-pt/web/api/document.dir/index.html create mode 100644 files/pt-pt/web/api/document/alinkcolor/index.html create mode 100644 files/pt-pt/web/api/document/bgcolor/index.html create mode 100644 files/pt-pt/web/api/document/cookie/index.html create mode 100644 files/pt-pt/web/api/document/dir/index.html create mode 100644 files/pt-pt/web/api/document/getelementsbyclassname/index.html create mode 100644 files/pt-pt/web/api/document_object_model/index.html create mode 100644 files/pt-pt/web/api/document_object_model/using_the_w3c_dom_level_1_core/index.html create mode 100644 files/pt-pt/web/api/element/clientleft/index.html create mode 100644 files/pt-pt/web/api/element/clienttop/index.html create mode 100644 files/pt-pt/web/api/element/index.html delete mode 100644 files/pt-pt/web/api/eventos_de_luz_ambiente/index.html create mode 100644 files/pt-pt/web/api/file_and_directory_entries_api/index.html create mode 100644 files/pt-pt/web/api/filesystem/index.html delete mode 100644 files/pt-pt/web/api/geolocation/utilizacao_da_geolocalizacao/index.html create mode 100644 files/pt-pt/web/api/geolocation_api/index.html create mode 100644 files/pt-pt/web/api/media_streams_api/index.html delete mode 100644 files/pt-pt/web/api/metadados/index.html create mode 100644 files/pt-pt/web/api/metadata/index.html delete mode 100644 files/pt-pt/web/api/navigatoronline/eventos_online_e_offline/index.html create mode 100644 files/pt-pt/web/api/navigatoronline/online_and_offline_events/index.html create mode 100644 files/pt-pt/web/api/node/appendchild/index.html create mode 100644 files/pt-pt/web/api/node/clonenode/index.html create mode 100644 files/pt-pt/web/api/node/insertbefore/index.html create mode 100644 files/pt-pt/web/api/notifications_api/using_the_notifications_api/index.html delete mode 100644 "files/pt-pt/web/api/notifications_api/utilizar_api_notifica\303\247\303\265es/index.html" create mode 100644 files/pt-pt/web/api/selection/index.html delete mode 100644 files/pt-pt/web/api/sistema_de_ficheiros/index.html create mode 100644 files/pt-pt/web/api/storage_api/index.html create mode 100644 files/pt-pt/web/api/web_audio_api/using_web_audio_api/index.html delete mode 100644 files/pt-pt/web/api/web_audio_api/utilizar_api_audio_web/index.html create mode 100644 files/pt-pt/web/api/web_authentication_api/index.html create mode 100644 files/pt-pt/web/api/web_storage_api/index.html create mode 100644 files/pt-pt/web/api/web_workers_api/using_web_workers/index.html delete mode 100644 files/pt-pt/web/api/web_workers_api/utilizacao_de_web_workers/index.html delete mode 100644 files/pt-pt/web/api/webgl_api/constantes/index.html create mode 100644 files/pt-pt/web/api/webgl_api/constants/index.html delete mode 100644 files/pt-pt/web/api/webgl_api/dados/index.html create mode 100644 files/pt-pt/web/api/webgl_api/data/index.html delete mode 100644 files/pt-pt/web/api/webgl_api/tipos/index.html create mode 100644 files/pt-pt/web/api/webgl_api/types/index.html create mode 100644 files/pt-pt/web/api/webgl_api/using_extensions/index.html delete mode 100644 "files/pt-pt/web/api/webgl_api/utilizar_extens\303\265es/index.html" create mode 100644 files/pt-pt/web/api/webrtc_api/index.html create mode 100644 files/pt-pt/web/api/webrtc_api/taking_still_photos/index.html delete mode 100644 "files/pt-pt/web/api/websockets_api/escrever_aplica\303\247\303\243o_cliente_de_websocket/index.html" delete mode 100644 files/pt-pt/web/api/websockets_api/escrever_servidores_de_websocket/index.html delete mode 100644 files/pt-pt/web/api/websockets_api/escrever_um_servidor_websocket_em_c/index.html delete mode 100644 files/pt-pt/web/api/websockets_api/escrever_um_servidor_websocket_em_java/index.html create mode 100644 files/pt-pt/web/api/websockets_api/writing_a_websocket_server_in_java/index.html create mode 100644 files/pt-pt/web/api/websockets_api/writing_websocket_client_applications/index.html create mode 100644 files/pt-pt/web/api/websockets_api/writing_websocket_server/index.html create mode 100644 files/pt-pt/web/api/websockets_api/writing_websocket_servers/index.html delete mode 100644 files/pt-pt/web/api/window/barra_lateral/index.html create mode 100644 files/pt-pt/web/api/window/sidebar/index.html (limited to 'files/pt-pt/web/api') diff --git a/files/pt-pt/web/api/ambient_light_events/index.html b/files/pt-pt/web/api/ambient_light_events/index.html new file mode 100644 index 0000000000..32b15a8ea1 --- /dev/null +++ b/files/pt-pt/web/api/ambient_light_events/index.html @@ -0,0 +1,70 @@ +--- +title: Eventos de Luz Ambiente +slug: Web/API/Eventos_de_Luz_Ambiente +tags: + - Luz Ambiente +translation_of: Web/API/Ambient_Light_Events +--- +
{{DefaultAPISidebar("Ambient Light Events")}}{{SeeCompatTable}}
+ +

Os eventos de luz ambiente são uma maneira prática de tornar uma página da Web ou um aplicação ciente de qualquer alteração na intensidade da luz. Isto permite-lhes reagir a essa alteração, por exemplo, alterando o contraste da cor da interface do utilizador (IU) ou alterando a exposição necessária para tirar uma fotografia.

+ +

Eventos de Luz

+ +

When the light sensor of a device detects a change in the light level, it notifies the browser of that change. When the browser gets such a notification, it fires a {{domxref("DeviceLightEvent")}} event that provides information about the exact light intensity.

+ +

This event can be captured at the window object level by using the {{domxref("EventTarget.addEventListener","addEventListener")}} method (using the {{event("devicelight")}} event name) or by attaching an event handler to the {{domxref("window.ondevicelight")}} property.

+ +

Once captured, the event object gives access to the light intensity expressed in lux through the {{domxref("DeviceLightEvent.value")}} property.

+ +

Exemplo

+ +
if ('ondevicelight' in window) {
+  window.addEventListener('devicelight', function(event) {
+    var body = document.querySelector('body');
+    if (event.value < 50) {
+      body.classList.add('darklight');
+      body.classList.remove('brightlight');
+    } else {
+      body.classList.add('brightlight');
+      body.classList.remove('darklight');
+    }
+  });
+} else {
+  console.log('devicelight event not supported');
+}
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName("AmbientLight", "", "Ambient Light Events")}}{{Spec2("AmbientLight")}}Initial definition
+ +

Compatibilidade de navegador

+ + + +

{{Compat("api.DeviceLightEvent")}}

+ +

 

+ +

Consultar também

+ + diff --git a/files/pt-pt/web/api/api_armazenamento/index.html b/files/pt-pt/web/api/api_armazenamento/index.html deleted file mode 100644 index 434cee963d..0000000000 --- a/files/pt-pt/web/api/api_armazenamento/index.html +++ /dev/null @@ -1,128 +0,0 @@ ---- -title: API de armazenamento -slug: Web/API/API_armazenamento -tags: - - API - - API de armazenamento - - Armazenamento - - Contextod e segurança - - Quotas - - Referencia - - Resumo - - Sinopse - - Utilização -translation_of: Web/API/Storage_API ---- -

{{securecontext_header}}{{DefaultAPISidebar("Storage")}}

- -

The Storage Standard defines a common, shared storage system to be used by all APIs and technologies that store content-accessible data for individual Web sites. The Storage API gives sites' code the ability to find out how much space they can use, how much they are already using, and even control whether or not they need to be alerted before the {{Glossary("user agent")}} disposes of site data in order to make room for other things.

- -

{{AvailableInWorkers}}

- -

Site storage—the data stored for a Web site which is managed by the Storage Standard—includes:

- - - -

Unidades de armazenamento de site

- -

The site storage system described by the Storage Standard and interacted with using the Storage API consists of a single site storage unit for each {{Glossary("origin")}}. In essence, every Web site or Web application has its own storage unit into which its data gets placed. The diagram below shows a site storage pool with three storage units within, showing how storage units can have different data types stored within and may have different quotas (maximum storage limits).

- -

A diagram showing how the site storage pool consists of multiple storage units that contain data from various APIs as well as possible unused space left before the quota is reached.

- - - -

{{Glossary("User agent", "User agents")}} are likely to use various techniques to determine the quota for various origins. One of the most likely methods—one which the specification specifically encourages, in fact—would be to consider the popularity and/or usage levels of individual sites to determine what their quotas should be.  It's also conceivable that the browser might offer a user interface to customize these quotas.

- -

Modos de caixa (Box)

- -

The actual data storage within each site storage unit is called its box. Each site storage unit has exactly one box into which all of its data is placed, and has a box mode that describes the data retention policy for that box. There are two modes:

- -
-
"best-effort"
-
The user agent will try to retain the data contained in the box for as long as it can, but will not warn users if storage space runs low and it becomes necessary to clear the box in order to relieve the storage pressure.
-
"persistent"
-
The user agent will retain the data as long as possible, clearing all "best-effort" boxes before considering clearing a box marked "persistent". If it becomes necessary to consider clearing persistent boxes, the user agent will notify the user and provide a way to clear one or more persistent boxes as needed.
-
- -

To change an origin's box mode requires permission to use the "persistent-storage" feature.

- -

Persistência de dados e limpeza

- -

If the site or app has the "persistent-storage" feature permission, it can use the {{domxref("StorageManager.persist()")}} method to request that its box be made persistent. It's also possible for the user agent to decide to make the site's storage unit persistent due to usage characteristics or other metrics. The "persistent-storage" feature's permission-related flags, algorithms, and types are all set to the standard defaults for a permission, except that the permission state must be the same across the entire origin, and that if the permission state isn't "granted" (meaning that for whatever reason, access to the persistent storage feature was denied), the origin's site storage unit's box mode is always "best-effort".

- -
-

Nota: Consulte Using the Permissions API para mais detalhes sobre como obter e gerir as permissões.

-
- -

When clearing site storage units, an origin's box is treated as a single entity; if the user agent needs to clear it and the user approves, the entire data store is cleared rather than providing some means of clearing only data from individual APIs.

- -

If a box is marked as "persistent", the contents won't be cleared by the user agent without either the data's origin itself or the user specifically doing so. This includes scenarios such as the user selecting a "Clear Caches" or "Clear Recent History" option. The user will be asked specifically for permission to remove persistent site storage units.

- -

Quotas e estimativas de utilização

- -

The user agent determines, using whatever mechanism it chooses, the maximum amount of storage a given site can use. This maximum is the origin's quota. The amount of this space which is in use by the site is called its usage. Both of these values are estimates; there are several reasons why they're not precise:

- - - -

User agents may use any method they choose to determine the size of origins' quotas, and are encouraged by the specification to provide popular or frequently-used sites with extra space.

- -

To determine the estimated quota and usage values for a given origin, use the {{domxref("StorageManager.estimate", "navigator.storage.estimate()")}} method, which returns a promise that, when resolved, receives a {{domxref("StorageEstimate")}} that contains these figures. For example:

- -
navigator.storage.estimate().then(estimate => {
-  // estimate.quota is the estimated quota
-  // estimate.usage is the estimated number of bytes used
-});
- -

Especificações

- - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('Storage')}}{{Spec2('Storage')}}Definição inicial.
- -

Compatibilidade de navegador

- -
-

StorageManager

- -
- - -

{{Compat("api.StorageManager")}}

-
-
- -

Consultar também

- - diff --git a/files/pt-pt/web/api/api_autenticacao_web/index.html b/files/pt-pt/web/api/api_autenticacao_web/index.html deleted file mode 100644 index ecc97dd5c0..0000000000 --- a/files/pt-pt/web/api/api_autenticacao_web/index.html +++ /dev/null @@ -1,149 +0,0 @@ ---- -title: APi de Autenticação da Web -slug: Web/API/API_Autenticacao_Web -tags: - - API - - API de Autenticação da Web - - Landing - - Referencia -translation_of: Web/API/Web_Authentication_API ---- -
{{draft}}{{SeeCompatTable}}{{securecontext_header}}{{DefaultAPISidebar("Web Authentication API")}}
- -

A "API de Autenticação da Web" é uma extensão de Credential Management API que permite uma autenticação forte com a criptografia de chave pública, permitindo a autenticação sem palavra-passe e/ou autenticação de segundo fator segura sem textos de SMS.

- -

Conceitos e utilização da autenticação da Web

- -

The Web Authtentication API (also referred to as WebAuthn) uses asymmetric (public-key) cryptography instead of passwords or SMS texts for registering, authenticating, and second-factor authentication with websites. This resolves significant security problems related to phishing, data breaches, and attacks against SMS texts or other second-factor authentication methods while at the same time significantly increasing ease of use (since users don't have to manage dozens of increasingly complicated passwords).

- -

Many websites already have pages that allow users to register new accounts or sign in to an existing account, and WebAuthn acts as a replacement or suppliment to those on those existing webpages. Similar to the other forms of the Credential Management API, the Web Authentication API has two basic methods that correspond to register and login:

- - - -

Por favor, note: both create() and get() require a Secure Context (e.g. - the server is connected by https or is the localhost), and will not be available for use if the browser is not operating in a secure context.

- -

In their most basic forms, both create() and get() receive a very large random number called a challenge from the server and they return the challenge signed by the private key back to the server. This proves to the server that a user is in possession of the private key required for authentication without revealing any secrets over the network.

- -

In order to understand how the create() and get() methods fit into the bigger picture, it is important to understand that they sit between two components that are outside the browser:

- -
    -
  1. Servidor - the WebAuthn API is intended to register new credentials on a server (also referred to as a service or a relying party) and later use those same credentials on that same server to authenticate a user.
  2. -
  3. Autenticador - the credentials are created and stored in a device called an authenticator. This is a new concept in authentication: when authenticating using passwords, the password is stored in a user's brain and no other device is needed; when authenticating using WebAuthn, the password is replaced with a key pair that is stored in an authenticator. The authenticator may be embedded into an operating system, such as Windows Hello, or may be a physical token, such as a USB or Bluetooth Security Key.
  4. -
- -

Registo

- -

A typical registration process has six steps, as illustrated in Figure 1 and described further below. This is a simplification of the data required for the registration process that is only intended to provide an overview. The full set of required fields, optional fields, and their meanings for creating a registration request can be found in the {{domxref("PublicKeyCredentialCreationOptions")}} dictionary. Likewise, the full set of response fields can be found in the {{domxref("PublicKeyCredential")}} interface (where {{domxref("PublicKeyCredential.response")}} is the {{domxref("AuthenticatorAttestationResponse")}} interface). Note most JavaScript programmers that are creating an application will only really care about steps 1 and 5 where the create() function is called and subsequently returns; however, steps 2, 3, and 4 are essential to understanding the processing that takes place in the browser and authenticator and what the resulting data means.

- -

WebAuthn registration component and dataflow diagram

- -

Figura 1 - a diagram showing the sequence of actions for a WebAuthn registration and the essential data associated with each action.

- -

Os passos de registo são:

- -
    -
  1. Registo de Pedidos da Aplicação - The application makes the initial registration request. The protocol and format of this request is outside of the scope of WebAuthn.
  2. -
  3. Servidor Envia Desafio, Informação do Utilziador, e Envio de Informação de Confiança - The server sends a challenge, user information, and relying party information to the JavaScript program. The protocol for communicating with the server is not specified and is outside of the scope of WebAuthn. Typically, server communications would be REST over https (probably using XMLHttpRequest or Fetch), but they could also be SOAP, RFC 2549 or nearly any other protocol provided that the protocol is secure. The parameters received from the server will be passed to the create() call, typically with little or no modification and returns a Promise that will resolve to a {{domxref("PublicKeyCredential")}} containing an {{domxref("AuthenticatorAttestationResponse")}}. Note that it is absolutely critical that the challenge be a large buffer of random information (e.g. - more than 100 bytes) and it MUST be generated on the server in order to ensure the security of the registration process.
  4. -
  5. Navegador Chama o authenticatorMakeCredential() no Autenticador - Internally, the browser will validate the parameters and fill in any defaults, which become the {{domxref("AuthenticatorResponse.clientDataJSON")}}. One of the most important parameters is the origin, which recorded as part of the clientData so that the origin can be verified by the server later. The parameters to the create() call are passed to the authenticator, along with a SHA-256 hash of the clientDataJSON (only a hash is sent because the link to the authenticator may be a low-bandwidth NFC or Bluetooth link and the authenticator is just going to sign over the hash to ensure that it isn't tampered with).
  6. -
  7. Autenticador Cria Novo Par de Chave e Certificação - Before doing anything, the authenticator will typically ask for some form of user verficiation. This could be entering a PIN, using a fingerprint, doing an iris scan, etc. to prove that the user is present and consenting of the registration. After the user verification, the authenticator will create a new asymmetric key pair and safely store the private key for future reference. The public key will become part of the attestation, which the authtenticator will sign over with a private key that was burned into the authenticator during its manufacturing process and that has a certificate chain that can be validated back to a root of trust.
  8. -
  9. Autenticador Devolve os Dados para o Navegador - The new public key, a globally unique credential id, and other attestation data are returned to the browser where they become the attestationObject.
  10. -
  11. Navegador Cria os Dados Finais, a Aplicação envia a resposta para o Servidor - The create() Promise resolves to an {{domxref("PublicKeyCredential")}}, which has a {{domxref("PublicKeyCredential.rawId")}} that is the globally unique credential id along with a response that is the {{domxref("AuthenticatorAttestationResponse")}} containing the {{domxref("AuthenticatorResponse.clientDataJSON")}} and {{domxref("AuthenticatorAttestationResponse.attestationObject")}}. The {{domxref("PublicKeyCredential")}} is sent back to the server using any desired formatting and protocol (note that the ArrayBuffer properties need to be be base64 encoded or similar).
  12. -
  13. Servidor Valida e Finaliza o Registo - Finally, the server is required to perform a series of checks to ensure that the registration was complete and not tampered with. These include: -
      -
    1. Verifying that the challenge is the same as the challenge that was sent
    2. -
    3. Ensuring that the origin was the origin expected
    4. -
    5. Validating that the signature over the clientDataHash and the attestation using the certificate chain for that specific model of authenticator
    6. -
    - A complete list of validation steps can be found in the WebAuthn specification. Assuming that the checks pan out, the server will store the new public key associated with the user's account for future use -- that is, whenever the user desires to use the public key for authentication.
  14. -
- -

Autenticação

- -

After a user has registered with WebAuthn, they can subsequently authenticate (a.k.a. - login or sign-in) with the service. The authentication flow looks similar to the registration flow, and the illustration of actions in Figure 2 may be recognizable as being similar to the illustration of registration actions in Figure 1. The primary differences between registration and authentication are that: 1) authentication doesn't require user or relying party information; and 2) authentication creates an assertion using the previously generated key pair for the service rather than creating an attestation with the key pair that was burned into the authenticator during manufacturing. Again, the discription of authentication below is a broad overview rather than getting into all the options and features of WebAuthn. The specific options for authenticating can be found in the {{domxref("PublicKeyCredentialRequestOptions")}} dictionary, and the resulting data can be found in the {{domxref("PublicKeyCredential")}} interface (where {{domxref("PublicKeyCredential.response")}} is the {{domxref("AuthenticatorAssertionResponse")}} interface) .

- -

WebAuthn authentication component and dataflow diagram

- -

Figure 2 - similar to Figure 1, a diagram showing the sequence of actions for a WebAuthn authentication and the essential data associated with each action.

- -
    -
  1. Auyenticação dos Pedidos da Aplicação - The application makes the initial authentication request. The protocol and format of this request is outside of the scope of WebAuthn.
  2. -
  3. Servidor Envia Desafio - The server sends a challenge JavaScript program. The protocol for communicating with the server is not specified and is outside of the scope of WebAuthn. Typically, server communications would be REST over https (probably using XMLHttpRequest or Fetch), but they could also be SOAP, RFC 2549 or nearly any other protocol provided that the protocol is secure. The parameters received from the server will be passed to the get() call, typically with little or no modification. Note that it is absolutely critical that the challenge be a large buffer of random information (e.g. - more than 100 bytes) and it MUST be generated on the server in order to ensure the security of the authentication process.
  4. -
  5. Navegador Chama o authenticatorGetCredential()  no Autenticador - Internally, the browser will validate the parameters and fill in any defaults, which become the {{domxref("AuthenticatorResponse.clientDataJSON")}}. One of the most important parameters is the origin, which recorded as part of the clientData so that the origin can be verified by the server later. The parameters to the create() call are passed to the authenticator, along with a SHA-256 hash of the clientDataJSON (only a hash is sent because the link to the authenticator may be a low-bandwidth NFC or Bluetooth link and the authenticator is just going to sign over the hash to ensure that it isn't tampered with).
  6. -
  7. Autenticador Cria uma Certificação  - The authenticator finds a credential for this service that matches the Relying Party ID and prompts a user to consent to the authentication. Assuming both of those steps are successful, the authenticator will create a new assertion by signing over the clientDataHash and authenticatorData with the private key generated for this account during the registration call.
  8. -
  9. Autenticador Devolve os Dados para o Navegador -  The authenticator returns the authenticatorData and assertion signature back to the browser.
  10. -
  11. Navegador Cria os Dados Finais, a Aplicação envia a resposta para o Servidor - The browser resolves the Promise to a {{domxref("PublicKeyCredential")}} with a {{domxref("PublicKeyCredential.response")}} that contains the {{domxref("AuthenticatorAssertionResponse")}}. It is up to the JavaScript application to transmit this data back to the server using any protocol and format of its choice.
  12. -
  13. Servidor Valida e Finaliza a Autenticação - Upon receiving the result of the authentication request, the server performs validation of the response such as: -
      -
    1. Using the public key that was stored during the registration request to validate the signature by the authenticator.
    2. -
    3. Ensuring that the challenge that was signed by the authenticator matches the challenge that was generated by the server.
    4. -
    5. Checking that the Relying Party ID is the one expected for this service.
    6. -
    - A full list of the steps for validating an assertion can be found in the WebAuthn specification. Assuming the validation is successful, the server will note that the user is now authenticated. This is outside the scope of the WebAuthn specification, but one option would be to drop a new cookie for the user session.
  14. -
- -

Interfaces

- -
-
{{domxref("CredentialsContainer")}}
-
WebAuthn extends the Credential Management API's create() and get() methods to take a new option: publicKey. When the publicKey option is passed to create() and / or get(), the Credential Management API will create a new public key pair or get an authentication for a key pair, respectively.
-
{{domxref("PublicKeyCredential")}}
-
A credential for logging in to a service using an un-phishable and data-breach resistant asymmetric key pair instead of a password.
-
{{domxref("AuthenticatorResponse")}}
-
Part of the PublicKeyCredential, the AuthenticatorResponse includes information from the browser (such as the challenge and origin); as well as information from the authenticator such as an AuthenticatorAttestationResponse (for new credentials) or an AuthenticatorAssertionResponse (when authenticating with existing credentials).
-
{{domxref("AuthenticatorAttestationResponse")}}
-
When a PublicKeyCredential has been created with the create() call, it will include an AuthenticatorAttestationResponse. This is the authenticator's way of providing a cryptographic root of trust for the new key pair that has been generated.
-
{{domxref("AuthenticatorAssertionResponse")}}
-
When a PublicKeyCredential is the result of a get() call, it will include an AuthenticatorAssertionResponse. This is the authenticator's way of proving to a service that it has the key pair and that the authentication request is valid and approved.
-
- -

Opções

- -
-
{{domxref("PublicKeyCredentialCreationOptions")}}
-
The options for creating a credential via navigator.credentials.create()
-
{{domxref("PublicKeyCredentialRequestOptions")}}
-
The options for using a credential via navigator.credentials.get()
-
- -

Exemplos

- - - -

Especificações

- - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('WebAuthn')}}{{Spec2('WebAuthn')}}Definção inicial.
- -

Compatibilidade do Navegador

- -
-
- - -

{{Compat("api.PublicKeyCredential")}}

-
-
- -

Consulte também:

- - diff --git a/files/pt-pt/web/api/api_de_armazenamento_da_web/index.html b/files/pt-pt/web/api/api_de_armazenamento_da_web/index.html deleted file mode 100644 index 192a51ee66..0000000000 --- a/files/pt-pt/web/api/api_de_armazenamento_da_web/index.html +++ /dev/null @@ -1,156 +0,0 @@ ---- -title: API de Armazenamento da Web -slug: Web/API/API_de_Armazenamento_da_Web -tags: - - API - - Armazenamento - - Armazenamento Local - - Armazenamento da Sessão - - Armazenamento da Web - - Referencia -translation_of: Web/API/Web_Storage_API ---- -

{{DefaultAPISidebar("Web Storage API")}}

- -

A API de Armazenamento da Web fornece mecanismos pelos quais os navegadores podem armazenar pares chave/valor, de uma maneira muito mais intuitiva do que utilizar cookies.

- -

Armazenamento da Web - conceitos e utilização

- -

The two mechanisms within Web Storage are as follows:

- - - -

These mechanisms are available via the {{domxref("Window.sessionStorage")}} and {{domxref("Window.localStorage")}} properties (to be more precise, in supporting browsers the Window object implements the WindowLocalStorage and WindowSessionStorage objects, which the localStorage and sessionStorage properties hang off) — invoking one of these will create an instance of the {{domxref("Storage")}} object, through which data items can be set, retrieved and removed. A different Storage object is used for the sessionStorage and localStorage for each origin — they function and are controlled separately.

- -
-

Nota: From Firefox 45 onwards, when the browser crashes/restarts, the amount of data saved per origin is limited to 10MB. This has been done to avoid memory issues caused by excessive usage of web storage.

-
- -
-

Nota: Access to Web Storage from third-party IFrames is denied if the user has disabled third-party cookies (Firefox implements this behaviour from version 43 onwards.)

-
- -
-

Nota: Web Storage is not the same as mozStorage (Mozilla's XPCOM interfaces to SQLite) or the Session store API (an XPCOM storage utility for use by extensions).

-
- -

Armazenamento da Web - Interfaces

- -
-
{{domxref("Storage")}}
-
Allows you to set, retrieve and remove data for a specific domain and storage type (session or local.)
-
{{domxref("Window")}}
-
The Web Storage API extends the {{domxref("Window")}} object with two new properties — {{domxref("Window.sessionStorage")}} and {{domxref("Window.localStorage")}} — which provide access to the current domain's session and local {{domxref("Storage")}} objects respectively, and a {{domxref("Window.onstorage")}} event handler that fires when a storage area changes (e.g. a new item is stored.)
-
{{domxref("StorageEvent")}}
-
The storage event is fired on a document's Window object when a storage area changes.
-
- -

Exemplos

- -

To illustrate some typical web storage usage, we have created a simple example, imaginatively called Web Storage Demo. The landing page provides controls that can be used to customize the colour, font and decorative image. When you choose different options, the page is instantly updated; in addition your choices are stored in localStorage,  so that when you leave the page then load it again later on your choices are remembered.

- -

In addition, we have provided an event output page — if you load this page in another tab, then make changes to your choices in the landing page, you'll see the updated storage information outputted as the {{domxref("StorageEvent")}} is fired.

- -

Especificações

- - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', 'webstorage.html#webstorage')}}{{Spec2('HTML WHATWG')}} 
- -

Compatibilidade de navegador

- -

{{ CompatibilityTable() }}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Armazenamento local4{{CompatVersionUnknown}}3.5810.504
Armazenamento da sessão5{{CompatVersionUnknown}}2810.504
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico2.1{{CompatVersionUnknown}}{{ CompatUnknown }}811iOS 3.2
-
- -

All browsers have varying capacity levels for both localStorage and sessionStorage. Here is a detailed rundown of all the storage capacities for various browsers.

- -
-

Nota: since iOS 5.1, Safari Mobile stores localStorage data in the cache folder, which is subject to occasional clean up, at the behest of the OS, typically if space is short.

-
- -

Modos Incógnito / Navegação Privada

- -

Most modern browsers support a privacy option called 'Incognito', 'Private Browsing' or something similar that doesn't store data like history and cookies. This is fundamentally incompatible with Web Storage for obvious reasons. As such, browser vendors are experimenting with different scenarios for how to deal with this incompatibility.

- -

Most browsers have opted for a strategy where storage APIs are still available and seemingly fully functional, with the one big difference that all stored data is wiped after the browser is closed. For these browsers there are still different interpretations of what should be done with existing stored data (from a regular browsing session). Should it be available to read when in Private mode? Then there are some browsers, most notably Safari, that have opted for a solution where storage is available, but is empty and has a quota of 0 bytes assigned, effectively making it impossible to write data to it.

- -

Developers should be aware of these different implementations and take them into account when developing websites depending on Web Storage APIs. For more information please have a look at this WHATWG blog post that specifically deals with this topic.

- -

Consulte também

- - diff --git a/files/pt-pt/web/api/api_de_canvas/index.html b/files/pt-pt/web/api/api_de_canvas/index.html deleted file mode 100644 index 17971de4ee..0000000000 --- a/files/pt-pt/web/api/api_de_canvas/index.html +++ /dev/null @@ -1,247 +0,0 @@ ---- -title: API de Canvas -slug: Web/API/API_de_canvas -translation_of: Web/API/Canvas_API ---- -
{{CanvasSidebar}}
- -

Added in HTML5, the HTML {{HTMLElement("canvas")}} element can be used to draw graphics via scripting in JavaScript. For example, it can be used to draw graphs, make photo compositions, create animations, or even do real-time video processing or rendering.

- -

Mozilla applications gained support for <canvas> starting with Gecko 1.8 (i.e. Firefox 1.5). The element was originally introduced by Apple for the OS X Dashboard and Safari. Internet Explorer supports <canvas> from version 9 onwards; for earlier versions of IE, a page can effectively add support for <canvas> by including a script from Google's Explorer Canvas project. Google Chrome and Opera 9 also support <canvas>.

- -

The <canvas> element is also used by WebGL to draw hardware-accelerated 3D graphics on web pages.

- -

Exemplo

- -

This is just a simple code snippet which uses the {{domxref("CanvasRenderingContext2D.fillRect()")}} method.

- -

HTML

- -
<canvas id="canvas"></canvas>
-
- -

JavaScript

- -
var canvas = document.getElementById('canvas');
-var ctx = canvas.getContext('2d');
-
-ctx.fillStyle = 'green';
-ctx.fillRect(10, 10, 100, 100);
-
- -

Edit the code below and see your changes update live in the canvas:

- - - -

{{ EmbedLiveSample('Playable_code', 700, 360) }}

- -

Referência

- -
- -
- -

The interfaces related to the WebGLRenderingContext are referenced under WebGL.

- -

{{domxref("CanvasCaptureMediaStream")}} is related.

- -

Guias e tutoriais

- -
-
Canvas tutorial
-
A comprehensive tutorial covering both the basic usage of <canvas> and its advanced features.
-
Code snippets: Canvas
-
Some extension developer-oriented code snippets involving <canvas>.
-
Demo: A basic ray-caster
-
A demo of ray-tracing animation using canvas.
-
Drawing DOM objects into a canvas
-
How to draw DOM content, such as HTML elements, into a canvas.
-
Manipulating video using canvas
-
Combining {{HTMLElement("video")}} and {{HTMLElement("canvas")}} to manipulate video data in real time.
-
- -

Recursos

- -

Genérico

- - - -

Bibliotecas

- - - -

Especificações

- - - - - - - - - - - - - - - - -
EpecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', 'scripting.html#the-canvas-element', '<canvas>')}}{{Spec2('HTML WHATWG')}} 
- -

Consulte também

- - - -
- - - - - -
diff --git a/files/pt-pt/web/api/api_de_canvas/tutorial/index.html b/files/pt-pt/web/api/api_de_canvas/tutorial/index.html deleted file mode 100644 index b93457336d..0000000000 --- a/files/pt-pt/web/api/api_de_canvas/tutorial/index.html +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: Tutorial de Canvas -slug: Web/API/API_de_canvas/Tutorial -tags: - - Canvas - - Guía - - HTML - - HTML5 - - Intermediário - - Web - - graficos -translation_of: Web/API/Canvas_API/Tutorial ---- -
{{CanvasSidebar}}
- -
- -
-

<canvas> is an HTML element which can be used to draw graphics via scripting (usually JavaScript). This can, for instance, be used to draw graphs, make photo composition or simple (and not so simple) animations. The images on this page show examples of <canvas> implementations which will be created in this tutorial.

-
- -

This tutorial describes how to use the <canvas> element to draw 2D graphics, starting with the basics. The examples provided should give you some clear ideas what you can do with canvas and will provide code snippets that may get you started in building your own content.

- -

First introduced in WebKit by Apple for the OS X Dashboard, <canvas> has since been implemented in browsers. Today, all major browsers support it.

- -

Antes de começar

- -

Using the <canvas> element is not very difficult, but you do need a basic understanding of HTML and JavaScript. The <canvas> element is not supported in some older browsers, but is supported in recent versions of all major browsers. The default size of the canvas is 300 px × 150 px (width × height). But custom sizes can be defined using the HTML height and width property. In order to draw graphics on the canvas we use a JavaScript context object, which creates graphics on the fly.

- -

Neste tutorial

- - - -

Consulte também:

- - - -

Uma nota para os colaboradores

- -

Due to an unfortunate technical error that occurred the week of June 17, 2013, we lost the history of this tutorial, including attributions to all past contributors to its content. We apologize for this, and hope you'll forgive this unfortunate mishap.

- -
{{ Next("Web/API/Canvas_API/Tutorial/Basic_usage") }}
diff --git a/files/pt-pt/web/api/api_do_estado_da_bateria/index.html b/files/pt-pt/web/api/api_do_estado_da_bateria/index.html deleted file mode 100644 index 4805a71bc6..0000000000 --- a/files/pt-pt/web/api/api_do_estado_da_bateria/index.html +++ /dev/null @@ -1,169 +0,0 @@ ---- -title: API do Estado da Bateria -slug: Web/API/API_do_Estado_da_Bateria -tags: - - API - - API de Bateria - - API do Estado da Bateria - - Aplicações - - Apps - - Firefox OS - - Guía - - Movel - - Resumo - - Sinopse -translation_of: Web/API/Battery_Status_API ---- -
{{obsolete_header}}
- -
{{DefaultAPISidebar("Battery API")}}
- -

A API do Estado da Bateria, mais conhecida como API de Bateria, fornece informação sobre o nível de carga da bateria do sistema e permite-lhe que seja notificado por eventos que são enviados quando o nível da bateria ou o estado de carregamento é alterado. Isto pode ser utilizado para ajustar a utilização de recursos da aplicação para reduzir o consumo de bateria quando a bateria estiver fraca ou para guardar as alterações antes que a bateria acabe para evitar a perda de dados.

- -

The Battery Status API extends {{domxref("window.navigator")}} with a {{domxref("navigator.getBattery()")}} method returning a battery promise, which is resolved in a {{domxref("BatteryManager")}} object providing also some new events you can handle to monitor the battery status.

- -

Exemplo

- -

In this example, we watch for changes both to the charging status (whether or not we're plugged in and charging) and for changes to the battery level and timing. This is done by listening for the {{event("chargingchange")}}, {{event("levelchange")}}, {{event("chargingtimechange")}}, {{event("dischargingtimechange")}} events.

- -
navigator.getBattery().then(function(battery) {
-  function updateAllBatteryInfo(){
-    updateChargeInfo();
-    updateLevelInfo();
-    updateChargingInfo();
-    updateDischargingInfo();
-  }
-  updateAllBatteryInfo();
-
-  battery.addEventListener('chargingchange', function(){
-    updateChargeInfo();
-  });
-  function updateChargeInfo(){
-    console.log("Battery charging? "
-                + (battery.charging ? "Yes" : "No"));
-  }
-
-  battery.addEventListener('levelchange', function(){
-    updateLevelInfo();
-  });
-  function updateLevelInfo(){
-    console.log("Battery level: "
-                + battery.level * 100 + "%");
-  }
-
-  battery.addEventListener('chargingtimechange', function(){
-    updateChargingInfo();
-  });
-  function updateChargingInfo(){
-    console.log("Battery charging time: "
-                 + battery.chargingTime + " seconds");
-  }
-
-  battery.addEventListener('dischargingtimechange', function(){
-    updateDischargingInfo();
-  });
-  function updateDischargingInfo(){
-    console.log("Battery discharging time: "
-                 + battery.dischargingTime + " seconds");
-  }
-
-});
-
- -

See also the example in the specification.

- -

Especificações

- - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName("Battery API")}}{{Spec2("Battery API")}}Initial definition
- -

Compatibilidade do navegador

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(39.0)}}{{CompatGeckoDesktop("10")}} {{property_prefix("moz")}}
- {{CompatGeckoDesktop("16")}}[1]
- {{CompatGeckoDesktop("43")}}[3]
- {{CompatGeckoDesktop("52")}}[4]
{{CompatNo}}25{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(40.0)}} -

{{CompatGeckoMobile("10")}} {{property_prefix("moz")}}
- {{CompatGeckoMobile("16")}}[1]
- {{CompatGeckoMobile("43")}}[3]
- {{CompatGeckoMobile("52")}}[3]

-
{{CompatNo}}25[2]{{CompatNo}}{{CompatChrome(42.0)}}[2]
-
- -

[1] Disabled by default in Firefox 10.0, but can be enabled setting the preference dom.battery.enabled to true. Starting with Firefox 11.0, mozBattery is enabled by default. The Battery API is currently supported on Android, Windows, and Linux with UPower installed. Support for MacOS is available starting with Gecko 18.0 {{geckoRelease("18.0")}}. Firefox also provides support for the deprecated {{domxref("navigator.battery")}}.

- -

[2] Values for {{domxref("BatteryManager.chargingTime")}} and {{domxref("BatteryManager.dischargingTime")}} are always equal to Infinity.

- -

[3] The new promise-based syntax for {{domxref("Navigator.getBattery()")}} is supported from Firefox 43 onwards.

- -

[4] From Firefox 52 onwards, the Battery Status API is only available in chrome/privileged code.

- -

Consultar também

- - diff --git a/files/pt-pt/web/api/api_entradas_de_diretoria_e_ficheiro/index.html b/files/pt-pt/web/api/api_entradas_de_diretoria_e_ficheiro/index.html deleted file mode 100644 index 26e56945ee..0000000000 --- a/files/pt-pt/web/api/api_entradas_de_diretoria_e_ficheiro/index.html +++ /dev/null @@ -1,191 +0,0 @@ ---- -title: API Entradas de Diretoria e Ficheiro -slug: Web/API/API_Entradas_de_Diretoria_e_Ficheiro -tags: - - API - - API Entradas de Diretoria e Ficheiro - - API Sistema de Ficheiros - - Ficheiros - - Não Padrão - - Referencia - - Resuno - - Sinopse -translation_of: Web/API/File_and_Directory_Entries_API ---- -

{{DefaultAPISidebar("File System API")}}{{Non-standard_header}}

- -

API Entradas de Diretoria e Ficheiro simula um sistema de ficheiros local em que as páginas da Web podem navegar dentro e aceder aos ficheiros na mesma. Pode desenvolver aplicações que lêem, escrevem e criam ficheiros e/ou diretorias num sistema de ficheiros virtual e ambiente de testes (sandbox).

- -
-

Because this is a non-standard API, whose specification is not currently on a standards track, it's important to keep in mind that not all browsers implement it, and those that do may implement only small portions of it. Check the {{anch("Browser compatibility")}} section for details.

-
- -

Two very similar APIs exist depending on whether you desire asynchronous or synchronous behavior. The synchronous API is indended to be used inside a {{domxref("Worker")}} and will return the values you desire. The asynchronous API will not block and functions and the API will not return values; instead, you will need to supply a callback function to handle the response whenever it arrives.

- -
-

The Firefox implementation of the File and Directory Entries API is very limited; there is no support for creating files. Only for accessing files which are selected by the user in a file {{HTMLElement("input")}} element (see {{domxref("HTMLInputElement")}} as well) or when a file or directory is provided to the Web site or app using drag and drop. Firefox also does not implement the synchronous API. Check the browser compatibility for any part of the API you use carefully, and see File and Directory Entries API support in Firefox for more details.

-
- -

Obter acesso a um sistema de ficheiros

- -

There are two ways to get access to file systems defined in the current specification draft:

- - - -

API Assíncrona

- -

The asynchronous API should be used for most operations, to prevent file system accesses from blocking the entire browser if used on the main thread. It includes the following interfaces:

- -
-
{{domxref("FileSystem")}}
-
Represents a file system.
-
{{domxref("FileSystemEntry")}}
-
The basic interface representing a single entry in a file system. This is implemented by other interfaces which represent files or directories.
-
{{domxref("FileSystemFileEntry")}}
-
Represents a single file in a file system.
-
{{domxref("FileSystemDirectoryEntry")}}
-
Represents a single directory in a file system.
-
{{domxref("FileSystemDirectoryReader")}}
-
Created by calling {{domxref("FileSystemDirectoryEntry.createReader()")}}, this interface provides the functionality which lets you read the contents of a directory.
-
{{domxref("FileSystemFlags")}}
-
Defines a set of values which are used when specifying option flags when calling certain methods in the File and Directory Entries API.
-
{{domxref("FileError")}}
-
Represents an error which is generated by asynchronous file system calls.
-
- -

There are also two global functions (which are not part of the specification at this time and are implemented only by Google Chrome). They're available on the {{domxref("Window")}} object and implemented in {{domxref("LocalFileSystem")}}: requestFileSystem() and resolveLocalFileSystemURL().

- -

API Síncrona

- -

The synchronous API is should only be used in {{domxref("Worker")}}s; these calls block until they're finished executing, and simply return the results instead of using callbacks. Using them on the main thread will block the browser, which is naughty. The interfaces below otherwise mirror the ones from the asynchronous API.

- -
-
{{domxref("FileSystemSync")}}
-
Represents a file system.
-
{{domxref("FileSystemEntrySync")}}
-
The basic interface representing a single entry in a file system. This is implemented by other interfaces which represent files or directories. {{domxref("EntrySync")}}
-
{{domxref("FileSystemFileEntrySync")}}
-
Represents a single file in a file system.
-
{{domxref("FileSystemDirectoryEntrySync")}}
-
Represents a single directory in a file system.
-
{{domxref("FileSystemDirectoryReaderSync")}}
-
Created by calling {{domxref("FileSystemDirectoryEntrySync.createReader()")}}, this interface provides the functionality which lets you read the contents of a directory.
-
{{domxref("FileException")}}
-
Represents an error which is generated by synchronous file system calls.
-
- -

There are also two global functions (which are not part of the specification at this time and are implemented only by Google Chrome). They're available on the {{domxref("Worker")}} object and implemented in {{domxref("LocalFileSystemSync")}}: requestFileSystemSync() and resolveLocalFileSystemSyncURL().

- -

Outras Interfaces

- -
-
{{domxref("LocalFileSystem")}}
-
Gives you access to a sandboxed file system.
-
{{domxref("LocalFileSystemSync")}}
-
 
-
{{domxref("LockedFile")}}
-
Provides tools to deal with a given file with all the necessary locks.
-
{{domxref("Metadata")}}{{experimental_inline}}
-
- -

Especificações

- - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('File System API')}}{{Spec2('File System API')}}Draft of proposed API
- -

This API has no official W3C or WHATWG specification.

- -

Compatibilidade de navegador

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Asynchronous API13 {{ property_prefix("webkit") }}{{ CompatGeckoDesktop(50) }}[1]{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
Synchronous API13 {{ property_prefix("webkit") }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Asynchronous API{{ CompatNo }}{{ CompatVersionUnknown }} {{ property_prefix("webkit") }}{{ CompatGeckoMobile(50) }}[1]{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
Synchronous API{{ CompatNo }}{{ CompatVersionUnknown }} {{ property_prefix("webkit") }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
-
- -

[1] Firefox 50 introduces partial support for the File and Directory Entries API. Be sure to check the compatibility tables for individual interfaces and methods before using them, to ensure that they're supported, before you use them. The API can be disabled by setting the value of the preference dom.webkitBlink.filesystem.enabled to false.

- -

Consulte também

- - diff --git a/files/pt-pt/web/api/api_transmissoes_multimedia/index.html b/files/pt-pt/web/api/api_transmissoes_multimedia/index.html deleted file mode 100644 index 399945ab71..0000000000 --- a/files/pt-pt/web/api/api_transmissoes_multimedia/index.html +++ /dev/null @@ -1,211 +0,0 @@ ---- -title: API de Captura de Transmissões de Multimédia (Media Streams) -slug: Web/API/API_transmissoes_multimedia -tags: - - API - - API de Transmissão de Multimédia - - Audio - - Avançado - - Guía - - Introdução - - Media - - Multimedia - - Video -translation_of: Web/API/Media_Streams_API ---- -
{{DefaultAPISidebar("Media Capture and Streams")}}
- -

A API de Media Capture and Streams, muitas vezes chamada de Media Stream API ou Stream API, é uma API relacionada com WebRTC que suporta transmissões de dados de áudio ou vídeo, os métodos para trabalhar com eles, as restrições associadas com o tipo de dados, as devoluções de retorno de sucesso e erro quando utilizar os dados de forma assíncrona, e os eventos que foram ativados durante o processo.

- -

Conceitos básicos

- -

The API is based on the manipulation of a {{domxref("MediaStream")}} object representing a flux of audio- or video-related data. See an example in Get the video.

- -

A MediaStream consists of zero or more {{domxref("MediaStreamTrack")}} objects, representing various audio or video tracks. Each MediaStreamTrack may have one or more channels. The channel represents the smallest unit of a media stream, such as an audio signal associated with a given speaker, like left or right in a stereo audio track.

- -

MediaStream objects have a single input and a single output. A MediaStream object generated by {{domxref("MediaDevices.getUserMedia", "getUserMedia()")}} is called local, and has as its source input one of the user's cameras or microphones. A non-local MediaStream may be representing to a media element, like {{HTMLElement("video")}} or {{HTMLElement("audio")}}, a stream originating over the network, and obtained via the WebRTC {{domxref("RTCPeerConnection")}} API, or a stream created using the Web Audio API {{domxref("MediaStreamAudioSourceNode")}}.   The output of the MediaStream object is linked to a consumer. It can be a media elements, like {{HTMLElement("audio")}} or {{HTMLElement("video")}},  the WebRTC {{domxref("RTCPeerConnection")}} API or a Web Audio API {{domxref("MediaStreamAudioDestinationNode")}}.

- -

Referência

- -
- -
- -

Guias e tutoriais

- -

{{LandingPageListSubpages}}

- -

Compatibilidade de navegador

- -

{{ CompatibilityTable }} 

- -
- - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeChromeFirefox (Gecko)EdgeInternet ExplorerOpera Safari (WebKit)
Stream API 21{{ property_prefix("webkit") }} Nightly 18{{ property_prefix("moz") }} {{ CompatVersionUnknown }}{{ CompatUnknown }} 12{{ CompatUnknown }} 
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
API de emissão{{ CompatNo }} {{CompatVersionUnknown}}{{ CompatUnknown }}{{ CompatUnknown }} {{ CompatNo }} {{ CompatNo }} 
-
- -

 

- -

Currently using WebRTC for accessing the camera is supported in Chrome, Opera and Firefox Nightly 18. Enabling WebRTC in Firefox Nightly requires you to set a flag in the configuration:

- - - -

Consulte também

- - - -
- - - - - -
diff --git a/files/pt-pt/web/api/api_webrtc/index.html b/files/pt-pt/web/api/api_webrtc/index.html deleted file mode 100644 index 8e1b31898b..0000000000 --- a/files/pt-pt/web/api/api_webrtc/index.html +++ /dev/null @@ -1,287 +0,0 @@ ---- -title: API de WebRTC -slug: Web/API/API_WebRTC -tags: - - API - - API de WebRTC - - API de WebRTCÁudio - - Multimedia - - Rede - - Video - - WebRTC - - emissão - - transmissão -translation_of: Web/API/WebRTC_API ---- -
{{APIRef("WebRTC")}}
- -

WebRTC (Comunicações da Web em Tempo Real) é uma tecnologia que permite às aplicações e sites da Web capturar e opcionalmente transmitir multimédia de áudio e/ou vídeo, bem como trocar dados arbitrariamente entre navegadores sem a necessidade de um intermediário. O conjunto de normas que compreende WebRTC torna possível a partilha de dados e realizar teleconferência peer-to-peer, sem precisar que o utilizador instale plug-ins ou qualquer outro software de terceiros.

- -

WebRTC consiste em diversos protocolos e APIs inter-relacionadas que trabalham em conjunto para obter isto. A documentação que irá encontrar aqui irá ajudá-lo a compreender o essencial de WebRTC, como configurar e utilizar ligações de dados e multimédia, e muito mais.

- -

Conceitos e utilização de WebRTC

- -

O WebRTC atende múltiplos propósitos e se destaca consideravelmente com Media Capture e Streams API. Juntos, eles fornecem recursos multimídia poderosos para a Web, incluindo suporte para conferências de áudio e vídeo, troca de arquivos, gerenciamento de identidade e interface com sistemas telefônicos legados, enviando sinais  {{Glossary("DTMF")}} . As conexões entre pares podem ser feitas sem exigir drivers especiais ou plug-ins, e muitas vezes podem ser feitas sem nenhum servidor intermediário.

- -

As conexões entre dois pares são criadas usando - e representadas pela interface - {{domxref("RTCPeerConnection")}} . Uma vez que uma conexão foi estabelecida e aberta, os fluxos de mídia ({{domxref("MediaStream")}}s) e / ou canais de dados ({{domxref("RTCDataChannel")}}s) podem ser adicionados à conexão.

- -

Os fluxos de mídia podem ser constituídos de qualquer número de faixas de informações de mídia; As faixas, que são representadas por objetos com base na interface {{domxref("MediaStreamTrack")}} , podem conter um dos vários tipos de dados de mídia, incluindo áudio, vídeo e texto (como legendas ou nomes de capítulos) . A maioria dos fluxos consistem em pelo menos uma faixa de áudio e provavelmente também uma faixa de vídeo, e pode ser usados para enviar e receber mídia ao vivo ou informações de mídia armazenada (como um filme transmitido).

- -

Você também pode usar a conexão entre dois pares para trocar dados binários arbitrários usando a interface {{domxref("RTCDataChannel")}} . Isso pode ser usado para informações back-channel, troca de metadados, pacotes com status de jogos, transferências de arquivos ou mesmo como um canal primário para transferência de dados.

- -

Mais detalhes e links para guias relevantes e tutoriais necessários

- -

Interfaces de WebRTC

- -

Como a WebRTC fornece interfaces que trabalham juntas para realizar uma variedade de tarefas, dividimos as interfaces na lista abaixo por categoria. Veja a barra lateral para uma lista alfabética.

- -

Gestão e configuração de ligação

- -

Essas interfaces são usadas para configurar, abrir e gerenciar conexões WebRTC.

- -
-
{{domxref("RTCPeerConnection")}}
-
Representa uma conexão WebRTC entre o computador local e um ponto remoto. Ele é usado para lidar com transmissão eficiente de dados entre os dois pares.
-
{{domxref("RTCDataChannel")}}
-
Representa um canal de dados bidirecional entre dois pares de uma conexão.
-
{{domxref("RTCDataChannelEvent")}}
-
Representa eventos que ocorrem ao anexar um {{domxref("RTCDataChannel")}} a um {{domxref("RTCPeerConnection")}} . O único evento enviado com esta interface é {{event("datachannel")}} .
-
{{domxref("RTCSessionDescription")}}
-
Representa os parâmetros de uma sessão. Cada RTCSessionDescription consiste em um tipo de descrição que indica qual parte do processo de negociação de oferta(offer) / resposta(answer) isso descreve e do SDP descritor da sessão.
-
{{domxref("RTCStatsReport")}}
-
Fornece informações detalhando estatísticas para uma conexão ou para uma faixa individual na conexão; O relatório pode ser obtido chamando {{domxref("RTCPeerConnection.getStats()")}} .
-
{{domxref("RTCIceCandidate")}}
-
Representa um servidor candidato que estabelece a conectividade de internet (ICE -internet connectivity establishment) para estabelecer um {{domxref("RTCPeerConnection")}} .
-
{{domxref("RTCIceTransport")}}
-
Representa informações sobre o transporte referentes ao estabelecimento de conectividade de internet (ICE - internet connectivity establishment).
-
{{domxref("RTCPeerConnectionIceEvent")}}
-
Representa eventos que ocorrem em relação aos candidatos ICE com o destino, geralmente um {{domxref("RTCPeerConnection")}} . Apenas um evento é deste tipo: {{event("icecandidate")}} .
-
{{domxref("RTCRtpSender")}}
-
Gerencia a codificação e a transmissão de dados para um {{domxref("MediaStreamTrack")}} em {{domxref("RTCPeerConnection")}}.
-
{{domxref("RTCRtpReceiver")}}
-
Gerencia a recepção e decodificação de dados para um {{domxref("MediaStreamTrack")}} em um {{domxref("RTCPeerConnection")}}.
-
{{domxref("RTCTrackEvent")}}
-
Indica que uma nova entrada {{domxref("MediaStreamTrack")}} foi criada e um objeto associado {{domxref("RTCRtpReceiver")}} foi adicionado ao objeto {{domxref("RTCPeerConnection")}} .
-
- -

Identidade e segurança

- -

A API WebRTC inclui uma série de interfaces para gerenciar segurança e identidade.

- -
-
{{domxref("RTCIdentityProvider")}}
-
Permite que um agente do usuário possa solicitar que uma confirmação de identidade seja gerada ou validada.
-
{{domxref("RTCIdentityAssertion")}}
-
Representa a identidade de um ponto remoto da conexão atual. Caso nenhum par (peer) seja configurado e verificado, esta interface retorna null. Uma vez configurado, este não poderá ser alterado.
-
{{domxref("RTCIdentityProviderRegistrar")}}
-
Registra um provedor de identidade (idP).
-
{{domxref("RTCIdentityEvent")}}
-
Representa uma confirmação de identidade gerada por um provedor de identidade (idP). Isso geralmente é para um {{domxref("RTCPeerConnection")}}. O único evento enviado com este tipo é {{event("identityresult")}}.
-
{{domxref("RTCIdentityErrorEvent")}}
-
Representa um erro associado ao provedor de identidade (idP). Isso geralmente é para um {{domxref("RTCPeerConnection")}} . Dois eventos são enviados com este tipo: {{event("idpassertionerror")}} e {{event("idpvalidationerror")}} .
-
{{domxref("RTCCertificate")}}
-
Representa um certificado que um {{domxref("RTCPeerConnection")}} usa para autenticar.
-
- -

Telefonia

- -

Essas interfaces estão relacionadas à interatividade com redes telefônicas de comutação pública (PTSNs).

- -
-
{{domxref("RTCDTMFSender")}}
-
Gerencia a codificação e a transmissão da sinalização multi-frequência de dois tons (DTMF) para um {{domxref("RTCPeerConnection")}}.
-
{{domxref("RTCDTMFToneChangeEvent")}}
-
Indica uma ocorrência de uma multi-frequência de dois tons (DTMF). Este evento não faz bolha (bubble) (exceto quando indicado de outra forma) e não é cancelável (exceto quando indicado de outra forma).
-
- -

Outros

- -
-
{{domxref("RTCIceServer")}}
-
Define como ligar a um único servidor de ICE (tais como um servidor STUN ou TURN).
-
- -

 

- -

Guias

- -
-
Introduction to WebRTC protocols
-
This article introduces the protocols on top of which the WebRTC API is built.
-
WebRTC connectivity
-
A guide to how WebRTC connections work and how the various protocols and interfaces can be used together to build powerful communication apps.
-
Lifetime of a WebRTC session
-
WebRTC lets you build peer-to-peer communication of arbitrary data, audio, or video—or any combination thereof—into a browser application. In this article, we'll look at the lifetime of a WebRTC session, from establishing the connection all the way through closing the connection when it's no longer needed.
-
Signaling and two-way video calling
-
A tutorial and example which turbs a WebSocket-based chat system created for a previous example and adds support for opening video calls among participants. The chat server's WebSocket connection is used for WebRTC signaling.
-
Using WebRTC data channels
-
This guide covers how you can use a peer connection and an associated {{domxref("RTCDataChannel")}} to exchange arbitrary data between two peers.
-
Using DTMF with WebRTC
-
WebRTC's support for interacting with gateways that link to old-school telephone systems includes support for sending DTMF tones using the {{domxref("RTCDTMFSender")}} interface. This guide shows how to do so.
-
- -

Tutoriais

- -
-
Improving compatibility using WebRTC adapter.js
-
The WebRTC organization provides on GitHub the WebRTC adapter to work around compatibility issues in different browsers' WebRTC implementations. The adapter is a JavaScript shim which lets your code to be written to the specification so that it will "just work" in all browsers with WebRTC support.
-
Taking still photos with WebRTC
-
This article shows how to use WebRTC to access the camera on a computer or mobile phone with WebRTC support and take a photo with it.
-
A simple RTCDataChannel sample
-
The {{domxref("RTCDataChannel")}} interface is a feature which lets you open a channel between two peers over which you may send and receive arbitrary data. The API is intentionally similar to the WebSocket API, so that the same programming model can be used for each.
-
- -

Recursos

- -

Protocolos

- -

WebRTC-proper protocols

- - - - - - - -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('WebRTC 1.0')}}{{Spec2('WebRTC 1.0')}}A definição inicial da API do WebRTC.
{{SpecName('Media Capture')}}{{Spec2('Media Capture')}}A definição inicial do objeto que transmite o fluxo de conteúdo de mídia.
{{SpecName('Media Capture DOM Elements')}}{{Spec2('Media Capture DOM Elements')}}A definição inicial sobre como obter fluxo de conteúdo de Elementos DOM
- -

Em adição a estas especificações que definem a API necessária para usar o WebRTC, existem vários protocolos, listados em recursos.

- - - - - -
- - - - - -
diff --git a/files/pt-pt/web/api/api_webrtc/tirar_fotografias/index.html b/files/pt-pt/web/api/api_webrtc/tirar_fotografias/index.html deleted file mode 100644 index 203ebfab5b..0000000000 --- a/files/pt-pt/web/api/api_webrtc/tirar_fotografias/index.html +++ /dev/null @@ -1,222 +0,0 @@ ---- -title: Tirar fotografias com a câmara da Web -slug: Web/API/API_WebRTC/Tirar_fotografias -tags: - - API - - Avançado - - Código amostra - - Exemplo - - Vídeo(2) - - WebRTC - - cãmara da Web -translation_of: Web/API/WebRTC_API/Taking_still_photos ---- -

{{WebRTCSidebar}}

- -

This article shows how to use WebRTC to access the camera on a computer or mobile phone with WebRTC support and take a photo with it. Try this sample then read on to learn how it works.

- -

You can also jump straight to the code on Github if you like.

- -

The HTML markup

- -

Our HTML interface has two main operational sections: the stream and capture panel and the presentation panel. Each of these is presented side-by-side in its own {{HTMLElement("div")}} to facilitate styling and control.

- -

The first panel on the left contains two components: a {{HTMLElement("video")}} element, which will receive the stream from WebRTC, and a {{HTMLElement("button")}} the user clicks to capture a video frame.

- -
  <div class="camera">
-    <video id="video">Video stream not available.</video>
-    <button id="startbutton">Take photo</button>
-  </div>
- -

This is straightforward, and we'll see how it ties together when we get into the JavaScript code.

- -

Next, we have a {{HTMLElement("canvas")}} element into which the captured frames are stored, potentially manipulated in some way, and then converted into an output image file. This canvas is kept hidden by styling the canvas with {{cssxref("display")}}:none, to avoid cluttering up the screen — the user does not need to see this intermediate stage.

- -

We also have an {{HTMLElement("img")}} element into which we will draw the image — this is the final display shown to the user.

- -
  <canvas id="canvas">
-  </canvas>
-  <div class="output">
-    <img id="photo" alt="The screen capture will appear in this box.">
-  </div>
- -

That's all of the relevant HTML. The rest is just some page layout fluff and a bit of text offering a link back to this page.

- -

O código de JavaScript

- -

Now let's take a look at the JavaScript code. We'll break it up into a few bite-sized pieces to make it easier to explain.

- -

Initialização

- -

We start by wrapping the whole script in an anonymous function to avoid global variables, then setting up various variables we'll be using.

- -
(function() {
-  var width = 320;    // We will scale the photo width to this
-  var height = 0;     // This will be computed based on the input stream
-
-  var streaming = false;
-
-  var video = null;
-  var canvas = null;
-  var photo = null;
-  var startbutton = null;
- -

Those variables are:

- -
-
largura
-
Whatever size the incoming video is, we're going to scale the resulting image to be 320 pixels wide.
-
altura
-
The output height of the image will be computed given the width and the aspect ratio of the stream.
-
transmissão
-
Indicates whether or not there is currently an active stream of video running.
-
vídeo
-
This will be a reference to the {{HTMLElement("video")}} element after the page is done loading.
-
canvas
-
This will be a reference to the {{HTMLElement("canvas")}} element after the page is done loading.
-
foto
-
This will be a reference to the {{HTMLElement("img")}} element after the page is done loading.
-
startbutton
-
This will be a reference to the {{HTMLElement("button")}} element that's used to trigger capture. We'll get that after the page is done loading.
-
- -

The startup() function

- -

The startup() function is run when the page has finished loading, courtesy of {{domxref("window.addEventListener()")}}. This function's job is to request access to the user's webcam, initialize the output {{HTMLElement("img")}} to a default state, and to establish the event listeners needed to receive each frame of video from the camera and react when the button is clicked to capture an image.

- -

Getting element references

- -

First, we grab references to the major elements we need to be able to access.

- -
  function startup() {
-    video = document.getElementById('video');
-    canvas = document.getElementById('canvas');
-    photo = document.getElementById('photo');
-    startbutton = document.getElementById('startbutton');
- -

Get the media stream

- -

The next task is to get the media stream:

- -
    navigator.mediaDevices.getUserMedia({ video: true, audio: false })
-    .then(function(stream) {
-        video.srcObject = stream;
-        video.play();
-    })
-    .catch(function(err) {
-        console.log("An error occured! " + err);
-    });
-
- -

Here, we're calling {{domxref("MediaDevices.getUserMedia()")}} and requesting a video stream (without audio). It returns a promise which we attach success and failure callbacks to.

- -

The success callback receives a stream object as input. It the {{HTMLElement("video")}} element's source to our new stream.

- -

Once the stream is linked to the <video> element, we start it playing by calling HTMLMediaElement.play().

- -

The error callback is called if opening the stream doesn't work. This will happen for example if there's no compatible camera connected, or the user denied access.

- -

Listen for the video to start playing

- -

After calling HTMLMediaElement.play() on the {{HTMLElement("video")}}, there's a (hopefully brief) period of time that elapses before the stream of video begins to flow. To avoid blocking until that happens, we add an event listener to video, canplay, which is delivered when the video playback actually begins. At that point, all the properties in the video object have been configured based on the stream's format.

- -
    video.addEventListener('canplay', function(ev){
-      if (!streaming) {
-        height = video.videoHeight / (video.videoWidth/width);
-
-        video.setAttribute('width', width);
-        video.setAttribute('height', height);
-        canvas.setAttribute('width', width);
-        canvas.setAttribute('height', height);
-        streaming = true;
-      }
-    }, false);
- -

This callback does nothing unless it's the first time it's been called; this is tested by looking at the value of our streaming variable, which is false the first time this method is run.

- -

If this is indeed the first run, we set the video's height based on the size difference between the video's actual size, video.videoWidth, and the width at which we're going to render it, width.

- -

Finally, the width and height of both the video and the canvas are set to match each other by calling {{domxref("Element.setAttribute()")}} on each of the two properties on each element, and setting widths and heights as appropriate. Finally, we set the streaming variable to true to prevent us from inadvertently running this setup code again.

- -

Handle clicks on the button

- -

To capture a still photo each time the user clicks the startbutton, we need to add an event listener to the button, to be called when the click event is issued:

- -
    startbutton.addEventListener('click', function(ev){
-      takepicture();
-      ev.preventDefault();
-    }, false);
- -

This method is simple enough: it just calls our takepicture() function, defined below in the section {{anch("Capturing a frame from the stream")}}, then calls {{domxref("Event.preventDefault()")}} on the received event to prevent the click from being handled more than once.

- -

Wrapping up the startup() method

- -

There are only two more lines of code in the startup() method:

- -
    clearphoto();
-  }
- -

This is where we call the clearphoto() method we'll describe below in the section {{anch("Clearing the photo box")}}.

- -

Clearing the photo box

- -

Clearing the photo box involves creating an image, then converting it into a format usable by the {{HTMLElement("img")}} element that displays the most recently captured frame. That code looks like this:

- -
  function clearphoto() {
-    var context = canvas.getContext('2d');
-    context.fillStyle = "#AAA";
-    context.fillRect(0, 0, canvas.width, canvas.height);
-
-    var data = canvas.toDataURL('image/png');
-    photo.setAttribute('src', data);
-  }
- -

We start by getting a reference to the hidden {{HTMLElement("canvas")}} element that we use for offscreen rendering.  Next we set the fillStyle to #AAA (a fairly light grey), and fill the entire canvas with that color by calling {{domxref("CanvasRenderingContext2D.fillRect()","fillRect()")}}.

- -

Last in this function, we convert the canvas into a PNG image and call {{domxref("Element.setAttribute", "photo.setAttribute()")}} to make our captured still box display the image.

- -

Capturing a frame from the stream

- -

There's one last function to define, and it's the point to the entire exercise: the takepicture() function, whose job it is to capture the currently displayed video frame, convert it into a PNG file, and display it in the captured frame box. The code looks like this:

- -
  function takepicture() {
-    var context = canvas.getContext('2d');
-    if (width && height) {
-      canvas.width = width;
-      canvas.height = height;
-      context.drawImage(video, 0, 0, width, height);
-
-      var data = canvas.toDataURL('image/png');
-      photo.setAttribute('src', data);
-    } else {
-      clearphoto();
-    }
-  }
- -

As is the case any time we need to work with the contents of a canvas, we start by getting the {{domxref("CanvasRenderingContext2D","2D drawing context")}} for the hidden canvas.

- -

Then, if the width and height are both non-zero (meaning that there's at least potentially valid image data), we set the width and height of the canvas to match that of the captured frame, then call {{domxref("CanvasRenderingContext2D.drawImage()", "drawImage()")}} to draw the current frame of the video into the context, filling the entire canvas with the frame image.

- -
-

Note: This takes advantage of the fact that the {{domxref("HTMLVideoElement")}} interface looks like a {{domxref("HTMLImageElement")}} to any API that accepts an HTMLImageElement as a parameter, with the video's current frame presented as the image's contents.

-
- -

Once the canvas contains the captured image, we convert it to PNG format by calling {{domxref("HTMLCanvasElement.toDataURL()")}} on it; finally, we call {{domxref("Element.setAttribute", "photo.setAttribute()")}} to make our captured still box display the image.

- -

If there isn't a valid image available (that is, the width and height are both 0), we clear the contents of the captured frame box by calling clearphoto().

- -

Fun with filters

- -

Since we're capturing images from the user's webcam by grabbing frames from a {{HTMLElement("video")}} element, we can very easily apply filters and fun effects to the video. As it turns out, any CSS filters you apply to the element using the {{cssxref("filter")}} property affect the captured photo. These filters can range from the simple (making the image black and white)  to the extreme (gaussian blurs and hue rotation).

- -

You can play with this effect using, for example, the Firefox developer tools' style editor; see Edit CSS filters for details on how to do so.

- -

Consultar também

- - diff --git a/files/pt-pt/web/api/battery_status_api/index.html b/files/pt-pt/web/api/battery_status_api/index.html new file mode 100644 index 0000000000..4805a71bc6 --- /dev/null +++ b/files/pt-pt/web/api/battery_status_api/index.html @@ -0,0 +1,169 @@ +--- +title: API do Estado da Bateria +slug: Web/API/API_do_Estado_da_Bateria +tags: + - API + - API de Bateria + - API do Estado da Bateria + - Aplicações + - Apps + - Firefox OS + - Guía + - Movel + - Resumo + - Sinopse +translation_of: Web/API/Battery_Status_API +--- +
{{obsolete_header}}
+ +
{{DefaultAPISidebar("Battery API")}}
+ +

A API do Estado da Bateria, mais conhecida como API de Bateria, fornece informação sobre o nível de carga da bateria do sistema e permite-lhe que seja notificado por eventos que são enviados quando o nível da bateria ou o estado de carregamento é alterado. Isto pode ser utilizado para ajustar a utilização de recursos da aplicação para reduzir o consumo de bateria quando a bateria estiver fraca ou para guardar as alterações antes que a bateria acabe para evitar a perda de dados.

+ +

The Battery Status API extends {{domxref("window.navigator")}} with a {{domxref("navigator.getBattery()")}} method returning a battery promise, which is resolved in a {{domxref("BatteryManager")}} object providing also some new events you can handle to monitor the battery status.

+ +

Exemplo

+ +

In this example, we watch for changes both to the charging status (whether or not we're plugged in and charging) and for changes to the battery level and timing. This is done by listening for the {{event("chargingchange")}}, {{event("levelchange")}}, {{event("chargingtimechange")}}, {{event("dischargingtimechange")}} events.

+ +
navigator.getBattery().then(function(battery) {
+  function updateAllBatteryInfo(){
+    updateChargeInfo();
+    updateLevelInfo();
+    updateChargingInfo();
+    updateDischargingInfo();
+  }
+  updateAllBatteryInfo();
+
+  battery.addEventListener('chargingchange', function(){
+    updateChargeInfo();
+  });
+  function updateChargeInfo(){
+    console.log("Battery charging? "
+                + (battery.charging ? "Yes" : "No"));
+  }
+
+  battery.addEventListener('levelchange', function(){
+    updateLevelInfo();
+  });
+  function updateLevelInfo(){
+    console.log("Battery level: "
+                + battery.level * 100 + "%");
+  }
+
+  battery.addEventListener('chargingtimechange', function(){
+    updateChargingInfo();
+  });
+  function updateChargingInfo(){
+    console.log("Battery charging time: "
+                 + battery.chargingTime + " seconds");
+  }
+
+  battery.addEventListener('dischargingtimechange', function(){
+    updateDischargingInfo();
+  });
+  function updateDischargingInfo(){
+    console.log("Battery discharging time: "
+                 + battery.dischargingTime + " seconds");
+  }
+
+});
+
+ +

See also the example in the specification.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName("Battery API")}}{{Spec2("Battery API")}}Initial definition
+ +

Compatibilidade do navegador

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(39.0)}}{{CompatGeckoDesktop("10")}} {{property_prefix("moz")}}
+ {{CompatGeckoDesktop("16")}}[1]
+ {{CompatGeckoDesktop("43")}}[3]
+ {{CompatGeckoDesktop("52")}}[4]
{{CompatNo}}25{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(40.0)}} +

{{CompatGeckoMobile("10")}} {{property_prefix("moz")}}
+ {{CompatGeckoMobile("16")}}[1]
+ {{CompatGeckoMobile("43")}}[3]
+ {{CompatGeckoMobile("52")}}[3]

+
{{CompatNo}}25[2]{{CompatNo}}{{CompatChrome(42.0)}}[2]
+
+ +

[1] Disabled by default in Firefox 10.0, but can be enabled setting the preference dom.battery.enabled to true. Starting with Firefox 11.0, mozBattery is enabled by default. The Battery API is currently supported on Android, Windows, and Linux with UPower installed. Support for MacOS is available starting with Gecko 18.0 {{geckoRelease("18.0")}}. Firefox also provides support for the deprecated {{domxref("navigator.battery")}}.

+ +

[2] Values for {{domxref("BatteryManager.chargingTime")}} and {{domxref("BatteryManager.dischargingTime")}} are always equal to Infinity.

+ +

[3] The new promise-based syntax for {{domxref("Navigator.getBattery()")}} is supported from Firefox 43 onwards.

+ +

[4] From Firefox 52 onwards, the Battery Status API is only available in chrome/privileged code.

+ +

Consultar também

+ + diff --git a/files/pt-pt/web/api/canvas_api/index.html b/files/pt-pt/web/api/canvas_api/index.html new file mode 100644 index 0000000000..17971de4ee --- /dev/null +++ b/files/pt-pt/web/api/canvas_api/index.html @@ -0,0 +1,247 @@ +--- +title: API de Canvas +slug: Web/API/API_de_canvas +translation_of: Web/API/Canvas_API +--- +
{{CanvasSidebar}}
+ +

Added in HTML5, the HTML {{HTMLElement("canvas")}} element can be used to draw graphics via scripting in JavaScript. For example, it can be used to draw graphs, make photo compositions, create animations, or even do real-time video processing or rendering.

+ +

Mozilla applications gained support for <canvas> starting with Gecko 1.8 (i.e. Firefox 1.5). The element was originally introduced by Apple for the OS X Dashboard and Safari. Internet Explorer supports <canvas> from version 9 onwards; for earlier versions of IE, a page can effectively add support for <canvas> by including a script from Google's Explorer Canvas project. Google Chrome and Opera 9 also support <canvas>.

+ +

The <canvas> element is also used by WebGL to draw hardware-accelerated 3D graphics on web pages.

+ +

Exemplo

+ +

This is just a simple code snippet which uses the {{domxref("CanvasRenderingContext2D.fillRect()")}} method.

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+
+ctx.fillStyle = 'green';
+ctx.fillRect(10, 10, 100, 100);
+
+ +

Edit the code below and see your changes update live in the canvas:

+ + + +

{{ EmbedLiveSample('Playable_code', 700, 360) }}

+ +

Referência

+ +
+ +
+ +

The interfaces related to the WebGLRenderingContext are referenced under WebGL.

+ +

{{domxref("CanvasCaptureMediaStream")}} is related.

+ +

Guias e tutoriais

+ +
+
Canvas tutorial
+
A comprehensive tutorial covering both the basic usage of <canvas> and its advanced features.
+
Code snippets: Canvas
+
Some extension developer-oriented code snippets involving <canvas>.
+
Demo: A basic ray-caster
+
A demo of ray-tracing animation using canvas.
+
Drawing DOM objects into a canvas
+
How to draw DOM content, such as HTML elements, into a canvas.
+
Manipulating video using canvas
+
Combining {{HTMLElement("video")}} and {{HTMLElement("canvas")}} to manipulate video data in real time.
+
+ +

Recursos

+ +

Genérico

+ + + +

Bibliotecas

+ + + +

Especificações

+ + + + + + + + + + + + + + + + +
EpecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', 'scripting.html#the-canvas-element', '<canvas>')}}{{Spec2('HTML WHATWG')}} 
+ +

Consulte também

+ + + +
+ + + + + +
diff --git a/files/pt-pt/web/api/canvas_api/tutorial/index.html b/files/pt-pt/web/api/canvas_api/tutorial/index.html new file mode 100644 index 0000000000..b93457336d --- /dev/null +++ b/files/pt-pt/web/api/canvas_api/tutorial/index.html @@ -0,0 +1,60 @@ +--- +title: Tutorial de Canvas +slug: Web/API/API_de_canvas/Tutorial +tags: + - Canvas + - Guía + - HTML + - HTML5 + - Intermediário + - Web + - graficos +translation_of: Web/API/Canvas_API/Tutorial +--- +
{{CanvasSidebar}}
+ +
+ +
+

<canvas> is an HTML element which can be used to draw graphics via scripting (usually JavaScript). This can, for instance, be used to draw graphs, make photo composition or simple (and not so simple) animations. The images on this page show examples of <canvas> implementations which will be created in this tutorial.

+
+ +

This tutorial describes how to use the <canvas> element to draw 2D graphics, starting with the basics. The examples provided should give you some clear ideas what you can do with canvas and will provide code snippets that may get you started in building your own content.

+ +

First introduced in WebKit by Apple for the OS X Dashboard, <canvas> has since been implemented in browsers. Today, all major browsers support it.

+ +

Antes de começar

+ +

Using the <canvas> element is not very difficult, but you do need a basic understanding of HTML and JavaScript. The <canvas> element is not supported in some older browsers, but is supported in recent versions of all major browsers. The default size of the canvas is 300 px × 150 px (width × height). But custom sizes can be defined using the HTML height and width property. In order to draw graphics on the canvas we use a JavaScript context object, which creates graphics on the fly.

+ +

Neste tutorial

+ + + +

Consulte também:

+ + + +

Uma nota para os colaboradores

+ +

Due to an unfortunate technical error that occurred the week of June 17, 2013, we lost the history of this tutorial, including attributions to all past contributors to its content. We apologize for this, and hope you'll forgive this unfortunate mishap.

+ +
{{ Next("Web/API/Canvas_API/Tutorial/Basic_usage") }}
diff --git a/files/pt-pt/web/api/document.dir/index.html b/files/pt-pt/web/api/document.dir/index.html deleted file mode 100644 index 9d82a6b4ab..0000000000 --- a/files/pt-pt/web/api/document.dir/index.html +++ /dev/null @@ -1,71 +0,0 @@ ---- -title: Document.dir -slug: Web/API/Document.dir -tags: - - API - - DOM - - HTML - - dir - - ltr - - rtl -translation_of: Web/API/Document/dir ---- -

{{Apiref("Document")}}{{non-standard_header}}

-

A propriedade Document.dir é uma {{domxref("DOMString")}} que representa a direccionalidade do texto do documento, quer seja da esquerda para a direita (por omissão) ou da direita para a esquerda. Os valores possíveis são 'rtl', da direita para a esquerda e 'ltr', da esquerda para a direita.

-

Síntaxe

-
dirStr = document.dir;
-document.dir = dirStr;
-
-

Especificações

-

Este atributo, apesar de implementado por diversos browsers não faz parte de nenhuma especificação.

-

Compatibilidade por browser

-

{{ CompatibilityTable() }}

-
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico{{CompatUnknown}}{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
-
- - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico{{ CompatUnknown() }}{{CompatVersionUnknown}} [1]{{ CompatVersionUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
-
-

[1] Antes do Firefox 23, a propriedade document.dir retornava "ltr" independentemente do valor atribuido a dir na raiz do elemento {{htmlelement("html")}}. Caso a direcção fosse definida no nó <html>, document.dir não teria qualquer efeito em alterá-la visivelmente (apesar disto, a obtenção da propriedade document.dir iria indicar que a direcção teria sido alterada). Contudo, se o atributo dir estiver definido no elemento <html> e for alterado, quer a direccionalidade do documento quer a propriedade document.dir irão reflectir a mudança.

-

Ver também

- diff --git a/files/pt-pt/web/api/document/alinkcolor/index.html b/files/pt-pt/web/api/document/alinkcolor/index.html new file mode 100644 index 0000000000..582760a339 --- /dev/null +++ b/files/pt-pt/web/api/document/alinkcolor/index.html @@ -0,0 +1,43 @@ +--- +title: document.alinkColor +slug: DOM/document.alinkColor +tags: + - DOM + - DOM 0 + - Gecko + - Referência_do_DOM_Gecko +translation_of: Web/API/Document/alinkColor +--- +
+
+

« Referência do DOM Gecko

+
+

Sumário

+

 

+
+

Obsoleto

+
+ Retorna ou define a cor de um link ativo no corpo do documento. Um link é ativo durante o tempo entre mousedown mouseup eventos. +

 

+
+
+

Sintaxe

+
document.alinkColor = cor
+
+

color é uma string contendo o nome da cor (em inglês), (por exemplo, "blue", "darkblue", etc) ou o valor em hexadecimal (por exemplo, #0000FF)

+
+
+

Notas 

+

O valor padrão para essa propriedade no Mozilla Firefox é o vermelho (#ee0000 em hexadecimal).

+

document.alinkColor é substituído no DOM Nível 2 HTML . Uma alternativa é o seletor CSS :active.

+

Outra alternativa é document.body.aLink, embora isso seja obsoleto em HTML 4.01, em favor da alternativa de CSS.

+

Gecko suporta tanto alinkColor / :active e :focus. Internet Explorer 6 e 7 suportam alinkColor / :active apenas para âncora HTML (<a>) links e o comportamento é o mesmo que :focus em Gecko. Não há suporte para :focus no IE.

+
+
+

Especificação

+

DOM Nível 0. Não faz parte do padrão.

+

MSDN - propriedade :alinkColor

+
+
+
+

 

diff --git a/files/pt-pt/web/api/document/bgcolor/index.html b/files/pt-pt/web/api/document/bgcolor/index.html new file mode 100644 index 0000000000..5cb60b2712 --- /dev/null +++ b/files/pt-pt/web/api/document/bgcolor/index.html @@ -0,0 +1,55 @@ +--- +title: document.bgColor +slug: DOM/document.bgColor +tags: + - DOM + - DOM 0 + - Gecko + - Referência_do_DOM_Gecko +translation_of: Web/API/Document/bgColor +--- +
+
+

« Referência do DOM Gecko

+
+

Sumário

+

 

+
+

Obsoleto

+
+ bgColor obtém / define a cor de fundo do documento atual. +

 

+
+
+

Sintaxe

+
document.bgColor = cor
+
+
+
+

Parâmetros

+
    +
  • color é uma seqüência que representa a cor como uma palavra (em inglês) (por exemplo, "red") ou valor em hexadecimal (por exemplo, "#Ff0000").
  • +
+
+
+

Exemplo

+
document.bgColor = "darkblue"; 
+
+
+
+

Notas

+

O valor padrão para essa propriedade no Mozilla Firefox é branco (#ffffff em hexadecimal).

+

document.bgColor é substituído no DOM Nível 2 HTML . A alternativa recomendada é o uso do estilo CSS background-color que pode ser acessada através do DOM com document.body.style.backgroundColor. Outra alternativa é document.body.bgColor, embora este também seja obsoleto em HTML 4.01 em favor da alternativa de CSS.

+

 

+
+
+

Especificação

+

DOM Nível 0. Não faz parte do padrão .

+

MSDN: Propriedade bgColor

+
+
+
+ +

 

diff --git a/files/pt-pt/web/api/document/cookie/index.html b/files/pt-pt/web/api/document/cookie/index.html new file mode 100644 index 0000000000..aa309f8a95 --- /dev/null +++ b/files/pt-pt/web/api/document/cookie/index.html @@ -0,0 +1,85 @@ +--- +title: document.cookie +slug: DOM/document.cookie +translation_of: Web/API/Document/cookie +--- +
+
+

« Referência do DOM Gecko

+ +
+

Sumário

+ +

Obter e definir os cookies associados com o documento atual.

+
+ +
+

Sintaxe

+ +
allCookies = document.cookie;
+ +
    +
  • allCookies é uma string contendo uma lista separada por vírgula de "cookies" (isto é, chave valor pares).
  • +
+ +
updatedCookie = document.cookie;
+ +
    +
  • +
    updatedCookie é uma string de forma chave valor. Observe que você só pode definir / atualizar um cookie de cada vez usando esse método.
    +
  • +
+ +
    +
  • Qualquer um dos seguintes valores de atributo cookie pode, opcionalmente, seguir o valor-chave par, especificando o cookie para definir / atualizar, e precedido por um ponto e vírgula : +
      +
    • ;path = caminho (Por exemplo, '/' , '/meuDiretorio' ). Se não for especificado, o padrão é o caminho atual do local do documento atual.
    • +
    • ;domain = domínio (por ex, 'exemplo1.com ', '.exemplo1.com', (inclui todos os subdomínios ), 'subdominio.exemplo1.com'). Se não for especificado, o padrão é a parte do host local do documento atual.
    • +
    • ;max-age = maxima-idade-em-segundos (Por exemplo, 60 * 60 * 24 * 365 para um ano)
    • +
    • ;expires = data-em-formato-GMTString (Poderia usar Date.toGMTString, agora obsoleto). Se não for especificado ele expira no final da sessão.
    • +
    • ;secure (cookie só podem ser transmitidos através do protocolo seguro como https)
    • +
    +
  • +
+ +
    +
  • A cadeia de valor do cookie pode usar encodeURIComponent() para garantir que a cadeia não contenha nenhuma vírgula, ponto-e-vírgula, ou espaços em branco (que não são permitidos nos valores de cookie).
  • +
+
+ +
+

Exemplo

+ +
+
    +
  1. document.cookie = "nome = Italo";
  2. +
  3. document.cookie = "comida_favorita = lasanha";
  4. +
  5. alert(document.cookie);
  6. +
  7. // Mostra: nome = Italo; comida_favorita = lasanha
  8. +
+
+
+ +
+

Segurança

+ +

É importante notar que o path não protege contra a leitura não autorizada do cookie de um caminho diferenteEle pode ser facilmente contornado com DOM simples (por exemplo, a criação de um elemento iframe oculto com o caminho do cookie, e depois aceder a este iframe contentDocument.cookiepropriedade). Ele pode ser facilmente (por exemplo, a criação de um elemento o caminho do cookie, e depois aceder a este A única maneira de proteger o acesso "cookie" é usando um domínio ou subdomínio diferente , devido à política de mesma origem.

+
+ +
+

Notas

+ +
Edit section
+ +

Começando com o Firefox 2, a melhor mecanismo para o lado de armazenamento do cliente está disponível - WHATWG DOM Storage com o Firefox 2, a para o lado de armazenamento do cliente está disponível.

+
+ +
+

Especificação

+ +

DOM Level 2: HTMLDocument.cookie

+
+
+
+ +

 

diff --git a/files/pt-pt/web/api/document/dir/index.html b/files/pt-pt/web/api/document/dir/index.html new file mode 100644 index 0000000000..9d82a6b4ab --- /dev/null +++ b/files/pt-pt/web/api/document/dir/index.html @@ -0,0 +1,71 @@ +--- +title: Document.dir +slug: Web/API/Document.dir +tags: + - API + - DOM + - HTML + - dir + - ltr + - rtl +translation_of: Web/API/Document/dir +--- +

{{Apiref("Document")}}{{non-standard_header}}

+

A propriedade Document.dir é uma {{domxref("DOMString")}} que representa a direccionalidade do texto do documento, quer seja da esquerda para a direita (por omissão) ou da direita para a esquerda. Os valores possíveis são 'rtl', da direita para a esquerda e 'ltr', da esquerda para a direita.

+

Síntaxe

+
dirStr = document.dir;
+document.dir = dirStr;
+
+

Especificações

+

Este atributo, apesar de implementado por diversos browsers não faz parte de nenhuma especificação.

+

Compatibilidade por browser

+

{{ CompatibilityTable() }}

+
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico{{CompatUnknown}}{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico{{ CompatUnknown() }}{{CompatVersionUnknown}} [1]{{ CompatVersionUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+

[1] Antes do Firefox 23, a propriedade document.dir retornava "ltr" independentemente do valor atribuido a dir na raiz do elemento {{htmlelement("html")}}. Caso a direcção fosse definida no nó <html>, document.dir não teria qualquer efeito em alterá-la visivelmente (apesar disto, a obtenção da propriedade document.dir iria indicar que a direcção teria sido alterada). Contudo, se o atributo dir estiver definido no elemento <html> e for alterado, quer a direccionalidade do documento quer a propriedade document.dir irão reflectir a mudança.

+

Ver também

+ diff --git a/files/pt-pt/web/api/document/getelementsbyclassname/index.html b/files/pt-pt/web/api/document/getelementsbyclassname/index.html new file mode 100644 index 0000000000..3ce79ed564 --- /dev/null +++ b/files/pt-pt/web/api/document/getelementsbyclassname/index.html @@ -0,0 +1,69 @@ +--- +title: document.getElementsByClassName +slug: DOM/document.getElementsByClassName +tags: + - Referência_do_DOM_Gecko +translation_of: Web/API/Document/getElementsByClassName +--- +

{{ Fx_minversion_header(3) }} {{ ApiRef() }}

+ +

Resumo

+ +

Retorna um conjunto de elementos com o nome de classe fornecido. Quando chamado no objeto document, todo o documento é pesquisado incluindo o nó raiz. Você pode chamar também getElementsByClassName em qualquer elemento; isso retornará apenas elementos sob o elemento raiz especificado com o nome de classe fornecido.

+ +

Sintaxe

+ +
elementos = document.getElementsByClassName(nome) // ou:elementos = elementoRaiz.getElementsByClassName(nome)
+
+ + + +

Exemplos

+ +

Devolve todos os elementos que têm a classe 'teste':

+ +
 document.getElementsByClassName('teste')
+
+ +

Devolve todos os elementos que têm as classes 'vermelho' e 'teste':

+ +
 document.getElementsByClassName('vermelho teste')
+
+ +

Devolve todos os elementos que têm a classe 'teste', dentro de um elemento que tem o ID 'principal':

+ +
 document.getElementById('principal').getElementsByClassName('teste')
+
+ +

E se formos adiante e adicionarmos extras do Array do JavaScript 1.6, podemos fazer algumas combinações realmente boas.

+ +

Encontre todos os elementos div que têm a classe 'teste'

+ +
 Array.filter( document.getElementsByClassName('teste'), function(elem){
+   return elem.nodeName == 'DIV';
+ });
+
+ +

Encontre todos os elementos que têm a classe 'teste' (como faz seu elemento pai)

+ +
 var teste = document.getElementsByClassName('teste');
+ Array.filter( teste, function(elem){
+   return Array.indexOf( teste, elem.parentNode ) > -1;
+ });
+
+ +

XXX escreva-me == Notas == Um método similar existe em <code>Element</code>

+ +

Especificação

+ +

WHATWG Web Applications 1.0: getElementsByClassName

+ +

Categorias

+ +

Interwiki Language Links

+ +

{{ languages( { "en": "en/DOM/document.getElementsByClassName", "fr": "fr/DOM/document.getElementsByClassName" } ) }}

diff --git a/files/pt-pt/web/api/document_object_model/index.html b/files/pt-pt/web/api/document_object_model/index.html new file mode 100644 index 0000000000..ea0cdc52f1 --- /dev/null +++ b/files/pt-pt/web/api/document_object_model/index.html @@ -0,0 +1,501 @@ +--- +title: Modelo de Objeto de Documento (DOM) +slug: DOM/DOM_Reference +tags: + - API + - DOM + - DOM Reference + - NeedsTranslation + - Referencia + - TopicStub +translation_of: Web/API/Document_Object_Model +--- +
{{DefaultAPISidebar("DOM")}}
+ +

Modelo de Objeto de Documento (DOM) interliga as páginas da Web para scripts ou linguagens de programação. Normalmente, isso significa que JavaScript, mas a modelagem de documentos HTML, SVG ou XML como objetos não é parte da linguagem de JavaScript. O modelo DOM representa um documento com uma árvore lógica. Cada ramo da árvore termina em um nodo, e cada nodo contém objetos. Os métodos DOM permitem o acesso programático à árvore; com eles, pode alterar a estrutura, o estilo ou o conteúdo do documento. Os nodos podem ter manipuladores de eventos anexados aos mesmos. Quando é acionado um evento, os manipuladores de eventos são executados .

+ +

Está disponível uma introdução ao DOM.

+ +

Interfaces DOM

+ +
+ +
+ +

Interfaces DOM obsoletas {{obsolete_inline}}

+ +

The Document Object Model has been highly simplified. To achieve this, the following interfaces present in the different DOM level 3 or earlier specification have been removed. It is still not very clear whether some may be reintroduced or not, but for the time being they have to be considered as obsolete and should be avoided:

+ +
+ +
+ +

Interfaces HTML

+ +

A document containing HTML is described using the {{domxref("HTMLDocument")}} interface. Note that the HTML specification also extends the {{domxref("Document")}} interface.

+ +

An HTMLDocument object also gives access to various features of browsers like the ta or the window, in which a page is drawn using the {{domxref("Window")}} interface, the {{domxref("window.style", "Style")}} associated to it (usually CSS), the history of the browser relative to the context, {{domxref("window.history", "History")}}. Eventually, {{domxref("Selection")}} is done on the document.

+ +

Interfaces de elemento HTML

+ +
+ +
+ +

Outras interfaces

+ +
+ +
+ +

Interfaces HTML obsoletas {{obsolete_inline}}

+ +
+ +
+ +

SGV - Interfaces

+ +

Interfaces de elemento SVG

+ +
+ +
+ +

Interfaces de tipo de dados SVG

+ +

Here are the DOM API for data types used in the definitions of SVG properties and attributes.

+ +
+

Nota: Starting in {{Gecko("5.0")}}, the following SVG-related DOM interfaces representing lists of objects are now indexable and can be accessed ; in addition, they have a length property indicating the number of items in the lists: {{domxref("SVGLengthList")}}, {{domxref("SVGNumberList")}}, {{domxref("SVGPathSegList")}}, and {{domxref("SVGPointList")}}.

+
+ +

Tipo estático

+ +
+ +
+ +

Tipo animado

+ +
+ +
+ +

Interfaces relacionadas com SMIL

+ +
+ +
+ +

Outras interfaces SVG

+ +
+ +
+ +

Consulte também

+ + + +
+ + + + + +
diff --git a/files/pt-pt/web/api/document_object_model/using_the_w3c_dom_level_1_core/index.html b/files/pt-pt/web/api/document_object_model/using_the_w3c_dom_level_1_core/index.html new file mode 100644 index 0000000000..ff80acdcf4 --- /dev/null +++ b/files/pt-pt/web/api/document_object_model/using_the_w3c_dom_level_1_core/index.html @@ -0,0 +1,79 @@ +--- +title: Utilizando o Núcleo DOM de Nível 1 do W3C +slug: Using_the_W3C_DOM_Level_1_Core +tags: + - DOM +translation_of: Web/API/Document_object_model/Using_the_W3C_DOM_Level_1_Core +--- +

O 'Núcleo DOM de Nível 1 do W3C' é um modelo de objetos poderoso para alterar o conteúdo de uma árvore de documentos. É suportado em todos os navegadores principais, incluindo o Mozilla Firefox e o Microsoft Internet Explorer. É uma base poderosa para scrips na Web.

+ +

 O que é uma árvore de conteúdos?

+ +

Muitos autores HTML pensam que o HTML é algo plano -- um punhado de texto com tags no meio. Entretanto, é muito mais do que somente isso. Qualquer documento HTML (ou do mesmo modo em qualquer documento SGML ou XML) é uma estrutura de árvore. Por exemplo, o seguinte documento e estrutura de árvore são similares (embora não sejam idênticos -- veja as notas em espaços em branco no DOM):

+ +
<html>
+<head>
+  <title>My Document</title>
+</head>
+<body>
+  <h1>Header</h1>
+  <p>Paragraph</p>
+</body>
+</html>
+
+ +

image:Using_the_W3C_DOM_Level_1_Core-doctree.jpg

+ +

Quando o Mozilla interpreta um documento, ele constrói uma árvore de conteúdos e então a utiliza para mostrar o documento.

+ +

Os termos utilizados para descrever árvores se aparecem frequentemente no Núcleo DOM Nível 1. Cada uma das caixas desenhadas na árvore acima é um nó na árvore. A linha acima de um nó expressa um relacionamento pai-filho: o nó ao topo é o pai, e o nó abaixo é o filho. Dois filhos do mesmo pai são, portanto, irmãos. Similarmente, pode-se referenciar ancestrais e descentes (Apesar de primos serem um tanto confusos).

+ +

O que o Núcleo DOM Nível 1 me permite fazer?

+ +

O DOM Nível 1 da W3C permite que você altere o conteúdo da árvore do modo que você desejar. É poderoso o bastante para construir qualquer documento HTML a partir do zero. Ele permite autores alterar qualquer coisa no documento a partir de um script, a qualquer instante. O modo mais fácil de um autor de uma página alterar o DOM dinamicamente é utilizando JavaScript. Em JavaScript, o documento é acessível do mesmo modo que em navegadores antigos: através da propriedade document do objeto global. Esse objeto document implementa a interface Document da especificação do Nível 1 do DOM do W3C.

+ +

Um exemplo simples

+ +

Suponha que autor queira  pegar o documento acima e alterar o conteúdo do cabeçalho, e escrever dois parágrafos ao invés de um. O seguinte script irá fazer o trabalho:

+ +
// document.getElementsByTagName("H1") retorna um NodeList dos elementos H1
+// no documento, e o primeiro é o número 0:
+var header = document.getElementsByTagName("H1").item(0);
+
+// o firstChild do cabeçalho é um Text node, e a propriedade data
+// do text node contém seu texto:
+header.firstChild.data = "A dynamic document";
+// agora o cabeçalho é "A dynamic document".
+
+// Recupera o primeiro elemento P no documento do mesmo modo:
+var para = document.getElementsByTagName("P").item(0);
+// e altera seu texto também:
+para.firstChild.data = "This is the first paragraph.";
+
+// cria um novo Text node para o segundo parágrafo
+var newText = document.createTextNode("This is the second paragraph.");
+// cria um novo Element para ser o segundo parágrafo
+var newElement = document.createElement("P");
+// insere o texto no segundo parágrafo
+newElement.appendChild(newText);
+// e coloca o parágrafo no final do documento acrescentando-o ao
+// BODY (que é o pai de para)
+para.parentNode.appendChild(newElement);
+
+ +

Você pode ver esse script como um exemplo completo.

+ +

Como posso aprender mais?

+ +

Agora que você está familiarizado com os conceitos básicos do DOM há um documento explicando os métodos fundamentais do DOM Nível 1. Ele é o acompanhamento desse documento.

+ +

Veja também a especificação do Núcleo DOM Nível 1 do W3C. É uma especificação razoavelmente clara, apesar de sua formalidade. A principal utilidade para os autores é a descrição dos diferentes tipos de objetos DOM e todas as suas propriedades e métodos. Veja também nossa outra documentação DOM.

+ +
+

Original Document Information

+ + +
diff --git a/files/pt-pt/web/api/element/clientleft/index.html b/files/pt-pt/web/api/element/clientleft/index.html new file mode 100644 index 0000000000..48ee3f11b4 --- /dev/null +++ b/files/pt-pt/web/api/element/clientleft/index.html @@ -0,0 +1,47 @@ +--- +title: element.clientLeft +slug: DOM/element.clientLeft +tags: + - PrecisaDeRevisãoEditorial + - Referência_do_DOM_Gecko +translation_of: Web/API/Element/clientLeft +--- +

{{ Fx_minversion_header(3) }} {{ ApiRef() }} Faltam duas imagens no documento

+

Resumo

+

A largura da borda esquerda de um elemento em pixels inclui a largura da barra de rolagem vertical se a direção do texto do elemento estiver da direita para a esquerda e se houver um excesso causando uma barra de rolagem vertical na esquerda para ser renderizada. clientLeft não inclui a margem ou o enchimento esquerdo. clientLeft é somente leitura.

+

Aplicações baseadas em Gecko suportam clientLeft començando com o Gecko 1.9 (Firefox 3, implementado em {{ Bug(111207) }}). Esta propriedade não é suportada pelo Firefox 2 e mais antigos.

+

Sintaxe

+
var left = element.clientLeft;
+
+

Exemplos

+
+
+

padding-top

+

Gentle, individualistic and very loyal, Birman cats fall between Siamese and Persian in character. If you admire cats that are non aggressive, that enjoy being with humans and tend to be on the quiet side, you may well find that Birman cats are just the felines for you.

+

Image:BirmanCat.jpgAll Birmans have colorpointed features, dark coloration of the face, ears, legs and tail.

+

Cat image and text coming from www.best-cat-art.com

+

padding-bottom

+
+ LeftTopRightBottommargin-topmargin-bottomborder-topborder-bottom{{ mediawiki.external('if IE') }}><span id="MrgLeft" style="position: absolute; left: 8px; top: 65px; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl;">margin-left</span><span id="BrdLeft" style="position: absolute; left: 33px; top: 65px; color: white; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl;">border-left</span><span id="PdgLeft" style="position: absolute; left: 55px; top: 65px; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl;">padding-left</span><span id="PdgRight" style="position: absolute; left: 275px; top: 60px; color: black; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl; white-space: nowrap;">padding-right</span><span id="BrdRight" style="position: absolute; left: 310px; top: 65px; color: white; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl;">border-right</span><span id="MrgRight" style="position: absolute; left: 340px; top: 65px; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl;">margin-right</span><!{{ mediawiki.external('endif') }}
+

Image:clientLeft.png

+

Vertical scrollbar position when layout.scrollbar.side property is set to 1 or to 3

+

Quando a propriedade + + layout.scrollbar.side + é configurada para 1 ou para 3 e quando a direção do texto é configurada da direita para a esquerda, então a barra de rolagem vertical é posicionada na esquerda e isto impacta na maneira como o clientLeft é computado.

+

Especificação

+

Não é parte de qualquer especificação W3C.

+

Notas

+

clientLeft foi primeiramente introduzido no objeto modelo DHTML do MS IE.

+

A posição da barra de rolagem vertical na direção do texto, direita para a esquerda, configura que o elemento dependerá da preferência + + layout.scrollbar.side +

+

Referências

+ +

Categorias

+

Interwiki Language Links

+

{{ languages( { "en": "en/DOM/element.clientLeft", "ja": "ja/DOM/element.clientLeft", "pl": "pl/DOM/element.clientLeft" } ) }}

diff --git a/files/pt-pt/web/api/element/clienttop/index.html b/files/pt-pt/web/api/element/clienttop/index.html new file mode 100644 index 0000000000..02f2ee736c --- /dev/null +++ b/files/pt-pt/web/api/element/clienttop/index.html @@ -0,0 +1,38 @@ +--- +title: element.clientTop +slug: DOM/element.clientTop +tags: + - PrecisaDeRevisãoEditorial + - Referência_do_DOM_Gecko +translation_of: Web/API/Element/clientTop +--- +

{{ Fx_minversion_header(3) }} {{ ApiRef() }} Falta uma imagem no documento

+

Resumo

+

A largura da borda superior de um elemento em pixels não inclui a margem superior ou o enchimento. clientTop é somente leitura.

+

Aplicações baseadas em Gecko suportam clientTop começando com Gecko 1.9 (Firefox 3, implementou em {{ Bug(111207) }}). Esta propriedade não é suportada no Firefox 2 e mais antigos.

+

Sintaxe

+
vartop = element.clientTop;
+
+

Exemplos

+
+
+

padding-top

+

Gentle, individualistic and very loyal, Birman cats fall between Siamese and Persian in character. If you admire cats that are non aggressive, that enjoy being with humans and tend to be on the quiet side, you may well find that Birman cats are just the felines for you.

+

Image:BirmanCat.jpgAll Birmans have colorpointed features, dark coloration of the face, ears, legs and tail.

+

Cat image and text coming from www.best-cat-art.com

+

padding-bottom

+
+ LeftTopRightBottommargin-topmargin-bottomborder-topborder-bottom{{ mediawiki.external('if IE') }}><span id="MrgLeft" style="position: absolute; left: 8px; top: 65px; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl;">margin-left</span><span id="BrdLeft" style="position: absolute; left: 33px; top: 65px; color: white; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl;">border-left</span><span id="PdgLeft" style="position: absolute; left: 55px; top: 65px; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl;">padding-left</span><span id="PdgRight" style="position: absolute; left: 275px; top: 60px; color: black; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl; white-space: nowrap;">padding-right</span><span id="BrdRight" style="position: absolute; left: 310px; top: 65px; color: white; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl;">border-right</span><span id="MrgRight" style="position: absolute; left: 340px; top: 65px; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl;">margin-right</span><!{{ mediawiki.external('endif') }}
+

Image:clientTop.png

+

Especificação

+

Não é parte de nenhuma especificação W3C.

+

Notas

+

clientTop foi primeiramente introduzido no objeto modelo DHTML do MS IE.

+

Referências

+ +

Categorias

+

Interwiki Language Links

+

{{ languages( { "en": "en/DOM/element.clientTop", "pl": "pl/DOM/element.clientTop" } ) }}

diff --git a/files/pt-pt/web/api/element/index.html b/files/pt-pt/web/api/element/index.html new file mode 100644 index 0000000000..7b9a55f260 --- /dev/null +++ b/files/pt-pt/web/api/element/index.html @@ -0,0 +1,573 @@ +--- +title: element +slug: DOM/element +tags: + - API + - API da Web + - DOM + - Element + - Elemento + - Interface + - Referencia + - Referência DOM +translation_of: Web/API/Element +--- +
{{APIRef("DOM")}}
+ +

Element é a classe base mais geral da qual todos os objetos em um {{DOMxRef("Document","documento")}} herdam. Este só tem métodos e propriedades comuns para todos os tipos de elementos. Classes mais específicas herdam de Element. Por exemplo, a interface {{DOMxRef("HTMLElement")}} é a interface base para os elementos HTML, enquanto a interface {{DOMxRef("SVGElement")}} é a base para todos os elementos SVG. A maioria das funcionalidades é especificada mais abaixo na hierarquia de classes.

+ +

Linguagens fora do âmbito da plataforma Web, como XUL através da interface XULElement, também implementa Element.

+ +

{{InheritanceDiagram}}

+ +

Propriedades

+ +

Inherits properties from its parent interface, {{DOMxRef("Node")}}, and by extension that interface's parent, {{DOMxRef("EventTarget")}}. It implements the properties of {{DOMxRef("ParentNode")}}, {{DOMxRef("ChildNode")}}, {{DOMxRef("NonDocumentTypeChildNode")}}, and {{DOMxRef("Animatable")}}.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NomeDescriçãoTipoDosponibilidade
attibutesTodos os atributos associados ao elementoNamedNodeMapAll
childNodesTodos os nós-filhos de um elemento.NodeListAll
classNameRetorna ou define a classe do elemento.StringHTML, XUL
clientHeightA altura interna de um elemento.NumberHTML
clientLeftA largura da borda esquerda de um elemento.NumberHTML
clientTopA largura da borda superior de um elemento.NumberHTML
clientWidthA largura interna de um elemento.NumberHTML
dirRetorna ou define a direcionalidade do elemento.StringHTML, XUL
firstChildO primeiro nó-filho direto de um elemento, ou null se o elemento não tem nós-filhos.NodeAll
idRetorna ou define o id do elemento.StringHTML, XUL
innerHTMLRetorna ou define a marcação e o conteúdo de um elemento.StringHTML
langRetorna ou define o atributo linguagem de um elemento, texto, e conteúdo do elemento.StringHTML
lastChildO último nó-filho direto de um elemento, ou null se o elemento não tem nós-filhos.NodeAll
localNameA parte local de um nome qualificado de um elemento.StringAll
NomeDescriçãoTipoDisponibilidade
nameRetorna/define o atributo name de um elemento.StringHTML
namespaceURIA URI de namespace do nó, ou null se não está especificado.StringAll
nextSiblingO nó imediatamente seguinte ao dado numa árvore, ou null se não existe nó-irmão.NodeAll
nodeNameO nome do nó.StringAll
nodeTypeUm número representando o tipo do nó. É sempre igual a 1 para elementos DOM.NumberAll
nodeValueO valor do nó. É sempre igual a null para elementos DOM.StringAll
offsetHeightA altura de um elemento, em relação ao layout.NumberHTML
offsetLeftA distância da borda esquerda do elemento para o a borda esquerda do seu offsetParent.NumberHTML
offsetParentO elemento para o qual todos cálculos de offset estão atualmente computados.ElementHTML
offsetTopA distância da borda superior do elemento para o a borda superior do seu offsetParent.NumberHTML
offsetWidthA largura de um elemento, em relação ao layout.NumberHTML
ownerDocumentO documento no qual o nó está, ou null se o nó não está dentro de nenhum.DocumentAll
NomeDescriçãoTipoDisponibilidade
parentNodeThe parent element of this node, or null if the node is not inside of a DOM Document.NodeAll
prefixThe namespace prefix of the node, or null if no prefix is specified.StringAll
previousSiblingThe node immediately preceding the given one in the tree, or null if there is no sibling node.NodeAll
scrollHeightThe scroll view height of an element.NumberHTML
scrollLeftGets/sets the left scroll offset of an element.NumberHTML
scrollTopGets/sets the top scroll offset of an element.NumberHTML
scrollWidthThe scroll view width of an element.NumberHTML
styleAn object representing the declarations of an element's style attributes.CSSStyleHTML, XUL
tabIndexGets/sets the position of the element in the tabbing order.NumberHTML
tagNameThe name of the tag for the given element.StringAll
textContentGets/sets the textual contents of an element and all its descendants.StringAll
+ +

Métodos

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Nome & DescriçãoRetornaDisponibilidade
addEventListener( type, listener, useCapture )
+ Register an event handler to a specific event type on the element.
-All
appendChild( appendedNode )
+ Insert a node as the last child node of this element.
NodeAll
blur()
+ Removes keyboard focus from the current element.
-HTML, XUL
click()
+ Simulates a click on the current element.
-HTML, XUL
cloneNode( deep )
+ Clone a node, and optionally, all of its contents.
NodeAll
dispatchEvent( event )
+ Dispatch an event to this node in the DOM.
BooleanAll
focus()
+ Gives keyboard focus to the current element.
-HTML, XUL
getAttribute( name )
+ Retrieve the value of the named attribute from the current node.
ObjectAll
getAttributeNS( namespace, name )
+ Retrieve the value of the attribute with the specified name and namespace, from the current node.
ObjectAll
getAttributeNode( name )
+ Retrieve the node representation of the named attribute from the current node.
AttrAll
getAttributeNodeNS( namespace, name )
+ Retrieve the node representation of the attribute with the specified name and namespace, from the current node.
AttrAll
Nome & DescriçãoRetornaDisponibilidade
getElementsByTagName( name )
+ Retrieve a set of all descendant elements, of a particular tag name, from the current element.
NodeSetAll
getElementsByTagNameNS( namespace, name )
+ Retrieve a set of all descendant elements, of a particular tag name and namespace, from the current element.
NodeSetAll
hasAttribute( name )
+ Check if the element has the specified attribute, or not.
BooleanAll
hasAttributeNS( namespace, name )
+ Check if the element has the specified attribute, in the specified namespace, or not.
BooleanAll
hasAttributes()
+ Check if the element has any attributes, or not.
BooleanAll
hasChildNodes()
+ Check if the element has any child nodes, or not.
BooleanAll
insertBefore( insertedNode, adjacentNode )
+ Inserts the first node before the second, child, Node in the DOM.
NodeAll
normalize()
+ Clean up all the text nodes under this element (merge adjacent, remove empty).
-All
removeAttribute( name )
+ Remove the named attribute from the current node.
-All
removeAttributeNS( namespace, name )
+ Remove the attribute with the specified name and namespace, from the current node.
-All
Nome & DescriçãoRetornaDisponibilidade
removeAttributeNode( name )
+ Remove the node representation of the named attribute from the current node.
-All
removeChild( removedNode )
+ Removes a child node from the current element.
NodeAll
removeEventListener( type, handler, useCapture )
+ Removes an event listener from the element.
-All
replaceChild( insertedNode, replacedNode )
+ Replaces one child node in the current element with another.
NodeAll
scrollIntoView( alignWithTop )
+ Scrolls the page until the element gets into the view.
-HTML
setAttribute( name, value )
+ Set the value of the named attribute from the current node.
-All
setAttributeNS( namespace, name, value )
+ Set the value of the attribute with the specified name and namespace, from the current node.
-All
setAttributeNode( name, attrNode )
+ Set the node representation of the named attribute from the current node.
-All
setAttributeNodeNS( namespace, name, attrNode )
+ Set the node representation of the attribute with the specified name and namespace, from the current node.
-All
+ +

Event Handlers

+ +

These are properties that correspond to the HTML 'on' event attributes.

+ +

Unlike the corresponding attributes, the values of these properties are functions (or any other object implementing the EventListener interface) rather than a string. In fact, assigning an event attribute in HTML creates a wrapper function around the specified code. For example, given the following HTML:

+ +
<div onclick="foo();">click me!</div>
+
+ +

If element is a reference to this div, the value of element.onclick is effectively:

+ +
function onclick(event) {
+   foo();
+}
+
+ +

Note how the event object is passed as parameter event to this wrapper function.

+ +
+
onblur
+
Returns the event handling code for the blur event.
+
+ +
+
onchange
+
Returns the event handling code for the change event.
+
+ +
+
onclick
+
Returns the event handling code for the click event.
+
+ +
+
ondblclick
+
Returns the event handling code for the dblclick event.
+
+ +
+
onfocus
+
Returns the event handling code for the focus event.
+
+ +
+
onkeydown
+
Returns the event handling code for the keydown event.
+
+ +
+
onkeypress
+
Returns the event handling code for the keypress event.
+
+ +
+
onkeyup
+
Returns the event handling code for the keyup event.
+
+ +
+
onmousedown
+
Returns the event handling code for the mousedown event.
+
+ +
+
onmousemove
+
Returns the event handling code for the mousemove event.
+
+ +
+
onmouseout
+
Returns the event handling code for the mouseout event.
+
+ +
+
onmouseover
+
Returns the event handling code for the mouseover event.
+
+ +
+
onmouseup
+
Returns the event handling code for the mouseup event.
+
+ +
+
onresize
+
Returns the event handling code for the resize event.
+
+ +
+
onscroll
+
Returns the event handling code for the scroll event.
+
+ +
 
+ +

Compatibilidade de navegador

+ + + +

{{Compat("api.Element")}}

diff --git a/files/pt-pt/web/api/eventos_de_luz_ambiente/index.html b/files/pt-pt/web/api/eventos_de_luz_ambiente/index.html deleted file mode 100644 index 32b15a8ea1..0000000000 --- a/files/pt-pt/web/api/eventos_de_luz_ambiente/index.html +++ /dev/null @@ -1,70 +0,0 @@ ---- -title: Eventos de Luz Ambiente -slug: Web/API/Eventos_de_Luz_Ambiente -tags: - - Luz Ambiente -translation_of: Web/API/Ambient_Light_Events ---- -
{{DefaultAPISidebar("Ambient Light Events")}}{{SeeCompatTable}}
- -

Os eventos de luz ambiente são uma maneira prática de tornar uma página da Web ou um aplicação ciente de qualquer alteração na intensidade da luz. Isto permite-lhes reagir a essa alteração, por exemplo, alterando o contraste da cor da interface do utilizador (IU) ou alterando a exposição necessária para tirar uma fotografia.

- -

Eventos de Luz

- -

When the light sensor of a device detects a change in the light level, it notifies the browser of that change. When the browser gets such a notification, it fires a {{domxref("DeviceLightEvent")}} event that provides information about the exact light intensity.

- -

This event can be captured at the window object level by using the {{domxref("EventTarget.addEventListener","addEventListener")}} method (using the {{event("devicelight")}} event name) or by attaching an event handler to the {{domxref("window.ondevicelight")}} property.

- -

Once captured, the event object gives access to the light intensity expressed in lux through the {{domxref("DeviceLightEvent.value")}} property.

- -

Exemplo

- -
if ('ondevicelight' in window) {
-  window.addEventListener('devicelight', function(event) {
-    var body = document.querySelector('body');
-    if (event.value < 50) {
-      body.classList.add('darklight');
-      body.classList.remove('brightlight');
-    } else {
-      body.classList.add('brightlight');
-      body.classList.remove('darklight');
-    }
-  });
-} else {
-  console.log('devicelight event not supported');
-}
-
- -

Especificações

- - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName("AmbientLight", "", "Ambient Light Events")}}{{Spec2("AmbientLight")}}Initial definition
- -

Compatibilidade de navegador

- - - -

{{Compat("api.DeviceLightEvent")}}

- -

 

- -

Consultar também

- - diff --git a/files/pt-pt/web/api/file_and_directory_entries_api/index.html b/files/pt-pt/web/api/file_and_directory_entries_api/index.html new file mode 100644 index 0000000000..26e56945ee --- /dev/null +++ b/files/pt-pt/web/api/file_and_directory_entries_api/index.html @@ -0,0 +1,191 @@ +--- +title: API Entradas de Diretoria e Ficheiro +slug: Web/API/API_Entradas_de_Diretoria_e_Ficheiro +tags: + - API + - API Entradas de Diretoria e Ficheiro + - API Sistema de Ficheiros + - Ficheiros + - Não Padrão + - Referencia + - Resuno + - Sinopse +translation_of: Web/API/File_and_Directory_Entries_API +--- +

{{DefaultAPISidebar("File System API")}}{{Non-standard_header}}

+ +

API Entradas de Diretoria e Ficheiro simula um sistema de ficheiros local em que as páginas da Web podem navegar dentro e aceder aos ficheiros na mesma. Pode desenvolver aplicações que lêem, escrevem e criam ficheiros e/ou diretorias num sistema de ficheiros virtual e ambiente de testes (sandbox).

+ +
+

Because this is a non-standard API, whose specification is not currently on a standards track, it's important to keep in mind that not all browsers implement it, and those that do may implement only small portions of it. Check the {{anch("Browser compatibility")}} section for details.

+
+ +

Two very similar APIs exist depending on whether you desire asynchronous or synchronous behavior. The synchronous API is indended to be used inside a {{domxref("Worker")}} and will return the values you desire. The asynchronous API will not block and functions and the API will not return values; instead, you will need to supply a callback function to handle the response whenever it arrives.

+ +
+

The Firefox implementation of the File and Directory Entries API is very limited; there is no support for creating files. Only for accessing files which are selected by the user in a file {{HTMLElement("input")}} element (see {{domxref("HTMLInputElement")}} as well) or when a file or directory is provided to the Web site or app using drag and drop. Firefox also does not implement the synchronous API. Check the browser compatibility for any part of the API you use carefully, and see File and Directory Entries API support in Firefox for more details.

+
+ +

Obter acesso a um sistema de ficheiros

+ +

There are two ways to get access to file systems defined in the current specification draft:

+ + + +

API Assíncrona

+ +

The asynchronous API should be used for most operations, to prevent file system accesses from blocking the entire browser if used on the main thread. It includes the following interfaces:

+ +
+
{{domxref("FileSystem")}}
+
Represents a file system.
+
{{domxref("FileSystemEntry")}}
+
The basic interface representing a single entry in a file system. This is implemented by other interfaces which represent files or directories.
+
{{domxref("FileSystemFileEntry")}}
+
Represents a single file in a file system.
+
{{domxref("FileSystemDirectoryEntry")}}
+
Represents a single directory in a file system.
+
{{domxref("FileSystemDirectoryReader")}}
+
Created by calling {{domxref("FileSystemDirectoryEntry.createReader()")}}, this interface provides the functionality which lets you read the contents of a directory.
+
{{domxref("FileSystemFlags")}}
+
Defines a set of values which are used when specifying option flags when calling certain methods in the File and Directory Entries API.
+
{{domxref("FileError")}}
+
Represents an error which is generated by asynchronous file system calls.
+
+ +

There are also two global functions (which are not part of the specification at this time and are implemented only by Google Chrome). They're available on the {{domxref("Window")}} object and implemented in {{domxref("LocalFileSystem")}}: requestFileSystem() and resolveLocalFileSystemURL().

+ +

API Síncrona

+ +

The synchronous API is should only be used in {{domxref("Worker")}}s; these calls block until they're finished executing, and simply return the results instead of using callbacks. Using them on the main thread will block the browser, which is naughty. The interfaces below otherwise mirror the ones from the asynchronous API.

+ +
+
{{domxref("FileSystemSync")}}
+
Represents a file system.
+
{{domxref("FileSystemEntrySync")}}
+
The basic interface representing a single entry in a file system. This is implemented by other interfaces which represent files or directories. {{domxref("EntrySync")}}
+
{{domxref("FileSystemFileEntrySync")}}
+
Represents a single file in a file system.
+
{{domxref("FileSystemDirectoryEntrySync")}}
+
Represents a single directory in a file system.
+
{{domxref("FileSystemDirectoryReaderSync")}}
+
Created by calling {{domxref("FileSystemDirectoryEntrySync.createReader()")}}, this interface provides the functionality which lets you read the contents of a directory.
+
{{domxref("FileException")}}
+
Represents an error which is generated by synchronous file system calls.
+
+ +

There are also two global functions (which are not part of the specification at this time and are implemented only by Google Chrome). They're available on the {{domxref("Worker")}} object and implemented in {{domxref("LocalFileSystemSync")}}: requestFileSystemSync() and resolveLocalFileSystemSyncURL().

+ +

Outras Interfaces

+ +
+
{{domxref("LocalFileSystem")}}
+
Gives you access to a sandboxed file system.
+
{{domxref("LocalFileSystemSync")}}
+
 
+
{{domxref("LockedFile")}}
+
Provides tools to deal with a given file with all the necessary locks.
+
{{domxref("Metadata")}}{{experimental_inline}}
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('File System API')}}{{Spec2('File System API')}}Draft of proposed API
+ +

This API has no official W3C or WHATWG specification.

+ +

Compatibilidade de navegador

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Asynchronous API13 {{ property_prefix("webkit") }}{{ CompatGeckoDesktop(50) }}[1]{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
Synchronous API13 {{ property_prefix("webkit") }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Asynchronous API{{ CompatNo }}{{ CompatVersionUnknown }} {{ property_prefix("webkit") }}{{ CompatGeckoMobile(50) }}[1]{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
Synchronous API{{ CompatNo }}{{ CompatVersionUnknown }} {{ property_prefix("webkit") }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
+
+ +

[1] Firefox 50 introduces partial support for the File and Directory Entries API. Be sure to check the compatibility tables for individual interfaces and methods before using them, to ensure that they're supported, before you use them. The API can be disabled by setting the value of the preference dom.webkitBlink.filesystem.enabled to false.

+ +

Consulte também

+ + diff --git a/files/pt-pt/web/api/filesystem/index.html b/files/pt-pt/web/api/filesystem/index.html new file mode 100644 index 0000000000..76c4db9d6c --- /dev/null +++ b/files/pt-pt/web/api/filesystem/index.html @@ -0,0 +1,54 @@ +--- +title: Sistema de Ficheiros +slug: Web/API/Sistema_de_ficheiros +tags: + - API + - File API + - File System API + - File and Directory Entries API + - Interface + - Não Standard + - Offline + - filesystem +translation_of: Web/API/FileSystem +--- +
+

{{APIRef("File System API")}}{{SeeCompatTable}}

+ +

A interface da "API de Entradas de Diretorias e Ficheiros" é usada para representar um sistema de ficheiros. Estes objetos podem ser obtidos a partir da propriedade {{domxref("FileSystemEntry.filesystem", "filesystem")}} em qualquer entrada do sistema de ficheiros. Alguns navegadores oferecem APIs adicionais para criar e gerir sistemas de ficheiros, por exemplo o método {{domxref("Window.requestFileSystem", "requestFileSystem()")}} encontrado no Chrome.

+ +

Esta interface não dá acesso ao filesystem do utilizador. Em vez disso, terá uma "drive virtual" dentro da sandbox do navegador. Se quiser ter acesso ao sistema de ficheiros dos utilizadores, necessita de invocar o utilizador.

+
+ +

Conceitos básicos

+ +

Existem duas formas para aceder ao objeto FileSystem:

+ +
    +
  1. Pode pedir por um dentro duma sandbox para só a sua app ao chamar window.requestFileSystem(). Se a chamada tiver sucesso, é executada uma callback handler, que recebe como parâmetro um objeto FileSystem que descreve o sistema de ficheiros.
  2. +
  3. Pode o pedir através duma entrada no sistema de ficheiros, com a propriadade {{domxref("FileSystemEntry.filesystem", "filesystem")}}.
  4. +
+ +

Atributos

+ +
+
{{domxref("FileSystem.name")}} {{ReadOnlyInline}}
+
Uma {{domxref("USVString")}} que representa o nome do sistema de ficheiros. Este nome é único na lista de sistemas de ficheiros exposta.
+
{{domxref("FileSystem.root")}} {{ReadOnlyInline}}
+
Um objeto de {{domxref("FileSystemDirectoryEntry")}} que representa a diretoria raiz do sistema de ficheiros. Através deste objeto, pode ganhar acesso a todos os ficheiros e diretorias no sistema.
+
+ +

Compatibilidade

+ + + +

{{Compat("api.FileSystem")}}

+ +

Ver também

+ + diff --git a/files/pt-pt/web/api/geolocation/utilizacao_da_geolocalizacao/index.html b/files/pt-pt/web/api/geolocation/utilizacao_da_geolocalizacao/index.html deleted file mode 100644 index 40fb7ce571..0000000000 --- a/files/pt-pt/web/api/geolocation/utilizacao_da_geolocalizacao/index.html +++ /dev/null @@ -1,242 +0,0 @@ ---- -title: API de Geolocalização -slug: Web/API/Geolocation/Utilizacao_da_geolocalizacao -tags: - - API de Geolocalização - - Guía - - Intermediário -translation_of: Web/API/Geolocation_API ---- -

{{securecontext_header}}{{APIRef("Geolocation API")}}

- -

A API de geolocalização permite que o utilizador forneça a sua localização nas aplicações da Web, se assim o desejar. Por motivos de segurança, é solicitado ao utilizador para dar permissão para informar a informação da localização.

- -

O objeto de geolocalização

- -

A API de Geolocation é publicada através do objeto {{domxref("navigator.geolocation")}}.

- -

Se o objeto existir, os serviços de geolocalização estarão disponíveis. Pode testar a presença de geolocalização assim:

- -
if ("geolocation" in navigator) {
-  /* geolocation is available */
-} else {
-  /* geolocation IS NOT available */
-}
-
- -
-

Nota: On Firefox 24 and older versions, "geolocation" in navigator always returned true even if the API was disabled. This has been fixed with Firefox 25 to comply with the spec. ({{bug(884921)}}).

-
- -

Obter a posição atual

- -

To obtain the user's current location, you can call the {{domxref("geolocation.getCurrentPosition()","getCurrentPosition()")}} method. This initiates an asynchronous request to detect the user's position, and queries the positioning hardware to get up-to-date information. When the position is determined, the defined callback function is executed. You can optionally provide a second callback function to be executed if an error occurs. A third, optional, parameter is an options object where you can set the maximum age of the position returned, the time to wait for a request, and if you want high accuracy for the position.

- -
-

Nota: By default, {{domxref("Geolocation.getCurrentPosition()","getCurrentPosition()")}} tries to answer as fast as possible with a low accuracy result. It is useful if you need a quick answer regardless of the accuracy. Devices with a GPS, for example, can take a minute or more to get a GPS fix, so less accurate data (IP location or wifi) may be returned to {{domxref("Geolocation.getCurrentPosition()","getCurrentPosition()")}}.

-
- -
navigator.geolocation.getCurrentPosition(function(position) {
-  do_something(position.coords.latitude, position.coords.longitude);
-});
- -

The above example will cause the do_something() function to execute when the location is obtained.

- -

Vigiar a posição atual

- -

If the position data changes (either by device movement or if more accurate geo information arrives), you can set up a callback function that is called with that updated position information. This is done using the {{domxref("Geolocation.watchPosition()","watchPosition()")}} function, which has the same input parameters as {{domxref("Geolocation.getCurrentPosition()","getCurrentPosition()")}}. The callback function is called multiple times, allowing the browser to either update your location as you move, or provide a more accurate location as different techniques are used to geolocate you. The error callback function, which is optional just as it is for {{domxref("Geolocation.getCurrentPosition()","getCurrentPosition()")}}, can be called repeatedly.

- -
-

Nota: pode utilizar {{domxref("Geolocation.watchPosition()","watchPosition()")}} sem uma chamada inicial {{domxref("Geolocation.getCurrentPosition()","getCurrentPosition()")}}.

-
- -
var watchID = navigator.geolocation.watchPosition(function(position) {
-  do_something(position.coords.latitude, position.coords.longitude);
-});
- -

The {{domxref("Geolocation.watchPosition()","watchPosition()")}} method returns an ID number that can be used to uniquely identify the requested position watcher; you use this value in tandem with the {{domxref("Geolocation.clearWatch()","clearWatch()")}} method to stop watching the user's location.

- -
navigator.geolocation.clearWatch(watchID);
-
- -

Resposta de ajuste preciso

- -

Both {{domxref("Geolocation.getCurrentPosition()","getCurrentPosition()")}} and {{domxref("Geolocation.watchPosition()","watchPosition()")}} accept a success callback, an optional error callback, and an optional PositionOptions object.

- -

{{page("/en-US/docs/DOM/navigator.geolocation.getCurrentPosition","PositionOptions")}}

- -

A call to {{domxref("Geolocation.watchPosition()","watchPosition")}} could look like:

- -
function geo_success(position) {
-  do_something(position.coords.latitude, position.coords.longitude);
-}
-
-function geo_error() {
-  alert("Sorry, no position available.");
-}
-
-var geo_options = {
-  enableHighAccuracy: true,
-  maximumAge        : 30000,
-  timeout           : 27000
-};
-
-var wpid = navigator.geolocation.watchPosition(geo_success, geo_error, geo_options);
- -

Descrever uma posição

- -

The user's location is described using a Position object referencing a Coordinates object.

- -

{{page("/en-US/docs/DOM/navigator/geolocation/getCurrentPosition","Position")}}

- -

{{page("/en-US/docs/DOM/navigator/geolocation/getCurrentPosition","Coordinates")}}

- -

Lidar com erros

- -

The error callback function, if provided when calling getCurrentPosition() or watchPosition(), expects a PositionError object as its first parameter.

- -
function errorCallback(error) {
-  alert('ERROR(' + error.code + '): ' + error.message);
-};
-
- -

{{page("/en-US/docs/DOM/navigator/geolocation/getCurrentPosition","PositionError")}}

- -

Exemplo de Geolocalização Live

- - - -

Conteúdo HTML

- -
<p><button onclick="geoFindMe()">Show my location</button></p>
-<div id="out"></div>
-
- -

Conteúdo JavaScript

- -
function geoFindMe() {
-  var output = document.getElementById("out");
-
-  if (!navigator.geolocation){
-    output.innerHTML = "<p>Geolocation is not supported by your browser</p>";
-    return;
-  }
-
-  function success(position) {
-    var latitude  = position.coords.latitude;
-    var longitude = position.coords.longitude;
-
-    output.innerHTML = '<p>Latitude is ' + latitude + '° <br>Longitude is ' + longitude + '°</p>';
-
-    var img = new Image();
-    img.src = "https://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=13&size=300x300&sensor=false";
-
-    output.appendChild(img);
-  }
-
-  function error() {
-    output.innerHTML = "Unable to retrieve your location";
-  }
-
-  output.innerHTML = "<p>Locating…</p>";
-
-  navigator.geolocation.getCurrentPosition(success, error);
-}
-
- -

Resultado Live

- -

{{EmbedLiveSample('Geolocation_Live_Example', 350, 410)}}

- -

Aviso para permissão

- -

Any add-on hosted on addons.mozilla.org which makes use of geolocation data must explicitly request permission before doing so. The following function will request permission in a manner similar to the automatic prompt displayed for web pages. The user's response will be saved in the preference specified by the pref parameter, if applicable. The function provided in the callback parameter will be called with a boolean value indicating the user's response. If true, the add-on may access geolocation data.

- -
function prompt(window, pref, message, callback) {
-    let branch = Components.classes["@mozilla.org/preferences-service;1"]
-                           .getService(Components.interfaces.nsIPrefBranch);
-
-    if (branch.getPrefType(pref) === branch.PREF_STRING) {
-        switch (branch.getCharPref(pref)) {
-        case "always":
-            return callback(true);
-        case "never":
-            return callback(false);
-        }
-    }
-
-    let done = false;
-
-    function remember(value, result) {
-        return function() {
-            done = true;
-            branch.setCharPref(pref, value);
-            callback(result);
-        }
-    }
-
-    let self = window.PopupNotifications.show(
-        window.gBrowser.selectedBrowser,
-        "geolocation",
-        message,
-        "geo-notification-icon",
-        {
-            label: "Share Location",
-            accessKey: "S",
-            callback: function(notification) {
-                done = true;
-                callback(true);
-            }
-        }, [
-            {
-                label: "Always Share",
-                accessKey: "A",
-                callback: remember("always", true)
-            },
-            {
-                label: "Never Share",
-                accessKey: "N",
-                callback: remember("never", false)
-            }
-        ], {
-            eventCallback: function(event) {
-                if (event === "dismissed") {
-                    if (!done) callback(false);
-                    done = true;
-                    window.PopupNotifications.remove(self);
-                }
-            },
-            persistWhileVisible: true
-        });
-}
-
-prompt(window,
-       "extensions.foo-addon.allowGeolocation",
-       "Foo Add-on wants to know your location.",
-       function callback(allowed) { alert(allowed); });
-
- -

Compatibilidade de navegador

- -

{{Compat("api.Geolocation")}}

- -

Disponibilidade

- -

Como a localização baseada em Wi-Fi é geralmente fornecida pelo Google, a API de Geolocalização "vanilla" pode estar indisponível na China. Pode utilizar os provedores locais de terceiros, tais como  Baidu, Autonavi, ou Tencent. Estes serviços utilziam o endereço de IP do utilizador e/ou uma aplicação local para fornecer o posicionamento melhorado.

- -

Consulte também

- - diff --git a/files/pt-pt/web/api/geolocation_api/index.html b/files/pt-pt/web/api/geolocation_api/index.html new file mode 100644 index 0000000000..40fb7ce571 --- /dev/null +++ b/files/pt-pt/web/api/geolocation_api/index.html @@ -0,0 +1,242 @@ +--- +title: API de Geolocalização +slug: Web/API/Geolocation/Utilizacao_da_geolocalizacao +tags: + - API de Geolocalização + - Guía + - Intermediário +translation_of: Web/API/Geolocation_API +--- +

{{securecontext_header}}{{APIRef("Geolocation API")}}

+ +

A API de geolocalização permite que o utilizador forneça a sua localização nas aplicações da Web, se assim o desejar. Por motivos de segurança, é solicitado ao utilizador para dar permissão para informar a informação da localização.

+ +

O objeto de geolocalização

+ +

A API de Geolocation é publicada através do objeto {{domxref("navigator.geolocation")}}.

+ +

Se o objeto existir, os serviços de geolocalização estarão disponíveis. Pode testar a presença de geolocalização assim:

+ +
if ("geolocation" in navigator) {
+  /* geolocation is available */
+} else {
+  /* geolocation IS NOT available */
+}
+
+ +
+

Nota: On Firefox 24 and older versions, "geolocation" in navigator always returned true even if the API was disabled. This has been fixed with Firefox 25 to comply with the spec. ({{bug(884921)}}).

+
+ +

Obter a posição atual

+ +

To obtain the user's current location, you can call the {{domxref("geolocation.getCurrentPosition()","getCurrentPosition()")}} method. This initiates an asynchronous request to detect the user's position, and queries the positioning hardware to get up-to-date information. When the position is determined, the defined callback function is executed. You can optionally provide a second callback function to be executed if an error occurs. A third, optional, parameter is an options object where you can set the maximum age of the position returned, the time to wait for a request, and if you want high accuracy for the position.

+ +
+

Nota: By default, {{domxref("Geolocation.getCurrentPosition()","getCurrentPosition()")}} tries to answer as fast as possible with a low accuracy result. It is useful if you need a quick answer regardless of the accuracy. Devices with a GPS, for example, can take a minute or more to get a GPS fix, so less accurate data (IP location or wifi) may be returned to {{domxref("Geolocation.getCurrentPosition()","getCurrentPosition()")}}.

+
+ +
navigator.geolocation.getCurrentPosition(function(position) {
+  do_something(position.coords.latitude, position.coords.longitude);
+});
+ +

The above example will cause the do_something() function to execute when the location is obtained.

+ +

Vigiar a posição atual

+ +

If the position data changes (either by device movement or if more accurate geo information arrives), you can set up a callback function that is called with that updated position information. This is done using the {{domxref("Geolocation.watchPosition()","watchPosition()")}} function, which has the same input parameters as {{domxref("Geolocation.getCurrentPosition()","getCurrentPosition()")}}. The callback function is called multiple times, allowing the browser to either update your location as you move, or provide a more accurate location as different techniques are used to geolocate you. The error callback function, which is optional just as it is for {{domxref("Geolocation.getCurrentPosition()","getCurrentPosition()")}}, can be called repeatedly.

+ +
+

Nota: pode utilizar {{domxref("Geolocation.watchPosition()","watchPosition()")}} sem uma chamada inicial {{domxref("Geolocation.getCurrentPosition()","getCurrentPosition()")}}.

+
+ +
var watchID = navigator.geolocation.watchPosition(function(position) {
+  do_something(position.coords.latitude, position.coords.longitude);
+});
+ +

The {{domxref("Geolocation.watchPosition()","watchPosition()")}} method returns an ID number that can be used to uniquely identify the requested position watcher; you use this value in tandem with the {{domxref("Geolocation.clearWatch()","clearWatch()")}} method to stop watching the user's location.

+ +
navigator.geolocation.clearWatch(watchID);
+
+ +

Resposta de ajuste preciso

+ +

Both {{domxref("Geolocation.getCurrentPosition()","getCurrentPosition()")}} and {{domxref("Geolocation.watchPosition()","watchPosition()")}} accept a success callback, an optional error callback, and an optional PositionOptions object.

+ +

{{page("/en-US/docs/DOM/navigator.geolocation.getCurrentPosition","PositionOptions")}}

+ +

A call to {{domxref("Geolocation.watchPosition()","watchPosition")}} could look like:

+ +
function geo_success(position) {
+  do_something(position.coords.latitude, position.coords.longitude);
+}
+
+function geo_error() {
+  alert("Sorry, no position available.");
+}
+
+var geo_options = {
+  enableHighAccuracy: true,
+  maximumAge        : 30000,
+  timeout           : 27000
+};
+
+var wpid = navigator.geolocation.watchPosition(geo_success, geo_error, geo_options);
+ +

Descrever uma posição

+ +

The user's location is described using a Position object referencing a Coordinates object.

+ +

{{page("/en-US/docs/DOM/navigator/geolocation/getCurrentPosition","Position")}}

+ +

{{page("/en-US/docs/DOM/navigator/geolocation/getCurrentPosition","Coordinates")}}

+ +

Lidar com erros

+ +

The error callback function, if provided when calling getCurrentPosition() or watchPosition(), expects a PositionError object as its first parameter.

+ +
function errorCallback(error) {
+  alert('ERROR(' + error.code + '): ' + error.message);
+};
+
+ +

{{page("/en-US/docs/DOM/navigator/geolocation/getCurrentPosition","PositionError")}}

+ +

Exemplo de Geolocalização Live

+ + + +

Conteúdo HTML

+ +
<p><button onclick="geoFindMe()">Show my location</button></p>
+<div id="out"></div>
+
+ +

Conteúdo JavaScript

+ +
function geoFindMe() {
+  var output = document.getElementById("out");
+
+  if (!navigator.geolocation){
+    output.innerHTML = "<p>Geolocation is not supported by your browser</p>";
+    return;
+  }
+
+  function success(position) {
+    var latitude  = position.coords.latitude;
+    var longitude = position.coords.longitude;
+
+    output.innerHTML = '<p>Latitude is ' + latitude + '° <br>Longitude is ' + longitude + '°</p>';
+
+    var img = new Image();
+    img.src = "https://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=13&size=300x300&sensor=false";
+
+    output.appendChild(img);
+  }
+
+  function error() {
+    output.innerHTML = "Unable to retrieve your location";
+  }
+
+  output.innerHTML = "<p>Locating…</p>";
+
+  navigator.geolocation.getCurrentPosition(success, error);
+}
+
+ +

Resultado Live

+ +

{{EmbedLiveSample('Geolocation_Live_Example', 350, 410)}}

+ +

Aviso para permissão

+ +

Any add-on hosted on addons.mozilla.org which makes use of geolocation data must explicitly request permission before doing so. The following function will request permission in a manner similar to the automatic prompt displayed for web pages. The user's response will be saved in the preference specified by the pref parameter, if applicable. The function provided in the callback parameter will be called with a boolean value indicating the user's response. If true, the add-on may access geolocation data.

+ +
function prompt(window, pref, message, callback) {
+    let branch = Components.classes["@mozilla.org/preferences-service;1"]
+                           .getService(Components.interfaces.nsIPrefBranch);
+
+    if (branch.getPrefType(pref) === branch.PREF_STRING) {
+        switch (branch.getCharPref(pref)) {
+        case "always":
+            return callback(true);
+        case "never":
+            return callback(false);
+        }
+    }
+
+    let done = false;
+
+    function remember(value, result) {
+        return function() {
+            done = true;
+            branch.setCharPref(pref, value);
+            callback(result);
+        }
+    }
+
+    let self = window.PopupNotifications.show(
+        window.gBrowser.selectedBrowser,
+        "geolocation",
+        message,
+        "geo-notification-icon",
+        {
+            label: "Share Location",
+            accessKey: "S",
+            callback: function(notification) {
+                done = true;
+                callback(true);
+            }
+        }, [
+            {
+                label: "Always Share",
+                accessKey: "A",
+                callback: remember("always", true)
+            },
+            {
+                label: "Never Share",
+                accessKey: "N",
+                callback: remember("never", false)
+            }
+        ], {
+            eventCallback: function(event) {
+                if (event === "dismissed") {
+                    if (!done) callback(false);
+                    done = true;
+                    window.PopupNotifications.remove(self);
+                }
+            },
+            persistWhileVisible: true
+        });
+}
+
+prompt(window,
+       "extensions.foo-addon.allowGeolocation",
+       "Foo Add-on wants to know your location.",
+       function callback(allowed) { alert(allowed); });
+
+ +

Compatibilidade de navegador

+ +

{{Compat("api.Geolocation")}}

+ +

Disponibilidade

+ +

Como a localização baseada em Wi-Fi é geralmente fornecida pelo Google, a API de Geolocalização "vanilla" pode estar indisponível na China. Pode utilizar os provedores locais de terceiros, tais como  Baidu, Autonavi, ou Tencent. Estes serviços utilziam o endereço de IP do utilizador e/ou uma aplicação local para fornecer o posicionamento melhorado.

+ +

Consulte também

+ + diff --git a/files/pt-pt/web/api/media_streams_api/index.html b/files/pt-pt/web/api/media_streams_api/index.html new file mode 100644 index 0000000000..399945ab71 --- /dev/null +++ b/files/pt-pt/web/api/media_streams_api/index.html @@ -0,0 +1,211 @@ +--- +title: API de Captura de Transmissões de Multimédia (Media Streams) +slug: Web/API/API_transmissoes_multimedia +tags: + - API + - API de Transmissão de Multimédia + - Audio + - Avançado + - Guía + - Introdução + - Media + - Multimedia + - Video +translation_of: Web/API/Media_Streams_API +--- +
{{DefaultAPISidebar("Media Capture and Streams")}}
+ +

A API de Media Capture and Streams, muitas vezes chamada de Media Stream API ou Stream API, é uma API relacionada com WebRTC que suporta transmissões de dados de áudio ou vídeo, os métodos para trabalhar com eles, as restrições associadas com o tipo de dados, as devoluções de retorno de sucesso e erro quando utilizar os dados de forma assíncrona, e os eventos que foram ativados durante o processo.

+ +

Conceitos básicos

+ +

The API is based on the manipulation of a {{domxref("MediaStream")}} object representing a flux of audio- or video-related data. See an example in Get the video.

+ +

A MediaStream consists of zero or more {{domxref("MediaStreamTrack")}} objects, representing various audio or video tracks. Each MediaStreamTrack may have one or more channels. The channel represents the smallest unit of a media stream, such as an audio signal associated with a given speaker, like left or right in a stereo audio track.

+ +

MediaStream objects have a single input and a single output. A MediaStream object generated by {{domxref("MediaDevices.getUserMedia", "getUserMedia()")}} is called local, and has as its source input one of the user's cameras or microphones. A non-local MediaStream may be representing to a media element, like {{HTMLElement("video")}} or {{HTMLElement("audio")}}, a stream originating over the network, and obtained via the WebRTC {{domxref("RTCPeerConnection")}} API, or a stream created using the Web Audio API {{domxref("MediaStreamAudioSourceNode")}}.   The output of the MediaStream object is linked to a consumer. It can be a media elements, like {{HTMLElement("audio")}} or {{HTMLElement("video")}},  the WebRTC {{domxref("RTCPeerConnection")}} API or a Web Audio API {{domxref("MediaStreamAudioDestinationNode")}}.

+ +

Referência

+ +
+ +
+ +

Guias e tutoriais

+ +

{{LandingPageListSubpages}}

+ +

Compatibilidade de navegador

+ +

{{ CompatibilityTable }} 

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)EdgeInternet ExplorerOpera Safari (WebKit)
Stream API 21{{ property_prefix("webkit") }} Nightly 18{{ property_prefix("moz") }} {{ CompatVersionUnknown }}{{ CompatUnknown }} 12{{ CompatUnknown }} 
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
API de emissão{{ CompatNo }} {{CompatVersionUnknown}}{{ CompatUnknown }}{{ CompatUnknown }} {{ CompatNo }} {{ CompatNo }} 
+
+ +

 

+ +

Currently using WebRTC for accessing the camera is supported in Chrome, Opera and Firefox Nightly 18. Enabling WebRTC in Firefox Nightly requires you to set a flag in the configuration:

+ + + +

Consulte também

+ + + +
+ + + + + +
diff --git a/files/pt-pt/web/api/metadados/index.html b/files/pt-pt/web/api/metadados/index.html deleted file mode 100644 index dd1c16c91d..0000000000 --- a/files/pt-pt/web/api/metadados/index.html +++ /dev/null @@ -1,116 +0,0 @@ ---- -title: Metadados -slug: Web/API/Metadados -tags: - - API - - API Entradas de Diretoria e Ficheiro - - API do Sistema de Ficheiros - - Ficheiros - - Interface - - Não Padrão - - Pff-line - - Referencia - - metadados -translation_of: Web/API/Metadata ---- -

{{ APIRef("File System API") }}{{SeeCompatTable}}{{Non-standard_header}}

- -

A interface de Metadados é utilizada por API Entradas de Diretoria e Ficheiro para conter a informação sobre a entrada do sistema de ficheiros. Estes metadados incluem o tamanho do ficheiro e a data e hora da modificação.

- -
-

Esta interface não está disponível através do escopo global; em vez disso, pode obter um objeto Metadata descrevendo uma {{domxref("FileSystemEntry")}} utilizando o método {{domxref("FileSystemEntry.getMetadata()")}}.

-
- -

Propriedades

- -
-
{{domxref("Metadata.modificationTime", "modificationTime")}} {{ReadOnlyInline}}
-
A {{jsxref("Date")}} object indicating the date and time the entry was modified.
-
- -
-
{{domxref("Metadata.size", "size")}} {{ReadOnlyInline}}
-
A 64-bit unsigned integer indicating the size of the entry in bytes.
-
- -

Especificações

- - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('File System API')}}{{Spec2('File System API')}}Draft of proposed API
- -

Esta API não é uma especificação oficial de W3C ou WHATWG.

- -

Compatibilidade de navegador

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico13 {{property_prefix("webkit")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeAndroidChrome para AndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico{{CompatNo}}0.16 {{property_prefix("webkit")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

Consulte também

- - diff --git a/files/pt-pt/web/api/metadata/index.html b/files/pt-pt/web/api/metadata/index.html new file mode 100644 index 0000000000..dd1c16c91d --- /dev/null +++ b/files/pt-pt/web/api/metadata/index.html @@ -0,0 +1,116 @@ +--- +title: Metadados +slug: Web/API/Metadados +tags: + - API + - API Entradas de Diretoria e Ficheiro + - API do Sistema de Ficheiros + - Ficheiros + - Interface + - Não Padrão + - Pff-line + - Referencia + - metadados +translation_of: Web/API/Metadata +--- +

{{ APIRef("File System API") }}{{SeeCompatTable}}{{Non-standard_header}}

+ +

A interface de Metadados é utilizada por API Entradas de Diretoria e Ficheiro para conter a informação sobre a entrada do sistema de ficheiros. Estes metadados incluem o tamanho do ficheiro e a data e hora da modificação.

+ +
+

Esta interface não está disponível através do escopo global; em vez disso, pode obter um objeto Metadata descrevendo uma {{domxref("FileSystemEntry")}} utilizando o método {{domxref("FileSystemEntry.getMetadata()")}}.

+
+ +

Propriedades

+ +
+
{{domxref("Metadata.modificationTime", "modificationTime")}} {{ReadOnlyInline}}
+
A {{jsxref("Date")}} object indicating the date and time the entry was modified.
+
+ +
+
{{domxref("Metadata.size", "size")}} {{ReadOnlyInline}}
+
A 64-bit unsigned integer indicating the size of the entry in bytes.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('File System API')}}{{Spec2('File System API')}}Draft of proposed API
+ +

Esta API não é uma especificação oficial de W3C ou WHATWG.

+ +

Compatibilidade de navegador

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico13 {{property_prefix("webkit")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidChrome para AndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico{{CompatNo}}0.16 {{property_prefix("webkit")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

Consulte também

+ + diff --git a/files/pt-pt/web/api/navigatoronline/eventos_online_e_offline/index.html b/files/pt-pt/web/api/navigatoronline/eventos_online_e_offline/index.html deleted file mode 100644 index 43aed9ed94..0000000000 --- a/files/pt-pt/web/api/navigatoronline/eventos_online_e_offline/index.html +++ /dev/null @@ -1,97 +0,0 @@ ---- -title: Eventos online e offline -slug: Web/API/NavigatorOnLine/Eventos_online_e_offline -tags: - - AJAX - - DOM - - Desenvolvimento_Web - - Todas_as_Categorias -translation_of: Web/API/NavigatorOnLine/Online_and_offline_events ---- -

O Firefox 3 implementou eventos Online/Offline da especificação WHATWG Web Applications 1.0.

- -

Visão geral

- -

Para construir uma boa aplicação web capaz de ser usada offline, você precisar saber quando sua aplicação está realmente offline. Casualmente, você pode também precisar saber quando a sua aplicação retornou ao estado 'online' novamente. Efetivamente, as exigências colapsam como tal:

- -
    -
  1. Você precisa saber quando o usuário torna-se online, então você pode re-sincronizar com o servidor.
  2. -
  3. Você precisa saber quando o usuário está offline, então você pode estar seguro para fazer suas requisições do servidor e elas se enfileirarem para um tempo posterior.
  4. -
- -

Este é o processo em que eventos online/offline ajudam a banalizar.

- -

API

- - - -

navigator.onLine é uma propriedade que mantém um valor true/false (true para online, false para offline). Esta propriedade é atualizada sempre que o usuário trocar do "Modo Offline" selecionando o item correspondente do menu (Arquivo -> Trabalhar Offline no Firefox).

- -

Adicionalmente, esta propriedade deve atualizar sempre que o navegador não for mais capaz de conectar a uma rede. De acordo com a especificação:

- -
O atributo navigator.onLine deve retornar falso se o agente de usuário não obtiver contato com a rede quando o usuário segue links ou quandoscripts de uma página remota forem requisitados.
- -

Firefox 2 atualiza esta propriedade quando trocando de/para o modo Offline do navegador, e quando perde/encontra conectividade com uma rede no Windows e Linux.

- -

Esta propriedade existe em antigas versões do Firefox e Internet Explorer (a especificação baseou-se fora destas implementações prévias), então você pode começar usando isto imediatamente. A detecção automática do estado da rede foi implementado no Firefox 2.

- -

Eventos "online" e "offline"

- -

O Firefox 3 introduz dois novos eventos: "online" e "offline". Estes dois eventos são colocados no <body> de cada página quando o navegador troca entre o modo online e offline. Adicionalmente, os eventos vão de document.body, para document, terminando em window. Ambos os eventos não são canceláveis (você não pode evitar o usuário de estar online, ou indo para offline).

- -

Você pode registrar ouvintes para estes eventos de algumas maneiras familiares:

- - - -

Exemplo

- -

um caso de teste simples que você pode rodar para verificar se os eventos estão trabalhando. XXX Quando os "mochitestes" para isto forem criados, apontar para este e atualizar este exemplo -nickolay

- -
 <!doctype html>
- <html>
- <head>
-   <script>
-     function updateOnlineStatus(msg) {
-       var status = document.getElementById("status");
-       var condition = navigator.onLine ? "ONLINE" : "OFFLINE";
-       status.setAttribute("class", condition);
-       var state = document.getElementById("state");
-       state.innerHTML = condition;
-       var log = document.getElementById("log");
-       log.appendChild(document.createTextNode("Event: " + msg + "; status=" + condition + "\n"));
-     }
-     function loaded() {
-       updateOnlineStatus("load");
-       document.body.addEventListener("offline", function () {
-         updateOnlineStatus("offline")
-       }, false);
-       document.body.addEventListener("online", function () {
-         updateOnlineStatus("online")
-       }, false);
-     }
-   </script>
-   <style>...</style>
- </head>
- <body onload="loaded()">
-   <div id="status"><p id="state"></p></div>
-   <div id="log"></div>
- </body>
- </html>
-
- -

Referências

- - - -

Categorias

- -

Interwiki Language Links

diff --git a/files/pt-pt/web/api/navigatoronline/online_and_offline_events/index.html b/files/pt-pt/web/api/navigatoronline/online_and_offline_events/index.html new file mode 100644 index 0000000000..43aed9ed94 --- /dev/null +++ b/files/pt-pt/web/api/navigatoronline/online_and_offline_events/index.html @@ -0,0 +1,97 @@ +--- +title: Eventos online e offline +slug: Web/API/NavigatorOnLine/Eventos_online_e_offline +tags: + - AJAX + - DOM + - Desenvolvimento_Web + - Todas_as_Categorias +translation_of: Web/API/NavigatorOnLine/Online_and_offline_events +--- +

O Firefox 3 implementou eventos Online/Offline da especificação WHATWG Web Applications 1.0.

+ +

Visão geral

+ +

Para construir uma boa aplicação web capaz de ser usada offline, você precisar saber quando sua aplicação está realmente offline. Casualmente, você pode também precisar saber quando a sua aplicação retornou ao estado 'online' novamente. Efetivamente, as exigências colapsam como tal:

+ +
    +
  1. Você precisa saber quando o usuário torna-se online, então você pode re-sincronizar com o servidor.
  2. +
  3. Você precisa saber quando o usuário está offline, então você pode estar seguro para fazer suas requisições do servidor e elas se enfileirarem para um tempo posterior.
  4. +
+ +

Este é o processo em que eventos online/offline ajudam a banalizar.

+ +

API

+ + + +

navigator.onLine é uma propriedade que mantém um valor true/false (true para online, false para offline). Esta propriedade é atualizada sempre que o usuário trocar do "Modo Offline" selecionando o item correspondente do menu (Arquivo -> Trabalhar Offline no Firefox).

+ +

Adicionalmente, esta propriedade deve atualizar sempre que o navegador não for mais capaz de conectar a uma rede. De acordo com a especificação:

+ +
O atributo navigator.onLine deve retornar falso se o agente de usuário não obtiver contato com a rede quando o usuário segue links ou quandoscripts de uma página remota forem requisitados.
+ +

Firefox 2 atualiza esta propriedade quando trocando de/para o modo Offline do navegador, e quando perde/encontra conectividade com uma rede no Windows e Linux.

+ +

Esta propriedade existe em antigas versões do Firefox e Internet Explorer (a especificação baseou-se fora destas implementações prévias), então você pode começar usando isto imediatamente. A detecção automática do estado da rede foi implementado no Firefox 2.

+ +

Eventos "online" e "offline"

+ +

O Firefox 3 introduz dois novos eventos: "online" e "offline". Estes dois eventos são colocados no <body> de cada página quando o navegador troca entre o modo online e offline. Adicionalmente, os eventos vão de document.body, para document, terminando em window. Ambos os eventos não são canceláveis (você não pode evitar o usuário de estar online, ou indo para offline).

+ +

Você pode registrar ouvintes para estes eventos de algumas maneiras familiares:

+ + + +

Exemplo

+ +

um caso de teste simples que você pode rodar para verificar se os eventos estão trabalhando. XXX Quando os "mochitestes" para isto forem criados, apontar para este e atualizar este exemplo -nickolay

+ +
 <!doctype html>
+ <html>
+ <head>
+   <script>
+     function updateOnlineStatus(msg) {
+       var status = document.getElementById("status");
+       var condition = navigator.onLine ? "ONLINE" : "OFFLINE";
+       status.setAttribute("class", condition);
+       var state = document.getElementById("state");
+       state.innerHTML = condition;
+       var log = document.getElementById("log");
+       log.appendChild(document.createTextNode("Event: " + msg + "; status=" + condition + "\n"));
+     }
+     function loaded() {
+       updateOnlineStatus("load");
+       document.body.addEventListener("offline", function () {
+         updateOnlineStatus("offline")
+       }, false);
+       document.body.addEventListener("online", function () {
+         updateOnlineStatus("online")
+       }, false);
+     }
+   </script>
+   <style>...</style>
+ </head>
+ <body onload="loaded()">
+   <div id="status"><p id="state"></p></div>
+   <div id="log"></div>
+ </body>
+ </html>
+
+ +

Referências

+ + + +

Categorias

+ +

Interwiki Language Links

diff --git a/files/pt-pt/web/api/node/appendchild/index.html b/files/pt-pt/web/api/node/appendchild/index.html new file mode 100644 index 0000000000..7495320be4 --- /dev/null +++ b/files/pt-pt/web/api/node/appendchild/index.html @@ -0,0 +1,31 @@ +--- +title: element.appendChild +slug: DOM/element.appendChild +tags: + - Referência_do_DOM_Gecko +translation_of: Web/API/Node/appendChild +--- +

{{ ApiRef() }}

+

Sumario

+

Adiciona um novo nó (filho) a um determinado elemento (objeto)

+

Sintaxe

+
element.appendChild(child)
+
+ +

Exemplo

+
// Cria um novo Elemento(Objeto)
+var p = document.createElement("p");
+
+// Adiciona ao Elemento Body (este deverá existir!)
+document.body.appendChild(p);
+
+

Notas

+

Se child é a referência para um nó ja existente no documento, appendChild moverá este para a nova posição (ou seja não é necessário remover um nó de uma posição para depois adicionar em outra). Isto significa que um nó não pode estar em dois lugares do documento ao mesmo tempo.

+

Você pode usar também cloneNode para copiar este nó e depois adicioná-lo a outro elemento. (Observe que ao criar um objeto ultilizando cloneNode ou createElement este não fará parte do documento até você torna-lo parte deste usando appendChild ou método similar)

+

Métodos relacionados : insertBefore, replaceChild and removeChild. <code>appendChild</code> é um dos métodos essenciais na programação usando DOM. O método <code>appendChild</code> insere um novo nó na estrutura DOM e este é a segunda parte da metodologia create-and-append.

+

Especificação

+

DOM Level 2 Core: appendChild

+

{{ languages( { "en": "en/DOM/element.appendChild", "fr": "fr/DOM/element.appendChild", "pl": "pl/DOM/element.appendChild" } ) }}

diff --git a/files/pt-pt/web/api/node/clonenode/index.html b/files/pt-pt/web/api/node/clonenode/index.html new file mode 100644 index 0000000000..71f0c5064a --- /dev/null +++ b/files/pt-pt/web/api/node/clonenode/index.html @@ -0,0 +1,55 @@ +--- +title: element.cloneNode +slug: DOM/element.cloneNode +translation_of: Web/API/Node/cloneNode +--- +

Resumo

+ +

Retorna a cópia de um elemento.

+ +

Syntax

+ +
dupNode = element.cloneNode(deep);
+
+ + + +

Example

+ +
p = document.getElementById("diogok");
+p_prime = p.cloneNode(true);
+
+ +

Notas

+ +

Clonando um nó copiamos todos seus atributos e seus respectivos valores

+ +

O nó clonado retornado por cloneNode não faz parte do documento enquanto não for adicionado a um outro nó que faça parte do documento usando appendChild ou outro método similar. Enquanto não for adicionado a um outro nó, será um nó sem pai. Ou seja, o clone não herda o pai do original.

+ +

Se deep for false, nada sobre os nós filhos será clonado. Qualquer texto contido no nó não será clonado junto, já que o texto fica contido em nós de texto.

+ +

Se deep for true, toda a subárvore (incluíndo texto) é copiado também. Para nós vazios (como os elementos IMG e INPUT) não importa qua valor que você coloque em deep, mas você ainda deve definir um valor

+ +

Note que o cloneNode pode causar o problema de termos dois elementos com um mesmo id em um documento!

+ +

Somente os eventos colocados em atributos inline são copiados. Os eventos adicionados após a renderização do nó via javascript não são copiados.

+ +
var elms = document.getElementById('foo');
+elms.onclick = function(){
+	alert('Eu não deveria ser copiado?');
+}
+var g = elms.cloneNode(true);
+g.id = 'foo2';
+g.style.top = '0px';
+document.body.appendChild(g);
+
+ +

No trecho de código acima o atributo onclick não é copiado. Nem mesmo com addEventListener.

+ +

Especificação

+ +

DOM Level 2 Core: cloneNode

diff --git a/files/pt-pt/web/api/node/insertbefore/index.html b/files/pt-pt/web/api/node/insertbefore/index.html new file mode 100644 index 0000000000..d0393410a6 --- /dev/null +++ b/files/pt-pt/web/api/node/insertbefore/index.html @@ -0,0 +1,60 @@ +--- +title: element.insertBefore +slug: DOM/element.insertBefore +tags: + - Referência_do_DOM_Gecko +translation_of: Web/API/Node/insertBefore +--- +

{{ ApiRef() }}

+

Sumário

+

Insere um nó filho ao nó atual, antes de um determinado elemento.

+

Síntaxe

+
varinsertedElement =parentElement.insertBefore(newElement,referenceElement)
+
+

If referenceElement is null, newElement is inserted at the end of the list of child nodes.

+ +

Se referenceElement é null o elemento é inserido em último lugar na lista de nós filhos. Ver childNodes

+

Exemplo

+
 <html>
+
+ <head>
+ <title>Gecko DOM insertBefore test</title>
+ </head>
+ <body>
+ <div>
+   <span id="childSpan">foo bar</span>
+ </div>
+
+ <script type="text/javascript">
+ // cria um elemento vazio
+ // sem ID ou qualquer outro atributo
+ var sp1 = document.createElement("span");
+
+ // atribui o ID 'newSpan' para o elemento criado
+ sp1.setAttribute("id", "newSpan");
+
+ //cria um conteudo para o novo elemento,um texto curto
+ var sp1_content = document.createTextNode("This is a new span element. ");
+ // adiciona o conteúdo a novo elemento
+ sp1.appendChild(sp1_content);
+
+ var sp2 = document.getElementById("childSpan");
+ var parentDiv = sp2.parentNode;
+
+ // insere o novo elemento antes sp2
+ parentDiv.insertBefore(sp1, sp2);
+ </script>
+
+ </body>
+ </html>
+
+

Não há um método insertAfter(insere depois), porém pode se obter um resultado semelhante usando a combinação entre insertBefore e nextSibling. Por exemplo, sp1 pode inserido depois de sp2 usando comando parentDiv.insertBefore(sp1, sp2.nextSibling); Se a propridade nextSibling retornar null indica que o elemento é o último nó filho, logo novo elemento será incluído no final da lista de nós filhos

+

 

+

Espeficação

+

insertBefore

+

{{ languages( { "en": "en/DOM/element.insertBefore", "pl": "pl/DOM/element.insertBefore", "fr": "fr/DOM/element.insertBefore" } ) }}

diff --git a/files/pt-pt/web/api/notifications_api/using_the_notifications_api/index.html b/files/pt-pt/web/api/notifications_api/using_the_notifications_api/index.html new file mode 100644 index 0000000000..ca76a8b6bd --- /dev/null +++ b/files/pt-pt/web/api/notifications_api/using_the_notifications_api/index.html @@ -0,0 +1,289 @@ +--- +title: Utilizar a API de Notificações +slug: Web/API/Notifications_API/Utilizar_API_Notificações +translation_of: Web/API/Notifications_API/Using_the_Notifications_API +--- +

{{APIRef("Web Notifications")}}

+ +

The Notifications API lets a web page or app send notifications that are displayed outside the page at the system level; this lets web apps send information to a user even if the application is idle or in the background. This article looks at the basics of using this API in your own apps.

+ +

{{AvailableInWorkers}}

+ +

Typically, system notifications refer to the operating system's standard notification mechanism: think for example of how a typical desktop system or mobile device brodcasts notifications.

+ +

+ +

The system notification system will vary of course by platform and browser, but this is ok, and the Notifications API is written to be general enough for compatibility with most system notification systems.

+ +

Exemplos

+ +
+
+

One of the most obvious use cases for web notifications is a web-based mail or IRC application that needs to notify the user when a new message is received, even if the user is doing something else with another application. Many real examples of this now exist, such as Slack.

+ +

We've written a couple of real world demos to give more of an idea of how web notifications can be used:

+ + +
+ +
+

.

+
+
+ +

Solicitar permissão

+ +

Before an app can send a notification, the user must grant the application the right to do so. This is a common requirement when an API tries to interact with something outside a web page — at least once, the user needs to specifically grant that application permission to present notifications, thereby letting the user control which apps/sites are allowed to display notifications.

+ +

Verificação do estado da permissão atual

+ +

You can check to see if you already have permission by checking the value of the {{domxref("Notification.permission")}} read only property. It can have one of three possible values:

+ +
+
default
+
The user hasn't been asked for permission yet, so notifications won't be displayed.
+
granted
+
The user has granted permission to display notifications, after having been asked previously.
+
denied
+
The user has explicitly declined permission to show notifications.
+
+ +

Obter permissão

+ +

If permission to display notifications hasn't been granted yet, the application needs to use the {{domxref("Notification.requestPermission()")}} method to request this form the user. In its simplest form, as used in the Emogotchi demo, we just include the following:

+ +
Notification.requestPermission();
+ +

The method also optionally accepts a callback function that is called once the user has responded to the request to display permissions (as seen in the second else ... if block below.) Commonly, you'll ask for permission to display notifications when your app is first initialized, and before trying to instantiate any. If you wanted to be really thorough, you could use a construct like the following (see To-do List Notifications):

+ +
function notifyMe() {
+  // Let's check if the browser supports notifications
+  if (!("Notification" in window)) {
+    alert("This browser does not support system notifications");
+  }
+
+  // Let's check whether notification permissions have already been granted
+  else if (Notification.permission === "granted") {
+    // If it's okay let's create a notification
+    var notification = new Notification("Hi there!");
+  }
+
+  // Otherwise, we need to ask the user for permission
+  else if (Notification.permission !== 'denied') {
+    Notification.requestPermission(function (permission) {
+      // If the user accepts, let's create a notification
+      if (permission === "granted") {
+        var notification = new Notification("Hi there!");
+      }
+    });
+  }
+
+  // Finally, if the user has denied notifications and you
+  // want to be respectful there is no need to bother them any more.
+}
+ +
+

Note: Before version 37, Chrome doesn't let you call {{domxref("Notification.requestPermission()")}} in the load event handler (see issue 274284).

+
+ +

Permissões de manifesto do Firefox OS

+ +

Please note that while the Notifications API is not {{Glossary("privileged")}} or {{Glossary("certified")}}, you should still include an entry in your manifest.webapp file when including it in an Firefox OS app:

+ +
"permissions": {
+  "desktop-notification": {
+    "description": "Needed for creating system notifications."
+  }
+},
+"messages": [{"notification": "path/to/your/index.html"}]
+
+
+ +
+

Note: When an application is installed, you shouldn't need to {{anch("Getting permission","explicitly request permission")}}, but you will still need the permissions and messages entries above for the notifications to be fired.

+
+ +

Criação de uma notificação

+ +

Creating a notification is easy; just use the {{domxref("Notification")}} constructor. This constructor expects a title to display within the notification and some options to enhance the notification such as an {{domxref("Notification.icon","icon")}} or a text {{domxref("Notification.body","body")}}.

+ +

For example, in the Emogotchi example we have two functions that can be called when a notification needs to be fired; which one is used depends on whether we want a set notification, or a notification that includes random body content:

+ +
function spawnNotification(theBody,theIcon,theTitle) {
+  var options = {
+      body: theBody,
+      icon: theIcon
+  }
+  var n = new Notification(theTitle,options);
+  setTimeout(n.close.bind(n), 5000);
+}
+
+function randomNotification() {
+  var randomQuote = quoteChooser();
+  var options = {
+      body: randomQuote,
+      icon: 'img/sad_head.png',
+  }
+
+  var n = new Notification('Emogotchi says',options);
+  setTimeout(n.close.bind(n), 5000);
+}
+ +

Fechar notificações

+ +

Firefox and Safari close notifications automatically after a few moments (around four seconds). This may also happen at the operating system level. Some browsers don't however, such as Chrome. To make sure that the notifications close in all browsers, at the end of the above functions, we call the {{domxref("Notification.close")}} function inside a {{domxref("WindowTimers.setTimeout","setTimeout()")}} function to close the notification after 4 seconds. Also note the use of bind() to make sure the close() call is associated with the notification.

+ +
setTimeout(n.close.bind(n), 5000);
+
+ +
+

Note: When you receive a "close" event, there is no guarantee that it's the user who closed the notification. This is in line with the specification, which states: "When a notification is closed, either by the underlying notifications platform or by the user, the close steps for it must be run."

+
+ +

Eventos de notificação

+ +

The notifications API spec lists two events that are triggered on the {{domxref("Notification")}} instance:

+ +
+
{{event("click")}}
+
Triggered when the user clicks on the notification.
+
{{event("error")}}
+
Triggered if something goes wrong with the notification; this is usually because the notification couldn't be displayed for some reason.
+
+ +

These events can be tracked using the {{domxref("Notification.onclick","onclick")}} and {{domxref("Notification.onerror","onerror")}} handlers. Because {{domxref("Notification")}} also inherits from {{domxref("EventTarget")}}, it's possible to use the {{domxref("EventTarget.addEventListener","addEventListener()")}} method on it.

+ +

There are also two other events that used to be listed in the spec, but were recently removed. These may still work in browsers for a while, but they should be treated as obsolete and not used:

+ +
+
{{event("close")}}
+
Triggered once the notification is closed.
+
{{event("show")}}
+
Triggered when the notification is displayed to the user.
+
+ +

Substituir notificações existentes

+ +

It is usually undesirable for a user to receive a lot of notifications in a short space of time — for example, what if a messenger application notified a user for each incoming message, and they were being sent a lot? To avoid spamming the user with too many notifications, it's possible to modify the pending notifications queue, replacing single or multiple pending notifications with a new one.

+ +

To do this, it's possible to add a tag to any new notification. If a notification already has the same tag and has not been displayed yet, the new notification replaces that previous notification. If the notification with the same tag has already been displayed, the previous notification is closed and the new one is displayed.

+ +

Exemplo de etiqueta

+ +

Assume the following basic HTML:

+ +
<button>Notify me!</button>
+ +

It's possible to handle multiple notifications this way:

+ +
window.addEventListener('load', function () {
+  // At first, let's check if we have permission for notification
+  // If not, let's ask for it
+  if (window.Notification && Notification.permission !== "granted") {
+    Notification.requestPermission(function (status) {
+      if (Notification.permission !== status) {
+        Notification.permission = status;
+      }
+    });
+  }
+
+  var button = document.getElementsByTagName('button')[0];
+
+  button.addEventListener('click', function () {
+    // If the user agreed to get notified
+    // Let's try to send ten notifications
+    if (window.Notification && Notification.permission === "granted") {
+      var i = 0;
+      // Using an interval cause some browsers (including Firefox) are blocking notifications if there are too much in a certain time.
+      var interval = window.setInterval(function () {
+        // Thanks to the tag, we should only see the "Hi! 9" notification
+        var n = new Notification("Hi! " + i, {tag: 'soManyNotification'});
+        if (i++ == 9) {
+          window.clearInterval(interval);
+        }
+      }, 200);
+    }
+
+    // If the user hasn't told if he wants to be notified or not
+    // Note: because of Chrome, we are not sure the permission property
+    // is set, therefore it's unsafe to check for the "default" value.
+    else if (window.Notification && Notification.permission !== "denied") {
+      Notification.requestPermission(function (status) {
+        if (Notification.permission !== status) {
+          Notification.permission = status;
+        }
+
+        // If the user said okay
+        if (status === "granted") {
+          var i = 0;
+          // Using an interval cause some browsers (including Firefox) are blocking notifications if there are too much in a certain time.
+          var interval = window.setInterval(function () {
+            // Thanks to the tag, we should only see the "Hi! 9" notification
+            var n = new Notification("Hi! " + i, {tag: 'soManyNotification'});
+            if (i++ == 9) {
+              window.clearInterval(interval);
+            }
+          }, 200);
+        }
+
+        // Otherwise, we can fallback to a regular modal alert
+        else {
+          alert("Hi!");
+        }
+      });
+    }
+
+    // If the user refuses to get notified
+    else {
+      // We can fallback to a regular modal alert
+      alert("Hi!");
+    }
+  });
+});
+ +

See the live result below:

+ +

{{ EmbedLiveSample('Tag_example', '100%', 30) }}

+ +

Receber notificação de cliques nas notificações da aplicação

+ +

When a user clicks on a notification generated by an app, you will be notified of this event in two different ways, depending on the circumstance:

+ +
    +
  1. A click event if your app has not closed or been put in the background between the time you create the notification and the time the user clicks on it.
  2. +
  3. A system message otherwise.
  4. +
+ +

See this code snippet for an example of how to deal with this.

+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Notifications')}}{{Spec2('Web Notifications')}}Living standard
+ +

Compatibilidade do navegador

+ +

{{page("/en-US/Web/API/Notification","Browser compatibility")}}

+ +

Consultar também

+ + diff --git "a/files/pt-pt/web/api/notifications_api/utilizar_api_notifica\303\247\303\265es/index.html" "b/files/pt-pt/web/api/notifications_api/utilizar_api_notifica\303\247\303\265es/index.html" deleted file mode 100644 index ca76a8b6bd..0000000000 --- "a/files/pt-pt/web/api/notifications_api/utilizar_api_notifica\303\247\303\265es/index.html" +++ /dev/null @@ -1,289 +0,0 @@ ---- -title: Utilizar a API de Notificações -slug: Web/API/Notifications_API/Utilizar_API_Notificações -translation_of: Web/API/Notifications_API/Using_the_Notifications_API ---- -

{{APIRef("Web Notifications")}}

- -

The Notifications API lets a web page or app send notifications that are displayed outside the page at the system level; this lets web apps send information to a user even if the application is idle or in the background. This article looks at the basics of using this API in your own apps.

- -

{{AvailableInWorkers}}

- -

Typically, system notifications refer to the operating system's standard notification mechanism: think for example of how a typical desktop system or mobile device brodcasts notifications.

- -

- -

The system notification system will vary of course by platform and browser, but this is ok, and the Notifications API is written to be general enough for compatibility with most system notification systems.

- -

Exemplos

- -
-
-

One of the most obvious use cases for web notifications is a web-based mail or IRC application that needs to notify the user when a new message is received, even if the user is doing something else with another application. Many real examples of this now exist, such as Slack.

- -

We've written a couple of real world demos to give more of an idea of how web notifications can be used:

- - -
- -
-

.

-
-
- -

Solicitar permissão

- -

Before an app can send a notification, the user must grant the application the right to do so. This is a common requirement when an API tries to interact with something outside a web page — at least once, the user needs to specifically grant that application permission to present notifications, thereby letting the user control which apps/sites are allowed to display notifications.

- -

Verificação do estado da permissão atual

- -

You can check to see if you already have permission by checking the value of the {{domxref("Notification.permission")}} read only property. It can have one of three possible values:

- -
-
default
-
The user hasn't been asked for permission yet, so notifications won't be displayed.
-
granted
-
The user has granted permission to display notifications, after having been asked previously.
-
denied
-
The user has explicitly declined permission to show notifications.
-
- -

Obter permissão

- -

If permission to display notifications hasn't been granted yet, the application needs to use the {{domxref("Notification.requestPermission()")}} method to request this form the user. In its simplest form, as used in the Emogotchi demo, we just include the following:

- -
Notification.requestPermission();
- -

The method also optionally accepts a callback function that is called once the user has responded to the request to display permissions (as seen in the second else ... if block below.) Commonly, you'll ask for permission to display notifications when your app is first initialized, and before trying to instantiate any. If you wanted to be really thorough, you could use a construct like the following (see To-do List Notifications):

- -
function notifyMe() {
-  // Let's check if the browser supports notifications
-  if (!("Notification" in window)) {
-    alert("This browser does not support system notifications");
-  }
-
-  // Let's check whether notification permissions have already been granted
-  else if (Notification.permission === "granted") {
-    // If it's okay let's create a notification
-    var notification = new Notification("Hi there!");
-  }
-
-  // Otherwise, we need to ask the user for permission
-  else if (Notification.permission !== 'denied') {
-    Notification.requestPermission(function (permission) {
-      // If the user accepts, let's create a notification
-      if (permission === "granted") {
-        var notification = new Notification("Hi there!");
-      }
-    });
-  }
-
-  // Finally, if the user has denied notifications and you
-  // want to be respectful there is no need to bother them any more.
-}
- -
-

Note: Before version 37, Chrome doesn't let you call {{domxref("Notification.requestPermission()")}} in the load event handler (see issue 274284).

-
- -

Permissões de manifesto do Firefox OS

- -

Please note that while the Notifications API is not {{Glossary("privileged")}} or {{Glossary("certified")}}, you should still include an entry in your manifest.webapp file when including it in an Firefox OS app:

- -
"permissions": {
-  "desktop-notification": {
-    "description": "Needed for creating system notifications."
-  }
-},
-"messages": [{"notification": "path/to/your/index.html"}]
-
-
- -
-

Note: When an application is installed, you shouldn't need to {{anch("Getting permission","explicitly request permission")}}, but you will still need the permissions and messages entries above for the notifications to be fired.

-
- -

Criação de uma notificação

- -

Creating a notification is easy; just use the {{domxref("Notification")}} constructor. This constructor expects a title to display within the notification and some options to enhance the notification such as an {{domxref("Notification.icon","icon")}} or a text {{domxref("Notification.body","body")}}.

- -

For example, in the Emogotchi example we have two functions that can be called when a notification needs to be fired; which one is used depends on whether we want a set notification, or a notification that includes random body content:

- -
function spawnNotification(theBody,theIcon,theTitle) {
-  var options = {
-      body: theBody,
-      icon: theIcon
-  }
-  var n = new Notification(theTitle,options);
-  setTimeout(n.close.bind(n), 5000);
-}
-
-function randomNotification() {
-  var randomQuote = quoteChooser();
-  var options = {
-      body: randomQuote,
-      icon: 'img/sad_head.png',
-  }
-
-  var n = new Notification('Emogotchi says',options);
-  setTimeout(n.close.bind(n), 5000);
-}
- -

Fechar notificações

- -

Firefox and Safari close notifications automatically after a few moments (around four seconds). This may also happen at the operating system level. Some browsers don't however, such as Chrome. To make sure that the notifications close in all browsers, at the end of the above functions, we call the {{domxref("Notification.close")}} function inside a {{domxref("WindowTimers.setTimeout","setTimeout()")}} function to close the notification after 4 seconds. Also note the use of bind() to make sure the close() call is associated with the notification.

- -
setTimeout(n.close.bind(n), 5000);
-
- -
-

Note: When you receive a "close" event, there is no guarantee that it's the user who closed the notification. This is in line with the specification, which states: "When a notification is closed, either by the underlying notifications platform or by the user, the close steps for it must be run."

-
- -

Eventos de notificação

- -

The notifications API spec lists two events that are triggered on the {{domxref("Notification")}} instance:

- -
-
{{event("click")}}
-
Triggered when the user clicks on the notification.
-
{{event("error")}}
-
Triggered if something goes wrong with the notification; this is usually because the notification couldn't be displayed for some reason.
-
- -

These events can be tracked using the {{domxref("Notification.onclick","onclick")}} and {{domxref("Notification.onerror","onerror")}} handlers. Because {{domxref("Notification")}} also inherits from {{domxref("EventTarget")}}, it's possible to use the {{domxref("EventTarget.addEventListener","addEventListener()")}} method on it.

- -

There are also two other events that used to be listed in the spec, but were recently removed. These may still work in browsers for a while, but they should be treated as obsolete and not used:

- -
-
{{event("close")}}
-
Triggered once the notification is closed.
-
{{event("show")}}
-
Triggered when the notification is displayed to the user.
-
- -

Substituir notificações existentes

- -

It is usually undesirable for a user to receive a lot of notifications in a short space of time — for example, what if a messenger application notified a user for each incoming message, and they were being sent a lot? To avoid spamming the user with too many notifications, it's possible to modify the pending notifications queue, replacing single or multiple pending notifications with a new one.

- -

To do this, it's possible to add a tag to any new notification. If a notification already has the same tag and has not been displayed yet, the new notification replaces that previous notification. If the notification with the same tag has already been displayed, the previous notification is closed and the new one is displayed.

- -

Exemplo de etiqueta

- -

Assume the following basic HTML:

- -
<button>Notify me!</button>
- -

It's possible to handle multiple notifications this way:

- -
window.addEventListener('load', function () {
-  // At first, let's check if we have permission for notification
-  // If not, let's ask for it
-  if (window.Notification && Notification.permission !== "granted") {
-    Notification.requestPermission(function (status) {
-      if (Notification.permission !== status) {
-        Notification.permission = status;
-      }
-    });
-  }
-
-  var button = document.getElementsByTagName('button')[0];
-
-  button.addEventListener('click', function () {
-    // If the user agreed to get notified
-    // Let's try to send ten notifications
-    if (window.Notification && Notification.permission === "granted") {
-      var i = 0;
-      // Using an interval cause some browsers (including Firefox) are blocking notifications if there are too much in a certain time.
-      var interval = window.setInterval(function () {
-        // Thanks to the tag, we should only see the "Hi! 9" notification
-        var n = new Notification("Hi! " + i, {tag: 'soManyNotification'});
-        if (i++ == 9) {
-          window.clearInterval(interval);
-        }
-      }, 200);
-    }
-
-    // If the user hasn't told if he wants to be notified or not
-    // Note: because of Chrome, we are not sure the permission property
-    // is set, therefore it's unsafe to check for the "default" value.
-    else if (window.Notification && Notification.permission !== "denied") {
-      Notification.requestPermission(function (status) {
-        if (Notification.permission !== status) {
-          Notification.permission = status;
-        }
-
-        // If the user said okay
-        if (status === "granted") {
-          var i = 0;
-          // Using an interval cause some browsers (including Firefox) are blocking notifications if there are too much in a certain time.
-          var interval = window.setInterval(function () {
-            // Thanks to the tag, we should only see the "Hi! 9" notification
-            var n = new Notification("Hi! " + i, {tag: 'soManyNotification'});
-            if (i++ == 9) {
-              window.clearInterval(interval);
-            }
-          }, 200);
-        }
-
-        // Otherwise, we can fallback to a regular modal alert
-        else {
-          alert("Hi!");
-        }
-      });
-    }
-
-    // If the user refuses to get notified
-    else {
-      // We can fallback to a regular modal alert
-      alert("Hi!");
-    }
-  });
-});
- -

See the live result below:

- -

{{ EmbedLiveSample('Tag_example', '100%', 30) }}

- -

Receber notificação de cliques nas notificações da aplicação

- -

When a user clicks on a notification generated by an app, you will be notified of this event in two different ways, depending on the circumstance:

- -
    -
  1. A click event if your app has not closed or been put in the background between the time you create the notification and the time the user clicks on it.
  2. -
  3. A system message otherwise.
  4. -
- -

See this code snippet for an example of how to deal with this.

- -

Especificações

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Web Notifications')}}{{Spec2('Web Notifications')}}Living standard
- -

Compatibilidade do navegador

- -

{{page("/en-US/Web/API/Notification","Browser compatibility")}}

- -

Consultar também

- - diff --git a/files/pt-pt/web/api/selection/index.html b/files/pt-pt/web/api/selection/index.html new file mode 100644 index 0000000000..a33e618def --- /dev/null +++ b/files/pt-pt/web/api/selection/index.html @@ -0,0 +1,76 @@ +--- +title: Selection (Seleção) +slug: DOM/Selection +translation_of: Web/API/Selection +--- +

Introdução

+ +

Selection é a classe do objeto retornado por window.getSelection() e outros métodos. Um objeto Selection representa os intervalos que o usuário tenha selecionado. Normalmente, ele tem apenas um intervalo, acessada assim:

+ +
selection = window.getSelection();
+range = selection.getRangeAt(0);
+ +

Chamar o método toString() retorna o texto contido na seleção, por exemplo:

+ +
selection = window.getSelection();
+window.alert(selection);
+
+ +

Glossário

+ +

Outros termos utilizados nesta seção.

+ +
+
Âncora (anchor)
+
A âncora de uma seleção é o ponto de início da seleção. Ao fazer uma seleção com um mouse, a âncora no documento é o local onde o botão do mouse é inicialmente pressionado. Como o usuário muda a seleção usando o mouse ou o teclado, a âncora não se move.
+
Foco (focus)
+
O foco da seleção é o ponto final da seleção. Ao fazer uma seleção com o mouse, o foco está no documento onde o botão do mouse é liberado. Como o usuário muda a seleção usando o mouse ou o teclado, o foco é a final da seleção que se move.
+
Intervalo (range)
+
Um intervalo é uma parte contígua de um documento. Um intervalo pode conter nós inteiro, bem como partes de nós, como uma parte de um nó de texto. Um usuário normalmente só seleciona um intervalo de cada vez, mas é possível que um usuário selecione vários intervalos (por exemplo, usando a tecla Control). Um intervalo pode ser recuperado a partir de uma seleção como um objeto Range. Objetos Range também podem ser criadas através do DOM e programaticamente adicionado ou removido de uma seleção.
+
+ +

Propriedades

+ +
+
anchorNode
+
Retorna o nó em que a seleção começa.
+
anchorOffset
+
Retorna o número de caracteres que a âncora da seleção é compensada dentro do anchorNode.
+
focusNode
+
Retorna o nó em que a seleção termina.
+
focusOffset
+
Retorna o número de caracteres que o foco da seleção é compensado dentro do focusNode.
+
isCollapsed
+
Retorna um booleano indicando se os pontos de início e fim da seleção estão na mesma posição.
+
rangeCount
+
Retorna o número de faixas na seleção.
+
+ +

Métodos

+ +
+
addRange
+
Um objeto de intervalo (Range) que será adicionado à seleção.
+
collapse
+
Recolhe a seleção atual para um único ponto.
+
collapseToStart
+
Move o foco da seleção para o mesmo ponto da âncora.
+
collapseToEnd
+
Move a âncora da seleção para o mesmo ponto que o foco. O foco não se move.
+
containsNode
+
Indica se um determinado nó é parte da seleção.
+
deleteFromDocument
+
Apaga o conteúdo da seleção do documento.
+
extend
+
Move o foco da seleção para um ponto especificado.
+
getRangeAt
+
Retorna um objeto de intervalo (Range) representando um dos intervalos atualmente selecionados.
+
removeAllRanges
+
Remove todos os intervalos da seleção.
+
removeRange
+
Remove uma faixa (range) da seleção.
+
selectAllChildren
+
Adiciona todos os filhos do nó especificado para a seleção.
+
toString
+
Retorna uma string a ser representada pelo objeto de seleção, ou seja, o texto atualmente selecionado.
+
diff --git a/files/pt-pt/web/api/sistema_de_ficheiros/index.html b/files/pt-pt/web/api/sistema_de_ficheiros/index.html deleted file mode 100644 index 76c4db9d6c..0000000000 --- a/files/pt-pt/web/api/sistema_de_ficheiros/index.html +++ /dev/null @@ -1,54 +0,0 @@ ---- -title: Sistema de Ficheiros -slug: Web/API/Sistema_de_ficheiros -tags: - - API - - File API - - File System API - - File and Directory Entries API - - Interface - - Não Standard - - Offline - - filesystem -translation_of: Web/API/FileSystem ---- -
-

{{APIRef("File System API")}}{{SeeCompatTable}}

- -

A interface da "API de Entradas de Diretorias e Ficheiros" é usada para representar um sistema de ficheiros. Estes objetos podem ser obtidos a partir da propriedade {{domxref("FileSystemEntry.filesystem", "filesystem")}} em qualquer entrada do sistema de ficheiros. Alguns navegadores oferecem APIs adicionais para criar e gerir sistemas de ficheiros, por exemplo o método {{domxref("Window.requestFileSystem", "requestFileSystem()")}} encontrado no Chrome.

- -

Esta interface não dá acesso ao filesystem do utilizador. Em vez disso, terá uma "drive virtual" dentro da sandbox do navegador. Se quiser ter acesso ao sistema de ficheiros dos utilizadores, necessita de invocar o utilizador.

-
- -

Conceitos básicos

- -

Existem duas formas para aceder ao objeto FileSystem:

- -
    -
  1. Pode pedir por um dentro duma sandbox para só a sua app ao chamar window.requestFileSystem(). Se a chamada tiver sucesso, é executada uma callback handler, que recebe como parâmetro um objeto FileSystem que descreve o sistema de ficheiros.
  2. -
  3. Pode o pedir através duma entrada no sistema de ficheiros, com a propriadade {{domxref("FileSystemEntry.filesystem", "filesystem")}}.
  4. -
- -

Atributos

- -
-
{{domxref("FileSystem.name")}} {{ReadOnlyInline}}
-
Uma {{domxref("USVString")}} que representa o nome do sistema de ficheiros. Este nome é único na lista de sistemas de ficheiros exposta.
-
{{domxref("FileSystem.root")}} {{ReadOnlyInline}}
-
Um objeto de {{domxref("FileSystemDirectoryEntry")}} que representa a diretoria raiz do sistema de ficheiros. Através deste objeto, pode ganhar acesso a todos os ficheiros e diretorias no sistema.
-
- -

Compatibilidade

- - - -

{{Compat("api.FileSystem")}}

- -

Ver também

- - diff --git a/files/pt-pt/web/api/storage_api/index.html b/files/pt-pt/web/api/storage_api/index.html new file mode 100644 index 0000000000..434cee963d --- /dev/null +++ b/files/pt-pt/web/api/storage_api/index.html @@ -0,0 +1,128 @@ +--- +title: API de armazenamento +slug: Web/API/API_armazenamento +tags: + - API + - API de armazenamento + - Armazenamento + - Contextod e segurança + - Quotas + - Referencia + - Resumo + - Sinopse + - Utilização +translation_of: Web/API/Storage_API +--- +

{{securecontext_header}}{{DefaultAPISidebar("Storage")}}

+ +

The Storage Standard defines a common, shared storage system to be used by all APIs and technologies that store content-accessible data for individual Web sites. The Storage API gives sites' code the ability to find out how much space they can use, how much they are already using, and even control whether or not they need to be alerted before the {{Glossary("user agent")}} disposes of site data in order to make room for other things.

+ +

{{AvailableInWorkers}}

+ +

Site storage—the data stored for a Web site which is managed by the Storage Standard—includes:

+ + + +

Unidades de armazenamento de site

+ +

The site storage system described by the Storage Standard and interacted with using the Storage API consists of a single site storage unit for each {{Glossary("origin")}}. In essence, every Web site or Web application has its own storage unit into which its data gets placed. The diagram below shows a site storage pool with three storage units within, showing how storage units can have different data types stored within and may have different quotas (maximum storage limits).

+ +

A diagram showing how the site storage pool consists of multiple storage units that contain data from various APIs as well as possible unused space left before the quota is reached.

+ + + +

{{Glossary("User agent", "User agents")}} are likely to use various techniques to determine the quota for various origins. One of the most likely methods—one which the specification specifically encourages, in fact—would be to consider the popularity and/or usage levels of individual sites to determine what their quotas should be.  It's also conceivable that the browser might offer a user interface to customize these quotas.

+ +

Modos de caixa (Box)

+ +

The actual data storage within each site storage unit is called its box. Each site storage unit has exactly one box into which all of its data is placed, and has a box mode that describes the data retention policy for that box. There are two modes:

+ +
+
"best-effort"
+
The user agent will try to retain the data contained in the box for as long as it can, but will not warn users if storage space runs low and it becomes necessary to clear the box in order to relieve the storage pressure.
+
"persistent"
+
The user agent will retain the data as long as possible, clearing all "best-effort" boxes before considering clearing a box marked "persistent". If it becomes necessary to consider clearing persistent boxes, the user agent will notify the user and provide a way to clear one or more persistent boxes as needed.
+
+ +

To change an origin's box mode requires permission to use the "persistent-storage" feature.

+ +

Persistência de dados e limpeza

+ +

If the site or app has the "persistent-storage" feature permission, it can use the {{domxref("StorageManager.persist()")}} method to request that its box be made persistent. It's also possible for the user agent to decide to make the site's storage unit persistent due to usage characteristics or other metrics. The "persistent-storage" feature's permission-related flags, algorithms, and types are all set to the standard defaults for a permission, except that the permission state must be the same across the entire origin, and that if the permission state isn't "granted" (meaning that for whatever reason, access to the persistent storage feature was denied), the origin's site storage unit's box mode is always "best-effort".

+ +
+

Nota: Consulte Using the Permissions API para mais detalhes sobre como obter e gerir as permissões.

+
+ +

When clearing site storage units, an origin's box is treated as a single entity; if the user agent needs to clear it and the user approves, the entire data store is cleared rather than providing some means of clearing only data from individual APIs.

+ +

If a box is marked as "persistent", the contents won't be cleared by the user agent without either the data's origin itself or the user specifically doing so. This includes scenarios such as the user selecting a "Clear Caches" or "Clear Recent History" option. The user will be asked specifically for permission to remove persistent site storage units.

+ +

Quotas e estimativas de utilização

+ +

The user agent determines, using whatever mechanism it chooses, the maximum amount of storage a given site can use. This maximum is the origin's quota. The amount of this space which is in use by the site is called its usage. Both of these values are estimates; there are several reasons why they're not precise:

+ + + +

User agents may use any method they choose to determine the size of origins' quotas, and are encouraged by the specification to provide popular or frequently-used sites with extra space.

+ +

To determine the estimated quota and usage values for a given origin, use the {{domxref("StorageManager.estimate", "navigator.storage.estimate()")}} method, which returns a promise that, when resolved, receives a {{domxref("StorageEstimate")}} that contains these figures. For example:

+ +
navigator.storage.estimate().then(estimate => {
+  // estimate.quota is the estimated quota
+  // estimate.usage is the estimated number of bytes used
+});
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('Storage')}}{{Spec2('Storage')}}Definição inicial.
+ +

Compatibilidade de navegador

+ +
+

StorageManager

+ +
+ + +

{{Compat("api.StorageManager")}}

+
+
+ +

Consultar também

+ + diff --git a/files/pt-pt/web/api/web_audio_api/using_web_audio_api/index.html b/files/pt-pt/web/api/web_audio_api/using_web_audio_api/index.html new file mode 100644 index 0000000000..d9a72f2694 --- /dev/null +++ b/files/pt-pt/web/api/web_audio_api/using_web_audio_api/index.html @@ -0,0 +1,259 @@ +--- +title: Utilizar a API de Áudio da Web +slug: Web/API/Web_Audio_API/Utilizar_api_audio_web +tags: + - API + - API de Áudio da Web + - Guía + - Referencia + - Utilização + - básicos +translation_of: Web/API/Web_Audio_API/Using_Web_Audio_API +--- +
{{DefaultAPISidebar("Web Audio API")}}
+ +
+

Vamos ver como começar a utilizar a API de Áudio da Web. Nós iremos ver resumidamente alguns conceitos, e depois estudar um exemplo simples de caixa de som que nos permite carregar uma faixa de áudio, reproduzi-la e pausá-la, e alterar o seu volume e panning estéreo.

+
+ +
+

The Web Audio API does not replace the <audio> media element, but rather complements it, just like <canvas> coexists alongside the <img> element. Your use case will determine what tools you use to implement audio. If you simply want to control playback of an audio track, the <audio> media element provides a better, quicker solution than the Web Audio API. If you want to carry out more complex audio processing, as well as playback, the Web Audio API provides much more power and control.

+ +

A powerful feature of the Web Audio API is that it does not have a strict "sound call limitation". For example, there is no ceiling of 32 or 64 sound calls at one time. Some processors may be capable of playing more than 1,000 simultaneous sounds without stuttering.

+
+ +

Código exemplo

+ +

A nossa caixa de música parece-se com isto:

+ +

A boombox with play, pan, and volume controls

+ +

Note the retro cassette deck with a play button, and vol and pan sliders to allow you to alter the volume and stereo panning. We could make this a lot more complex, but this is ideal for simple learning at this stage.

+ +

Check out the final demo here on Codepen, or see the source code on GitHub.

+ +

Suporte para navegador

+ +

Modern browsers have good support for most features of the Web Audio API. There are a lot of features of the API, so for more exact information, you'll have to check the browser compatibility tables at the bottom of each reference page.

+ +

Gráficos de áudio

+ +

Everything within the Web Audio API is based around the concept of an audio graph, which is made up of nodes.

+ +

The Web Audio API handles audio operations inside an audio context, and has been designed to allow modular routing. Basic audio operations are performed with audio nodes, which are linked together to form an audio routing graph. You have input nodes, which are the source of the sounds you are manipulating, modification nodes that change those sounds as desired, and output nodes (destinations), which allow you to save or hear those sounds.

+ +

Several audio sources with different channel layouts are supported, even within a single context. Because of this modular design, you can create complex audio functions with dynamic effects.

+ +

Contxeto de Áudio

+ +

To be able to do anything with the Web Audio API, we need to create an instance of the audio context. This then gives us access to all the features and functionality of the API.

+ +
// for legacy browsers
+const AudioContext = window.AudioContext || window.webkitAudioContext;
+
+const audioCtx = new AudioContext();
+
+ +

So what's going on when we do this? A {{domxref("BaseAudioContext")}} is created for us automatically and extended to an online audio context. We'll want this because we're looking to play live sound.

+ +
+

Note: If you just want to process audio data, for instance, buffer and stream it but not play it, you might want to look into creating an {{domxref("OfflineAudioContext")}}.

+
+ +

Carregar som

+ +

Now, the audio context we've created needs some sound to play through it. There are a few ways to do this with the API. Let's begin with a simple method — as we have a boombox, we most likely want to play a full song track. Also, for accessibility, it's nice to expose that track in the DOM. We'll expose the song on the page using an {{htmlelement("audio")}} element.

+ +
<audio src="myCoolTrack.mp3" type="audio/mpeg"></audio>
+
+ +
+

Nota: If the sound file you're loading is held on a different domain you will need to use the crossorigin attribute; see Cross Origin Resource Sharing (CORS)  for more information.

+
+ +

To use all the nice things we get with the Web Audio API, we need to grab the source from this element and pipe it into the context we have created. Lucky for us there's a method that allows us to do just that — {{domxref("AudioContext.createMediaElementSource")}}:

+ +
// get the audio element
+const audioElement = document.querySelector('audio');
+
+// pass it into the audio context
+const track = audioCtx.createMediaElementSource(audioElement);
+
+ +
+

Nota: The <audio> element above is represented in the DOM by an object of type {{domxref("HTMLMediaElement")}}, which comes with its own set of functionality. All of this has stayed intact; we are merely allowing the sound to be available to the Web Audio API.

+
+ +

Controlar o som

+ +

When playing sound on the web, it's important to allow the user to control it. Depending on the use case, there's a myriad of options, but we'll provide functionality to play/pause the sound, alter the track's volume, and pan it from left to right.

+ +
+

Nota: We need to take into account the new autoplay policy that modern browsers have, which calls for a user gesture before media can play (see Chrome's Autoplay Policy Changes, for example). This has been implemented because autoplaying media is really bad for many reasons — it is annoying and intrusive at the very least, and also causes accessibility problems. This is accounted for by our play/pause button.

+
+ +

Let's take a look at our play and pause functionality to start with. We have a play button that changes to a pause button when the track is playing:

+ +
<button data-playing="false" role="switch" aria-checked="false">
+    <span>Play/Pause</span>
+</button>
+
+ +

Before we can play our track we need to connect our audio graph from the audio source/input node to the destination.

+ +

We've already created an input node by passing our audio element into the API. For the most part, you don't need to create an output node, you can just connect your other nodes to {{domxref("BaseAudioContext.destination")}}, which handles the situation for you:

+ +
track.connect(audioCtx.destination);
+
+ +

A good way to visualise these nodes is by drawing an audio graph so you can visualize it. This is what our current audio graph looks like:

+ +

an audio graph with an audio element source connected to the default destination

+ +

Now we can add the play and pause functionality.

+ +
// select our play button
+const playButton = document.querySelector('button');
+
+playButton.addEventListener('click', function() {
+
+    // check if context is in suspended state (autoplay policy)
+    if (audioCtx.state === 'suspended') {
+        audioCtx.resume();
+    }
+
+    // play or pause track depending on state
+    if (this.dataset.playing === 'false') {
+        audioElement.play();
+        this.dataset.playing = 'true';
+    } else if (this.dataset.playing === 'true') {
+        audioElement.pause();
+        this.dataset.playing = 'false';
+    }
+
+}, false);
+
+ +

We also need to take into account what to do when the track finishes playing. Our HTMLMediaElement fires an ended event once it's finished playing, so we can listen for that and run code accordingly:

+ +
audioElement.addEventListener('ended', () => {
+    playButton.dataset.playing = 'false';
+}, false);
+
+ +

Um aparte sobre o editor de Áudio da Web

+ +

Firefox has a tool available called the Web Audio editor. On any page that has an audio graph running on it, you can open the developer tools, and use the Web Audio tab to view the audio graph, see what properties each node has available, and change the values of those properties to see what effect that has.

+ +

The Firefox web audio editor showing an audio graph with AudioBufferSource, IIRFilter, and AudioDestination

+ +
+

Nota: The Web Audio editor is not enabled by default. To display it, you need to go into the Firefox developer tools settings and check the Web Audio checkbox in the Default Developer Tools section.

+
+ +

Modificar o som

+ +

Let's delve into some basic modification nodes, to change the sound that we have. This is where the Web Audio API really starts to come in handy. First of all, let's change the volume. This can be done using a {{domxref("GainNode")}}, which represents how big our sound wave is.

+ +

There are two ways you can create nodes with the Web Audio API. You can use the factory method on the context itself (e.g. audioCtx.createGain()) or via a constructor of the node (e.g. new GainNode()). We'll use the factory method in our code:

+ +
const gainNode = audioCtx.createGain();
+
+ +

Now we have to update our audio graph from before, so the input is connected to the gain, then the gain node is connected to the destination:

+ +
track.connect(gainNode).connect(audioCtx.destination);
+
+ +

This will make our audio graph look like this:

+ +

an audio graph with an audio element source, connected to a gain node that modifies the audio source, and then going to the default destination

+ +

The default value for gain is 1; this keeps the current volume the same. Gain can be set to a minimum of about -3.4 and a max of about 3.4. Here we'll allow the boombox to move the gain up to 2 (double the original volume) and down to 0 (this will effectively mute our sound).

+ +

Let's give the user control to do this — we'll use a range input:

+ +
<input type="range" id="volume" min="0" max="2" value="1" step="0.01" />
+
+ +
+

Nota: Range inputs are a really handy input type for updating values on audio nodes. You can specify a range's values and use them directly with the audio node's parameters.

+
+ +

So let's grab this input's value and update the gain value when the input node has its value changed by the user:

+ +
const volumeControl = document.querySelector('#volume');
+
+volumeControl.addEventListener('input', function() {
+    gainNode.gain.value = this.value;
+}, false);
+
+ +
+

Nota: The values of node objects (e.g. GainNode.gain) are not simple values; they are actually objects of type {{domxref("AudioParam")}} — these called parameters. This is why we have to set GainNode.gain's value property, rather than just setting the value on gain directly. This enables them to be much more flexible, allowing for passing the parameter a specific set of values to change between over a set period of time, for example.

+
+ +

Great, now the user can update the track's volume! The gain node is the perfect node to use if you want to add mute functionality.

+ +

Adicionar panning estéreo à sua aplicação

+ +

Let's add another modification node to practise what we've just learnt.

+ +

There's a {{domxref("StereoPannerNode")}} node, which changes the balance of the sound between the left and right speakers, if the user has stereo capabilities.

+ +

Note: The StereoPannerNode is for simple cases in which you just want stereo panning from left to right. There is also a {{domxref("PannerNode")}}, which allows for a great deal of control over 3D space, or sound spatialisation, for creating more complex effects. This is used in games and 3D apps to create birds flying overhead, or sound coming from behind the user for instance.

+ +

To visualise it, we will be making our audio graph look like this:

+ +

An image showing the audio graph showing an input node, two modification nodes (a gain node and a stereo panner node) and a destination node.

+ +

Let's use the constructor method of creating a node this time. When we do it this way, we have to pass in the context and any options that that particular node may take:

+ +
const pannerOptions = {pan: 0};
+const panner = new StereoPannerNode(audioCtx, pannerOptions);
+
+ +
+

Nota: The constructor method of creating nodes is not supported by all browsers at this time. The older factory methods are supported more widely.

+
+ +

Here our values range from -1 (far left) and 1 (far right). Again let's use a range type input to vary this parameter:

+ +
<input type="range" id="panner" min="-1" max="1" value="0" step="0.01" />
+
+ +

We use the values from that input to adjust our panner values in the same way as we did before:

+ +
const pannerControl = document.querySelector('#panner');
+
+pannerControl.addEventListener('input', function() {
+    panner.pan.value = this.value;
+}, false);
+
+ +

Let's adjust our audio graph again, to connect all the nodes together:

+ +
track.connect(gainNode).connect(panner).connect(audioCtx.destination);
+
+ +

The only thing left to do is give the app a try: Check out the final demo here on Codepen.

+ +

Resumo

+ +

Great! We have a boombox that plays our 'tape', and we can adjust the volume and stereo panning, giving us a fairly basic working audio graph.

+ +

This makes up quite a few basics that you would need to start to add audio to your website or web app. There's a lot more functionality to the Web Audio API, but once you've grasped the concept of nodes and putting your audio graph together, we can move on to looking at more complex functionality.

+ +

Mais exemplos

+ +

There are other examples available to learn more about the Web Audio API.

+ +

The Voice-change-O-matic is a fun voice manipulator and sound visualization web app that allows you to choose different effects and visualizations. The application is fairly rudimentary, but it demonstrates the simultaneous use of multiple Web Audio API features. (run the Voice-change-O-matic live).

+ +

A UI with a sound wave being shown, and options for choosing voice effects and visualizations.

+ +

Another application developed specifically to demonstrate the Web Audio API is the Violent Theremin, a simple web application that allows you to change pitch and volume by moving your mouse pointer. It also provides a psychedelic lightshow (see Violent Theremin source code).

+ +

A page full of rainbow colours, with two buttons labeled Clear screen and mute.

+ +

Consulte também a nossa repositório de exemplos de áudio para mais exemplos.

diff --git a/files/pt-pt/web/api/web_audio_api/utilizar_api_audio_web/index.html b/files/pt-pt/web/api/web_audio_api/utilizar_api_audio_web/index.html deleted file mode 100644 index d9a72f2694..0000000000 --- a/files/pt-pt/web/api/web_audio_api/utilizar_api_audio_web/index.html +++ /dev/null @@ -1,259 +0,0 @@ ---- -title: Utilizar a API de Áudio da Web -slug: Web/API/Web_Audio_API/Utilizar_api_audio_web -tags: - - API - - API de Áudio da Web - - Guía - - Referencia - - Utilização - - básicos -translation_of: Web/API/Web_Audio_API/Using_Web_Audio_API ---- -
{{DefaultAPISidebar("Web Audio API")}}
- -
-

Vamos ver como começar a utilizar a API de Áudio da Web. Nós iremos ver resumidamente alguns conceitos, e depois estudar um exemplo simples de caixa de som que nos permite carregar uma faixa de áudio, reproduzi-la e pausá-la, e alterar o seu volume e panning estéreo.

-
- -
-

The Web Audio API does not replace the <audio> media element, but rather complements it, just like <canvas> coexists alongside the <img> element. Your use case will determine what tools you use to implement audio. If you simply want to control playback of an audio track, the <audio> media element provides a better, quicker solution than the Web Audio API. If you want to carry out more complex audio processing, as well as playback, the Web Audio API provides much more power and control.

- -

A powerful feature of the Web Audio API is that it does not have a strict "sound call limitation". For example, there is no ceiling of 32 or 64 sound calls at one time. Some processors may be capable of playing more than 1,000 simultaneous sounds without stuttering.

-
- -

Código exemplo

- -

A nossa caixa de música parece-se com isto:

- -

A boombox with play, pan, and volume controls

- -

Note the retro cassette deck with a play button, and vol and pan sliders to allow you to alter the volume and stereo panning. We could make this a lot more complex, but this is ideal for simple learning at this stage.

- -

Check out the final demo here on Codepen, or see the source code on GitHub.

- -

Suporte para navegador

- -

Modern browsers have good support for most features of the Web Audio API. There are a lot of features of the API, so for more exact information, you'll have to check the browser compatibility tables at the bottom of each reference page.

- -

Gráficos de áudio

- -

Everything within the Web Audio API is based around the concept of an audio graph, which is made up of nodes.

- -

The Web Audio API handles audio operations inside an audio context, and has been designed to allow modular routing. Basic audio operations are performed with audio nodes, which are linked together to form an audio routing graph. You have input nodes, which are the source of the sounds you are manipulating, modification nodes that change those sounds as desired, and output nodes (destinations), which allow you to save or hear those sounds.

- -

Several audio sources with different channel layouts are supported, even within a single context. Because of this modular design, you can create complex audio functions with dynamic effects.

- -

Contxeto de Áudio

- -

To be able to do anything with the Web Audio API, we need to create an instance of the audio context. This then gives us access to all the features and functionality of the API.

- -
// for legacy browsers
-const AudioContext = window.AudioContext || window.webkitAudioContext;
-
-const audioCtx = new AudioContext();
-
- -

So what's going on when we do this? A {{domxref("BaseAudioContext")}} is created for us automatically and extended to an online audio context. We'll want this because we're looking to play live sound.

- -
-

Note: If you just want to process audio data, for instance, buffer and stream it but not play it, you might want to look into creating an {{domxref("OfflineAudioContext")}}.

-
- -

Carregar som

- -

Now, the audio context we've created needs some sound to play through it. There are a few ways to do this with the API. Let's begin with a simple method — as we have a boombox, we most likely want to play a full song track. Also, for accessibility, it's nice to expose that track in the DOM. We'll expose the song on the page using an {{htmlelement("audio")}} element.

- -
<audio src="myCoolTrack.mp3" type="audio/mpeg"></audio>
-
- -
-

Nota: If the sound file you're loading is held on a different domain you will need to use the crossorigin attribute; see Cross Origin Resource Sharing (CORS)  for more information.

-
- -

To use all the nice things we get with the Web Audio API, we need to grab the source from this element and pipe it into the context we have created. Lucky for us there's a method that allows us to do just that — {{domxref("AudioContext.createMediaElementSource")}}:

- -
// get the audio element
-const audioElement = document.querySelector('audio');
-
-// pass it into the audio context
-const track = audioCtx.createMediaElementSource(audioElement);
-
- -
-

Nota: The <audio> element above is represented in the DOM by an object of type {{domxref("HTMLMediaElement")}}, which comes with its own set of functionality. All of this has stayed intact; we are merely allowing the sound to be available to the Web Audio API.

-
- -

Controlar o som

- -

When playing sound on the web, it's important to allow the user to control it. Depending on the use case, there's a myriad of options, but we'll provide functionality to play/pause the sound, alter the track's volume, and pan it from left to right.

- -
-

Nota: We need to take into account the new autoplay policy that modern browsers have, which calls for a user gesture before media can play (see Chrome's Autoplay Policy Changes, for example). This has been implemented because autoplaying media is really bad for many reasons — it is annoying and intrusive at the very least, and also causes accessibility problems. This is accounted for by our play/pause button.

-
- -

Let's take a look at our play and pause functionality to start with. We have a play button that changes to a pause button when the track is playing:

- -
<button data-playing="false" role="switch" aria-checked="false">
-    <span>Play/Pause</span>
-</button>
-
- -

Before we can play our track we need to connect our audio graph from the audio source/input node to the destination.

- -

We've already created an input node by passing our audio element into the API. For the most part, you don't need to create an output node, you can just connect your other nodes to {{domxref("BaseAudioContext.destination")}}, which handles the situation for you:

- -
track.connect(audioCtx.destination);
-
- -

A good way to visualise these nodes is by drawing an audio graph so you can visualize it. This is what our current audio graph looks like:

- -

an audio graph with an audio element source connected to the default destination

- -

Now we can add the play and pause functionality.

- -
// select our play button
-const playButton = document.querySelector('button');
-
-playButton.addEventListener('click', function() {
-
-    // check if context is in suspended state (autoplay policy)
-    if (audioCtx.state === 'suspended') {
-        audioCtx.resume();
-    }
-
-    // play or pause track depending on state
-    if (this.dataset.playing === 'false') {
-        audioElement.play();
-        this.dataset.playing = 'true';
-    } else if (this.dataset.playing === 'true') {
-        audioElement.pause();
-        this.dataset.playing = 'false';
-    }
-
-}, false);
-
- -

We also need to take into account what to do when the track finishes playing. Our HTMLMediaElement fires an ended event once it's finished playing, so we can listen for that and run code accordingly:

- -
audioElement.addEventListener('ended', () => {
-    playButton.dataset.playing = 'false';
-}, false);
-
- -

Um aparte sobre o editor de Áudio da Web

- -

Firefox has a tool available called the Web Audio editor. On any page that has an audio graph running on it, you can open the developer tools, and use the Web Audio tab to view the audio graph, see what properties each node has available, and change the values of those properties to see what effect that has.

- -

The Firefox web audio editor showing an audio graph with AudioBufferSource, IIRFilter, and AudioDestination

- -
-

Nota: The Web Audio editor is not enabled by default. To display it, you need to go into the Firefox developer tools settings and check the Web Audio checkbox in the Default Developer Tools section.

-
- -

Modificar o som

- -

Let's delve into some basic modification nodes, to change the sound that we have. This is where the Web Audio API really starts to come in handy. First of all, let's change the volume. This can be done using a {{domxref("GainNode")}}, which represents how big our sound wave is.

- -

There are two ways you can create nodes with the Web Audio API. You can use the factory method on the context itself (e.g. audioCtx.createGain()) or via a constructor of the node (e.g. new GainNode()). We'll use the factory method in our code:

- -
const gainNode = audioCtx.createGain();
-
- -

Now we have to update our audio graph from before, so the input is connected to the gain, then the gain node is connected to the destination:

- -
track.connect(gainNode).connect(audioCtx.destination);
-
- -

This will make our audio graph look like this:

- -

an audio graph with an audio element source, connected to a gain node that modifies the audio source, and then going to the default destination

- -

The default value for gain is 1; this keeps the current volume the same. Gain can be set to a minimum of about -3.4 and a max of about 3.4. Here we'll allow the boombox to move the gain up to 2 (double the original volume) and down to 0 (this will effectively mute our sound).

- -

Let's give the user control to do this — we'll use a range input:

- -
<input type="range" id="volume" min="0" max="2" value="1" step="0.01" />
-
- -
-

Nota: Range inputs are a really handy input type for updating values on audio nodes. You can specify a range's values and use them directly with the audio node's parameters.

-
- -

So let's grab this input's value and update the gain value when the input node has its value changed by the user:

- -
const volumeControl = document.querySelector('#volume');
-
-volumeControl.addEventListener('input', function() {
-    gainNode.gain.value = this.value;
-}, false);
-
- -
-

Nota: The values of node objects (e.g. GainNode.gain) are not simple values; they are actually objects of type {{domxref("AudioParam")}} — these called parameters. This is why we have to set GainNode.gain's value property, rather than just setting the value on gain directly. This enables them to be much more flexible, allowing for passing the parameter a specific set of values to change between over a set period of time, for example.

-
- -

Great, now the user can update the track's volume! The gain node is the perfect node to use if you want to add mute functionality.

- -

Adicionar panning estéreo à sua aplicação

- -

Let's add another modification node to practise what we've just learnt.

- -

There's a {{domxref("StereoPannerNode")}} node, which changes the balance of the sound between the left and right speakers, if the user has stereo capabilities.

- -

Note: The StereoPannerNode is for simple cases in which you just want stereo panning from left to right. There is also a {{domxref("PannerNode")}}, which allows for a great deal of control over 3D space, or sound spatialisation, for creating more complex effects. This is used in games and 3D apps to create birds flying overhead, or sound coming from behind the user for instance.

- -

To visualise it, we will be making our audio graph look like this:

- -

An image showing the audio graph showing an input node, two modification nodes (a gain node and a stereo panner node) and a destination node.

- -

Let's use the constructor method of creating a node this time. When we do it this way, we have to pass in the context and any options that that particular node may take:

- -
const pannerOptions = {pan: 0};
-const panner = new StereoPannerNode(audioCtx, pannerOptions);
-
- -
-

Nota: The constructor method of creating nodes is not supported by all browsers at this time. The older factory methods are supported more widely.

-
- -

Here our values range from -1 (far left) and 1 (far right). Again let's use a range type input to vary this parameter:

- -
<input type="range" id="panner" min="-1" max="1" value="0" step="0.01" />
-
- -

We use the values from that input to adjust our panner values in the same way as we did before:

- -
const pannerControl = document.querySelector('#panner');
-
-pannerControl.addEventListener('input', function() {
-    panner.pan.value = this.value;
-}, false);
-
- -

Let's adjust our audio graph again, to connect all the nodes together:

- -
track.connect(gainNode).connect(panner).connect(audioCtx.destination);
-
- -

The only thing left to do is give the app a try: Check out the final demo here on Codepen.

- -

Resumo

- -

Great! We have a boombox that plays our 'tape', and we can adjust the volume and stereo panning, giving us a fairly basic working audio graph.

- -

This makes up quite a few basics that you would need to start to add audio to your website or web app. There's a lot more functionality to the Web Audio API, but once you've grasped the concept of nodes and putting your audio graph together, we can move on to looking at more complex functionality.

- -

Mais exemplos

- -

There are other examples available to learn more about the Web Audio API.

- -

The Voice-change-O-matic is a fun voice manipulator and sound visualization web app that allows you to choose different effects and visualizations. The application is fairly rudimentary, but it demonstrates the simultaneous use of multiple Web Audio API features. (run the Voice-change-O-matic live).

- -

A UI with a sound wave being shown, and options for choosing voice effects and visualizations.

- -

Another application developed specifically to demonstrate the Web Audio API is the Violent Theremin, a simple web application that allows you to change pitch and volume by moving your mouse pointer. It also provides a psychedelic lightshow (see Violent Theremin source code).

- -

A page full of rainbow colours, with two buttons labeled Clear screen and mute.

- -

Consulte também a nossa repositório de exemplos de áudio para mais exemplos.

diff --git a/files/pt-pt/web/api/web_authentication_api/index.html b/files/pt-pt/web/api/web_authentication_api/index.html new file mode 100644 index 0000000000..ecc97dd5c0 --- /dev/null +++ b/files/pt-pt/web/api/web_authentication_api/index.html @@ -0,0 +1,149 @@ +--- +title: APi de Autenticação da Web +slug: Web/API/API_Autenticacao_Web +tags: + - API + - API de Autenticação da Web + - Landing + - Referencia +translation_of: Web/API/Web_Authentication_API +--- +
{{draft}}{{SeeCompatTable}}{{securecontext_header}}{{DefaultAPISidebar("Web Authentication API")}}
+ +

A "API de Autenticação da Web" é uma extensão de Credential Management API que permite uma autenticação forte com a criptografia de chave pública, permitindo a autenticação sem palavra-passe e/ou autenticação de segundo fator segura sem textos de SMS.

+ +

Conceitos e utilização da autenticação da Web

+ +

The Web Authtentication API (also referred to as WebAuthn) uses asymmetric (public-key) cryptography instead of passwords or SMS texts for registering, authenticating, and second-factor authentication with websites. This resolves significant security problems related to phishing, data breaches, and attacks against SMS texts or other second-factor authentication methods while at the same time significantly increasing ease of use (since users don't have to manage dozens of increasingly complicated passwords).

+ +

Many websites already have pages that allow users to register new accounts or sign in to an existing account, and WebAuthn acts as a replacement or suppliment to those on those existing webpages. Similar to the other forms of the Credential Management API, the Web Authentication API has two basic methods that correspond to register and login:

+ + + +

Por favor, note: both create() and get() require a Secure Context (e.g. - the server is connected by https or is the localhost), and will not be available for use if the browser is not operating in a secure context.

+ +

In their most basic forms, both create() and get() receive a very large random number called a challenge from the server and they return the challenge signed by the private key back to the server. This proves to the server that a user is in possession of the private key required for authentication without revealing any secrets over the network.

+ +

In order to understand how the create() and get() methods fit into the bigger picture, it is important to understand that they sit between two components that are outside the browser:

+ +
    +
  1. Servidor - the WebAuthn API is intended to register new credentials on a server (also referred to as a service or a relying party) and later use those same credentials on that same server to authenticate a user.
  2. +
  3. Autenticador - the credentials are created and stored in a device called an authenticator. This is a new concept in authentication: when authenticating using passwords, the password is stored in a user's brain and no other device is needed; when authenticating using WebAuthn, the password is replaced with a key pair that is stored in an authenticator. The authenticator may be embedded into an operating system, such as Windows Hello, or may be a physical token, such as a USB or Bluetooth Security Key.
  4. +
+ +

Registo

+ +

A typical registration process has six steps, as illustrated in Figure 1 and described further below. This is a simplification of the data required for the registration process that is only intended to provide an overview. The full set of required fields, optional fields, and their meanings for creating a registration request can be found in the {{domxref("PublicKeyCredentialCreationOptions")}} dictionary. Likewise, the full set of response fields can be found in the {{domxref("PublicKeyCredential")}} interface (where {{domxref("PublicKeyCredential.response")}} is the {{domxref("AuthenticatorAttestationResponse")}} interface). Note most JavaScript programmers that are creating an application will only really care about steps 1 and 5 where the create() function is called and subsequently returns; however, steps 2, 3, and 4 are essential to understanding the processing that takes place in the browser and authenticator and what the resulting data means.

+ +

WebAuthn registration component and dataflow diagram

+ +

Figura 1 - a diagram showing the sequence of actions for a WebAuthn registration and the essential data associated with each action.

+ +

Os passos de registo são:

+ +
    +
  1. Registo de Pedidos da Aplicação - The application makes the initial registration request. The protocol and format of this request is outside of the scope of WebAuthn.
  2. +
  3. Servidor Envia Desafio, Informação do Utilziador, e Envio de Informação de Confiança - The server sends a challenge, user information, and relying party information to the JavaScript program. The protocol for communicating with the server is not specified and is outside of the scope of WebAuthn. Typically, server communications would be REST over https (probably using XMLHttpRequest or Fetch), but they could also be SOAP, RFC 2549 or nearly any other protocol provided that the protocol is secure. The parameters received from the server will be passed to the create() call, typically with little or no modification and returns a Promise that will resolve to a {{domxref("PublicKeyCredential")}} containing an {{domxref("AuthenticatorAttestationResponse")}}. Note that it is absolutely critical that the challenge be a large buffer of random information (e.g. - more than 100 bytes) and it MUST be generated on the server in order to ensure the security of the registration process.
  4. +
  5. Navegador Chama o authenticatorMakeCredential() no Autenticador - Internally, the browser will validate the parameters and fill in any defaults, which become the {{domxref("AuthenticatorResponse.clientDataJSON")}}. One of the most important parameters is the origin, which recorded as part of the clientData so that the origin can be verified by the server later. The parameters to the create() call are passed to the authenticator, along with a SHA-256 hash of the clientDataJSON (only a hash is sent because the link to the authenticator may be a low-bandwidth NFC or Bluetooth link and the authenticator is just going to sign over the hash to ensure that it isn't tampered with).
  6. +
  7. Autenticador Cria Novo Par de Chave e Certificação - Before doing anything, the authenticator will typically ask for some form of user verficiation. This could be entering a PIN, using a fingerprint, doing an iris scan, etc. to prove that the user is present and consenting of the registration. After the user verification, the authenticator will create a new asymmetric key pair and safely store the private key for future reference. The public key will become part of the attestation, which the authtenticator will sign over with a private key that was burned into the authenticator during its manufacturing process and that has a certificate chain that can be validated back to a root of trust.
  8. +
  9. Autenticador Devolve os Dados para o Navegador - The new public key, a globally unique credential id, and other attestation data are returned to the browser where they become the attestationObject.
  10. +
  11. Navegador Cria os Dados Finais, a Aplicação envia a resposta para o Servidor - The create() Promise resolves to an {{domxref("PublicKeyCredential")}}, which has a {{domxref("PublicKeyCredential.rawId")}} that is the globally unique credential id along with a response that is the {{domxref("AuthenticatorAttestationResponse")}} containing the {{domxref("AuthenticatorResponse.clientDataJSON")}} and {{domxref("AuthenticatorAttestationResponse.attestationObject")}}. The {{domxref("PublicKeyCredential")}} is sent back to the server using any desired formatting and protocol (note that the ArrayBuffer properties need to be be base64 encoded or similar).
  12. +
  13. Servidor Valida e Finaliza o Registo - Finally, the server is required to perform a series of checks to ensure that the registration was complete and not tampered with. These include: +
      +
    1. Verifying that the challenge is the same as the challenge that was sent
    2. +
    3. Ensuring that the origin was the origin expected
    4. +
    5. Validating that the signature over the clientDataHash and the attestation using the certificate chain for that specific model of authenticator
    6. +
    + A complete list of validation steps can be found in the WebAuthn specification. Assuming that the checks pan out, the server will store the new public key associated with the user's account for future use -- that is, whenever the user desires to use the public key for authentication.
  14. +
+ +

Autenticação

+ +

After a user has registered with WebAuthn, they can subsequently authenticate (a.k.a. - login or sign-in) with the service. The authentication flow looks similar to the registration flow, and the illustration of actions in Figure 2 may be recognizable as being similar to the illustration of registration actions in Figure 1. The primary differences between registration and authentication are that: 1) authentication doesn't require user or relying party information; and 2) authentication creates an assertion using the previously generated key pair for the service rather than creating an attestation with the key pair that was burned into the authenticator during manufacturing. Again, the discription of authentication below is a broad overview rather than getting into all the options and features of WebAuthn. The specific options for authenticating can be found in the {{domxref("PublicKeyCredentialRequestOptions")}} dictionary, and the resulting data can be found in the {{domxref("PublicKeyCredential")}} interface (where {{domxref("PublicKeyCredential.response")}} is the {{domxref("AuthenticatorAssertionResponse")}} interface) .

+ +

WebAuthn authentication component and dataflow diagram

+ +

Figure 2 - similar to Figure 1, a diagram showing the sequence of actions for a WebAuthn authentication and the essential data associated with each action.

+ +
    +
  1. Auyenticação dos Pedidos da Aplicação - The application makes the initial authentication request. The protocol and format of this request is outside of the scope of WebAuthn.
  2. +
  3. Servidor Envia Desafio - The server sends a challenge JavaScript program. The protocol for communicating with the server is not specified and is outside of the scope of WebAuthn. Typically, server communications would be REST over https (probably using XMLHttpRequest or Fetch), but they could also be SOAP, RFC 2549 or nearly any other protocol provided that the protocol is secure. The parameters received from the server will be passed to the get() call, typically with little or no modification. Note that it is absolutely critical that the challenge be a large buffer of random information (e.g. - more than 100 bytes) and it MUST be generated on the server in order to ensure the security of the authentication process.
  4. +
  5. Navegador Chama o authenticatorGetCredential()  no Autenticador - Internally, the browser will validate the parameters and fill in any defaults, which become the {{domxref("AuthenticatorResponse.clientDataJSON")}}. One of the most important parameters is the origin, which recorded as part of the clientData so that the origin can be verified by the server later. The parameters to the create() call are passed to the authenticator, along with a SHA-256 hash of the clientDataJSON (only a hash is sent because the link to the authenticator may be a low-bandwidth NFC or Bluetooth link and the authenticator is just going to sign over the hash to ensure that it isn't tampered with).
  6. +
  7. Autenticador Cria uma Certificação  - The authenticator finds a credential for this service that matches the Relying Party ID and prompts a user to consent to the authentication. Assuming both of those steps are successful, the authenticator will create a new assertion by signing over the clientDataHash and authenticatorData with the private key generated for this account during the registration call.
  8. +
  9. Autenticador Devolve os Dados para o Navegador -  The authenticator returns the authenticatorData and assertion signature back to the browser.
  10. +
  11. Navegador Cria os Dados Finais, a Aplicação envia a resposta para o Servidor - The browser resolves the Promise to a {{domxref("PublicKeyCredential")}} with a {{domxref("PublicKeyCredential.response")}} that contains the {{domxref("AuthenticatorAssertionResponse")}}. It is up to the JavaScript application to transmit this data back to the server using any protocol and format of its choice.
  12. +
  13. Servidor Valida e Finaliza a Autenticação - Upon receiving the result of the authentication request, the server performs validation of the response such as: +
      +
    1. Using the public key that was stored during the registration request to validate the signature by the authenticator.
    2. +
    3. Ensuring that the challenge that was signed by the authenticator matches the challenge that was generated by the server.
    4. +
    5. Checking that the Relying Party ID is the one expected for this service.
    6. +
    + A full list of the steps for validating an assertion can be found in the WebAuthn specification. Assuming the validation is successful, the server will note that the user is now authenticated. This is outside the scope of the WebAuthn specification, but one option would be to drop a new cookie for the user session.
  14. +
+ +

Interfaces

+ +
+
{{domxref("CredentialsContainer")}}
+
WebAuthn extends the Credential Management API's create() and get() methods to take a new option: publicKey. When the publicKey option is passed to create() and / or get(), the Credential Management API will create a new public key pair or get an authentication for a key pair, respectively.
+
{{domxref("PublicKeyCredential")}}
+
A credential for logging in to a service using an un-phishable and data-breach resistant asymmetric key pair instead of a password.
+
{{domxref("AuthenticatorResponse")}}
+
Part of the PublicKeyCredential, the AuthenticatorResponse includes information from the browser (such as the challenge and origin); as well as information from the authenticator such as an AuthenticatorAttestationResponse (for new credentials) or an AuthenticatorAssertionResponse (when authenticating with existing credentials).
+
{{domxref("AuthenticatorAttestationResponse")}}
+
When a PublicKeyCredential has been created with the create() call, it will include an AuthenticatorAttestationResponse. This is the authenticator's way of providing a cryptographic root of trust for the new key pair that has been generated.
+
{{domxref("AuthenticatorAssertionResponse")}}
+
When a PublicKeyCredential is the result of a get() call, it will include an AuthenticatorAssertionResponse. This is the authenticator's way of proving to a service that it has the key pair and that the authentication request is valid and approved.
+
+ +

Opções

+ +
+
{{domxref("PublicKeyCredentialCreationOptions")}}
+
The options for creating a credential via navigator.credentials.create()
+
{{domxref("PublicKeyCredentialRequestOptions")}}
+
The options for using a credential via navigator.credentials.get()
+
+ +

Exemplos

+ + + +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('WebAuthn')}}{{Spec2('WebAuthn')}}Definção inicial.
+ +

Compatibilidade do Navegador

+ +
+
+ + +

{{Compat("api.PublicKeyCredential")}}

+
+
+ +

Consulte também:

+ + diff --git a/files/pt-pt/web/api/web_storage_api/index.html b/files/pt-pt/web/api/web_storage_api/index.html new file mode 100644 index 0000000000..7287b4bca5 --- /dev/null +++ b/files/pt-pt/web/api/web_storage_api/index.html @@ -0,0 +1,108 @@ +--- +title: DOM Storage +slug: DOM/Storage +--- +

{{ ApiRef() }} {{ Fx_minversion_header(2) }}

+

Resumo

+

DOM Storage é o nome dado ao conjunto de características de armazenamento relacionadas (storage-related features) inicialmente apresentadas na especificação Web Applications 1.0, e agora dividida em sua própria especificação W3C Web Storage. DOM Storage foi desenhado para proporcionar uma alternativa mais segura e fácil de usar, para o armazenamento de informações em cookies. Atualmente ela está disponível somente nos navegadores baseados no Mozilla e WebKit, começando notavelmente com o Firefox 2 e o Safari 4.

+
+ Nota: DOM Storage não é o mesmo que mozStorage (Interface XPCOM da Mozilla para o SQLite) ou Session store API (uma ferramenta de armazenamento XPCOM para uso de extensões).
+

Descrição

+

O mecanismo DOM Storage é um meio através do qual pares de strings de chaves/valores podem ser armazenados com segurança e mais tarde recuperados para uso.  A meta desta adição é proporcionar um meio compreensível através do qual aplicações interativas possam ser construídas (incluindo habilidades avançadas, tal como ser capaz de trabalhar "offline" por períodos de tempo maiores).

+

Atualmente, somente navegadores baseados no Mozilla, Internet Explorer 8 beta 2 e Safari (não outros navegadores baseados em webkit, por exemplo, o Google Chrome) proporcionam um trabalho de implementação da especificação do DOM Storage. O Internet Explorer anterior a versão 8 tem uma característica similar chamada "userData behavior" que permite guardar dados através de múltiplas sessões do navegador.

+

Dom Storage é útil porque não existem métodos diretamente nos navegadores, bons para guardar quantidades de dados razoáveis por qualquer período de tempo. Os cookies do navegador (Browser cookies) tem uma capacidade limitada e não proporcionam suporte para organizar dados armazenados, e outros métodos (tal como Flash Local Storage) que requerem um plugin externo.

+

Umas dos primeiros aplicativos públicos a fazer uso da nova funcionalidade DOM Storage (em adição ao userData Behavior do Internet Explorer) foi o halfnote (um aplicativo de tomada de notas) escrito por Aaron Boodman. Em seu aplicativo, Aaron simultaneamente salvava notas no servidor (quando a conexão a internet estava disponível) e em um armazenamento local de dados. Isto permitia ao usuário escrever seguramente, cópias de notas mesmo com uma conexão esporádica à internet.

+

Embora o conceito e implementação apresentados no halfnote seja comparativamente simples, sua criação mostra a possibilidade para uma nova geração de aplicativos web que sejam utilizáveis tanto online quanto offline.

+

Referência

+

A seguir vem objetos globais que existem como propriedades de todos os window object. Isto significa que eles podem ser acessados por sessionStorage ou window.sessionStorage. (Isto é importante porque você pode então usar IFrames para armazenar, ou acessar, dados adicionais, além do que está imediatamente incluído em sua página).

+

Storage

+

Este é um construtor (Storage) para todas as instâncias Storage (sessionStorage e globalStorage[location.host]). Storage.prototype.removeKey = function(key){ this.removeItem(this.key(key)) } assim configuradao, pode ser acessado como localStorage.removeKey e sessionStorage.removeKey.

+

Itens globalStorage não são instâncias de Storage, e sim uma instância de StorageObsolete.

+

Storage é definido pelo WhatWG Storage Interface como:

+
interface Storage {
+  readonly attribute unsigned long length;
+  [IndexGetter] DOMString key(in unsigned long index);
+  [NameGetter] DOMString getItem(in DOMString key);
+  [NameSetter] void setItem(in DOMString key, in DOMString data);
+  [NameDeleter] void removeItem(in DOMString key);
+  void clear();
+};
+

 

+

sessionStorage

+

Este é um objeto global (sessionStorage) que mantém uma área de armazenamento disponível enquanto durar a sessão da página. Uma sessão de página dura enquanto o navegador estiver aberto e continua mesmo sobre recarregamentos e restaurações. Abrindo uma página em uma nova aba ou janela causará o início de uma nova sessão.

+
// Save data to a the current session's store
+sessionStorage.username = "John";
+
+// Access some stored data
+alert( "username = " + sessionStorage.username );
+
+

O objeto sessionStorage é útil para guardar dados temporários que devem ser salvos e restaurados se o navegador for atualizado acidentalmente.

+

{{ fx_minversion_note("3.5", "Nas versões anteriores ao Firefox 3.5, os dados em sessionStorage não eram restaurados automaticamente depois de recuperar-se de uma quebra no navegador. A partir do Firefox 3.5, isto funciona como na especificação.") }}

+

Exemplos:

+

Autosalvar o conteúdo de uma campo de texto, e se o navegador for atualizado acidentalmente , restaurar o conteúdo do campo de texto, não tendo perdas na escrita.

+
 // Get the text field that we're going to track
+ var field = document.getElementById("field");
+
+ // See if we have an autosave value
+ // (this will only happen if the page is accidentally refreshed)
+ if ( sessionStorage.autosave ) {
+     // Restore the contents of the text field
+     field.value = sessionStorage.autosave;
+ }
+
+ // Check the contents of the text field every second
+ setInterval(function(){
+     // And save the results into the session storage object
+     sessionStorage.autosave = field.value;
+ }, 1000);
+
+

Mais informações:

+ +

globalStorage

+

{{ Non-standard_header() }} Este é um objeto global (globalStorage) que mantém múltiplas áreas de armazenamento privadas que podem ser usadas para guardar dados por um longo período de tempo (por exemplo, sobre múltiplas láginas e sessões do navegador).

+
+ Nota: globalStorage não é uma instância de Storage, mas uma instância StorageList contendo instâncias StorageObsolete.
+
// Save data that only scripts on the mozilla.org domain can access
+globalStorage['mozilla.org'].snippet = "<b>Hello</b>, how are you?";
+
+

Especificamente, o objeto globalStorage fornece acesso a um número de diferentes objetos de armazenamento em que os dados sejam armazenados. Por exemplo, se construirmos uma página web que use globalStorage em seu domínio (developer.mozilla.org) é necessário termos o objeto de armazenamento a seguir disponível para nós:

+ +

{{ Fx_minversion_note(3, "O Firefox 2 passou a permitir acesso aos objetos de armazenamento superiores ao documento corrente na hierarquia do domínio. Por razões de segurança isto não é mais permitido no Firefox 3. Além disso, a proposta de adição ao HTML 5 foi removida da especificação do HTML 5 em favor de localStorage, que foi implementado no Firefox 3.5.") }}

+

Exemplos:

+

Todos estes exemplos requerem que você tenha uns script inserido (com o código seguinte) em todas as páginas que você quiser ver o resultado.

+

Lembrar o nome de usuário para o subdomínio particular que está sendo visitado:

+
 globalStorage['developer.mozilla.org'].username = "John";
+
+

Manter o número de vezes que um usuário visitou todas as páginas do seu domínio:

+
 // parseInt must be used since all data is stored as a string
+ globalStorage['mozilla.org'].visits =
+     parseInt( globalStorage['mozilla.org'].visits || 0 ) + 1;
+
+

localStorage

+

localStorage é o mesmo que globalStorage[location.hostname], com a exceção de ser projetado para a origem do HTML 5 (esquema + nome do host + porta não padrão) e localStorage é uma instância de Storage diferente de globalStorage[location.hostname] que é uma instância de StorageObsolete. Por exemplo, http://example.com não está disponível para acessar o mesmo objeto localStorage que https://example.com mas eles podem acessar o mesmo item globalStorage. localStorage é uma interface padrão enquanto globalStorage não é padrão. localStorage foi adicionada ao Firefox 3.5.

+

Por favor, note que configurar a propriedade globalStorage[location.hostname] não a configura em localStorage e por extensão Storage.prototype não afeta itens globalStorage, somente extendendo o que StorageObsolete.prototype faz.

+
+ Nota: Quando o navegador entra em modo de navegação privada, um novo banco de dados temporário é criado para guardar dados de armazenamento local; este banco de dados é vazio, e é jogado fora qunado o modo de navegação privado é desativado.
+

Mais informações

+ +

Exemplos

+ + + +

{{ languages( { "en": "en/DOM/Storage", "es": "es/DOM/Almacenamiento", "fr": "fr/DOM/Storage", "ja": "ja/DOM/Storage", "pl": "pl/DOM/Storage", "zh-cn": "cn/DOM/Storage" } ) }}

diff --git a/files/pt-pt/web/api/web_workers_api/using_web_workers/index.html b/files/pt-pt/web/api/web_workers_api/using_web_workers/index.html new file mode 100644 index 0000000000..d9705559e7 --- /dev/null +++ b/files/pt-pt/web/api/web_workers_api/using_web_workers/index.html @@ -0,0 +1,1091 @@ +--- +title: Utilização de Web Workers +slug: Web/API/Web_Workers_API/Utilizacao_de_web_workers +tags: + - Avançado + - Firefox + - Guía + - JavaScript + - Operadores + - Workers +translation_of: Web/API/Web_Workers_API/Using_web_workers +--- +
+

Web Workers é um meio simples para o conteúdo da Web para executar scripts em segmentos em segundo plano. O segmento do worker pode realizar tarefas sem interferir com a interface do utilizador. Em adição, eles podem executar I/O, utilizando XMLHttpRequest (embora e responseXML e os atributos de channel são sempre nulos). Uma vez criado, um worker pode enviar mensagens para o código JavaScript que o criou publicando mensagens para um manipulador de evento especificado por esse código (e vice-versa.) Este artigo fornece uma introdução detalhada para utilizar workers da Web.

+
+ +

API de Workers da Web

+ +

A worker is an object created using a constructor (e.g. {{domxref("Worker.Worker", "Worker()")}}) that runs a named JavaScript file — this file contains the code that will run in the worker thread; workers run in another global context that is different from the current {{domxref("window")}}. Thus, using the {{domxref("window")}} shortcut to get the current global scope (instead of {{domxref("window.self","self")}}) within a {{domxref("Worker")}} will return an error.

+ +

The worker context is represented by a {{domxref("DedicatedWorkerGlobalScope")}} object in the case of dedicated workers (standard workers that are utilized by a single script; shared workers use {{domxref("SharedWorkerGlobalScope")}}). A dedicated worker is only accessible from the script that first spawned it, whereas shared workers can be accessed from multiple scripts.

+ +
+

Nota: See The Web Workers API landing page for reference documentation on workers and additional guides.

+
+ +

You can run whatever code you like inside the worker thread, with some exceptions. For example, you can't directly manipulate the DOM from inside a worker, or use some default methods and properties of the {{domxref("window")}} object. But you can use a large number of items available under window, including WebSockets, and data storage mechanisms like IndexedDB and the Firefox OS-only Data Store API. See Functions and classes available to workers for more details.

+ +

Data is sent between workers and the main thread via a system of messages — both sides send their messages using the postMessage() method, and respond to messages via the onmessage event handler (the message is contained within the {{event("Message")}} event's data attribute.) The data is copied rather than shared.

+ +

Workers may, in turn, spawn new workers, as long as those workers are hosted within the same origin as the parent page. In addition, workers may use XMLHttpRequest for network I/O, with the exception that the responseXML and channel attributes on XMLHttpRequest always return null.

+ +

Workers dedicados

+ +

As mentioned above, a dedicated worker is only accessible by the script that called it. In this section we'll discuss the JavaScript found in our Basic dedicated worker example (run dedicated worker): This allows you to enter two numbers to be multiplied together. The numbers are sent to a dedicated worker, multiplied together, and the result is returned to the page and displayed.

+ +

This example is rather trivial, but we decided to keep it simple while introducing you to basic worker concepts. More advanced details are covered later on in the article.

+ +

Detecção da funcionalidade worker

+ +

For slightly more controlled error handling and backwards compatibility, it is a good idea to wrap your worker accessing code in the following (main.js):

+ +
if (window.Worker) {
+
+  ...
+
+}
+ +

Geração de um worker dedicado

+ +

Creating a new worker is simple. All you need to do is call the {{domxref("Worker.Worker", "Worker()")}} constructor, specifying the URI of a script to execute in the worker thread (main.js):

+ +
+
var myWorker = new Worker('worker.js');
+
+
+ +

Enviar mensagens para /e de um worker dedicado

+ +

The magic of workers happens via the {{domxref("Worker.postMessage", "postMessage()")}} method and the {{domxref("Worker.onmessage", "onmessage")}} event handler. When you want to send a message to the worker, you post messages to it like this (main.js):

+ +
first.onchange = function() {
+  myWorker.postMessage([first.value,second.value]);
+  console.log('Message posted to worker');
+}
+
+second.onchange = function() {
+  myWorker.postMessage([first.value,second.value]);
+  console.log('Message posted to worker');
+}
+ +

So here we have two {{htmlelement("input")}} elements represented by the variables first and second; when the value of either is changed, myWorker.postMessage([first.value,second.value]) is used to send the value inside both to the worker, as an array. You can send pretty much anything you like in the message.

+ +

In the worker, we can respond when the message is received by writing an event handler block like this (worker.js):

+ +
onmessage = function(e) {
+  console.log('Message received from main script');
+  var workerResult = 'Result: ' + (e.data[0] * e.data[1]);
+  console.log('Posting message back to main script');
+  postMessage(workerResult);
+}
+ +

The onmessage handler allows us to run some code whenever a message is received, with the message itself being available in the message event's data attribute. Here we simply multiply together the two numbers then use postMessage() again, to post the result back to the main thread.

+ +

Back in the main thread, we use onmessage again, to respond to the message sent back from the worker:

+ +
myWorker.onmessage = function(e) {
+  result.textContent = e.data;
+  console.log('Message received from worker');
+}
+ +

Here we grab the message event data and set it as the textContent of the result paragraph, so the user can see the result of the calculation.

+ +
+

Nota: The URI passed as a parameter to the Worker constructor must obey the same-origin policy .

+ +

There is currently disagreement among browsers vendors on what URIs are of the same-origin; Gecko 10.0 {{geckoRelease("10.0")}} and later do allow data URIs and Internet Explorer 10 does not allow Blob URIs as a valid script for workers.

+
+ +
Nota: Notice that onmessage and postMessage() need to be hung off the Worker object when used in the main script thread, but not when used in the worker. This is because, inside the worker, the worker is effectively the global scope.
+ +
Nota: When a message is passed between the main thread and worker, it is copied or "transferred" (moved), not shared. Read {{anch("Transferring data to and from workers further details", "Transferring data to and from workers: further details")}} for a much more thorough explanation.
+ +

Terminar um worker

+ +

If you need to immediately terminate a running worker from the main thread, you can do so by calling the worker's {{domxref("Worker", "terminate")}} method:

+ +
myWorker.terminate();
+ +

The worker thread is killed immediately without an opportunity to complete its operations or clean up after itself.

+ +

In the worker thread, workers may close themselves by calling their own {{domxref("WorkerGlobalScope", "close")}} method:

+ +
close();
+ +

Lidar com erros

+ +

When a runtime error occurs in the worker, its onerror event handler is called. It receives an event named error which implements the ErrorEvent interface.

+ +

The event doesn't bubble and is cancelable; to prevent the default action from taking place, the worker can call the error event's preventDefault() method.

+ +

The error event has the following three fields that are of interest:

+ +
+
message
+
A human-readable error message.
+
filename
+
The name of the script file in which the error occurred.
+
lineno
+
The line number of the script file on which the error occurred.
+
+ +

Gerar subworkers

+ +

Workers may spawn more workers if they wish. So-called sub-workers must be hosted within the same origin as the parent page. Also, the URIs for subworkers are resolved relative to the parent worker's location rather than that of the owning page. This makes it easier for workers to keep track of where their dependencies are.

+ +

Importar scripts e bibliotecas

+ +

Worker threads have access to a global function, importScripts(), which lets them import scripts. It accepts zero or more URIs as parameters to resources to import; all of the following examples are valid:

+ +
importScripts();                         /* imports nothing */
+importScripts('foo.js');                 /* imports just "foo.js" */
+importScripts('foo.js', 'bar.js');       /* imports two scripts */
+importScripts('//example.com/hello.js'); /* You can import scripts from other origins */
+ +

The browser loads each listed script and executes it. Any global objects from each script may then be used by the worker. If the script can't be loaded, NETWORK_ERROR is thrown, and subsequent code will not be executed. Previously executed code (including code deferred using {{domxref("window.setTimeout()")}}) will still be functional though. Function declarations after the importScripts() method are also kept, since these are always evaluated before the rest of the code.

+ +
Note: Scripts may be downloaded in any order, but will be executed in the order in which you pass the filenames into importScripts() . This is done synchronously; importScripts() does not return until all the scripts have been loaded and executed.
+ +

Shared workers (Partilhados)

+ +

A shared worker is accessible by multiple scripts — even if they are being accessed by different windows, iframes or even workers. In this section we'll discuss the JavaScript found in our Basic shared worker example (run shared worker): This is very similar to the basic dedicated worker example, except that it has two functions available handled by different script files: multiplying two numbers, or squaring a number. Both scripts use the same worker to do the actual calculation required.

+ +

Here we'll concentrate on the differences between dedicated and shared workers. Note that in this example we have two HTML pages, each with JavaScript applied that uses the same single worker file.

+ +
+

Nota: If SharedWorker can be accessed from several browsing contexts, all those browsing contexts must share the exact same origin (same protocol, host, and port).

+
+ +
+

Nota: In Firefox, shared workers cannot be shared between documents loaded in private and non-private windows ({{bug(1177621)}}).

+
+ +

Gerar um shared worker

+ +

Spawning a new shared worker is pretty much the same as with a dedicated worker, but with a different constructor name (see index.html and index2.html) — each one has to spin up the worker using code like the following:

+ +
var myWorker = new SharedWorker('worker.js');
+ +

One big difference is that with a shared worker you have to communicate via a port object — an explicit port is opened that the scripts can use to communicate with the worker (this is done implicitly in the case of dedicated workers).

+ +

The port connection needs to be started either implicitly by use of the onmessage event handler or explicitly with the start() method before any messages can be posted. Although the multiply.js and worker.js files in the demo currently call the start() method, those calls are not necessary since the onmessage event handler is being used. Calling start() is only needed if the message event is wired up via the addEventListener() method.

+ +

When using the start() method to open the port connection, it needs to be called from both the parent thread and the worker thread if two-way communication is needed.

+ +
myWorker.port.start();  // called in parent thread
+ +
port.start();  // called in worker thread, assuming the port variable references a port
+ +

Enviar mensagens para/e de um shared worker

+ +

Now messages can be sent to the worker as before, but the postMessage() method has to be invoked through the port object (again, you'll see similar constructs in both multiply.js and square.js):

+ +
squareNumber.onchange = function() {
+  myWorker.port.postMessage([squareNumber.value,squareNumber.value]);
+  console.log('Message posted to worker');
+}
+ +

Now, on to the worker. There is a bit more complexity here as well (worker.js):

+ +
onconnect = function(e) {
+  var port = e.ports[0];
+
+  port.onmessage = function(e) {
+    var workerResult = 'Result: ' + (e.data[0] * e.data[1]);
+    port.postMessage(workerResult);
+  }
+}
+ +

First, we use an onconnect handler to fire code when a connection to the port happens (i.e. when the onmessage event handler in the parent thread is setup, or when the start() method is explicitly called in the parent thread).

+ +

We use the ports attribute of this event object to grab the port and store it in a variable.

+ +

Next, we add a message handler on the port to do the calculation and return the result to the main thread. Setting up this message handler in the worker thread also implicitly opens the port connection back to the parent thread, so the call to port.start() is not actually needed, as noted above.

+ +

Finally, back in the main script, we deal with the message (again, you'll see similar constructs in both multiply.js and square.js):

+ +
myWorker.port.onmessage = function(e) {
+  result2.textContent = e.data;
+  console.log('Message received from worker');
+}
+ +

When a message comes back through the port from the worker, we check what result type it is, then insert the calculation result inside the appropriate result paragraph.

+ +

Sobre a segurança de segmento

+ +

The {{domxref("Worker")}} interface spawns real OS-level threads, and mindful programmers may be concerned that concurrency can cause “interesting” effects in your code if you aren't careful.

+ +

However, since web workers have carefully controlled communication points with other threads, it's actually very hard to cause concurrency problems. There's no access to non-threadsafe components or the DOM. And you have to pass specific data in and out of a thread through serialized objects. So you have to work really hard to cause problems in your code.

+ +

An example of a catastrophy would be like the following:

+ +

Conteúdo HTML

+ +
<html>
+<head>
+<title>Multithreading Catastrophy</title>
+<style>
+body { margin: 0px; }
+canvas { position: absolute; top: 0; bottom: 0; left: 0; right:0; width: 100%; height: 100%; }
+</style>
+<script src="main.js" async></script>
+</head>
+<body>
+<canvas id="canvas"></canvas>
+</body>
+</html>
+ +

Conteúdo main.js

+ +
// main.js
+var myworker = new Worker("worker.js"), width=window.innerWidth, height=window.innerHeight, context=document.getElementById('canvas').getContext('2d');
+var imagedatatmp=context.createImageData(width,height);
+
+myworker.onmessage = function(data){
+    imageData = imagedatatmp.from(data);
+};
+
+setTimeout(function draw_canvas() {
+    context.putImageData(imageData);
+    setTimeout(draw_canvas, 1000/60);
+},10);
+
+window.onresize = window.reload; // Quick (to type) n' dirty way to resize;
+ +

Conteúdo worker.js

+ +
// worker.js
+window.onmessage = function(width, height){
+var noise = function(x, y, z) {
+    var p = new Array(512), permutation = [151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180];
+    for (var i = 0;i < 256;i++) p[256 + i] = p[i] = permutation[i];
+    var X = Math.floor(x) & 255, Y = Math.floor(y) & 255, Z = Math.floor(z) & 255; x -= Math.floor(x), y -= Math.floor(y), z -= Math.floor(z);
+    var u = fade(x), v = fade(y), w = fade(z);
+    var A = p[X] + Y, AA = p[A] + Z, AB = p[A + 1] + Z, B = p[X + 1] + Y, BA = p[B] + Z, BB = p[B + 1] + Z;
+    return scale(lerp(w, lerp(v, lerp(u, grad(p[AA], x, y, z), grad(p[BA], x - 1, y, z)), lerp(u, grad(p[AB], x, y - 1, z), grad(p[BB], x - 1, y - 1, z))), lerp(v, lerp(u, grad(p[AA + 1], x, y, z - 1), grad(p[BA + 1], x - 1, y, z - 1)), lerp(u, grad(p[AB + 1], x, y - 1, z - 1), grad(p[BB + 1], x - 1, y - 1, z - 1)))));
+};
+  function fade(t) { return t * t * t * (t * (t * 6 - 15) + 10); }
+  function lerp(t, a, b) { return a + t * (b - a); }
+  function grad(hash, x, y, z) {
+    var h = hash & 15; var u = h < 8 ? x : y, v = h < 4 ? y : h == 12 || h == 14 ? x : z;
+    return ((h & 1) == 0 ? u : -u) + ((h & 2) == 0 ? v : -v);
+  }
+  function scale(n) { return (1 + n) / 2; }
+var length = width*height; var canvasnoisedata=new UInt32Array(length);
+
+setTimeout(function make_noise() {
+var i=length, z=Math.random()*1024;
+  while ( i-- ) {
+      canvasnoisedata[i] = noise(i%width+z,i/width+z,z);
+  }
+  setTimeout(make_noise, 1000/60);
+},1000/60);
+
+setTimeout(function post_noise() {
+    postMessage( canvasnoisedata );
+    setTimeout(post_noise, 1000/60);
+},1000/60);
+};
+
+ +

Resultado

+ +

{{ EmbedLiveSample('ats.html') }}

+ +

Política de segurança de conteúdo

+ +

Workers are considered to have their own execution context, distinct from the document that created them. For this reason they are, in general, not governed by the content security policy of the document (or parent worker) that created them. So for example, suppose a document is served with the following header:

+ +
Content-Security-Policy: script-src 'self'
+ +
Among other things, this will prevent any scripts it includes from using eval(). However, if the script constructs a worker, code running in the worker's context will be allowed to use eval().
+
+To specify a content security policy for the worker, set a Content-Security-Policy response header for the request which delivered the worker script itself.
+
+The exception to this is if the worker script's origin is a globally unique identifier (for example, if its URL has a scheme of data or blob). In this case, the worker does inherit the CSP of the document or worker that created it.
+ +
 
+ +

Transferir dados para/e de workers: detalhes adicionais

+ +

Data passed between the main page and workers is copied, not shared. Objects are serialized as they're handed to the worker, and subsequently, de-serialized on the other end. The page and worker do not share the same instance, so the end result is that a duplicate is created on each end. Most browsers implement this feature as structured cloning.

+ +

To illustrate this, let's create for didactical purpose a function named emulateMessage(), which will simulate the behavior of a value that is cloned and not shared during the passage from a worker to the main page or vice versa:

+ +
function emulateMessage(vVal) {
+    return eval('(' + JSON.stringify(vVal) + ')');
+}
+
+// Tests
+
+// test #1
+var example1 = new Number(3);
+console.log(typeof example1); // object
+console.log(typeof emulateMessage(example1)); // number
+
+// test #2
+var example2 = true;
+console.log(typeof example2); // boolean
+console.log(typeof emulateMessage(example2)); // boolean
+
+// test #3
+var example3 = new String('Hello World');
+console.log(typeof example3); // object
+console.log(typeof emulateMessage(example3)); // string
+
+// test #4
+var example4 = {
+    'name': 'John Smith',
+    "age": 43
+};
+console.log(typeof example4); // object
+console.log(typeof emulateMessage(example4)); // object
+
+// test #5
+function Animal(sType, nAge) {
+    this.type = sType;
+    this.age = nAge;
+}
+var example5 = new Animal('Cat', 3);
+alert(example5.constructor); // Animal
+alert(emulateMessage(example5).constructor); // Object
+ +

A value that is cloned and not shared is called message. As you will probably know by now, messages can be sent to and from the main thread by using postMessage(), and the message event's {{domxref("MessageEvent.data", "data")}} attribute contains data passed back from the worker.

+ +

example.html: (a página principal):

+ +
var myWorker = new Worker('my_task.js');
+
+myWorker.onmessage = function(oEvent) {
+  console.log('Worker said : ' + oEvent.data);
+};
+
+myWorker.postMessage('ali');
+ +

my_task.js (o worker):

+ +
postMessage("I\'m working before postMessage(\'ali\').");
+
+onmessage = function(oEvent) {
+  postMessage('Hi ' + oEvent.data);
+};
+ +

The structured cloning algorithm can accept JSON and a few things that JSON can't — like circular references.

+ +

Passagem de exemplos de dados

+ +

Exemplo #1: Criar um genérico "assíncrono eval()"

+ +

The following example shows how to use a worker in order to asynchronously execute any JavaScript code allowed in a worker, through eval() within the worker:

+ +
// Syntax: asyncEval(code[, listener])
+
+var asyncEval = (function () {
+  var aListeners = [], oParser = new Worker('data:text/javascript;charset=US-ASCII,onmessage%20%3D%20function%20%28oEvent%29%20%7B%0A%09postMessage%28%7B%0A%09%09%22id%22%3A%20oEvent.data.id%2C%0A%09%09%22evaluated%22%3A%20eval%28oEvent.data.code%29%0A%09%7D%29%3B%0A%7D');
+
+  oParser.onmessage = function(oEvent) {
+    if (aListeners[oEvent.data.id]) { aListeners[oEvent.data.id](oEvent.data.evaluated); }
+    delete aListeners[oEvent.data.id];
+  };
+
+  return function(sCode, fListener) {
+    aListeners.push(fListener || null);
+    oParser.postMessage({
+      'id': aListeners.length - 1,
+      'code': sCode
+    });
+  };
+})();
+ +

The data URL is equivalent to a network request, with the following response:

+ +
onmessage = function(oEvent) {
+  postMessage({
+    'id': oEvent.data.id,
+    'evaluated': eval(oEvent.data.code)
+  });
+}
+ +

Amostra de utilização:

+ +
// asynchronous alert message...
+asyncEval('3 + 2', function(sMessage) {
+    alert('3 + 2 = ' + sMessage);
+});
+
+// asynchronous print message...
+asyncEval("\"Hello World!!!\"", function(sHTML) {
+    document.body.appendChild(document.createTextNode(sHTML));
+});
+
+// asynchronous void...
+asyncEval("(function () {\n\tvar oReq = new XMLHttpRequest();\n\toReq.open(\"get\", \"http://www.mozilla.org/\", false);\n\toReq.send(null);\n\treturn oReq.responseText;\n})()");
+ +

Exemplo #2: Passagem avançada da 'Dados' JSON e criar um sistema de troca

+ +

If you have to pass some complex data and have to call many different functions both on the main page and in the Worker, you can create a system which groups everything together.

+ +

First, we create a QueryableWorker class that takes the url of the worker, a default listener, and an error handler, and this class is going to keep track of a list of listeners and help us communicate with the worker:

+ +
function QueryableWorker(url, defaultListener, onError) {
+    var instance = this,
+        worker = new Worker(url),
+        listeners = {};
+
+    this.defaultListener = defaultListener || function() {};
+
+    if (onError) {worker.onerror = onError;}
+
+    this.postMessage = function(message) {
+        worker.postMessage(message);
+    }
+
+    this.terminate = function() {
+        worker.terminate();
+    }
+}
+ +

Then we add the methods of adding/removing listeners:

+ +
this.addListeners = function(name, listener) {
+    listeners[name] = listener;
+}
+
+this.removeListeners = function(name) {
+    delete listeners[name];
+}
+ +

Here we let the worker handle two simple operations for illustration: getting the difference of two numbers and making an alert after three seconds. In order to achieve that we first implement a sendQuery method which queries if the worker actually has the corresponding methods to do what we want.

+ +
/*
+  This functions takes at least one argument, the method name we want to query.
+  Then we can pass in the arguments that the method needs.
+ */
+this.sendQuery = function() {
+    if (arguments.length < 1) {
+         throw new TypeError('QueryableWorker.sendQuery takes at least one argument');
+         return;
+    }
+    worker.postMessage({
+        'queryMethod': arguments[0],
+        'queryArguments': Array.prototype.slice.call(arguments, 1)
+    });
+}
+ +

We finish QueryableWorker with the onmessage method. If the worker has the corresponding methods we queried, it should return the name of the corresponding listener and the arguments it needs, we just need to find it in listeners.:

+ +
worker.onmessage = function(event) {
+    if (event.data instanceof Object &&
+        event.data.hasOwnProperty('queryMethodListener') &&
+        event.data.hasOwnProperty('queryMethodArguments')) {
+        listeners[event.data.queryMethodListener].apply(instance, event.data.queryMethodArguments);
+    } else {
+        this.defaultListener.call(instance, event.data);
+    }
+}
+
+ +

Now onto the worker.  First we need to have the methods to handle the two simple operations:

+ +
var queryableFunctions = {
+    getDifference: function(a, b) {
+        reply('printStuff', a - b);
+    },
+    waitSomeTime: function() {
+        setTimeout(function() {
+            reply('doAlert', 3, 'seconds');
+        }, 3000);
+    }
+}
+
+function reply() {
+    if (arguments.length < 1) {
+        throw new TypeError('reply - takes at least one argument');
+        return;
+    }
+    postMessage({
+        queryMethodListener: arguments[0],
+        queryMethodArguments: Array.prototype.slice.call(arguments, 1)
+    });
+}
+
+/* This method is called when main page calls QueryWorker's postMessage method directly*/
+function defaultReply(message) {
+    // do something
+}
+
+ +

And the onmessage method is now trivial:

+ +
onmessage = function(event) {
+    if (event.data instanceof Object &&
+        event.data.hasOwnProperty('queryMethod') &&
+        event.data.hasOwnProperty('queryMethodArguments')) {
+        queryableFunctions[event.data.queryMethod]
+            .apply(self, event.data.queryMethodArguments);
+    } else {
+        defaultReply(event.data);
+    }
+}
+
+ +

Here are the full implementation:

+ +

example.html (the main page):

+ +
<!doctype html>
+  <html>
+    <head>
+      <meta charset="UTF-8"  />
+      <title>MDN Example - Queryable worker</title>
+    <script type="text/javascript">
+    /*
+      QueryableWorker instances methods:
+        * sendQuery(queryable function name, argument to pass 1, argument to pass 2, etc. etc): calls a Worker's queryable function
+        * postMessage(string or JSON Data): see Worker.prototype.postMessage()
+        * terminate(): terminates the Worker
+        * addListener(name, function): adds a listener
+        * removeListener(name): removes a listener
+      QueryableWorker instances properties:
+        * defaultListener: the default listener executed only when the Worker calls the postMessage() function directly
+     */
+    function QueryableWorker(url, defaultListener, onError) {
+      var instance = this,
+      worker = new Worker(url),
+      listeners = {};
+
+      this.defaultListener = defaultListener || function() {};
+
+      if (onError) {worker.onerror = onError;}
+
+      this.postMessage = function(message) {
+        worker.postMessage(message);
+      }
+
+      this.terminate = function() {
+        worker.terminate();
+      }
+
+      this.addListener = function(name, listener) {
+        listeners[name] = listener;
+      }
+
+      this.removeListener = function(name) {
+        delete listeners[name];
+      }
+
+      /*
+        This functions takes at least one argument, the method name we want to query.
+        Then we can pass in the arguments that the method needs.
+      */
+      this.sendQuery = function() {
+        if (arguments.length < 1) {
+          throw new TypeError('QueryableWorker.sendQuery takes at least one argument');
+          return;
+        }
+        worker.postMessage({
+          'queryMethod': arguments[0],
+          'queryMethodArguments': Array.prototype.slice.call(arguments, 1)
+        });
+      }
+
+      worker.onmessage = function(event) {
+        if (event.data instanceof Object &&
+          event.data.hasOwnProperty('queryMethodListener') &&
+          event.data.hasOwnProperty('queryMethodArguments')) {
+          listeners[event.data.queryMethodListener].apply(instance, event.data.queryMethodArguments);
+        } else {
+          this.defaultListener.call(instance, event.data);
+        }
+      }
+    }
+
+    // your custom "queryable" worker
+    var myTask = new QueryableWorker('my_task.js');
+
+    // your custom "listeners"
+    myTask.addListener('printStuff', function (result) {
+      document.getElementById('firstLink').parentNode.appendChild(document.createTextNode('The difference is ' + result + '!'));
+    });
+
+    myTask.addListener('doAlert', function (time, unit) {
+      alert('Worker waited for ' + time + ' ' + unit + ' :-)');
+    });
+</script>
+</head>
+<body>
+  <ul>
+    <li><a id="firstLink" href="javascript:myTask.sendQuery('getDifference', 5, 3);">What is the difference between 5 and 3?</a></li>
+    <li><a href="javascript:myTask.sendQuery('waitSomeTime');">Wait 3 seconds</a></li>
+    <li><a href="javascript:myTask.terminate();">terminate() the Worker</a></li>
+  </ul>
+</body>
+</html>
+ +

my_task.js (o worker):

+ +
var queryableFunctions = {
+  // example #1: get the difference between two numbers:
+  getDifference: function(nMinuend, nSubtrahend) {
+      reply('printStuff', nMinuend - nSubtrahend);
+  },
+  // example #2: wait three seconds
+  waitSomeTime: function() {
+      setTimeout(function() { reply('doAlert', 3, 'seconds'); }, 3000);
+  }
+};
+
+// system functions
+
+function defaultReply(message) {
+  // your default PUBLIC function executed only when main page calls the queryableWorker.postMessage() method directly
+  // do something
+}
+
+function reply() {
+  if (arguments.length < 1) { throw new TypeError('reply - not enough arguments'); return; }
+  postMessage({ 'queryMethodListener': arguments[0], 'queryMethodArguments': Array.prototype.slice.call(arguments, 1) });
+}
+
+onmessage = function(oEvent) {
+  if (oEvent.data instanceof Object && oEvent.data.hasOwnProperty('queryMethod') && oEvent.data.hasOwnProperty('queryMethodArguments')) {
+    queryableFunctions[oEvent.data.queryMethod].apply(self, oEvent.data.queryMethodArguments);
+  } else {
+    defaultReply(oEvent.data);
+  }
+};
+ +

It is possible to switch the content of each mainpage -> worker and worker -> mainpage message. And the property names "queryMethod", "queryMethodListeners", "queryMethodArguments" can be anything as long as they are consistent in QueryableWorker and the worker.

+ +

Passing data by transferring ownership (transferable objects)

+ +

Google Chrome 17+ and Firefox 18+ contain an additional way to pass certain types of objects (transferable objects, that is objects implementing the {{domxref("Transferable")}} interface) to or from a worker with high performance. Transferable objects are transferred from one context to another with a zero-copy operation, which results in a vast performance improvement when sending large data sets. Think of it as pass-by-reference if you're from the C/C++ world. However, unlike pass-by-reference, the 'version' from the calling context is no longer available once transferred. Its ownership is transferred to the new context. For example, when transferring an {{domxref("ArrayBuffer")}} from your main app to a worker script, the original {{domxref("ArrayBuffer")}} is cleared and no longer usable. Its content is (quite literally) transferred to the worker context.

+ +
// Create a 32MB "file" and fill it.
+var uInt8Array = new Uint8Array(1024 * 1024 * 32); // 32MB
+for (var i = 0; i < uInt8Array.length; ++i) {
+  uInt8Array[i] = i;
+}
+
+worker.postMessage(uInt8Array.buffer, [uInt8Array.buffer]);
+
+ +
+

Nota: For more information on transferable objects, performance, and feature-detection for this method, read Transferable Objects: Lightning Fast! on HTML5 Rocks.

+
+ +

Workers integrados

+ +

There is not an "official" way to embed the code of a worker within a web page, like {{HTMLElement("script")}} elements do for normal scripts. But a {{HTMLElement("script")}} element that does not have a src attribute and has a type attribute that does not identify an executable MIME type can be considered a data block element that JavaScript could use. "Data blocks" is a more general feature of HTML5 that can carry almost any textual data. So, a worker could be embedded in this way:

+ +
<!DOCTYPE html>
+<html>
+<head>
+<meta charset="UTF-8" />
+<title>MDN Example - Embedded worker</title>
+<script type="text/js-worker">
+  // This script WON'T be parsed by JS engines because its MIME type is text/js-worker.
+  var myVar = 'Hello World!';
+  // Rest of your worker code goes here.
+</script>
+<script type="text/javascript">
+  // This script WILL be parsed by JS engines because its MIME type is text/javascript.
+  function pageLog(sMsg) {
+    // Use a fragment: browser will only render/reflow once.
+    var oFragm = document.createDocumentFragment();
+    oFragm.appendChild(document.createTextNode(sMsg));
+    oFragm.appendChild(document.createElement('br'));
+    document.querySelector('#logDisplay').appendChild(oFragm);
+  }
+</script>
+<script type="text/js-worker">
+  // This script WON'T be parsed by JS engines because its MIME type is text/js-worker.
+  onmessage = function(oEvent) {
+    postMessage(myVar);
+  };
+  // Rest of your worker code goes here.
+</script>
+<script type="text/javascript">
+  // This script WILL be parsed by JS engines because its MIME type is text/javascript.
+
+  // In the past...:
+  // blob builder existed
+  // ...but now we use Blob...:
+  var blob = new Blob(Array.prototype.map.call(document.querySelectorAll('script[type=\'text\/js-worker\']'), function (oScript) { return oScript.textContent; }),{type: 'text/javascript'});
+
+  // Creating a new document.worker property containing all our "text/js-worker" scripts.
+  document.worker = new Worker(window.URL.createObjectURL(blob));
+
+  document.worker.onmessage = function(oEvent) {
+    pageLog('Received: ' + oEvent.data);
+  };
+
+  // Start the worker.
+  window.onload = function() { document.worker.postMessage(''); };
+</script>
+</head>
+<body><div id="logDisplay"></div></body>
+</html>
+ +

The embedded worker is now nested into a new custom document.worker property.

+ +

It is also worth noting that you can also convert a function into a Blob, then generate an object URL from that blob. For example:

+ +
function fn2workerURL(fn) {
+  var blob = new Blob(['('+fn.toString()+')()'], {type: 'application/javascript'})
+  return URL.createObjectURL(blob)
+}
+ +

Exemplos adicionais

+ +

This section provides further examples of how to use web workers.

+ +

Realizar computações em segundo plano

+ +

Workers are mainly useful for allowing your code to perform processor-intensive calculations without blocking the user interface thread. In this example, a worker is used to calculate Fibonacci numbers.

+ +

O código de JavaScript

+ +

The following JavaScript code is stored in the "fibonacci.js" file referenced by the HTML in the next section.

+ +
var results = [];
+
+function resultReceiver(event) {
+  results.push(parseInt(event.data));
+  if (results.length == 2) {
+    postMessage(results[0] + results[1]);
+  }
+}
+
+function errorReceiver(event) {
+  throw event.data;
+}
+
+onmessage = function(event) {
+  var n = parseInt(event.data);
+
+  if (n == 0 || n == 1) {
+    postMessage(n);
+    return;
+  }
+
+  for (var i = 1; i <= 2; i++) {
+    var worker = new Worker('fibonacci.js');
+    worker.onmessage = resultReceiver;
+    worker.onerror = errorReceiver;
+    worker.postMessage(n - i);
+  }
+ };
+ +

The worker sets the property onmessage to a function which will receive messages sent when the worker object's postMessage() is called (note that this differs from defining a global variable of that name, or defining a function with that name. var onmessage and function onmessage will define global properties with those names, but they will not register the function to receive messages sent by the web page that created the worker). This starts the recursion, spawning new copies of itself to handle each iteration of the calculation.

+ +

O código de HTML

+ +
<!DOCTYPE html>
+<html>
+  <head>
+    <meta charset="UTF-8"  />
+    <title>Test threads fibonacci</title>
+  </head>
+  <body>
+
+  <div id="result"></div>
+
+  <script language="javascript">
+
+    var worker = new Worker('fibonacci.js');
+
+    worker.onmessage = function(event) {
+      document.getElementById('result').textContent = event.data;
+      dump('Got: ' + event.data + '\n');
+    };
+
+    worker.onerror = function(error) {
+      dump('Worker error: ' + error.message + '\n');
+      throw error;
+    };
+
+    worker.postMessage('5');
+
+  </script>
+  </body>
+</html>
+
+ +

The web page creates a div element with the ID result , which gets used to display the result, then spawns the worker. After spawning the worker, the onmessage handler is configured to display the results by setting the contents of the div element, and the onerror handler is set to dump the error message.

+ +

Finally, a message is sent to the worker to start it.

+ +

Try this example.

+ +

Executar I/O da Web em segundo plano

+ +

You can find an example of this in the article Using workers in extensions .

+ +

Dividir tarefas entre mútiplos workers

+ +

As multi-core computers become increasingly common, it's often useful to divide computationally complex tasks among multiple workers, which may then perform those tasks on multiple-processor cores.

+ +

Outros tipos de worker

+ +

In addition to dedicated and shared web workers, there are other types of worker available:

+ + + +

Funções e interfaces disponíveis nos workers

+ +

You can use most standard JavaScript features inside a web worker, including:

+ + + +

The main thing you can't do in a Worker is directly affect the parent page. This includes manipulating the DOM and using that page's objects. You have to do it indirectly, by sending a message back to the main script via {{domxref("DedicatedWorkerGlobalScope.postMessage")}}, then actioning the changes from there.

+ +
+

Note: For a complete list of functions available to workers, see Functions and interfaces available to workers.

+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', '#workers', 'Web workers')}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade de navegador

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support4[1]{{CompatGeckoDesktop("1.9.1")}}10.010.6[1]4[2]
Shared workers4[1]{{CompatGeckoDesktop(29)}}{{CompatNo}}10.65
+ {{CompatNo}} 6.1[4]
Passing data using structured cloning13{{CompatGeckoDesktop(8)}}10.011.56
Passing data using transferable objects17 {{property_prefix("webkit")}}
+ 21
{{CompatGeckoDesktop(18)}}{{CompatNo}}156
Global {{domxref("window.URL", "URL")}}10[3]
+ 23
{{CompatGeckoDesktop(21)}}11156[3]
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support4.44[1]3.51.0.110.011.5[1]5.1[2]
Shared workers{{CompatNo}}4[1]81.0.1{{CompatNo}}{{CompatNo}}{{CompatNo}}
Passing data using structured cloning{{CompatNo}}481.0.1{{CompatNo}}{{CompatNo}}{{CompatNo}}
Passing data using transferable objects{{CompatNo}}{{CompatNo}}181.0.1{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] Chrome and Opera give an error "Uncaught SecurityError: Failed to construct 'Worker': Script at 'file:///Path/to/worker.js' cannot be accessed from origin 'null'." when you try to run a worker locally. It needs to be on a proper domain.

+ +

[2] As of Safari 7.1.2, you can call console.log from inside a worker, but it won't print anything to the console. Older versions of Safari don't allow you to call console.log from inside a worker.

+ +

[3] This feature is implemented prefixed as webkitURL.

+ +

[4] Safari removed SharedWorker support.

+ +

Consultar também

+ + + +
+ + + + + +
diff --git a/files/pt-pt/web/api/web_workers_api/utilizacao_de_web_workers/index.html b/files/pt-pt/web/api/web_workers_api/utilizacao_de_web_workers/index.html deleted file mode 100644 index d9705559e7..0000000000 --- a/files/pt-pt/web/api/web_workers_api/utilizacao_de_web_workers/index.html +++ /dev/null @@ -1,1091 +0,0 @@ ---- -title: Utilização de Web Workers -slug: Web/API/Web_Workers_API/Utilizacao_de_web_workers -tags: - - Avançado - - Firefox - - Guía - - JavaScript - - Operadores - - Workers -translation_of: Web/API/Web_Workers_API/Using_web_workers ---- -
-

Web Workers é um meio simples para o conteúdo da Web para executar scripts em segmentos em segundo plano. O segmento do worker pode realizar tarefas sem interferir com a interface do utilizador. Em adição, eles podem executar I/O, utilizando XMLHttpRequest (embora e responseXML e os atributos de channel são sempre nulos). Uma vez criado, um worker pode enviar mensagens para o código JavaScript que o criou publicando mensagens para um manipulador de evento especificado por esse código (e vice-versa.) Este artigo fornece uma introdução detalhada para utilizar workers da Web.

-
- -

API de Workers da Web

- -

A worker is an object created using a constructor (e.g. {{domxref("Worker.Worker", "Worker()")}}) that runs a named JavaScript file — this file contains the code that will run in the worker thread; workers run in another global context that is different from the current {{domxref("window")}}. Thus, using the {{domxref("window")}} shortcut to get the current global scope (instead of {{domxref("window.self","self")}}) within a {{domxref("Worker")}} will return an error.

- -

The worker context is represented by a {{domxref("DedicatedWorkerGlobalScope")}} object in the case of dedicated workers (standard workers that are utilized by a single script; shared workers use {{domxref("SharedWorkerGlobalScope")}}). A dedicated worker is only accessible from the script that first spawned it, whereas shared workers can be accessed from multiple scripts.

- -
-

Nota: See The Web Workers API landing page for reference documentation on workers and additional guides.

-
- -

You can run whatever code you like inside the worker thread, with some exceptions. For example, you can't directly manipulate the DOM from inside a worker, or use some default methods and properties of the {{domxref("window")}} object. But you can use a large number of items available under window, including WebSockets, and data storage mechanisms like IndexedDB and the Firefox OS-only Data Store API. See Functions and classes available to workers for more details.

- -

Data is sent between workers and the main thread via a system of messages — both sides send their messages using the postMessage() method, and respond to messages via the onmessage event handler (the message is contained within the {{event("Message")}} event's data attribute.) The data is copied rather than shared.

- -

Workers may, in turn, spawn new workers, as long as those workers are hosted within the same origin as the parent page. In addition, workers may use XMLHttpRequest for network I/O, with the exception that the responseXML and channel attributes on XMLHttpRequest always return null.

- -

Workers dedicados

- -

As mentioned above, a dedicated worker is only accessible by the script that called it. In this section we'll discuss the JavaScript found in our Basic dedicated worker example (run dedicated worker): This allows you to enter two numbers to be multiplied together. The numbers are sent to a dedicated worker, multiplied together, and the result is returned to the page and displayed.

- -

This example is rather trivial, but we decided to keep it simple while introducing you to basic worker concepts. More advanced details are covered later on in the article.

- -

Detecção da funcionalidade worker

- -

For slightly more controlled error handling and backwards compatibility, it is a good idea to wrap your worker accessing code in the following (main.js):

- -
if (window.Worker) {
-
-  ...
-
-}
- -

Geração de um worker dedicado

- -

Creating a new worker is simple. All you need to do is call the {{domxref("Worker.Worker", "Worker()")}} constructor, specifying the URI of a script to execute in the worker thread (main.js):

- -
-
var myWorker = new Worker('worker.js');
-
-
- -

Enviar mensagens para /e de um worker dedicado

- -

The magic of workers happens via the {{domxref("Worker.postMessage", "postMessage()")}} method and the {{domxref("Worker.onmessage", "onmessage")}} event handler. When you want to send a message to the worker, you post messages to it like this (main.js):

- -
first.onchange = function() {
-  myWorker.postMessage([first.value,second.value]);
-  console.log('Message posted to worker');
-}
-
-second.onchange = function() {
-  myWorker.postMessage([first.value,second.value]);
-  console.log('Message posted to worker');
-}
- -

So here we have two {{htmlelement("input")}} elements represented by the variables first and second; when the value of either is changed, myWorker.postMessage([first.value,second.value]) is used to send the value inside both to the worker, as an array. You can send pretty much anything you like in the message.

- -

In the worker, we can respond when the message is received by writing an event handler block like this (worker.js):

- -
onmessage = function(e) {
-  console.log('Message received from main script');
-  var workerResult = 'Result: ' + (e.data[0] * e.data[1]);
-  console.log('Posting message back to main script');
-  postMessage(workerResult);
-}
- -

The onmessage handler allows us to run some code whenever a message is received, with the message itself being available in the message event's data attribute. Here we simply multiply together the two numbers then use postMessage() again, to post the result back to the main thread.

- -

Back in the main thread, we use onmessage again, to respond to the message sent back from the worker:

- -
myWorker.onmessage = function(e) {
-  result.textContent = e.data;
-  console.log('Message received from worker');
-}
- -

Here we grab the message event data and set it as the textContent of the result paragraph, so the user can see the result of the calculation.

- -
-

Nota: The URI passed as a parameter to the Worker constructor must obey the same-origin policy .

- -

There is currently disagreement among browsers vendors on what URIs are of the same-origin; Gecko 10.0 {{geckoRelease("10.0")}} and later do allow data URIs and Internet Explorer 10 does not allow Blob URIs as a valid script for workers.

-
- -
Nota: Notice that onmessage and postMessage() need to be hung off the Worker object when used in the main script thread, but not when used in the worker. This is because, inside the worker, the worker is effectively the global scope.
- -
Nota: When a message is passed between the main thread and worker, it is copied or "transferred" (moved), not shared. Read {{anch("Transferring data to and from workers further details", "Transferring data to and from workers: further details")}} for a much more thorough explanation.
- -

Terminar um worker

- -

If you need to immediately terminate a running worker from the main thread, you can do so by calling the worker's {{domxref("Worker", "terminate")}} method:

- -
myWorker.terminate();
- -

The worker thread is killed immediately without an opportunity to complete its operations or clean up after itself.

- -

In the worker thread, workers may close themselves by calling their own {{domxref("WorkerGlobalScope", "close")}} method:

- -
close();
- -

Lidar com erros

- -

When a runtime error occurs in the worker, its onerror event handler is called. It receives an event named error which implements the ErrorEvent interface.

- -

The event doesn't bubble and is cancelable; to prevent the default action from taking place, the worker can call the error event's preventDefault() method.

- -

The error event has the following three fields that are of interest:

- -
-
message
-
A human-readable error message.
-
filename
-
The name of the script file in which the error occurred.
-
lineno
-
The line number of the script file on which the error occurred.
-
- -

Gerar subworkers

- -

Workers may spawn more workers if they wish. So-called sub-workers must be hosted within the same origin as the parent page. Also, the URIs for subworkers are resolved relative to the parent worker's location rather than that of the owning page. This makes it easier for workers to keep track of where their dependencies are.

- -

Importar scripts e bibliotecas

- -

Worker threads have access to a global function, importScripts(), which lets them import scripts. It accepts zero or more URIs as parameters to resources to import; all of the following examples are valid:

- -
importScripts();                         /* imports nothing */
-importScripts('foo.js');                 /* imports just "foo.js" */
-importScripts('foo.js', 'bar.js');       /* imports two scripts */
-importScripts('//example.com/hello.js'); /* You can import scripts from other origins */
- -

The browser loads each listed script and executes it. Any global objects from each script may then be used by the worker. If the script can't be loaded, NETWORK_ERROR is thrown, and subsequent code will not be executed. Previously executed code (including code deferred using {{domxref("window.setTimeout()")}}) will still be functional though. Function declarations after the importScripts() method are also kept, since these are always evaluated before the rest of the code.

- -
Note: Scripts may be downloaded in any order, but will be executed in the order in which you pass the filenames into importScripts() . This is done synchronously; importScripts() does not return until all the scripts have been loaded and executed.
- -

Shared workers (Partilhados)

- -

A shared worker is accessible by multiple scripts — even if they are being accessed by different windows, iframes or even workers. In this section we'll discuss the JavaScript found in our Basic shared worker example (run shared worker): This is very similar to the basic dedicated worker example, except that it has two functions available handled by different script files: multiplying two numbers, or squaring a number. Both scripts use the same worker to do the actual calculation required.

- -

Here we'll concentrate on the differences between dedicated and shared workers. Note that in this example we have two HTML pages, each with JavaScript applied that uses the same single worker file.

- -
-

Nota: If SharedWorker can be accessed from several browsing contexts, all those browsing contexts must share the exact same origin (same protocol, host, and port).

-
- -
-

Nota: In Firefox, shared workers cannot be shared between documents loaded in private and non-private windows ({{bug(1177621)}}).

-
- -

Gerar um shared worker

- -

Spawning a new shared worker is pretty much the same as with a dedicated worker, but with a different constructor name (see index.html and index2.html) — each one has to spin up the worker using code like the following:

- -
var myWorker = new SharedWorker('worker.js');
- -

One big difference is that with a shared worker you have to communicate via a port object — an explicit port is opened that the scripts can use to communicate with the worker (this is done implicitly in the case of dedicated workers).

- -

The port connection needs to be started either implicitly by use of the onmessage event handler or explicitly with the start() method before any messages can be posted. Although the multiply.js and worker.js files in the demo currently call the start() method, those calls are not necessary since the onmessage event handler is being used. Calling start() is only needed if the message event is wired up via the addEventListener() method.

- -

When using the start() method to open the port connection, it needs to be called from both the parent thread and the worker thread if two-way communication is needed.

- -
myWorker.port.start();  // called in parent thread
- -
port.start();  // called in worker thread, assuming the port variable references a port
- -

Enviar mensagens para/e de um shared worker

- -

Now messages can be sent to the worker as before, but the postMessage() method has to be invoked through the port object (again, you'll see similar constructs in both multiply.js and square.js):

- -
squareNumber.onchange = function() {
-  myWorker.port.postMessage([squareNumber.value,squareNumber.value]);
-  console.log('Message posted to worker');
-}
- -

Now, on to the worker. There is a bit more complexity here as well (worker.js):

- -
onconnect = function(e) {
-  var port = e.ports[0];
-
-  port.onmessage = function(e) {
-    var workerResult = 'Result: ' + (e.data[0] * e.data[1]);
-    port.postMessage(workerResult);
-  }
-}
- -

First, we use an onconnect handler to fire code when a connection to the port happens (i.e. when the onmessage event handler in the parent thread is setup, or when the start() method is explicitly called in the parent thread).

- -

We use the ports attribute of this event object to grab the port and store it in a variable.

- -

Next, we add a message handler on the port to do the calculation and return the result to the main thread. Setting up this message handler in the worker thread also implicitly opens the port connection back to the parent thread, so the call to port.start() is not actually needed, as noted above.

- -

Finally, back in the main script, we deal with the message (again, you'll see similar constructs in both multiply.js and square.js):

- -
myWorker.port.onmessage = function(e) {
-  result2.textContent = e.data;
-  console.log('Message received from worker');
-}
- -

When a message comes back through the port from the worker, we check what result type it is, then insert the calculation result inside the appropriate result paragraph.

- -

Sobre a segurança de segmento

- -

The {{domxref("Worker")}} interface spawns real OS-level threads, and mindful programmers may be concerned that concurrency can cause “interesting” effects in your code if you aren't careful.

- -

However, since web workers have carefully controlled communication points with other threads, it's actually very hard to cause concurrency problems. There's no access to non-threadsafe components or the DOM. And you have to pass specific data in and out of a thread through serialized objects. So you have to work really hard to cause problems in your code.

- -

An example of a catastrophy would be like the following:

- -

Conteúdo HTML

- -
<html>
-<head>
-<title>Multithreading Catastrophy</title>
-<style>
-body { margin: 0px; }
-canvas { position: absolute; top: 0; bottom: 0; left: 0; right:0; width: 100%; height: 100%; }
-</style>
-<script src="main.js" async></script>
-</head>
-<body>
-<canvas id="canvas"></canvas>
-</body>
-</html>
- -

Conteúdo main.js

- -
// main.js
-var myworker = new Worker("worker.js"), width=window.innerWidth, height=window.innerHeight, context=document.getElementById('canvas').getContext('2d');
-var imagedatatmp=context.createImageData(width,height);
-
-myworker.onmessage = function(data){
-    imageData = imagedatatmp.from(data);
-};
-
-setTimeout(function draw_canvas() {
-    context.putImageData(imageData);
-    setTimeout(draw_canvas, 1000/60);
-},10);
-
-window.onresize = window.reload; // Quick (to type) n' dirty way to resize;
- -

Conteúdo worker.js

- -
// worker.js
-window.onmessage = function(width, height){
-var noise = function(x, y, z) {
-    var p = new Array(512), permutation = [151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180];
-    for (var i = 0;i < 256;i++) p[256 + i] = p[i] = permutation[i];
-    var X = Math.floor(x) & 255, Y = Math.floor(y) & 255, Z = Math.floor(z) & 255; x -= Math.floor(x), y -= Math.floor(y), z -= Math.floor(z);
-    var u = fade(x), v = fade(y), w = fade(z);
-    var A = p[X] + Y, AA = p[A] + Z, AB = p[A + 1] + Z, B = p[X + 1] + Y, BA = p[B] + Z, BB = p[B + 1] + Z;
-    return scale(lerp(w, lerp(v, lerp(u, grad(p[AA], x, y, z), grad(p[BA], x - 1, y, z)), lerp(u, grad(p[AB], x, y - 1, z), grad(p[BB], x - 1, y - 1, z))), lerp(v, lerp(u, grad(p[AA + 1], x, y, z - 1), grad(p[BA + 1], x - 1, y, z - 1)), lerp(u, grad(p[AB + 1], x, y - 1, z - 1), grad(p[BB + 1], x - 1, y - 1, z - 1)))));
-};
-  function fade(t) { return t * t * t * (t * (t * 6 - 15) + 10); }
-  function lerp(t, a, b) { return a + t * (b - a); }
-  function grad(hash, x, y, z) {
-    var h = hash & 15; var u = h < 8 ? x : y, v = h < 4 ? y : h == 12 || h == 14 ? x : z;
-    return ((h & 1) == 0 ? u : -u) + ((h & 2) == 0 ? v : -v);
-  }
-  function scale(n) { return (1 + n) / 2; }
-var length = width*height; var canvasnoisedata=new UInt32Array(length);
-
-setTimeout(function make_noise() {
-var i=length, z=Math.random()*1024;
-  while ( i-- ) {
-      canvasnoisedata[i] = noise(i%width+z,i/width+z,z);
-  }
-  setTimeout(make_noise, 1000/60);
-},1000/60);
-
-setTimeout(function post_noise() {
-    postMessage( canvasnoisedata );
-    setTimeout(post_noise, 1000/60);
-},1000/60);
-};
-
- -

Resultado

- -

{{ EmbedLiveSample('ats.html') }}

- -

Política de segurança de conteúdo

- -

Workers are considered to have their own execution context, distinct from the document that created them. For this reason they are, in general, not governed by the content security policy of the document (or parent worker) that created them. So for example, suppose a document is served with the following header:

- -
Content-Security-Policy: script-src 'self'
- -
Among other things, this will prevent any scripts it includes from using eval(). However, if the script constructs a worker, code running in the worker's context will be allowed to use eval().
-
-To specify a content security policy for the worker, set a Content-Security-Policy response header for the request which delivered the worker script itself.
-
-The exception to this is if the worker script's origin is a globally unique identifier (for example, if its URL has a scheme of data or blob). In this case, the worker does inherit the CSP of the document or worker that created it.
- -
 
- -

Transferir dados para/e de workers: detalhes adicionais

- -

Data passed between the main page and workers is copied, not shared. Objects are serialized as they're handed to the worker, and subsequently, de-serialized on the other end. The page and worker do not share the same instance, so the end result is that a duplicate is created on each end. Most browsers implement this feature as structured cloning.

- -

To illustrate this, let's create for didactical purpose a function named emulateMessage(), which will simulate the behavior of a value that is cloned and not shared during the passage from a worker to the main page or vice versa:

- -
function emulateMessage(vVal) {
-    return eval('(' + JSON.stringify(vVal) + ')');
-}
-
-// Tests
-
-// test #1
-var example1 = new Number(3);
-console.log(typeof example1); // object
-console.log(typeof emulateMessage(example1)); // number
-
-// test #2
-var example2 = true;
-console.log(typeof example2); // boolean
-console.log(typeof emulateMessage(example2)); // boolean
-
-// test #3
-var example3 = new String('Hello World');
-console.log(typeof example3); // object
-console.log(typeof emulateMessage(example3)); // string
-
-// test #4
-var example4 = {
-    'name': 'John Smith',
-    "age": 43
-};
-console.log(typeof example4); // object
-console.log(typeof emulateMessage(example4)); // object
-
-// test #5
-function Animal(sType, nAge) {
-    this.type = sType;
-    this.age = nAge;
-}
-var example5 = new Animal('Cat', 3);
-alert(example5.constructor); // Animal
-alert(emulateMessage(example5).constructor); // Object
- -

A value that is cloned and not shared is called message. As you will probably know by now, messages can be sent to and from the main thread by using postMessage(), and the message event's {{domxref("MessageEvent.data", "data")}} attribute contains data passed back from the worker.

- -

example.html: (a página principal):

- -
var myWorker = new Worker('my_task.js');
-
-myWorker.onmessage = function(oEvent) {
-  console.log('Worker said : ' + oEvent.data);
-};
-
-myWorker.postMessage('ali');
- -

my_task.js (o worker):

- -
postMessage("I\'m working before postMessage(\'ali\').");
-
-onmessage = function(oEvent) {
-  postMessage('Hi ' + oEvent.data);
-};
- -

The structured cloning algorithm can accept JSON and a few things that JSON can't — like circular references.

- -

Passagem de exemplos de dados

- -

Exemplo #1: Criar um genérico "assíncrono eval()"

- -

The following example shows how to use a worker in order to asynchronously execute any JavaScript code allowed in a worker, through eval() within the worker:

- -
// Syntax: asyncEval(code[, listener])
-
-var asyncEval = (function () {
-  var aListeners = [], oParser = new Worker('data:text/javascript;charset=US-ASCII,onmessage%20%3D%20function%20%28oEvent%29%20%7B%0A%09postMessage%28%7B%0A%09%09%22id%22%3A%20oEvent.data.id%2C%0A%09%09%22evaluated%22%3A%20eval%28oEvent.data.code%29%0A%09%7D%29%3B%0A%7D');
-
-  oParser.onmessage = function(oEvent) {
-    if (aListeners[oEvent.data.id]) { aListeners[oEvent.data.id](oEvent.data.evaluated); }
-    delete aListeners[oEvent.data.id];
-  };
-
-  return function(sCode, fListener) {
-    aListeners.push(fListener || null);
-    oParser.postMessage({
-      'id': aListeners.length - 1,
-      'code': sCode
-    });
-  };
-})();
- -

The data URL is equivalent to a network request, with the following response:

- -
onmessage = function(oEvent) {
-  postMessage({
-    'id': oEvent.data.id,
-    'evaluated': eval(oEvent.data.code)
-  });
-}
- -

Amostra de utilização:

- -
// asynchronous alert message...
-asyncEval('3 + 2', function(sMessage) {
-    alert('3 + 2 = ' + sMessage);
-});
-
-// asynchronous print message...
-asyncEval("\"Hello World!!!\"", function(sHTML) {
-    document.body.appendChild(document.createTextNode(sHTML));
-});
-
-// asynchronous void...
-asyncEval("(function () {\n\tvar oReq = new XMLHttpRequest();\n\toReq.open(\"get\", \"http://www.mozilla.org/\", false);\n\toReq.send(null);\n\treturn oReq.responseText;\n})()");
- -

Exemplo #2: Passagem avançada da 'Dados' JSON e criar um sistema de troca

- -

If you have to pass some complex data and have to call many different functions both on the main page and in the Worker, you can create a system which groups everything together.

- -

First, we create a QueryableWorker class that takes the url of the worker, a default listener, and an error handler, and this class is going to keep track of a list of listeners and help us communicate with the worker:

- -
function QueryableWorker(url, defaultListener, onError) {
-    var instance = this,
-        worker = new Worker(url),
-        listeners = {};
-
-    this.defaultListener = defaultListener || function() {};
-
-    if (onError) {worker.onerror = onError;}
-
-    this.postMessage = function(message) {
-        worker.postMessage(message);
-    }
-
-    this.terminate = function() {
-        worker.terminate();
-    }
-}
- -

Then we add the methods of adding/removing listeners:

- -
this.addListeners = function(name, listener) {
-    listeners[name] = listener;
-}
-
-this.removeListeners = function(name) {
-    delete listeners[name];
-}
- -

Here we let the worker handle two simple operations for illustration: getting the difference of two numbers and making an alert after three seconds. In order to achieve that we first implement a sendQuery method which queries if the worker actually has the corresponding methods to do what we want.

- -
/*
-  This functions takes at least one argument, the method name we want to query.
-  Then we can pass in the arguments that the method needs.
- */
-this.sendQuery = function() {
-    if (arguments.length < 1) {
-         throw new TypeError('QueryableWorker.sendQuery takes at least one argument');
-         return;
-    }
-    worker.postMessage({
-        'queryMethod': arguments[0],
-        'queryArguments': Array.prototype.slice.call(arguments, 1)
-    });
-}
- -

We finish QueryableWorker with the onmessage method. If the worker has the corresponding methods we queried, it should return the name of the corresponding listener and the arguments it needs, we just need to find it in listeners.:

- -
worker.onmessage = function(event) {
-    if (event.data instanceof Object &&
-        event.data.hasOwnProperty('queryMethodListener') &&
-        event.data.hasOwnProperty('queryMethodArguments')) {
-        listeners[event.data.queryMethodListener].apply(instance, event.data.queryMethodArguments);
-    } else {
-        this.defaultListener.call(instance, event.data);
-    }
-}
-
- -

Now onto the worker.  First we need to have the methods to handle the two simple operations:

- -
var queryableFunctions = {
-    getDifference: function(a, b) {
-        reply('printStuff', a - b);
-    },
-    waitSomeTime: function() {
-        setTimeout(function() {
-            reply('doAlert', 3, 'seconds');
-        }, 3000);
-    }
-}
-
-function reply() {
-    if (arguments.length < 1) {
-        throw new TypeError('reply - takes at least one argument');
-        return;
-    }
-    postMessage({
-        queryMethodListener: arguments[0],
-        queryMethodArguments: Array.prototype.slice.call(arguments, 1)
-    });
-}
-
-/* This method is called when main page calls QueryWorker's postMessage method directly*/
-function defaultReply(message) {
-    // do something
-}
-
- -

And the onmessage method is now trivial:

- -
onmessage = function(event) {
-    if (event.data instanceof Object &&
-        event.data.hasOwnProperty('queryMethod') &&
-        event.data.hasOwnProperty('queryMethodArguments')) {
-        queryableFunctions[event.data.queryMethod]
-            .apply(self, event.data.queryMethodArguments);
-    } else {
-        defaultReply(event.data);
-    }
-}
-
- -

Here are the full implementation:

- -

example.html (the main page):

- -
<!doctype html>
-  <html>
-    <head>
-      <meta charset="UTF-8"  />
-      <title>MDN Example - Queryable worker</title>
-    <script type="text/javascript">
-    /*
-      QueryableWorker instances methods:
-        * sendQuery(queryable function name, argument to pass 1, argument to pass 2, etc. etc): calls a Worker's queryable function
-        * postMessage(string or JSON Data): see Worker.prototype.postMessage()
-        * terminate(): terminates the Worker
-        * addListener(name, function): adds a listener
-        * removeListener(name): removes a listener
-      QueryableWorker instances properties:
-        * defaultListener: the default listener executed only when the Worker calls the postMessage() function directly
-     */
-    function QueryableWorker(url, defaultListener, onError) {
-      var instance = this,
-      worker = new Worker(url),
-      listeners = {};
-
-      this.defaultListener = defaultListener || function() {};
-
-      if (onError) {worker.onerror = onError;}
-
-      this.postMessage = function(message) {
-        worker.postMessage(message);
-      }
-
-      this.terminate = function() {
-        worker.terminate();
-      }
-
-      this.addListener = function(name, listener) {
-        listeners[name] = listener;
-      }
-
-      this.removeListener = function(name) {
-        delete listeners[name];
-      }
-
-      /*
-        This functions takes at least one argument, the method name we want to query.
-        Then we can pass in the arguments that the method needs.
-      */
-      this.sendQuery = function() {
-        if (arguments.length < 1) {
-          throw new TypeError('QueryableWorker.sendQuery takes at least one argument');
-          return;
-        }
-        worker.postMessage({
-          'queryMethod': arguments[0],
-          'queryMethodArguments': Array.prototype.slice.call(arguments, 1)
-        });
-      }
-
-      worker.onmessage = function(event) {
-        if (event.data instanceof Object &&
-          event.data.hasOwnProperty('queryMethodListener') &&
-          event.data.hasOwnProperty('queryMethodArguments')) {
-          listeners[event.data.queryMethodListener].apply(instance, event.data.queryMethodArguments);
-        } else {
-          this.defaultListener.call(instance, event.data);
-        }
-      }
-    }
-
-    // your custom "queryable" worker
-    var myTask = new QueryableWorker('my_task.js');
-
-    // your custom "listeners"
-    myTask.addListener('printStuff', function (result) {
-      document.getElementById('firstLink').parentNode.appendChild(document.createTextNode('The difference is ' + result + '!'));
-    });
-
-    myTask.addListener('doAlert', function (time, unit) {
-      alert('Worker waited for ' + time + ' ' + unit + ' :-)');
-    });
-</script>
-</head>
-<body>
-  <ul>
-    <li><a id="firstLink" href="javascript:myTask.sendQuery('getDifference', 5, 3);">What is the difference between 5 and 3?</a></li>
-    <li><a href="javascript:myTask.sendQuery('waitSomeTime');">Wait 3 seconds</a></li>
-    <li><a href="javascript:myTask.terminate();">terminate() the Worker</a></li>
-  </ul>
-</body>
-</html>
- -

my_task.js (o worker):

- -
var queryableFunctions = {
-  // example #1: get the difference between two numbers:
-  getDifference: function(nMinuend, nSubtrahend) {
-      reply('printStuff', nMinuend - nSubtrahend);
-  },
-  // example #2: wait three seconds
-  waitSomeTime: function() {
-      setTimeout(function() { reply('doAlert', 3, 'seconds'); }, 3000);
-  }
-};
-
-// system functions
-
-function defaultReply(message) {
-  // your default PUBLIC function executed only when main page calls the queryableWorker.postMessage() method directly
-  // do something
-}
-
-function reply() {
-  if (arguments.length < 1) { throw new TypeError('reply - not enough arguments'); return; }
-  postMessage({ 'queryMethodListener': arguments[0], 'queryMethodArguments': Array.prototype.slice.call(arguments, 1) });
-}
-
-onmessage = function(oEvent) {
-  if (oEvent.data instanceof Object && oEvent.data.hasOwnProperty('queryMethod') && oEvent.data.hasOwnProperty('queryMethodArguments')) {
-    queryableFunctions[oEvent.data.queryMethod].apply(self, oEvent.data.queryMethodArguments);
-  } else {
-    defaultReply(oEvent.data);
-  }
-};
- -

It is possible to switch the content of each mainpage -> worker and worker -> mainpage message. And the property names "queryMethod", "queryMethodListeners", "queryMethodArguments" can be anything as long as they are consistent in QueryableWorker and the worker.

- -

Passing data by transferring ownership (transferable objects)

- -

Google Chrome 17+ and Firefox 18+ contain an additional way to pass certain types of objects (transferable objects, that is objects implementing the {{domxref("Transferable")}} interface) to or from a worker with high performance. Transferable objects are transferred from one context to another with a zero-copy operation, which results in a vast performance improvement when sending large data sets. Think of it as pass-by-reference if you're from the C/C++ world. However, unlike pass-by-reference, the 'version' from the calling context is no longer available once transferred. Its ownership is transferred to the new context. For example, when transferring an {{domxref("ArrayBuffer")}} from your main app to a worker script, the original {{domxref("ArrayBuffer")}} is cleared and no longer usable. Its content is (quite literally) transferred to the worker context.

- -
// Create a 32MB "file" and fill it.
-var uInt8Array = new Uint8Array(1024 * 1024 * 32); // 32MB
-for (var i = 0; i < uInt8Array.length; ++i) {
-  uInt8Array[i] = i;
-}
-
-worker.postMessage(uInt8Array.buffer, [uInt8Array.buffer]);
-
- -
-

Nota: For more information on transferable objects, performance, and feature-detection for this method, read Transferable Objects: Lightning Fast! on HTML5 Rocks.

-
- -

Workers integrados

- -

There is not an "official" way to embed the code of a worker within a web page, like {{HTMLElement("script")}} elements do for normal scripts. But a {{HTMLElement("script")}} element that does not have a src attribute and has a type attribute that does not identify an executable MIME type can be considered a data block element that JavaScript could use. "Data blocks" is a more general feature of HTML5 that can carry almost any textual data. So, a worker could be embedded in this way:

- -
<!DOCTYPE html>
-<html>
-<head>
-<meta charset="UTF-8" />
-<title>MDN Example - Embedded worker</title>
-<script type="text/js-worker">
-  // This script WON'T be parsed by JS engines because its MIME type is text/js-worker.
-  var myVar = 'Hello World!';
-  // Rest of your worker code goes here.
-</script>
-<script type="text/javascript">
-  // This script WILL be parsed by JS engines because its MIME type is text/javascript.
-  function pageLog(sMsg) {
-    // Use a fragment: browser will only render/reflow once.
-    var oFragm = document.createDocumentFragment();
-    oFragm.appendChild(document.createTextNode(sMsg));
-    oFragm.appendChild(document.createElement('br'));
-    document.querySelector('#logDisplay').appendChild(oFragm);
-  }
-</script>
-<script type="text/js-worker">
-  // This script WON'T be parsed by JS engines because its MIME type is text/js-worker.
-  onmessage = function(oEvent) {
-    postMessage(myVar);
-  };
-  // Rest of your worker code goes here.
-</script>
-<script type="text/javascript">
-  // This script WILL be parsed by JS engines because its MIME type is text/javascript.
-
-  // In the past...:
-  // blob builder existed
-  // ...but now we use Blob...:
-  var blob = new Blob(Array.prototype.map.call(document.querySelectorAll('script[type=\'text\/js-worker\']'), function (oScript) { return oScript.textContent; }),{type: 'text/javascript'});
-
-  // Creating a new document.worker property containing all our "text/js-worker" scripts.
-  document.worker = new Worker(window.URL.createObjectURL(blob));
-
-  document.worker.onmessage = function(oEvent) {
-    pageLog('Received: ' + oEvent.data);
-  };
-
-  // Start the worker.
-  window.onload = function() { document.worker.postMessage(''); };
-</script>
-</head>
-<body><div id="logDisplay"></div></body>
-</html>
- -

The embedded worker is now nested into a new custom document.worker property.

- -

It is also worth noting that you can also convert a function into a Blob, then generate an object URL from that blob. For example:

- -
function fn2workerURL(fn) {
-  var blob = new Blob(['('+fn.toString()+')()'], {type: 'application/javascript'})
-  return URL.createObjectURL(blob)
-}
- -

Exemplos adicionais

- -

This section provides further examples of how to use web workers.

- -

Realizar computações em segundo plano

- -

Workers are mainly useful for allowing your code to perform processor-intensive calculations without blocking the user interface thread. In this example, a worker is used to calculate Fibonacci numbers.

- -

O código de JavaScript

- -

The following JavaScript code is stored in the "fibonacci.js" file referenced by the HTML in the next section.

- -
var results = [];
-
-function resultReceiver(event) {
-  results.push(parseInt(event.data));
-  if (results.length == 2) {
-    postMessage(results[0] + results[1]);
-  }
-}
-
-function errorReceiver(event) {
-  throw event.data;
-}
-
-onmessage = function(event) {
-  var n = parseInt(event.data);
-
-  if (n == 0 || n == 1) {
-    postMessage(n);
-    return;
-  }
-
-  for (var i = 1; i <= 2; i++) {
-    var worker = new Worker('fibonacci.js');
-    worker.onmessage = resultReceiver;
-    worker.onerror = errorReceiver;
-    worker.postMessage(n - i);
-  }
- };
- -

The worker sets the property onmessage to a function which will receive messages sent when the worker object's postMessage() is called (note that this differs from defining a global variable of that name, or defining a function with that name. var onmessage and function onmessage will define global properties with those names, but they will not register the function to receive messages sent by the web page that created the worker). This starts the recursion, spawning new copies of itself to handle each iteration of the calculation.

- -

O código de HTML

- -
<!DOCTYPE html>
-<html>
-  <head>
-    <meta charset="UTF-8"  />
-    <title>Test threads fibonacci</title>
-  </head>
-  <body>
-
-  <div id="result"></div>
-
-  <script language="javascript">
-
-    var worker = new Worker('fibonacci.js');
-
-    worker.onmessage = function(event) {
-      document.getElementById('result').textContent = event.data;
-      dump('Got: ' + event.data + '\n');
-    };
-
-    worker.onerror = function(error) {
-      dump('Worker error: ' + error.message + '\n');
-      throw error;
-    };
-
-    worker.postMessage('5');
-
-  </script>
-  </body>
-</html>
-
- -

The web page creates a div element with the ID result , which gets used to display the result, then spawns the worker. After spawning the worker, the onmessage handler is configured to display the results by setting the contents of the div element, and the onerror handler is set to dump the error message.

- -

Finally, a message is sent to the worker to start it.

- -

Try this example.

- -

Executar I/O da Web em segundo plano

- -

You can find an example of this in the article Using workers in extensions .

- -

Dividir tarefas entre mútiplos workers

- -

As multi-core computers become increasingly common, it's often useful to divide computationally complex tasks among multiple workers, which may then perform those tasks on multiple-processor cores.

- -

Outros tipos de worker

- -

In addition to dedicated and shared web workers, there are other types of worker available:

- - - -

Funções e interfaces disponíveis nos workers

- -

You can use most standard JavaScript features inside a web worker, including:

- - - -

The main thing you can't do in a Worker is directly affect the parent page. This includes manipulating the DOM and using that page's objects. You have to do it indirectly, by sending a message back to the main script via {{domxref("DedicatedWorkerGlobalScope.postMessage")}}, then actioning the changes from there.

- -
-

Note: For a complete list of functions available to workers, see Functions and interfaces available to workers.

-
- -

Especificações

- - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', '#workers', 'Web workers')}}{{Spec2('HTML WHATWG')}} 
- -

Compatibilidade de navegador

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support4[1]{{CompatGeckoDesktop("1.9.1")}}10.010.6[1]4[2]
Shared workers4[1]{{CompatGeckoDesktop(29)}}{{CompatNo}}10.65
- {{CompatNo}} 6.1[4]
Passing data using structured cloning13{{CompatGeckoDesktop(8)}}10.011.56
Passing data using transferable objects17 {{property_prefix("webkit")}}
- 21
{{CompatGeckoDesktop(18)}}{{CompatNo}}156
Global {{domxref("window.URL", "URL")}}10[3]
- 23
{{CompatGeckoDesktop(21)}}11156[3]
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support4.44[1]3.51.0.110.011.5[1]5.1[2]
Shared workers{{CompatNo}}4[1]81.0.1{{CompatNo}}{{CompatNo}}{{CompatNo}}
Passing data using structured cloning{{CompatNo}}481.0.1{{CompatNo}}{{CompatNo}}{{CompatNo}}
Passing data using transferable objects{{CompatNo}}{{CompatNo}}181.0.1{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

[1] Chrome and Opera give an error "Uncaught SecurityError: Failed to construct 'Worker': Script at 'file:///Path/to/worker.js' cannot be accessed from origin 'null'." when you try to run a worker locally. It needs to be on a proper domain.

- -

[2] As of Safari 7.1.2, you can call console.log from inside a worker, but it won't print anything to the console. Older versions of Safari don't allow you to call console.log from inside a worker.

- -

[3] This feature is implemented prefixed as webkitURL.

- -

[4] Safari removed SharedWorker support.

- -

Consultar também

- - - -
- - - - - -
diff --git a/files/pt-pt/web/api/webgl_api/constantes/index.html b/files/pt-pt/web/api/webgl_api/constantes/index.html deleted file mode 100644 index 8328c7976f..0000000000 --- a/files/pt-pt/web/api/webgl_api/constantes/index.html +++ /dev/null @@ -1,4023 +0,0 @@ ---- -title: Contantes de WebGL -slug: Web/API/WebGL_API/Constantes -tags: - - API - - Referencia - - WebGL - - constantes -translation_of: Web/API/WebGL_API/Constants ---- -
{{WebGLSidebar}}
- -

The WebGL API provides several constants that are passed into or returned by functions. All constants are of type {{domxref("GLenum")}}.

- -

Standard WebGL constants are installed on the {{domxref("WebGLRenderingContext")}} and {{domxref("WebGL2RenderingContext")}} objects, so that you use them as gl.CONSTANT_NAME:

- -
var canvas = document.getElementById('myCanvas');
-var gl = canvas.getContext('webgl');
-
-gl.getParameter(gl.LINE_WIDTH);
-
- -

Some constants are also provided by WebGL extensions. A list is provided below.

- -
var debugInfo = gl.getExtension('WEBGL_debug_renderer_info');
-var vendor = gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL);
- -

The WebGL tutorial has more information, examples, and resources on how to get started with WebGL.

- -

Tabela de conteúdos

- - - -

Standard WebGL 1 constants

- -

These constants are defined on the {{domxref("WebGLRenderingContext")}} interface.

- -

Limpar buffers

- -

Constants passed to {{domxref("WebGLRenderingContext.clear()")}} to clear buffer masks.

- - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
DEPTH_BUFFER_BIT0x00000100Passed to clear to clear the current depth buffer.
STENCIL_BUFFER_BIT0x00000400Passed to clear to clear the current stencil buffer.
COLOR_BUFFER_BIT0x00004000Passed to clear to clear the current color buffer.
- -

Renderizar primitivos

- -

Constants passed to {{domxref("WebGLRenderingContext.drawElements()")}} or {{domxref("WebGLRenderingContext.drawArrays()")}} to specify what kind of primitive to render.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
POINTS0x0000Passed to drawElements or drawArrays to draw single points.
LINES0x0001Passed to drawElements or drawArrays to draw lines. Each vertex connects to the one after it.
LINE_LOOP0x0002Passed to drawElements or drawArrays to draw lines. Each set of two vertices is treated as a separate line segment.
LINE_STRIP0x0003Passed to drawElements or drawArrays to draw a connected group of line segments from the first vertex to the last.
TRIANGLES0x0004Passed to drawElements or drawArrays to draw triangles. Each set of three vertices creates a separate triangle.
TRIANGLE_STRIP0x0005Passed to drawElements or drawArrays to draw a connected group of triangles.
TRIANGLE_FAN0x0006Passed to drawElements or drawArrays to draw a connected group of triangles. Each vertex connects to the previous and the first vertex in the fan.
- -

Modos de mistura

- -

Constants passed to {{domxref("WebGLRenderingContext.blendFunc()")}} or {{domxref("WebGLRenderingContext.blendFuncSeparate()")}} to specify the blending mode (for both, RBG and alpha, or separately).

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Nome da constanteValorDescrição
ZERO0Passed to blendFunc or blendFuncSeparate to turn off a component.
ONE1Passed to blendFunc or blendFuncSeparate to turn on a component.
SRC_COLOR0x0300Passed to blendFunc or blendFuncSeparate to multiply a component by the source elements color.
ONE_MINUS_SRC_COLOR0x0301Passed to blendFunc or blendFuncSeparate to multiply a component by one minus the source elements color.
SRC_ALPHA0x0302Passed to blendFunc or blendFuncSeparate to multiply a component by the source's alpha.
ONE_MINUS_SRC_ALPHA0x0303Passed to blendFunc or blendFuncSeparate to multiply a component by one minus the source's alpha.
DST_ALPHA0x0304Passed to blendFunc or blendFuncSeparate to multiply a component by the destination's alpha.
ONE_MINUS_DST_ALPHA0x0305Passed to blendFunc or blendFuncSeparate to multiply a component by one minus the destination's alpha.
DST_COLOR0x0306Passed to blendFunc or blendFuncSeparate to multiply a component by the destination's color.
ONE_MINUS_DST_COLOR0x0307Passed to blendFunc or blendFuncSeparate to multiply a component by one minus the destination's color.
SRC_ALPHA_SATURATE0x0308Passed to blendFunc or blendFuncSeparate to multiply a component by the minimum of source's alpha or one minus the destination's alpha.
CONSTANT_COLOR0x8001Passed to blendFunc or blendFuncSeparate to specify a constant color blend function.
ONE_MINUS_CONSTANT_COLOR0x8002Passed to blendFunc or blendFuncSeparate to specify one minus a constant color blend function.
CONSTANT_ALPHA0x8003Passed to blendFunc or blendFuncSeparate to specify a constant alpha blend function.
ONE_MINUS_CONSTANT_ALPHA0x8004Passed to blendFunc or blendFuncSeparate to specify one minus a constant alpha blend function.
- -

Equações de mistura

- -

Constants passed to {{domxref("WebGLRenderingContext.blendEquation()")}} or {{domxref("WebGLRenderingContext.blendEquationSeparate()")}} to control how the blending is calculated (for both, RBG and alpha, or separately).

- - - - - - - - - - - - - - - - - - - - - - - - - - -
Nome da constanteValorDescrição
FUNC_ADD0x8006Passed to blendEquation or blendEquationSeparate to set an addition blend function.
FUNC_SUBSTRACT0x800APassed to blendEquation or blendEquationSeparate to specify a subtraction blend function (source - destination).
FUNC_REVERSE_SUBTRACT0x800BPassed to blendEquation or blendEquationSeparate to specify a reverse subtraction blend function (destination - source).
- -

Obter informação do parâmetro GL

- -

Constants passed to {{domxref("WebGLRenderingContext.getParameter()")}} to specify what information to return.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Nome da constanteValorDescrição
BLEND_EQUATION0x8009Passed to getParameter to get the current RGB blend function.
BLEND_EQUATION_RGB0x8009Passed to getParameter to get the current RGB blend function. Same as BLEND_EQUATION
BLEND_EQUATION_ALPHA0x883DPassed to getParameter to get the current alpha blend function. Same as BLEND_EQUATION
BLEND_DST_RGB0x80C8Passed to getParameter to get the current destination RGB blend function.
BLEND_SRC_RGB0x80C9Passed to getParameter to get the current destination RGB blend function.
BLEND_DST_ALPHA0x80CAPassed to getParameter to get the current destination alpha blend function.
BLEND_SRC_ALPHA0x80CBPassed to getParameter to get the current source alpha blend function.
BLEND_COLOR0x8005Passed to getParameter to return a the current blend color.
ARRAY_BUFFER_BINDING0x8894Passed to getParameter to get the array buffer binding.
ELEMENT_ARRAY_BUFFER_BINDING0x8895Passed to getParameter to get the current element array buffer.
LINE_WIDTH0x0B21Passed to getParameter to get the current lineWidth (set by the lineWidth method).
ALIASED_POINT_SIZE_RANGE0x846DPassed to getParameter to get the current size of a point drawn with gl.POINTS
ALIASED_LINE_WIDTH_RANGE0x846EPassed to getParameter to get the range of available widths for a line. Returns a length-2 array with the lo value at 0, and hight at 1.
CULL_FACE_MODE0x0B45Passed to getParameter to get the current value of cullFace. Should return FRONT, BACK, or FRONT_AND_BACK
FRONT_FACE0x0B46Passed to getParameter to determine the current value of frontFace. Should return CW or CCW.
DEPTH_RANGE0x0B70Passed to getParameter to return a length-2 array of floats giving the current depth range.
DEPTH_WRITEMASK0x0B72Passed to getParameter to determine if the depth write mask is enabled.
DEPTH_CLEAR_VALUE0x0B73Passed to getParameter to determine the current depth clear value.
DEPTH_FUNC0x0B74Passed to getParameter to get the current depth function. Returns NEVER, ALWAYS, LESS, EQUAL, LEQUAL, GREATER, GEQUAL, or NOTEQUAL.
STENCIL_CLEAR_VALUE0x0B91Passed to getParameter to get the value the stencil will be cleared to.
STENCIL_FUNC0x0B92Passed to getParameter to get the current stencil function. Returns NEVER, ALWAYS, LESS, EQUAL, LEQUAL, GREATER, GEQUAL, or NOTEQUAL.
STENCIL_FAIL0x0B94Passed to getParameter to get the current stencil fail function. Should return KEEP, REPLACE, INCR, DECR, INVERT, INCR_WRAP, or DECR_WRAP.
STENCIL_PASS_DEPTH_FAIL0x0B95Passed to getParameter to get the current stencil fail function should the depth buffer test fail. Should return KEEP, REPLACE, INCR, DECR, INVERT, INCR_WRAP, or DECR_WRAP.
STENCIL_PASS_DEPTH_PASS0x0B96Passed to getParameter to get the current stencil fail function should the depth buffer test pass. Should return KEEP, REPLACE, INCR, DECR, INVERT, INCR_WRAP, or DECR_WRAP.
STENCIL_REF0x0B97Passed to getParameter to get the reference value used for stencil tests.
STENCIL_VALUE_MASK0x0B93 
STENCIL_WRITEMASK0x0B98 
STENCIL_BACK_FUNC0x8800 
STENCIL_BACK_FAIL0x8801 
STENCIL_BACK_PASS_DEPTH_FAIL0x8802 
STENCIL_BACK_PASS_DEPTH_PASS0x8803 
STENCIL_BACK_REF0x8CA3 
STENCIL_BACK_VALUE_MASK0x8CA4 
STENCIL_BACK_WRITEMASK0x8CA5 
VIEWPORT0x0BA2Returns an {{jsxref("Int32Array")}} with four elements for the current viewport dimensions.
SCISSOR_BOX0x0C10Returns an {{jsxref("Int32Array")}} with four elements for the current scissor box dimensions.
COLOR_CLEAR_VALUE0x0C22 
COLOR_WRITEMASK0x0C23 
UNPACK_ALIGNMENT0x0CF5 
PACK_ALIGNMENT0x0D05 
MAX_TEXTURE_SIZE0x0D33 
MAX_VIEWPORT_DIMS0x0D3A 
SUBPIXEL_BITS0x0D50 
RED_BITS0x0D52 
GREEN_BITS0x0D53 
BLUE_BITS0x0D54 
ALPHA_BITS0x0D55 
DEPTH_BITS0x0D56 
STENCIL_BITS0x0D57 
POLYGON_OFFSET_UNITS0x2A00 
POLYGON_OFFSET_FACTOR0x8038 
TEXTURE_BINDING_2D0x8069 
SAMPLE_BUFFERS0x80A8 
SAMPLES0x80A9 
SAMPLE_COVERAGE_VALUE0x80AA 
SAMPLE_COVERAGE_INVERT0x80AB 
COMPRESSED_TEXTURE_FORMATS0x86A3 
VENDOR0x1F00 
RENDERER0x1F01 
VERSION0x1F02 
IMPLEMENTATION_COLOR_READ_TYPE0x8B9A 
IMPLEMENTATION_COLOR_READ_FORMAT0x8B9B 
BROWSER_DEFAULT_WEBGL0x9244 
- -

Buffers

- -

Constants passed to {{domxref("WebGLRenderingContext.bufferData()")}}, {{domxref("WebGLRenderingContext.bufferSubData()")}}, {{domxref("WebGLRenderingContext.bindBuffer()")}}, or {{domxref("WebGLRenderingContext.getBufferParameter()")}}.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
STATIC_DRAW0x88E4Passed to bufferData as a hint about whether the contents of the buffer are likely to be used often and not change often.
STREAM_DRAW0x88E0Passed to bufferData as a hint about whether the contents of the buffer are likely to not be used often.
DYNAMIC_DRAW0x88E8Passed to bufferData as a hint about whether the contents of the buffer are likely to be used often and change often.
ARRAY_BUFFER0x8892Passed to bindBuffer or bufferData to specify the type of buffer being used.
ELEMENT_ARRAY_BUFFER0x8893Passed to bindBuffer or bufferData to specify the type of buffer being used.
BUFFER_SIZE0x8764Passed to getBufferParameter to get a buffer's size.
BUFFER_USAGE0x8765Passed to getBufferParameter to get the hint for the buffer passed in when it was created.
- -

Atributos de Vertex

- -

Constants passed to {{domxref("WebGLRenderingContext.getVertexAttrib()")}}.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Nome da constanteValorDescrição
CURRENT_VERTEX_ATTRIB0x8626Passed to getVertexAttrib to read back the current vertex attribute.
VERTEX_ATTRIB_ARRAY_ENABLED0x8622 
VERTEX_ATTRIB_ARRAY_SIZE0x8623 
VERTEX_ATTRIB_ARRAY_STRIDE0x8624 
VERTEX_ATTRIB_ARRAY_TYPE0x8625 
VERTEX_ATTRIB_ARRAY_NORMALIZED0x886A 
VERTEX_ATTRIB_ARRAY_POINTER0x8645 
VERTEX_ATTRIB_ARRAY_BUFFER_BINDING0x889F 
- -

Culling

- -

Constants passed to {{domxref("WebGLRenderingContext.cullFace()")}}.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
CULL_FACE0x0B44Passed to enable/disable to turn on/off culling. Can also be used with getParameter to find the current culling method.
FRONT0x0404Passed to cullFace to specify that only front faces should be drawn.
BACK0x0405Passed to cullFace to specify that only back faces should be drawn.
FRONT_AND_BACK0x0408Passed to cullFace to specify that front and back faces should be drawn.
- -

Enabling and disabling

- -

Constants passed to {{domxref("WebGLRenderingContext.enable()")}} or {{domxref("WebGLRenderingContext.disable()")}}.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
BLEND0x0BE2Passed to enable/disable to turn on/off blending. Can also be used with getParameter to find the current blending method.
DEPTH_TEST0x0B71Passed to enable/disable to turn on/off the depth test. Can also be used with getParameter to query the depth test.
DITHER0x0BD0Passed to enable/disable to turn on/off dithering. Can also be used with getParameter to find the current dithering method.
POLYGON_OFFSET_FILL0x8037Passed to enable/disable to turn on/off the polygon offset. Useful for rendering hidden-line images, decals, and or solids with highlighted edges. Can also be used with getParameter to query the scissor test.
SAMPLE_ALPHA_TO_COVERAGE0x809EPassed to enable/disable to turn on/off the alpha to coverage. Used in multi-sampling alpha channels.
SAMPLE_COVERAGE0x80A0Passed to enable/disable to turn on/off the sample coverage. Used in multi-sampling.
SCISSOR_TEST0x0C11Passed to enable/disable to turn on/off the scissor test. Can also be used with getParameter to query the scissor test.
STENCIL_TEST0x0B90Passed to enable/disable to turn on/off the stencil test. Can also be used with getParameter to query the stencil test.
- -

Errors

- -

Constants returned from {{domxref("WebGLRenderingContext.getError()")}}.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
NO_ERROR0Returned from getError.
INVALID_ENUM0x0500Returned from getError.
INVALID_VALUE0x0501Returned from getError.
INVALID_OPERATION0x0502Returned from getError.
OUT_OF_MEMORY0x0505Returned from getError.
CONTEXT_LOST_WEBGL0x9242Returned from getError.
- -

Front face directions

- -

Constants passed to {{domxref("WebGLRenderingContext.frontFace()")}}.

- - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
CW0x0900Passed to frontFace to specify the front face of a polygon is drawn in the clockwise direction
CCW0x0901Passed to frontFace to specify the front face of a polygon is drawn in the counter clockwise direction
- -

Hints

- -

Constants passed to {{domxref("WebGLRenderingContext.hint()")}}

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
DONT_CARE0x1100There is no preference for this behavior.
FASTEST0x1101The most efficient behavior should be used.
NICEST0x1102The most correct or the highest quality option should be used.
GENERATE_MIPMAP_HINT0x8192Hint for the quality of filtering when generating mipmap images with {{domxref("WebGLRenderingContext.generateMipmap()")}}.
- -

Data types

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
BYTE0x1400 
UNSIGNED_BYTE0x1401 
SHORT0x1402 
UNSIGNED_SHORT0x1403 
INT0x1404 
UNSIGNED_INT0x1405 
FLOAT0x1406 
- -

Pixel formats

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
DEPTH_COMPONENT0x1902 
ALPHA0x1906 
RGB0x1907 
RGBA0x1908 
LUMINANCE0x1909 
LUMINANCE_ALPHA0x190A 
- -

Pixel types

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
UNSIGNED_BYTE0x1401 
UNSIGNED_SHORT_4_4_4_40x8033 
UNSIGNED_SHORT_5_5_5_10x8034 
UNSIGNED_SHORT_5_6_50x8363 
- -

Shaders

- -

Constants passed to {{domxref("WebGLRenderingContext.createShader()")}} or {{domxref("WebGLRenderingContext.getShaderParameter()")}}

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
FRAGMENT_SHADER0x8B30Passed to createShader to define a fragment shader.
VERTEX_SHADER0x8B31Passed to createShader to define a vertex shader
COMPILE_STATUS0x8B81Passed to getShaderParamter to get the status of the compilation. Returns false if the shader was not compiled. You can then query getShaderInfoLog to find the exact error
DELETE_STATUS0x8B80Passed to getShaderParamter to determine if a shader was deleted via deleteShader. Returns true if it was, false otherwise.
LINK_STATUS0x8B82Passed to getProgramParameter after calling linkProgram to determine if a program was linked correctly. Returns false if there were errors. Use getProgramInfoLog to find the exact error.
VALIDATE_STATUS0x8B83Passed to getProgramParameter after calling validateProgram to determine if it is valid. Returns false if errors were found.
ATTACHED_SHADERS0x8B85Passed to getProgramParameter after calling attachShader to determine if the shader was attached correctly. Returns false if errors occurred.
ACTIVE_ATTRIBUTES0x8B89Passed to getProgramParameter to get the number of attributes active in a program.
ACTIVE_UNIFORMS0x8B86Passed to getProgramParamter to get the number of uniforms active in a program.
MAX_VERTEX_ATTRIBS0x8869The maximum number of entries possible in the vertex attribute list.
MAX_VERTEX_UNIFORM_VECTORS0x8DFB 
MAX_VARYING_VECTORS0x8DFC 
MAX_COMBINED_TEXTURE_IMAGE_UNITS0x8B4D 
MAX_VERTEX_TEXTURE_IMAGE_UNITS0x8B4C 
MAX_TEXTURE_IMAGE_UNITS0x8872Implementation dependent number of maximum texture units. At least 8.
MAX_FRAGMENT_UNIFORM_VECTORS0x8DFD 
SHADER_TYPE0x8B4F 
SHADING_LANGUAGE_VERSION0x8B8C 
CURRENT_PROGRAM0x8B8D 
- -

Depth or stencil tests

- -

Constants passed to {{domxref("WebGLRenderingContext.depthFunc()")}} or {{domxref("WebGLRenderingContext.stencilFunc()")}}.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
NEVER0x0200Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
ALWAYS0x0207Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn.
LESS0x0201Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
EQUAL0x0202Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
LEQUAL0x0203Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value.
GREATER0x0204Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
GEQUAL0x0206Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value.
NOTEQUAL0x0205Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value.
- -

Stencil actions

- -

Constants passed to {{domxref("WebGLRenderingContext.stencilOp()")}}.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
KEEP0x1E00 
REPLACE0x1E01 
INCR0x1E02 
DECR0x1E03 
INVERT0x150A 
INCR_WRAP0x8507 
DECR_WRAP0x8508 
- -

Textures

- -

Constants passed to {{domxref("WebGLRenderingContext.texParameteri()")}}, {{domxref("WebGLRenderingContext.texParameterf()")}}, {{domxref("WebGLRenderingContext.bindTexture()")}}, {{domxref("WebGLRenderingContext.texImage2D()")}}, and others.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
NEAREST0x2600 
LINEAR0x2601 
NEAREST_MIPMAP_NEAREST0x2700 
LINEAR_MIPMAP_NEAREST0x2701 
NEAREST_MIPMAP_LINEAR0x2702 
LINEAR_MIPMAP_LINEAR0x2703 
TEXTURE_MAG_FILTER0x2800 
TEXTURE_MIN_FILTER0x2801 
TEXTURE_WRAP_S0x2802 
TEXTURE_WRAP_T0x2803 
TEXTURE_2D0x0DE1 
TEXTURE0x1702 
TEXTURE_CUBE_MAP0x8513 
TEXTURE_BINDING_CUBE_MAP0x8514 
TEXTURE_CUBE_MAP_POSITIVE_X0x8515 
TEXTURE_CUBE_MAP_NEGATIVE_X0x8516 
TEXTURE_CUBE_MAP_POSITIVE_Y0x8517 
TEXTURE_CUBE_MAP_NEGATIVE_Y0x8518 
TEXTURE_CUBE_MAP_POSITIVE_Z0x8519 
TEXTURE_CUBE_MAP_NEGATIVE_Z0x851A 
MAX_CUBE_MAP_TEXTURE_SIZE0x851C 
TEXTURE0 - 310x84C0 - 0x84DFA texture unit.
ACTIVE_TEXTURE0x84E0The current active texture unit.
REPEAT0x2901 
CLAMP_TO_EDGE0x812F 
MIRRORED_REPEAT0x8370 
- -

Uniform types

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
FLOAT_VEC20x8B50 
FLOAT_VEC30x8B51 
FLOAT_VEC40x8B52 
INT_VEC20x8B53 
INT_VEC30x8B54 
INT_VEC40x8B55 
BOOL0x8B56 
BOOL_VEC20x8B57 
BOOL_VEC30x8B58 
BOOL_VEC40x8B59 
FLOAT_MAT20x8B5A 
FLOAT_MAT30x8B5B 
FLOAT_MAT40x8B5C 
SAMPLER_2D0x8B5E 
SAMPLER_CUBE0x8B60 
- -

Shader precision-specified types

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
LOW_FLOAT0x8DF0 
MEDIUM_FLOAT0x8DF1 
HIGH_FLOAT0x8DF2 
LOW_INT0x8DF3 
MEDIUM_INT0x8DF4 
HIGH_INT0x8DF5 
- -

Framebuffers and renderbuffers

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
FRAMEBUFFER0x8D40 
RENDERBUFFER0x8D41 
RGBA40x8056 
RGB5_A10x8057 
RGB5650x8D62 
DEPTH_COMPONENT160x81A5 
STENCIL_INDEX0x1901 
STENCIL_INDEX80x8D48 
DEPTH_STENCIL0x84F9 
RENDERBUFFER_WIDTH0x8D42 
RENDERBUFFER_HEIGHT0x8D43 
RENDERBUFFER_INTERNAL_FORMAT0x8D44 
RENDERBUFFER_RED_SIZE0x8D50 
RENDERBUFFER_GREEN_SIZE0x8D51 
RENDERBUFFER_BLUE_SIZE0x8D52 
RENDERBUFFER_ALPHA_SIZE0x8D53 
RENDERBUFFER_DEPTH_SIZE0x8D54 
RENDERBUFFER_STENCIL_SIZE0x8D55 
FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE0x8CD0 
FRAMEBUFFER_ATTACHMENT_OBJECT_NAME0x8CD1 
FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL0x8CD2 
FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE0x8CD3 
COLOR_ATTACHMENT00x8CE0 
DEPTH_ATTACHMENT0x8D00 
STENCIL_ATTACHMENT0x8D20 
DEPTH_STENCIL_ATTACHMENT0x821A 
NONE0 
FRAMEBUFFER_COMPLETE0x8CD5 
FRAMEBUFFER_INCOMPLETE_ATTACHMENT0x8CD6 
FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT0x8CD7 
FRAMEBUFFER_INCOMPLETE_DIMENSIONS0x8CD9 
FRAMEBUFFER_UNSUPPORTED0x8CDD 
FRAMEBUFFER_BINDING0x8CA6 
RENDERBUFFER_BINDING0x8CA7 
MAX_RENDERBUFFER_SIZE0x84E8 
INVALID_FRAMEBUFFER_OPERATION0x0506 
- -

Pixel storage modes

- -

Constants passed to {{domxref("WebGLRenderingContext.pixelStorei()")}}.

- - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
UNPACK_FLIP_Y_WEBGL0x9240 
UNPACK_PREMULTIPLY_ALPHA_WEBGL0x9241 
UNPACK_COLORSPACE_CONVERSION_WEBGL0x9243 
- -

Constantes adicionais definidas em WebGL 2

- -

These constants are defined on the {{domxref("WebGL2RenderingContext")}} interface. All WebGL 1 constants are also available in a WebGL 2 context.

- -

Obter a informação do parâmetro GL

- -

Constants passed to {{domxref("WebGLRenderingContext.getParameter()")}} to specify what information to return.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
READ_BUFFER0x0C02 
UNPACK_ROW_LENGTH0x0CF2 
UNPACK_SKIP_ROWS0x0CF3 
UNPACK_SKIP_PIXELS0x0CF4 
PACK_ROW_LENGTH0x0D02 
PACK_SKIP_ROWS0x0D03 
PACK_SKIP_PIXELS0x0D04 
TEXTURE_BINDING_3D0x806A 
UNPACK_SKIP_IMAGES0x806D 
UNPACK_IMAGE_HEIGHT0x806E 
MAX_3D_TEXTURE_SIZE0x8073 
MAX_ELEMENTS_VERTICES0x80E8 
MAX_ELEMENTS_INDICES0x80E9 
MAX_TEXTURE_LOD_BIAS0x84FD 
MAX_FRAGMENT_UNIFORM_COMPONENTS0x8B49 
MAX_VERTEX_UNIFORM_COMPONENTS0x8B4A 
MAX_ARRAY_TEXTURE_LAYERS0x88FF 
MIN_PROGRAM_TEXEL_OFFSET0x8904 
MAX_PROGRAM_TEXEL_OFFSET0x8905 
MAX_VARYING_COMPONENTS0x8B4B 
FRAGMENT_SHADER_DERIVATIVE_HINT0x8B8B 
RASTERIZER_DISCARD0x8C89 
VERTEX_ARRAY_BINDING0x85B5 
MAX_VERTEX_OUTPUT_COMPONENTS0x9122 
MAX_FRAGMENT_INPUT_COMPONENTS0x9125 
MAX_SERVER_WAIT_TIMEOUT0x9111 
MAX_ELEMENT_INDEX0x8D6B 
- -

Texturas

- -

Constants passed to {{domxref("WebGLRenderingContext.texParameteri()")}}, {{domxref("WebGLRenderingContext.texParameterf()")}}, {{domxref("WebGLRenderingContext.bindTexture()")}}, {{domxref("WebGLRenderingContext.texImage2D()")}}, and others.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
RED0x1903 
RGB80x8051 
RGBA80x8058 
RGB10_A20x8059 
TEXTURE_3D0x806F 
TEXTURE_WRAP_R0x8072 
TEXTURE_MIN_LOD0x813A 
TEXTURE_MAX_LOD0x813B 
TEXTURE_BASE_LEVEL0x813C 
TEXTURE_MAX_LEVEL0x813D 
TEXTURE_COMPARE_MODE0x884C 
TEXTURE_COMPARE_FUNC0x884D 
SRGB0x8C40 
SRGB80x8C41 
SRGB8_ALPHA80x8C43 
COMPARE_REF_TO_TEXTURE0x884E 
RGBA32F0x8814 
RGB32F0x8815 
RGBA16F0x881A 
RGB16F0x881B 
TEXTURE_2D_ARRAY0x8C1A 
TEXTURE_BINDING_2D_ARRAY0x8C1D 
R11F_G11F_B10F0x8C3A 
RGB9_E50x8C3D 
RGBA32UI0x8D70 
RGB32UI0x8D71 
RGBA16UI0x8D76 
RGB16UI0x8D77 
RGBA8UI0x8D7C 
RGB8UI0x8D7D 
RGBA32I0x8D82 
RGB32I0x8D83 
RGBA16I0x8D88 
RGB16I0x8D89 
RGBA8I0x8D8E 
RGB8I0x8D8F 
RED_INTEGER0x8D94 
RGB_INTEGER0x8D98 
RGBA_INTEGER0x8D99 
R80x8229 
RG80x822B 
R16F0x822D 
R32F0x822E 
RG16F0x822F 
RG32F0x8230 
R8I0x8231 
R8UI0x8232 
R16I0x8233 
R16UI0x8234 
R32I0x8235 
R32UI0x8236 
RG8I0x8237 
RG8UI0x8238 
RG16I0x8239 
RG16UI0x823A 
RG32I0x823B 
RG32UI0x823C 
R8_SNORM0x8F94 
RG8_SNORM0x8F95 
RGB8_SNORM0x8F96 
RGBA8_SNORM0x8F97 
RGB10_A2UI0x906F 
TEXTURE_IMMUTABLE_FORMAT 0x912F 
TEXTURE_IMMUTABLE_LEVELS0x82DF 
- -

Tipos de píxel

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
UNSIGNED_INT_2_10_10_10_REV0x8368 
UNSIGNED_INT_10F_11F_11F_REV0x8C3B 
UNSIGNED_INT_5_9_9_9_REV0x8C3E 
FLOAT_32_UNSIGNED_INT_24_8_REV0x8DAD 
UNSIGNED_INT_24_80x84FA 
HALF_FLOAT0x140B 
RG0x8227 
RG_INTEGER0x8228 
INT_2_10_10_10_REV0x8D9F 
- -

Consultas

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
CURRENT_QUERY0x8865 
QUERY_RESULT 0x8866 
QUERY_RESULT_AVAILABLE0x8867 
ANY_SAMPLES_PASSED0x8C2F 
ANY_SAMPLES_PASSED_CONSERVATIVE0x8D6A 
- -

Draw buffers

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
MAX_DRAW_BUFFERS0x8824 
DRAW_BUFFER00x8825 
DRAW_BUFFER10x8826 
DRAW_BUFFER20x8827 
DRAW_BUFFER30x8828 
DRAW_BUFFER40x8829 
DRAW_BUFFER50x882A 
DRAW_BUFFER60x882B 
DRAW_BUFFER70x882C 
DRAW_BUFFER80x882D 
DRAW_BUFFER90x882E 
DRAW_BUFFER100x882F 
DRAW_BUFFER110x8830 
DRAW_BUFFER120x8831 
DRAW_BUFFER130x8832 
DRAW_BUFFER140x8833 
DRAW_BUFFER150x8834 
MAX_COLOR_ATTACHMENTS0x8CDF 
COLOR_ATTACHMENT10x8CE1 
COLOR_ATTACHMENT20x8CE2 
COLOR_ATTACHMENT30x8CE3 
COLOR_ATTACHMENT40x8CE4 
COLOR_ATTACHMENT50x8CE5 
COLOR_ATTACHMENT60x8CE6 
COLOR_ATTACHMENT70x8CE7 
COLOR_ATTACHMENT80x8CE8 
COLOR_ATTACHMENT90x8CE9 
COLOR_ATTACHMENT100x8CEA 
COLOR_ATTACHMENT110x8CEB 
COLOR_ATTACHMENT120x8CEC 
COLOR_ATTACHMENT130x8CED 
COLOR_ATTACHMENT140x8CEE 
COLOR_ATTACHMENT150x8CEF 
- -

Samplers

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
SAMPLER_3D0x8B5F 
SAMPLER_2D_SHADOW0x8B62 
SAMPLER_2D_ARRAY0x8DC1 
SAMPLER_2D_ARRAY_SHADOW0x8DC4 
SAMPLER_CUBE_SHADOW0x8DC5 
INT_SAMPLER_2D0x8DCA 
INT_SAMPLER_3D0x8DCB 
INT_SAMPLER_CUBE0x8DCC 
INT_SAMPLER_2D_ARRAY0x8DCF 
UNSIGNED_INT_SAMPLER_2D0x8DD2 
UNSIGNED_INT_SAMPLER_3D0x8DD3 
UNSIGNED_INT_SAMPLER_CUBE0x8DD4 
UNSIGNED_INT_SAMPLER_2D_ARRAY0x8DD7 
MAX_SAMPLES0x8D57 
SAMPLER_BINDING0x8919 
- -

Buffers

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
PIXEL_PACK_BUFFER0x88EB 
PIXEL_UNPACK_BUFFER0x88EC 
PIXEL_PACK_BUFFER_BINDING0x88ED 
PIXEL_UNPACK_BUFFER_BINDING 0x88EF 
COPY_READ_BUFFER0x8F36 
COPY_WRITE_BUFFER0x8F37 
COPY_READ_BUFFER_BINDING0x8F36 
COPY_WRITE_BUFFER_BINDING0x8F37 
- -

Tipos de dados

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
FLOAT_MAT2x30x8B65 
FLOAT_MAT2x40x8B66 
FLOAT_MAT3x20x8B67 
FLOAT_MAT3x4 0x8B68 
FLOAT_MAT4x20x8B69 
FLOAT_MAT4x30x8B6A 
UNSIGNED_INT_VEC20x8DC6 
UNSIGNED_INT_VEC30x8DC7 
UNSIGNED_INT_VEC40x8DC8 
UNSIGNED_NORMALIZED0x8C17 
SIGNED_NORMALIZED0x8F9C 
- -

Atributos de Vertex

- - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
VERTEX_ATTRIB_ARRAY_INTEGER 0x88FD 
VERTEX_ATTRIB_ARRAY_DIVISOR0x88FE 
- -

Transform feedback

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
TRANSFORM_FEEDBACK_BUFFER_MODE0x8C7F 
MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS0x8C80 
TRANSFORM_FEEDBACK_VARYINGS0x8C83 
TRANSFORM_FEEDBACK_BUFFER_START0x8C84 
TRANSFORM_FEEDBACK_BUFFER_SIZE0x8C85 
TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN0x8C88 
MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS0x8C8A 
MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS0x8C8B 
INTERLEAVED_ATTRIBS0x8C8C 
SEPARATE_ATTRIBS0x8C8D 
TRANSFORM_FEEDBACK_BUFFER0x8C8E 
TRANSFORM_FEEDBACK_BUFFER_BINDING0x8C8F 
TRANSFORM_FEEDBACK0x8E22 
TRANSFORM_FEEDBACK_PAUSED0x8E23 
TRANSFORM_FEEDBACK_ACTIVE0x8E24 
TRANSFORM_FEEDBACK_BINDING0x8E25 
- -

Framebuffers e renderbuffers

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING0x8210 
FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE0x8211 
FRAMEBUFFER_ATTACHMENT_RED_SIZE0x8212 
FRAMEBUFFER_ATTACHMENT_GREEN_SIZE0x8213 
FRAMEBUFFER_ATTACHMENT_BLUE_SIZE0x8214 
FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE0x8215 
FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE0x8216 
FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE0x8217 
FRAMEBUFFER_DEFAULT0x8218 
DEPTH_STENCIL_ATTACHMENT0x821A 
DEPTH_STENCIL0x84F9 
DEPTH24_STENCIL80x88F0 
DRAW_FRAMEBUFFER_BINDING0x8CA6 
READ_FRAMEBUFFER0x8CA8 
DRAW_FRAMEBUFFER0x8CA9 
READ_FRAMEBUFFER_BINDING0x8CAA 
RENDERBUFFER_SAMPLES0x8CAB 
FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER0x8CD4 
FRAMEBUFFER_INCOMPLETE_MULTISAMPLE0x8D56 
- -

Uniforms

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
UNIFORM_BUFFER0x8A11 
UNIFORM_BUFFER_BINDING0x8A28 
UNIFORM_BUFFER_START0x8A29 
UNIFORM_BUFFER_SIZE0x8A2A 
MAX_VERTEX_UNIFORM_BLOCKS0x8A2B 
MAX_FRAGMENT_UNIFORM_BLOCKS0x8A2D 
MAX_COMBINED_UNIFORM_BLOCKS0x8A2E 
MAX_UNIFORM_BUFFER_BINDINGS0x8A2F 
MAX_UNIFORM_BLOCK_SIZE0x8A30 
MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS0x8A31 
MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS0x8A33 
UNIFORM_BUFFER_OFFSET_ALIGNMENT0x8A34 
ACTIVE_UNIFORM_BLOCKS0x8A36 
UNIFORM_TYPE 0x8A37 
UNIFORM_SIZE0x8A38 
UNIFORM_BLOCK_INDEX0x8A3A 
UNIFORM_OFFSET0x8A3B 
UNIFORM_ARRAY_STRIDE0x8A3C 
UNIFORM_MATRIX_STRIDE0x8A3D 
UNIFORM_IS_ROW_MAJOR0x8A3E 
UNIFORM_BLOCK_BINDING0x8A3F 
UNIFORM_BLOCK_DATA_SIZE0x8A40 
UNIFORM_BLOCK_ACTIVE_UNIFORMS0x8A42 
UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES0x8A43 
UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER0x8A44 
UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER0x8A46 
- -

Objetos de sincronização

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
OBJECT_TYPE0x9112 
SYNC_CONDITION0x9113 
SYNC_STATUS0x9114 
SYNC_FLAGS0x9115 
SYNC_FENCE0x9116 
SYNC_GPU_COMMANDS_COMPLETE0x9117 
UNSIGNALED0x9118 
SIGNALED0x9119 
ALREADY_SIGNALED0x911A 
TIMEOUT_EXPIRED0x911B 
CONDITION_SATISFIED0x911C 
WAIT_FAILED0x911D 
SYNC_FLUSH_COMMANDS_BIT0x00000001 
- -

Constantes diversas

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
COLOR0x1800 
DEPTH0x1801 
STENCIL0x1802 
MIN0x8007 
MAX0x8008 
DEPTH_COMPONENT240x81A6 
STREAM_READ0x88E1 
STREAM_COPY0x88E2 
STATIC_READ0x88E5 
STATIC_COPY0x88E6 
DYNAMIC_READ0x88E9 
DYNAMIC_COPY0x88EA 
DEPTH_COMPONENT32F0x8CAC 
DEPTH32F_STENCIL80x8CAD 
INVALID_INDEX0xFFFFFFFF 
TIMEOUT_IGNORED-1 
MAX_CLIENT_WAIT_TIMEOUT_WEBGL0x9247 
- -

Constantes definidas nas extensões de WebGL

- -

{{domxref("ANGLE_instanced_arrays")}}

- - - - - - - - - - - - - - - - -
Constant nameValueDescription
VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE0x88FEDescribes the frequency divisor used for instanced rendering.
- -

{{domxref("WEBGL_debug_renderer_info")}}

- - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
UNMASKED_VENDOR_WEBGL0x9245Passed to getParameter to get the vendor string of the graphics driver.
UNMASKED_RENDERER_WEBGL0x9246Passed to getParameter to get the renderer string of the graphics driver.
- -

{{domxref("EXT_texture_filter_anisotropic")}}

- - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
MAX_TEXTURE_MAX_ANISOTROPY_EXT0x84FFReturns the maximum available anisotropy.
TEXTURE_MAX_ANISOTROPY_EXT0x84FEPassed to texParameter to set the desired maximum anisotropy for a texture.
- -

{{domxref("WEBGL_compressed_texture_s3tc")}}

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
COMPRESSED_RGB_S3TC_DXT1_EXT0x83F0A DXT1-compressed image in an RGB image format.
COMPRESSED_RGBA_S3TC_DXT1_EXT0x83F1A DXT1-compressed image in an RGB image format with a simple on/off alpha value.
COMPRESSED_RGBA_S3TC_DXT3_EXT0x83F2A DXT3-compressed image in an RGBA image format. Compared to a 32-bit RGBA texture, it offers 4:1 compression.
COMPRESSED_RGBA_S3TC_DXT5_EXT0x83F3A DXT5-compressed image in an RGBA image format. It also provides a 4:1 compression, but differs to the DXT3 compression in how the alpha compression is done.
- -

{{domxref("WEBGL_compressed_texture_etc")}}

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
COMPRESSED_R11_EAC0x9270One-channel (red) unsigned format compression.
COMPRESSED_SIGNED_R11_EAC0x9271One-channel (red) signed format compression.
COMPRESSED_RG11_EAC0x9272Two-channel (red and green) unsigned format compression.
COMPRESSED_SIGNED_RG11_EAC0x9273Two-channel (red and green) signed format compression.
COMPRESSED_RGB8_ETC20x9274Compresses RBG8 data with no alpha channel.
COMPRESSED_RGBA8_ETC2_EAC0x9275Compresses RGBA8 data. The RGB part is encoded the same as RGB_ETC2, but the alpha part is encoded separately.
COMPRESSED_SRGB8_ETC20x9276Compresses sRBG8 data with no alpha channel.
COMPRESSED_SRGB8_ALPHA8_ETC2_EAC0x9277Compresses sRGBA8 data. The sRGB part is encoded the same as SRGB_ETC2, but the alpha part is encoded separately.
COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC20x9278Similar to RGB8_ETC, but with ability to punch through the alpha channel, which means to make it completely opaque or transparent.
COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC20x9279Similar to SRGB8_ETC, but with ability to punch through the alpha channel, which means to make it completely opaque or transparent.
- -

{{domxref("WEBGL_compressed_texture_pvrtc")}}

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
COMPRESSED_RGB_PVRTC_4BPPV1_IMG0x8C00RGB compression in 4-bit mode. One block for each 4×4 pixels.
COMPRESSED_RGBA_PVRTC_4BPPV1_IMG0x8C02RGBA compression in 4-bit mode. One block for each 4×4 pixels.
COMPRESSED_RGB_PVRTC_2BPPV1_IMG0x8C01RGB compression in 2-bit mode. One block for each 8×4 pixels.
COMPRESSED_RGBA_PVRTC_2BPPV1_IMG0x8C03RGBA compression in 2-bit mode. One block for each 8×4 pixe
- -

{{domxref("WEBGL_compressed_texture_etc1")}}

- - - - - - - - - - - - - - - - -
Constant nameValueDescription
COMPRESSED_RGB_ETC1_WEBGL0x8D64Compresses 24-bit RGB data with no alpha channel.
- -

{{domxref("WEBGL_compressed_texture_atc")}}

- - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
COMPRESSED_RGB_ATC_WEBGL0x8C92Compresses RGB textures with no alpha channel.
COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL0x8C92Compresses RGBA textures using explicit alpha encoding (useful when alpha transitions are sharp).
COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL0x87EECompresses RGBA textures using interpolated alpha encoding (useful when alpha transitions are gradient).
- -

{{domxref("WEBGL_depth_texture")}}

- - - - - - - - - - - - - - - - -
Constant nameValueDescription
UNSIGNED_INT_24_8_WEBGL0x84FAUnsigned integer type for 24-bit depth texture data.
- -

{{domxref("OES_texture_half_float")}}

- - - - - - - - - - - - - - - - -
Constant nameValueDescription
HALF_FLOAT_OES0x8D61Half floating-point type (16-bit).
- -

{{domxref("WEBGL_color_buffer_float")}}

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
RGBA32F_EXT0x8814RGBA 32-bit floating-point color-renderable format.
RGB32F_EXT0x8815RGB 32-bit floating-point color-renderable format.
FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT0x8211 
UNSIGNED_NORMALIZED_EXT0x8C17 
- -

{{domxref("EXT_blend_minmax")}}

- - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
MIN_EXT0x8007Produces the minimum color components of the source and destination colors.
MAX_EXT0x8008Produces the maximum color components of the source and destination colors.
- -

{{domxref("EXT_sRGB")}}

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
SRGB_EXT0x8C40Unsized sRGB format that leaves the precision up to the driver.
SRGB_ALPHA_EXT0x8C42Unsized sRGB format with unsized alpha component.
SRGB8_ALPHA8_EXT0x8C43Sized (8-bit) sRGB and alpha formats.
FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT0x8210Returns the framebuffer color encoding.
- -

{{domxref("OES_standard_derivatives")}}

- - - - - - - - - - - - - - - - -
Constant nameValueDescription
FRAGMENT_SHADER_DERIVATIVE_HINT_OES0x8B8BIndicates the accuracy of the derivative calculation for the GLSL built-in functions: dFdx, dFdy, and fwidth.
- -

{{domxref("WEBGL_draw_buffers")}}

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
COLOR_ATTACHMENT0_WEBGL0x8CE0Framebuffer color attachment point
COLOR_ATTACHMENT1_WEBGL0x8CE1Framebuffer color attachment point
COLOR_ATTACHMENT2_WEBGL0x8CE2Framebuffer color attachment point
COLOR_ATTACHMENT3_WEBGL0x8CE3Framebuffer color attachment point
COLOR_ATTACHMENT4_WEBGL0x8CE4Framebuffer color attachment point
COLOR_ATTACHMENT5_WEBGL0x8CE5Framebuffer color attachment point
COLOR_ATTACHMENT6_WEBGL0x8CE6Framebuffer color attachment point
COLOR_ATTACHMENT7_WEBGL0x8CE7Framebuffer color attachment point
COLOR_ATTACHMENT8_WEBGL0x8CE8Framebuffer color attachment point
COLOR_ATTACHMENT9_WEBGL0x8CE9Framebuffer color attachment point
COLOR_ATTACHMENT10_WEBGL0x8CEAFramebuffer color attachment point
COLOR_ATTACHMENT11_WEBGL0x8CEBFramebuffer color attachment point
COLOR_ATTACHMENT12_WEBGL0x8CECFramebuffer color attachment point
COLOR_ATTACHMENT13_WEBGL0x8CEDFramebuffer color attachment point
COLOR_ATTACHMENT14_WEBGL0x8CEEFramebuffer color attachment point
COLOR_ATTACHMENT15_WEBGL0x8CEFFramebuffer color attachment point
DRAW_BUFFER0_WEBGL0x8825Draw buffer
DRAW_BUFFER1_WEBGL0x8826Draw buffer
DRAW_BUFFER2_WEBGL0x8827Draw buffer
DRAW_BUFFER3_WEBGL0x8828Draw buffer
DRAW_BUFFER4_WEBGL0x8829Draw buffer
DRAW_BUFFER5_WEBGL0x882ADraw buffer
DRAW_BUFFER6_WEBGL0x882BDraw buffer
DRAW_BUFFER7_WEBGL0x882CDraw buffer
DRAW_BUFFER8_WEBGL0x882DDraw buffer
DRAW_BUFFER9_WEBGL0x882EDraw buffer
DRAW_BUFFER10_WEBGL0x882FDraw buffer
DRAW_BUFFER11_WEBGL0x8830Draw buffer
DRAW_BUFFER12_WEBGL0x8831Draw buffer
DRAW_BUFFER13_WEBGL0x8832Draw buffer
DRAW_BUFFER14_WEBGL0x8833Draw buffer
DRAW_BUFFER15_WEBGL0x8834Draw buffer
MAX_COLOR_ATTACHMENTS_WEBGL0x8CDFMaximum number of framebuffer color attachment points
MAX_DRAW_BUFFERS_WEBGL0x8824Maximum number of draw buffers
- -

{{domxref("OES_vertex_array_object")}}

- - - - - - - - - - - - - - - - -
Constant nameValueDescription
VERTEX_ARRAY_BINDING_OES0x85B5The bound vertex array object (VAO).
- -

{{domxref("EXT_disjoint_timer_query")}}

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Nome da constanteValorDescrição
QUERY_COUNTER_BITS_EXT0x8864The number of bits used to hold the query result for the given target.
CURRENT_QUERY_EXT0x8865The currently active query.
QUERY_RESULT_EXT0x8866The query result.
QUERY_RESULT_AVAILABLE_EXT0x8867A Boolean indicating whether or not a query result is available.
TIME_ELAPSED_EXT0x88BFElapsed time (in nanoseconds).
TIMESTAMP_EXT0x8E28The current time.
GPU_DISJOINT_EXT0x8FBBA Boolean indicating whether or not the GPU performed any disjoint operation.
- -

Especificações

- - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('WebGL', "#5.14", "WebGLRenderingContext")}}{{Spec2('WebGL')}}Initial definition
{{SpecName('WebGL2', "#3.7", "WebGL2RenderingContext")}}{{Spec2('WebGL2')}}Defines additional constants.
- -

Consulte também

- - - -
- - - - - -
diff --git a/files/pt-pt/web/api/webgl_api/constants/index.html b/files/pt-pt/web/api/webgl_api/constants/index.html new file mode 100644 index 0000000000..8328c7976f --- /dev/null +++ b/files/pt-pt/web/api/webgl_api/constants/index.html @@ -0,0 +1,4023 @@ +--- +title: Contantes de WebGL +slug: Web/API/WebGL_API/Constantes +tags: + - API + - Referencia + - WebGL + - constantes +translation_of: Web/API/WebGL_API/Constants +--- +
{{WebGLSidebar}}
+ +

The WebGL API provides several constants that are passed into or returned by functions. All constants are of type {{domxref("GLenum")}}.

+ +

Standard WebGL constants are installed on the {{domxref("WebGLRenderingContext")}} and {{domxref("WebGL2RenderingContext")}} objects, so that you use them as gl.CONSTANT_NAME:

+ +
var canvas = document.getElementById('myCanvas');
+var gl = canvas.getContext('webgl');
+
+gl.getParameter(gl.LINE_WIDTH);
+
+ +

Some constants are also provided by WebGL extensions. A list is provided below.

+ +
var debugInfo = gl.getExtension('WEBGL_debug_renderer_info');
+var vendor = gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL);
+ +

The WebGL tutorial has more information, examples, and resources on how to get started with WebGL.

+ +

Tabela de conteúdos

+ + + +

Standard WebGL 1 constants

+ +

These constants are defined on the {{domxref("WebGLRenderingContext")}} interface.

+ +

Limpar buffers

+ +

Constants passed to {{domxref("WebGLRenderingContext.clear()")}} to clear buffer masks.

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
DEPTH_BUFFER_BIT0x00000100Passed to clear to clear the current depth buffer.
STENCIL_BUFFER_BIT0x00000400Passed to clear to clear the current stencil buffer.
COLOR_BUFFER_BIT0x00004000Passed to clear to clear the current color buffer.
+ +

Renderizar primitivos

+ +

Constants passed to {{domxref("WebGLRenderingContext.drawElements()")}} or {{domxref("WebGLRenderingContext.drawArrays()")}} to specify what kind of primitive to render.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
POINTS0x0000Passed to drawElements or drawArrays to draw single points.
LINES0x0001Passed to drawElements or drawArrays to draw lines. Each vertex connects to the one after it.
LINE_LOOP0x0002Passed to drawElements or drawArrays to draw lines. Each set of two vertices is treated as a separate line segment.
LINE_STRIP0x0003Passed to drawElements or drawArrays to draw a connected group of line segments from the first vertex to the last.
TRIANGLES0x0004Passed to drawElements or drawArrays to draw triangles. Each set of three vertices creates a separate triangle.
TRIANGLE_STRIP0x0005Passed to drawElements or drawArrays to draw a connected group of triangles.
TRIANGLE_FAN0x0006Passed to drawElements or drawArrays to draw a connected group of triangles. Each vertex connects to the previous and the first vertex in the fan.
+ +

Modos de mistura

+ +

Constants passed to {{domxref("WebGLRenderingContext.blendFunc()")}} or {{domxref("WebGLRenderingContext.blendFuncSeparate()")}} to specify the blending mode (for both, RBG and alpha, or separately).

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Nome da constanteValorDescrição
ZERO0Passed to blendFunc or blendFuncSeparate to turn off a component.
ONE1Passed to blendFunc or blendFuncSeparate to turn on a component.
SRC_COLOR0x0300Passed to blendFunc or blendFuncSeparate to multiply a component by the source elements color.
ONE_MINUS_SRC_COLOR0x0301Passed to blendFunc or blendFuncSeparate to multiply a component by one minus the source elements color.
SRC_ALPHA0x0302Passed to blendFunc or blendFuncSeparate to multiply a component by the source's alpha.
ONE_MINUS_SRC_ALPHA0x0303Passed to blendFunc or blendFuncSeparate to multiply a component by one minus the source's alpha.
DST_ALPHA0x0304Passed to blendFunc or blendFuncSeparate to multiply a component by the destination's alpha.
ONE_MINUS_DST_ALPHA0x0305Passed to blendFunc or blendFuncSeparate to multiply a component by one minus the destination's alpha.
DST_COLOR0x0306Passed to blendFunc or blendFuncSeparate to multiply a component by the destination's color.
ONE_MINUS_DST_COLOR0x0307Passed to blendFunc or blendFuncSeparate to multiply a component by one minus the destination's color.
SRC_ALPHA_SATURATE0x0308Passed to blendFunc or blendFuncSeparate to multiply a component by the minimum of source's alpha or one minus the destination's alpha.
CONSTANT_COLOR0x8001Passed to blendFunc or blendFuncSeparate to specify a constant color blend function.
ONE_MINUS_CONSTANT_COLOR0x8002Passed to blendFunc or blendFuncSeparate to specify one minus a constant color blend function.
CONSTANT_ALPHA0x8003Passed to blendFunc or blendFuncSeparate to specify a constant alpha blend function.
ONE_MINUS_CONSTANT_ALPHA0x8004Passed to blendFunc or blendFuncSeparate to specify one minus a constant alpha blend function.
+ +

Equações de mistura

+ +

Constants passed to {{domxref("WebGLRenderingContext.blendEquation()")}} or {{domxref("WebGLRenderingContext.blendEquationSeparate()")}} to control how the blending is calculated (for both, RBG and alpha, or separately).

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
Nome da constanteValorDescrição
FUNC_ADD0x8006Passed to blendEquation or blendEquationSeparate to set an addition blend function.
FUNC_SUBSTRACT0x800APassed to blendEquation or blendEquationSeparate to specify a subtraction blend function (source - destination).
FUNC_REVERSE_SUBTRACT0x800BPassed to blendEquation or blendEquationSeparate to specify a reverse subtraction blend function (destination - source).
+ +

Obter informação do parâmetro GL

+ +

Constants passed to {{domxref("WebGLRenderingContext.getParameter()")}} to specify what information to return.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Nome da constanteValorDescrição
BLEND_EQUATION0x8009Passed to getParameter to get the current RGB blend function.
BLEND_EQUATION_RGB0x8009Passed to getParameter to get the current RGB blend function. Same as BLEND_EQUATION
BLEND_EQUATION_ALPHA0x883DPassed to getParameter to get the current alpha blend function. Same as BLEND_EQUATION
BLEND_DST_RGB0x80C8Passed to getParameter to get the current destination RGB blend function.
BLEND_SRC_RGB0x80C9Passed to getParameter to get the current destination RGB blend function.
BLEND_DST_ALPHA0x80CAPassed to getParameter to get the current destination alpha blend function.
BLEND_SRC_ALPHA0x80CBPassed to getParameter to get the current source alpha blend function.
BLEND_COLOR0x8005Passed to getParameter to return a the current blend color.
ARRAY_BUFFER_BINDING0x8894Passed to getParameter to get the array buffer binding.
ELEMENT_ARRAY_BUFFER_BINDING0x8895Passed to getParameter to get the current element array buffer.
LINE_WIDTH0x0B21Passed to getParameter to get the current lineWidth (set by the lineWidth method).
ALIASED_POINT_SIZE_RANGE0x846DPassed to getParameter to get the current size of a point drawn with gl.POINTS
ALIASED_LINE_WIDTH_RANGE0x846EPassed to getParameter to get the range of available widths for a line. Returns a length-2 array with the lo value at 0, and hight at 1.
CULL_FACE_MODE0x0B45Passed to getParameter to get the current value of cullFace. Should return FRONT, BACK, or FRONT_AND_BACK
FRONT_FACE0x0B46Passed to getParameter to determine the current value of frontFace. Should return CW or CCW.
DEPTH_RANGE0x0B70Passed to getParameter to return a length-2 array of floats giving the current depth range.
DEPTH_WRITEMASK0x0B72Passed to getParameter to determine if the depth write mask is enabled.
DEPTH_CLEAR_VALUE0x0B73Passed to getParameter to determine the current depth clear value.
DEPTH_FUNC0x0B74Passed to getParameter to get the current depth function. Returns NEVER, ALWAYS, LESS, EQUAL, LEQUAL, GREATER, GEQUAL, or NOTEQUAL.
STENCIL_CLEAR_VALUE0x0B91Passed to getParameter to get the value the stencil will be cleared to.
STENCIL_FUNC0x0B92Passed to getParameter to get the current stencil function. Returns NEVER, ALWAYS, LESS, EQUAL, LEQUAL, GREATER, GEQUAL, or NOTEQUAL.
STENCIL_FAIL0x0B94Passed to getParameter to get the current stencil fail function. Should return KEEP, REPLACE, INCR, DECR, INVERT, INCR_WRAP, or DECR_WRAP.
STENCIL_PASS_DEPTH_FAIL0x0B95Passed to getParameter to get the current stencil fail function should the depth buffer test fail. Should return KEEP, REPLACE, INCR, DECR, INVERT, INCR_WRAP, or DECR_WRAP.
STENCIL_PASS_DEPTH_PASS0x0B96Passed to getParameter to get the current stencil fail function should the depth buffer test pass. Should return KEEP, REPLACE, INCR, DECR, INVERT, INCR_WRAP, or DECR_WRAP.
STENCIL_REF0x0B97Passed to getParameter to get the reference value used for stencil tests.
STENCIL_VALUE_MASK0x0B93 
STENCIL_WRITEMASK0x0B98 
STENCIL_BACK_FUNC0x8800 
STENCIL_BACK_FAIL0x8801 
STENCIL_BACK_PASS_DEPTH_FAIL0x8802 
STENCIL_BACK_PASS_DEPTH_PASS0x8803 
STENCIL_BACK_REF0x8CA3 
STENCIL_BACK_VALUE_MASK0x8CA4 
STENCIL_BACK_WRITEMASK0x8CA5 
VIEWPORT0x0BA2Returns an {{jsxref("Int32Array")}} with four elements for the current viewport dimensions.
SCISSOR_BOX0x0C10Returns an {{jsxref("Int32Array")}} with four elements for the current scissor box dimensions.
COLOR_CLEAR_VALUE0x0C22 
COLOR_WRITEMASK0x0C23 
UNPACK_ALIGNMENT0x0CF5 
PACK_ALIGNMENT0x0D05 
MAX_TEXTURE_SIZE0x0D33 
MAX_VIEWPORT_DIMS0x0D3A 
SUBPIXEL_BITS0x0D50 
RED_BITS0x0D52 
GREEN_BITS0x0D53 
BLUE_BITS0x0D54 
ALPHA_BITS0x0D55 
DEPTH_BITS0x0D56 
STENCIL_BITS0x0D57 
POLYGON_OFFSET_UNITS0x2A00 
POLYGON_OFFSET_FACTOR0x8038 
TEXTURE_BINDING_2D0x8069 
SAMPLE_BUFFERS0x80A8 
SAMPLES0x80A9 
SAMPLE_COVERAGE_VALUE0x80AA 
SAMPLE_COVERAGE_INVERT0x80AB 
COMPRESSED_TEXTURE_FORMATS0x86A3 
VENDOR0x1F00 
RENDERER0x1F01 
VERSION0x1F02 
IMPLEMENTATION_COLOR_READ_TYPE0x8B9A 
IMPLEMENTATION_COLOR_READ_FORMAT0x8B9B 
BROWSER_DEFAULT_WEBGL0x9244 
+ +

Buffers

+ +

Constants passed to {{domxref("WebGLRenderingContext.bufferData()")}}, {{domxref("WebGLRenderingContext.bufferSubData()")}}, {{domxref("WebGLRenderingContext.bindBuffer()")}}, or {{domxref("WebGLRenderingContext.getBufferParameter()")}}.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
STATIC_DRAW0x88E4Passed to bufferData as a hint about whether the contents of the buffer are likely to be used often and not change often.
STREAM_DRAW0x88E0Passed to bufferData as a hint about whether the contents of the buffer are likely to not be used often.
DYNAMIC_DRAW0x88E8Passed to bufferData as a hint about whether the contents of the buffer are likely to be used often and change often.
ARRAY_BUFFER0x8892Passed to bindBuffer or bufferData to specify the type of buffer being used.
ELEMENT_ARRAY_BUFFER0x8893Passed to bindBuffer or bufferData to specify the type of buffer being used.
BUFFER_SIZE0x8764Passed to getBufferParameter to get a buffer's size.
BUFFER_USAGE0x8765Passed to getBufferParameter to get the hint for the buffer passed in when it was created.
+ +

Atributos de Vertex

+ +

Constants passed to {{domxref("WebGLRenderingContext.getVertexAttrib()")}}.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Nome da constanteValorDescrição
CURRENT_VERTEX_ATTRIB0x8626Passed to getVertexAttrib to read back the current vertex attribute.
VERTEX_ATTRIB_ARRAY_ENABLED0x8622 
VERTEX_ATTRIB_ARRAY_SIZE0x8623 
VERTEX_ATTRIB_ARRAY_STRIDE0x8624 
VERTEX_ATTRIB_ARRAY_TYPE0x8625 
VERTEX_ATTRIB_ARRAY_NORMALIZED0x886A 
VERTEX_ATTRIB_ARRAY_POINTER0x8645 
VERTEX_ATTRIB_ARRAY_BUFFER_BINDING0x889F 
+ +

Culling

+ +

Constants passed to {{domxref("WebGLRenderingContext.cullFace()")}}.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
CULL_FACE0x0B44Passed to enable/disable to turn on/off culling. Can also be used with getParameter to find the current culling method.
FRONT0x0404Passed to cullFace to specify that only front faces should be drawn.
BACK0x0405Passed to cullFace to specify that only back faces should be drawn.
FRONT_AND_BACK0x0408Passed to cullFace to specify that front and back faces should be drawn.
+ +

Enabling and disabling

+ +

Constants passed to {{domxref("WebGLRenderingContext.enable()")}} or {{domxref("WebGLRenderingContext.disable()")}}.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
BLEND0x0BE2Passed to enable/disable to turn on/off blending. Can also be used with getParameter to find the current blending method.
DEPTH_TEST0x0B71Passed to enable/disable to turn on/off the depth test. Can also be used with getParameter to query the depth test.
DITHER0x0BD0Passed to enable/disable to turn on/off dithering. Can also be used with getParameter to find the current dithering method.
POLYGON_OFFSET_FILL0x8037Passed to enable/disable to turn on/off the polygon offset. Useful for rendering hidden-line images, decals, and or solids with highlighted edges. Can also be used with getParameter to query the scissor test.
SAMPLE_ALPHA_TO_COVERAGE0x809EPassed to enable/disable to turn on/off the alpha to coverage. Used in multi-sampling alpha channels.
SAMPLE_COVERAGE0x80A0Passed to enable/disable to turn on/off the sample coverage. Used in multi-sampling.
SCISSOR_TEST0x0C11Passed to enable/disable to turn on/off the scissor test. Can also be used with getParameter to query the scissor test.
STENCIL_TEST0x0B90Passed to enable/disable to turn on/off the stencil test. Can also be used with getParameter to query the stencil test.
+ +

Errors

+ +

Constants returned from {{domxref("WebGLRenderingContext.getError()")}}.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
NO_ERROR0Returned from getError.
INVALID_ENUM0x0500Returned from getError.
INVALID_VALUE0x0501Returned from getError.
INVALID_OPERATION0x0502Returned from getError.
OUT_OF_MEMORY0x0505Returned from getError.
CONTEXT_LOST_WEBGL0x9242Returned from getError.
+ +

Front face directions

+ +

Constants passed to {{domxref("WebGLRenderingContext.frontFace()")}}.

+ + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
CW0x0900Passed to frontFace to specify the front face of a polygon is drawn in the clockwise direction
CCW0x0901Passed to frontFace to specify the front face of a polygon is drawn in the counter clockwise direction
+ +

Hints

+ +

Constants passed to {{domxref("WebGLRenderingContext.hint()")}}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
DONT_CARE0x1100There is no preference for this behavior.
FASTEST0x1101The most efficient behavior should be used.
NICEST0x1102The most correct or the highest quality option should be used.
GENERATE_MIPMAP_HINT0x8192Hint for the quality of filtering when generating mipmap images with {{domxref("WebGLRenderingContext.generateMipmap()")}}.
+ +

Data types

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
BYTE0x1400 
UNSIGNED_BYTE0x1401 
SHORT0x1402 
UNSIGNED_SHORT0x1403 
INT0x1404 
UNSIGNED_INT0x1405 
FLOAT0x1406 
+ +

Pixel formats

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
DEPTH_COMPONENT0x1902 
ALPHA0x1906 
RGB0x1907 
RGBA0x1908 
LUMINANCE0x1909 
LUMINANCE_ALPHA0x190A 
+ +

Pixel types

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
UNSIGNED_BYTE0x1401 
UNSIGNED_SHORT_4_4_4_40x8033 
UNSIGNED_SHORT_5_5_5_10x8034 
UNSIGNED_SHORT_5_6_50x8363 
+ +

Shaders

+ +

Constants passed to {{domxref("WebGLRenderingContext.createShader()")}} or {{domxref("WebGLRenderingContext.getShaderParameter()")}}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
FRAGMENT_SHADER0x8B30Passed to createShader to define a fragment shader.
VERTEX_SHADER0x8B31Passed to createShader to define a vertex shader
COMPILE_STATUS0x8B81Passed to getShaderParamter to get the status of the compilation. Returns false if the shader was not compiled. You can then query getShaderInfoLog to find the exact error
DELETE_STATUS0x8B80Passed to getShaderParamter to determine if a shader was deleted via deleteShader. Returns true if it was, false otherwise.
LINK_STATUS0x8B82Passed to getProgramParameter after calling linkProgram to determine if a program was linked correctly. Returns false if there were errors. Use getProgramInfoLog to find the exact error.
VALIDATE_STATUS0x8B83Passed to getProgramParameter after calling validateProgram to determine if it is valid. Returns false if errors were found.
ATTACHED_SHADERS0x8B85Passed to getProgramParameter after calling attachShader to determine if the shader was attached correctly. Returns false if errors occurred.
ACTIVE_ATTRIBUTES0x8B89Passed to getProgramParameter to get the number of attributes active in a program.
ACTIVE_UNIFORMS0x8B86Passed to getProgramParamter to get the number of uniforms active in a program.
MAX_VERTEX_ATTRIBS0x8869The maximum number of entries possible in the vertex attribute list.
MAX_VERTEX_UNIFORM_VECTORS0x8DFB 
MAX_VARYING_VECTORS0x8DFC 
MAX_COMBINED_TEXTURE_IMAGE_UNITS0x8B4D 
MAX_VERTEX_TEXTURE_IMAGE_UNITS0x8B4C 
MAX_TEXTURE_IMAGE_UNITS0x8872Implementation dependent number of maximum texture units. At least 8.
MAX_FRAGMENT_UNIFORM_VECTORS0x8DFD 
SHADER_TYPE0x8B4F 
SHADING_LANGUAGE_VERSION0x8B8C 
CURRENT_PROGRAM0x8B8D 
+ +

Depth or stencil tests

+ +

Constants passed to {{domxref("WebGLRenderingContext.depthFunc()")}} or {{domxref("WebGLRenderingContext.stencilFunc()")}}.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
NEVER0x0200Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
ALWAYS0x0207Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn.
LESS0x0201Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
EQUAL0x0202Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
LEQUAL0x0203Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value.
GREATER0x0204Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
GEQUAL0x0206Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value.
NOTEQUAL0x0205Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value.
+ +

Stencil actions

+ +

Constants passed to {{domxref("WebGLRenderingContext.stencilOp()")}}.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
KEEP0x1E00 
REPLACE0x1E01 
INCR0x1E02 
DECR0x1E03 
INVERT0x150A 
INCR_WRAP0x8507 
DECR_WRAP0x8508 
+ +

Textures

+ +

Constants passed to {{domxref("WebGLRenderingContext.texParameteri()")}}, {{domxref("WebGLRenderingContext.texParameterf()")}}, {{domxref("WebGLRenderingContext.bindTexture()")}}, {{domxref("WebGLRenderingContext.texImage2D()")}}, and others.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
NEAREST0x2600 
LINEAR0x2601 
NEAREST_MIPMAP_NEAREST0x2700 
LINEAR_MIPMAP_NEAREST0x2701 
NEAREST_MIPMAP_LINEAR0x2702 
LINEAR_MIPMAP_LINEAR0x2703 
TEXTURE_MAG_FILTER0x2800 
TEXTURE_MIN_FILTER0x2801 
TEXTURE_WRAP_S0x2802 
TEXTURE_WRAP_T0x2803 
TEXTURE_2D0x0DE1 
TEXTURE0x1702 
TEXTURE_CUBE_MAP0x8513 
TEXTURE_BINDING_CUBE_MAP0x8514 
TEXTURE_CUBE_MAP_POSITIVE_X0x8515 
TEXTURE_CUBE_MAP_NEGATIVE_X0x8516 
TEXTURE_CUBE_MAP_POSITIVE_Y0x8517 
TEXTURE_CUBE_MAP_NEGATIVE_Y0x8518 
TEXTURE_CUBE_MAP_POSITIVE_Z0x8519 
TEXTURE_CUBE_MAP_NEGATIVE_Z0x851A 
MAX_CUBE_MAP_TEXTURE_SIZE0x851C 
TEXTURE0 - 310x84C0 - 0x84DFA texture unit.
ACTIVE_TEXTURE0x84E0The current active texture unit.
REPEAT0x2901 
CLAMP_TO_EDGE0x812F 
MIRRORED_REPEAT0x8370 
+ +

Uniform types

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
FLOAT_VEC20x8B50 
FLOAT_VEC30x8B51 
FLOAT_VEC40x8B52 
INT_VEC20x8B53 
INT_VEC30x8B54 
INT_VEC40x8B55 
BOOL0x8B56 
BOOL_VEC20x8B57 
BOOL_VEC30x8B58 
BOOL_VEC40x8B59 
FLOAT_MAT20x8B5A 
FLOAT_MAT30x8B5B 
FLOAT_MAT40x8B5C 
SAMPLER_2D0x8B5E 
SAMPLER_CUBE0x8B60 
+ +

Shader precision-specified types

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
LOW_FLOAT0x8DF0 
MEDIUM_FLOAT0x8DF1 
HIGH_FLOAT0x8DF2 
LOW_INT0x8DF3 
MEDIUM_INT0x8DF4 
HIGH_INT0x8DF5 
+ +

Framebuffers and renderbuffers

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
FRAMEBUFFER0x8D40 
RENDERBUFFER0x8D41 
RGBA40x8056 
RGB5_A10x8057 
RGB5650x8D62 
DEPTH_COMPONENT160x81A5 
STENCIL_INDEX0x1901 
STENCIL_INDEX80x8D48 
DEPTH_STENCIL0x84F9 
RENDERBUFFER_WIDTH0x8D42 
RENDERBUFFER_HEIGHT0x8D43 
RENDERBUFFER_INTERNAL_FORMAT0x8D44 
RENDERBUFFER_RED_SIZE0x8D50 
RENDERBUFFER_GREEN_SIZE0x8D51 
RENDERBUFFER_BLUE_SIZE0x8D52 
RENDERBUFFER_ALPHA_SIZE0x8D53 
RENDERBUFFER_DEPTH_SIZE0x8D54 
RENDERBUFFER_STENCIL_SIZE0x8D55 
FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE0x8CD0 
FRAMEBUFFER_ATTACHMENT_OBJECT_NAME0x8CD1 
FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL0x8CD2 
FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE0x8CD3 
COLOR_ATTACHMENT00x8CE0 
DEPTH_ATTACHMENT0x8D00 
STENCIL_ATTACHMENT0x8D20 
DEPTH_STENCIL_ATTACHMENT0x821A 
NONE0 
FRAMEBUFFER_COMPLETE0x8CD5 
FRAMEBUFFER_INCOMPLETE_ATTACHMENT0x8CD6 
FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT0x8CD7 
FRAMEBUFFER_INCOMPLETE_DIMENSIONS0x8CD9 
FRAMEBUFFER_UNSUPPORTED0x8CDD 
FRAMEBUFFER_BINDING0x8CA6 
RENDERBUFFER_BINDING0x8CA7 
MAX_RENDERBUFFER_SIZE0x84E8 
INVALID_FRAMEBUFFER_OPERATION0x0506 
+ +

Pixel storage modes

+ +

Constants passed to {{domxref("WebGLRenderingContext.pixelStorei()")}}.

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
UNPACK_FLIP_Y_WEBGL0x9240 
UNPACK_PREMULTIPLY_ALPHA_WEBGL0x9241 
UNPACK_COLORSPACE_CONVERSION_WEBGL0x9243 
+ +

Constantes adicionais definidas em WebGL 2

+ +

These constants are defined on the {{domxref("WebGL2RenderingContext")}} interface. All WebGL 1 constants are also available in a WebGL 2 context.

+ +

Obter a informação do parâmetro GL

+ +

Constants passed to {{domxref("WebGLRenderingContext.getParameter()")}} to specify what information to return.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
READ_BUFFER0x0C02 
UNPACK_ROW_LENGTH0x0CF2 
UNPACK_SKIP_ROWS0x0CF3 
UNPACK_SKIP_PIXELS0x0CF4 
PACK_ROW_LENGTH0x0D02 
PACK_SKIP_ROWS0x0D03 
PACK_SKIP_PIXELS0x0D04 
TEXTURE_BINDING_3D0x806A 
UNPACK_SKIP_IMAGES0x806D 
UNPACK_IMAGE_HEIGHT0x806E 
MAX_3D_TEXTURE_SIZE0x8073 
MAX_ELEMENTS_VERTICES0x80E8 
MAX_ELEMENTS_INDICES0x80E9 
MAX_TEXTURE_LOD_BIAS0x84FD 
MAX_FRAGMENT_UNIFORM_COMPONENTS0x8B49 
MAX_VERTEX_UNIFORM_COMPONENTS0x8B4A 
MAX_ARRAY_TEXTURE_LAYERS0x88FF 
MIN_PROGRAM_TEXEL_OFFSET0x8904 
MAX_PROGRAM_TEXEL_OFFSET0x8905 
MAX_VARYING_COMPONENTS0x8B4B 
FRAGMENT_SHADER_DERIVATIVE_HINT0x8B8B 
RASTERIZER_DISCARD0x8C89 
VERTEX_ARRAY_BINDING0x85B5 
MAX_VERTEX_OUTPUT_COMPONENTS0x9122 
MAX_FRAGMENT_INPUT_COMPONENTS0x9125 
MAX_SERVER_WAIT_TIMEOUT0x9111 
MAX_ELEMENT_INDEX0x8D6B 
+ +

Texturas

+ +

Constants passed to {{domxref("WebGLRenderingContext.texParameteri()")}}, {{domxref("WebGLRenderingContext.texParameterf()")}}, {{domxref("WebGLRenderingContext.bindTexture()")}}, {{domxref("WebGLRenderingContext.texImage2D()")}}, and others.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
RED0x1903 
RGB80x8051 
RGBA80x8058 
RGB10_A20x8059 
TEXTURE_3D0x806F 
TEXTURE_WRAP_R0x8072 
TEXTURE_MIN_LOD0x813A 
TEXTURE_MAX_LOD0x813B 
TEXTURE_BASE_LEVEL0x813C 
TEXTURE_MAX_LEVEL0x813D 
TEXTURE_COMPARE_MODE0x884C 
TEXTURE_COMPARE_FUNC0x884D 
SRGB0x8C40 
SRGB80x8C41 
SRGB8_ALPHA80x8C43 
COMPARE_REF_TO_TEXTURE0x884E 
RGBA32F0x8814 
RGB32F0x8815 
RGBA16F0x881A 
RGB16F0x881B 
TEXTURE_2D_ARRAY0x8C1A 
TEXTURE_BINDING_2D_ARRAY0x8C1D 
R11F_G11F_B10F0x8C3A 
RGB9_E50x8C3D 
RGBA32UI0x8D70 
RGB32UI0x8D71 
RGBA16UI0x8D76 
RGB16UI0x8D77 
RGBA8UI0x8D7C 
RGB8UI0x8D7D 
RGBA32I0x8D82 
RGB32I0x8D83 
RGBA16I0x8D88 
RGB16I0x8D89 
RGBA8I0x8D8E 
RGB8I0x8D8F 
RED_INTEGER0x8D94 
RGB_INTEGER0x8D98 
RGBA_INTEGER0x8D99 
R80x8229 
RG80x822B 
R16F0x822D 
R32F0x822E 
RG16F0x822F 
RG32F0x8230 
R8I0x8231 
R8UI0x8232 
R16I0x8233 
R16UI0x8234 
R32I0x8235 
R32UI0x8236 
RG8I0x8237 
RG8UI0x8238 
RG16I0x8239 
RG16UI0x823A 
RG32I0x823B 
RG32UI0x823C 
R8_SNORM0x8F94 
RG8_SNORM0x8F95 
RGB8_SNORM0x8F96 
RGBA8_SNORM0x8F97 
RGB10_A2UI0x906F 
TEXTURE_IMMUTABLE_FORMAT 0x912F 
TEXTURE_IMMUTABLE_LEVELS0x82DF 
+ +

Tipos de píxel

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
UNSIGNED_INT_2_10_10_10_REV0x8368 
UNSIGNED_INT_10F_11F_11F_REV0x8C3B 
UNSIGNED_INT_5_9_9_9_REV0x8C3E 
FLOAT_32_UNSIGNED_INT_24_8_REV0x8DAD 
UNSIGNED_INT_24_80x84FA 
HALF_FLOAT0x140B 
RG0x8227 
RG_INTEGER0x8228 
INT_2_10_10_10_REV0x8D9F 
+ +

Consultas

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
CURRENT_QUERY0x8865 
QUERY_RESULT 0x8866 
QUERY_RESULT_AVAILABLE0x8867 
ANY_SAMPLES_PASSED0x8C2F 
ANY_SAMPLES_PASSED_CONSERVATIVE0x8D6A 
+ +

Draw buffers

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
MAX_DRAW_BUFFERS0x8824 
DRAW_BUFFER00x8825 
DRAW_BUFFER10x8826 
DRAW_BUFFER20x8827 
DRAW_BUFFER30x8828 
DRAW_BUFFER40x8829 
DRAW_BUFFER50x882A 
DRAW_BUFFER60x882B 
DRAW_BUFFER70x882C 
DRAW_BUFFER80x882D 
DRAW_BUFFER90x882E 
DRAW_BUFFER100x882F 
DRAW_BUFFER110x8830 
DRAW_BUFFER120x8831 
DRAW_BUFFER130x8832 
DRAW_BUFFER140x8833 
DRAW_BUFFER150x8834 
MAX_COLOR_ATTACHMENTS0x8CDF 
COLOR_ATTACHMENT10x8CE1 
COLOR_ATTACHMENT20x8CE2 
COLOR_ATTACHMENT30x8CE3 
COLOR_ATTACHMENT40x8CE4 
COLOR_ATTACHMENT50x8CE5 
COLOR_ATTACHMENT60x8CE6 
COLOR_ATTACHMENT70x8CE7 
COLOR_ATTACHMENT80x8CE8 
COLOR_ATTACHMENT90x8CE9 
COLOR_ATTACHMENT100x8CEA 
COLOR_ATTACHMENT110x8CEB 
COLOR_ATTACHMENT120x8CEC 
COLOR_ATTACHMENT130x8CED 
COLOR_ATTACHMENT140x8CEE 
COLOR_ATTACHMENT150x8CEF 
+ +

Samplers

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
SAMPLER_3D0x8B5F 
SAMPLER_2D_SHADOW0x8B62 
SAMPLER_2D_ARRAY0x8DC1 
SAMPLER_2D_ARRAY_SHADOW0x8DC4 
SAMPLER_CUBE_SHADOW0x8DC5 
INT_SAMPLER_2D0x8DCA 
INT_SAMPLER_3D0x8DCB 
INT_SAMPLER_CUBE0x8DCC 
INT_SAMPLER_2D_ARRAY0x8DCF 
UNSIGNED_INT_SAMPLER_2D0x8DD2 
UNSIGNED_INT_SAMPLER_3D0x8DD3 
UNSIGNED_INT_SAMPLER_CUBE0x8DD4 
UNSIGNED_INT_SAMPLER_2D_ARRAY0x8DD7 
MAX_SAMPLES0x8D57 
SAMPLER_BINDING0x8919 
+ +

Buffers

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
PIXEL_PACK_BUFFER0x88EB 
PIXEL_UNPACK_BUFFER0x88EC 
PIXEL_PACK_BUFFER_BINDING0x88ED 
PIXEL_UNPACK_BUFFER_BINDING 0x88EF 
COPY_READ_BUFFER0x8F36 
COPY_WRITE_BUFFER0x8F37 
COPY_READ_BUFFER_BINDING0x8F36 
COPY_WRITE_BUFFER_BINDING0x8F37 
+ +

Tipos de dados

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
FLOAT_MAT2x30x8B65 
FLOAT_MAT2x40x8B66 
FLOAT_MAT3x20x8B67 
FLOAT_MAT3x4 0x8B68 
FLOAT_MAT4x20x8B69 
FLOAT_MAT4x30x8B6A 
UNSIGNED_INT_VEC20x8DC6 
UNSIGNED_INT_VEC30x8DC7 
UNSIGNED_INT_VEC40x8DC8 
UNSIGNED_NORMALIZED0x8C17 
SIGNED_NORMALIZED0x8F9C 
+ +

Atributos de Vertex

+ + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
VERTEX_ATTRIB_ARRAY_INTEGER 0x88FD 
VERTEX_ATTRIB_ARRAY_DIVISOR0x88FE 
+ +

Transform feedback

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
TRANSFORM_FEEDBACK_BUFFER_MODE0x8C7F 
MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS0x8C80 
TRANSFORM_FEEDBACK_VARYINGS0x8C83 
TRANSFORM_FEEDBACK_BUFFER_START0x8C84 
TRANSFORM_FEEDBACK_BUFFER_SIZE0x8C85 
TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN0x8C88 
MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS0x8C8A 
MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS0x8C8B 
INTERLEAVED_ATTRIBS0x8C8C 
SEPARATE_ATTRIBS0x8C8D 
TRANSFORM_FEEDBACK_BUFFER0x8C8E 
TRANSFORM_FEEDBACK_BUFFER_BINDING0x8C8F 
TRANSFORM_FEEDBACK0x8E22 
TRANSFORM_FEEDBACK_PAUSED0x8E23 
TRANSFORM_FEEDBACK_ACTIVE0x8E24 
TRANSFORM_FEEDBACK_BINDING0x8E25 
+ +

Framebuffers e renderbuffers

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING0x8210 
FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE0x8211 
FRAMEBUFFER_ATTACHMENT_RED_SIZE0x8212 
FRAMEBUFFER_ATTACHMENT_GREEN_SIZE0x8213 
FRAMEBUFFER_ATTACHMENT_BLUE_SIZE0x8214 
FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE0x8215 
FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE0x8216 
FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE0x8217 
FRAMEBUFFER_DEFAULT0x8218 
DEPTH_STENCIL_ATTACHMENT0x821A 
DEPTH_STENCIL0x84F9 
DEPTH24_STENCIL80x88F0 
DRAW_FRAMEBUFFER_BINDING0x8CA6 
READ_FRAMEBUFFER0x8CA8 
DRAW_FRAMEBUFFER0x8CA9 
READ_FRAMEBUFFER_BINDING0x8CAA 
RENDERBUFFER_SAMPLES0x8CAB 
FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER0x8CD4 
FRAMEBUFFER_INCOMPLETE_MULTISAMPLE0x8D56 
+ +

Uniforms

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
UNIFORM_BUFFER0x8A11 
UNIFORM_BUFFER_BINDING0x8A28 
UNIFORM_BUFFER_START0x8A29 
UNIFORM_BUFFER_SIZE0x8A2A 
MAX_VERTEX_UNIFORM_BLOCKS0x8A2B 
MAX_FRAGMENT_UNIFORM_BLOCKS0x8A2D 
MAX_COMBINED_UNIFORM_BLOCKS0x8A2E 
MAX_UNIFORM_BUFFER_BINDINGS0x8A2F 
MAX_UNIFORM_BLOCK_SIZE0x8A30 
MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS0x8A31 
MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS0x8A33 
UNIFORM_BUFFER_OFFSET_ALIGNMENT0x8A34 
ACTIVE_UNIFORM_BLOCKS0x8A36 
UNIFORM_TYPE 0x8A37 
UNIFORM_SIZE0x8A38 
UNIFORM_BLOCK_INDEX0x8A3A 
UNIFORM_OFFSET0x8A3B 
UNIFORM_ARRAY_STRIDE0x8A3C 
UNIFORM_MATRIX_STRIDE0x8A3D 
UNIFORM_IS_ROW_MAJOR0x8A3E 
UNIFORM_BLOCK_BINDING0x8A3F 
UNIFORM_BLOCK_DATA_SIZE0x8A40 
UNIFORM_BLOCK_ACTIVE_UNIFORMS0x8A42 
UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES0x8A43 
UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER0x8A44 
UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER0x8A46 
+ +

Objetos de sincronização

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
OBJECT_TYPE0x9112 
SYNC_CONDITION0x9113 
SYNC_STATUS0x9114 
SYNC_FLAGS0x9115 
SYNC_FENCE0x9116 
SYNC_GPU_COMMANDS_COMPLETE0x9117 
UNSIGNALED0x9118 
SIGNALED0x9119 
ALREADY_SIGNALED0x911A 
TIMEOUT_EXPIRED0x911B 
CONDITION_SATISFIED0x911C 
WAIT_FAILED0x911D 
SYNC_FLUSH_COMMANDS_BIT0x00000001 
+ +

Constantes diversas

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
COLOR0x1800 
DEPTH0x1801 
STENCIL0x1802 
MIN0x8007 
MAX0x8008 
DEPTH_COMPONENT240x81A6 
STREAM_READ0x88E1 
STREAM_COPY0x88E2 
STATIC_READ0x88E5 
STATIC_COPY0x88E6 
DYNAMIC_READ0x88E9 
DYNAMIC_COPY0x88EA 
DEPTH_COMPONENT32F0x8CAC 
DEPTH32F_STENCIL80x8CAD 
INVALID_INDEX0xFFFFFFFF 
TIMEOUT_IGNORED-1 
MAX_CLIENT_WAIT_TIMEOUT_WEBGL0x9247 
+ +

Constantes definidas nas extensões de WebGL

+ +

{{domxref("ANGLE_instanced_arrays")}}

+ + + + + + + + + + + + + + + + +
Constant nameValueDescription
VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE0x88FEDescribes the frequency divisor used for instanced rendering.
+ +

{{domxref("WEBGL_debug_renderer_info")}}

+ + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
UNMASKED_VENDOR_WEBGL0x9245Passed to getParameter to get the vendor string of the graphics driver.
UNMASKED_RENDERER_WEBGL0x9246Passed to getParameter to get the renderer string of the graphics driver.
+ +

{{domxref("EXT_texture_filter_anisotropic")}}

+ + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
MAX_TEXTURE_MAX_ANISOTROPY_EXT0x84FFReturns the maximum available anisotropy.
TEXTURE_MAX_ANISOTROPY_EXT0x84FEPassed to texParameter to set the desired maximum anisotropy for a texture.
+ +

{{domxref("WEBGL_compressed_texture_s3tc")}}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
COMPRESSED_RGB_S3TC_DXT1_EXT0x83F0A DXT1-compressed image in an RGB image format.
COMPRESSED_RGBA_S3TC_DXT1_EXT0x83F1A DXT1-compressed image in an RGB image format with a simple on/off alpha value.
COMPRESSED_RGBA_S3TC_DXT3_EXT0x83F2A DXT3-compressed image in an RGBA image format. Compared to a 32-bit RGBA texture, it offers 4:1 compression.
COMPRESSED_RGBA_S3TC_DXT5_EXT0x83F3A DXT5-compressed image in an RGBA image format. It also provides a 4:1 compression, but differs to the DXT3 compression in how the alpha compression is done.
+ +

{{domxref("WEBGL_compressed_texture_etc")}}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
COMPRESSED_R11_EAC0x9270One-channel (red) unsigned format compression.
COMPRESSED_SIGNED_R11_EAC0x9271One-channel (red) signed format compression.
COMPRESSED_RG11_EAC0x9272Two-channel (red and green) unsigned format compression.
COMPRESSED_SIGNED_RG11_EAC0x9273Two-channel (red and green) signed format compression.
COMPRESSED_RGB8_ETC20x9274Compresses RBG8 data with no alpha channel.
COMPRESSED_RGBA8_ETC2_EAC0x9275Compresses RGBA8 data. The RGB part is encoded the same as RGB_ETC2, but the alpha part is encoded separately.
COMPRESSED_SRGB8_ETC20x9276Compresses sRBG8 data with no alpha channel.
COMPRESSED_SRGB8_ALPHA8_ETC2_EAC0x9277Compresses sRGBA8 data. The sRGB part is encoded the same as SRGB_ETC2, but the alpha part is encoded separately.
COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC20x9278Similar to RGB8_ETC, but with ability to punch through the alpha channel, which means to make it completely opaque or transparent.
COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC20x9279Similar to SRGB8_ETC, but with ability to punch through the alpha channel, which means to make it completely opaque or transparent.
+ +

{{domxref("WEBGL_compressed_texture_pvrtc")}}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
COMPRESSED_RGB_PVRTC_4BPPV1_IMG0x8C00RGB compression in 4-bit mode. One block for each 4×4 pixels.
COMPRESSED_RGBA_PVRTC_4BPPV1_IMG0x8C02RGBA compression in 4-bit mode. One block for each 4×4 pixels.
COMPRESSED_RGB_PVRTC_2BPPV1_IMG0x8C01RGB compression in 2-bit mode. One block for each 8×4 pixels.
COMPRESSED_RGBA_PVRTC_2BPPV1_IMG0x8C03RGBA compression in 2-bit mode. One block for each 8×4 pixe
+ +

{{domxref("WEBGL_compressed_texture_etc1")}}

+ + + + + + + + + + + + + + + + +
Constant nameValueDescription
COMPRESSED_RGB_ETC1_WEBGL0x8D64Compresses 24-bit RGB data with no alpha channel.
+ +

{{domxref("WEBGL_compressed_texture_atc")}}

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
COMPRESSED_RGB_ATC_WEBGL0x8C92Compresses RGB textures with no alpha channel.
COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL0x8C92Compresses RGBA textures using explicit alpha encoding (useful when alpha transitions are sharp).
COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL0x87EECompresses RGBA textures using interpolated alpha encoding (useful when alpha transitions are gradient).
+ +

{{domxref("WEBGL_depth_texture")}}

+ + + + + + + + + + + + + + + + +
Constant nameValueDescription
UNSIGNED_INT_24_8_WEBGL0x84FAUnsigned integer type for 24-bit depth texture data.
+ +

{{domxref("OES_texture_half_float")}}

+ + + + + + + + + + + + + + + + +
Constant nameValueDescription
HALF_FLOAT_OES0x8D61Half floating-point type (16-bit).
+ +

{{domxref("WEBGL_color_buffer_float")}}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
RGBA32F_EXT0x8814RGBA 32-bit floating-point color-renderable format.
RGB32F_EXT0x8815RGB 32-bit floating-point color-renderable format.
FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT0x8211 
UNSIGNED_NORMALIZED_EXT0x8C17 
+ +

{{domxref("EXT_blend_minmax")}}

+ + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
MIN_EXT0x8007Produces the minimum color components of the source and destination colors.
MAX_EXT0x8008Produces the maximum color components of the source and destination colors.
+ +

{{domxref("EXT_sRGB")}}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
SRGB_EXT0x8C40Unsized sRGB format that leaves the precision up to the driver.
SRGB_ALPHA_EXT0x8C42Unsized sRGB format with unsized alpha component.
SRGB8_ALPHA8_EXT0x8C43Sized (8-bit) sRGB and alpha formats.
FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT0x8210Returns the framebuffer color encoding.
+ +

{{domxref("OES_standard_derivatives")}}

+ + + + + + + + + + + + + + + + +
Constant nameValueDescription
FRAGMENT_SHADER_DERIVATIVE_HINT_OES0x8B8BIndicates the accuracy of the derivative calculation for the GLSL built-in functions: dFdx, dFdy, and fwidth.
+ +

{{domxref("WEBGL_draw_buffers")}}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
COLOR_ATTACHMENT0_WEBGL0x8CE0Framebuffer color attachment point
COLOR_ATTACHMENT1_WEBGL0x8CE1Framebuffer color attachment point
COLOR_ATTACHMENT2_WEBGL0x8CE2Framebuffer color attachment point
COLOR_ATTACHMENT3_WEBGL0x8CE3Framebuffer color attachment point
COLOR_ATTACHMENT4_WEBGL0x8CE4Framebuffer color attachment point
COLOR_ATTACHMENT5_WEBGL0x8CE5Framebuffer color attachment point
COLOR_ATTACHMENT6_WEBGL0x8CE6Framebuffer color attachment point
COLOR_ATTACHMENT7_WEBGL0x8CE7Framebuffer color attachment point
COLOR_ATTACHMENT8_WEBGL0x8CE8Framebuffer color attachment point
COLOR_ATTACHMENT9_WEBGL0x8CE9Framebuffer color attachment point
COLOR_ATTACHMENT10_WEBGL0x8CEAFramebuffer color attachment point
COLOR_ATTACHMENT11_WEBGL0x8CEBFramebuffer color attachment point
COLOR_ATTACHMENT12_WEBGL0x8CECFramebuffer color attachment point
COLOR_ATTACHMENT13_WEBGL0x8CEDFramebuffer color attachment point
COLOR_ATTACHMENT14_WEBGL0x8CEEFramebuffer color attachment point
COLOR_ATTACHMENT15_WEBGL0x8CEFFramebuffer color attachment point
DRAW_BUFFER0_WEBGL0x8825Draw buffer
DRAW_BUFFER1_WEBGL0x8826Draw buffer
DRAW_BUFFER2_WEBGL0x8827Draw buffer
DRAW_BUFFER3_WEBGL0x8828Draw buffer
DRAW_BUFFER4_WEBGL0x8829Draw buffer
DRAW_BUFFER5_WEBGL0x882ADraw buffer
DRAW_BUFFER6_WEBGL0x882BDraw buffer
DRAW_BUFFER7_WEBGL0x882CDraw buffer
DRAW_BUFFER8_WEBGL0x882DDraw buffer
DRAW_BUFFER9_WEBGL0x882EDraw buffer
DRAW_BUFFER10_WEBGL0x882FDraw buffer
DRAW_BUFFER11_WEBGL0x8830Draw buffer
DRAW_BUFFER12_WEBGL0x8831Draw buffer
DRAW_BUFFER13_WEBGL0x8832Draw buffer
DRAW_BUFFER14_WEBGL0x8833Draw buffer
DRAW_BUFFER15_WEBGL0x8834Draw buffer
MAX_COLOR_ATTACHMENTS_WEBGL0x8CDFMaximum number of framebuffer color attachment points
MAX_DRAW_BUFFERS_WEBGL0x8824Maximum number of draw buffers
+ +

{{domxref("OES_vertex_array_object")}}

+ + + + + + + + + + + + + + + + +
Constant nameValueDescription
VERTEX_ARRAY_BINDING_OES0x85B5The bound vertex array object (VAO).
+ +

{{domxref("EXT_disjoint_timer_query")}}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Nome da constanteValorDescrição
QUERY_COUNTER_BITS_EXT0x8864The number of bits used to hold the query result for the given target.
CURRENT_QUERY_EXT0x8865The currently active query.
QUERY_RESULT_EXT0x8866The query result.
QUERY_RESULT_AVAILABLE_EXT0x8867A Boolean indicating whether or not a query result is available.
TIME_ELAPSED_EXT0x88BFElapsed time (in nanoseconds).
TIMESTAMP_EXT0x8E28The current time.
GPU_DISJOINT_EXT0x8FBBA Boolean indicating whether or not the GPU performed any disjoint operation.
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('WebGL', "#5.14", "WebGLRenderingContext")}}{{Spec2('WebGL')}}Initial definition
{{SpecName('WebGL2', "#3.7", "WebGL2RenderingContext")}}{{Spec2('WebGL2')}}Defines additional constants.
+ +

Consulte também

+ + + +
+ + + + + +
diff --git a/files/pt-pt/web/api/webgl_api/dados/index.html b/files/pt-pt/web/api/webgl_api/dados/index.html deleted file mode 100644 index 8257367513..0000000000 --- a/files/pt-pt/web/api/webgl_api/dados/index.html +++ /dev/null @@ -1,133 +0,0 @@ ---- -title: Dados em WebGL -slug: Web/API/WebGL_API/Dados -tags: - - 3D - - API de WebGL - - Atributos - - Desenho - - Gráficos 3D - - Guía - - Intermediário - - Uniforms - - Varyings - - WebGL - - graficos -translation_of: Web/API/WebGL_API/Data ---- -
{{WebGLSidebar}}{{draft}}
- -

Shader programs have access to three kinds of data storage, each of which has a specific use case. Each kind of variable is accessible by one or both types of shader program (depending on the data store type) and possibly by the site's JavaScript code, depending on the specific type of variable.

- -

Tipos de dados GLSL

- -

<<document the basic types, vectors, etc; see Data Type (GLSL) on the Khronos WebGL wiki>>

- -

Variáveis de GLSL

- -

There are three kinds of "variable" or data storage available in GLSL, each of which with its own purpose and use cases: {{anch("Attributes", "attributes")}}, {{anch("Varyings", "varyings")}}, and {{anch("Uniforms", "uniforms")}}.

- -

Atributos

- -

Attributes are GLSL variables which are only available to the vertex shader (as variables) and the JavaScript code. Attributes are typically used to store color information, texture coordinates, and any other data calculated or retrieved that needs to be shared between the JavaScript code and the vertex shader.

- -

<<add how to use them>>

- -

Varyings

- -

Varyings are variables that are declared by the vertex shader and used to pass data from the vertex shader to the fragment shader. This is commonly used to share a vertex's {{interwiki("wikipedia", "Normal_(geometry)", "normal vector")}} after it has been computed by the vertex shader.

- -

<<how to use>>

- -

Uniforms

- -

Uniforms are set by the JavaScript code and are available to both the vertex and fragment shaders. They're used to provide values that will be the same for everything drawn in the frame, such as lighting positions and magnitudes, global transformation and perspective details, and so forth.

- -

<<add details>>

- -

Buffers

- -

<<add information>>

- -

Texturas

- -

<<add information>>

- -
- - - - - -
diff --git a/files/pt-pt/web/api/webgl_api/data/index.html b/files/pt-pt/web/api/webgl_api/data/index.html new file mode 100644 index 0000000000..8257367513 --- /dev/null +++ b/files/pt-pt/web/api/webgl_api/data/index.html @@ -0,0 +1,133 @@ +--- +title: Dados em WebGL +slug: Web/API/WebGL_API/Dados +tags: + - 3D + - API de WebGL + - Atributos + - Desenho + - Gráficos 3D + - Guía + - Intermediário + - Uniforms + - Varyings + - WebGL + - graficos +translation_of: Web/API/WebGL_API/Data +--- +
{{WebGLSidebar}}{{draft}}
+ +

Shader programs have access to three kinds of data storage, each of which has a specific use case. Each kind of variable is accessible by one or both types of shader program (depending on the data store type) and possibly by the site's JavaScript code, depending on the specific type of variable.

+ +

Tipos de dados GLSL

+ +

<<document the basic types, vectors, etc; see Data Type (GLSL) on the Khronos WebGL wiki>>

+ +

Variáveis de GLSL

+ +

There are three kinds of "variable" or data storage available in GLSL, each of which with its own purpose and use cases: {{anch("Attributes", "attributes")}}, {{anch("Varyings", "varyings")}}, and {{anch("Uniforms", "uniforms")}}.

+ +

Atributos

+ +

Attributes are GLSL variables which are only available to the vertex shader (as variables) and the JavaScript code. Attributes are typically used to store color information, texture coordinates, and any other data calculated or retrieved that needs to be shared between the JavaScript code and the vertex shader.

+ +

<<add how to use them>>

+ +

Varyings

+ +

Varyings are variables that are declared by the vertex shader and used to pass data from the vertex shader to the fragment shader. This is commonly used to share a vertex's {{interwiki("wikipedia", "Normal_(geometry)", "normal vector")}} after it has been computed by the vertex shader.

+ +

<<how to use>>

+ +

Uniforms

+ +

Uniforms are set by the JavaScript code and are available to both the vertex and fragment shaders. They're used to provide values that will be the same for everything drawn in the frame, such as lighting positions and magnitudes, global transformation and perspective details, and so forth.

+ +

<<add details>>

+ +

Buffers

+ +

<<add information>>

+ +

Texturas

+ +

<<add information>>

+ +
+ + + + + +
diff --git a/files/pt-pt/web/api/webgl_api/tipos/index.html b/files/pt-pt/web/api/webgl_api/tipos/index.html deleted file mode 100644 index a1762958ae..0000000000 --- a/files/pt-pt/web/api/webgl_api/tipos/index.html +++ /dev/null @@ -1,242 +0,0 @@ ---- -title: Tipos de WebGL -slug: Web/API/WebGL_API/Tipos -translation_of: Web/API/WebGL_API/Types ---- -
{{WebGLSidebar}}
- -

Os seguintes tipos são utilizados nas interfaces de WebGL.

- -

WebGL 1

- -

These types are used within a {{domxref("WebGLRenderingContext")}}.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TipoTipo de IDL WebDescrição
GLenumunsigned longUsed for enums. See also the list of constants.
GLbooleanbooleanA {{jsxref("Boolean")}}.
GLbitfieldunsigned longA bit field that stores multiple, logical bits. Used for example in {{domxref("WebGLRenderingContext.clear()")}}.
GLbytebyte8-bit twos complement signed integer.
GLshortshort16-bit twos complement signed integer.
GLintlong32-bit twos complement signed integer.
GLsizeilongUsed for sizes (e.g. width and height of the drawing buffer).
GLintptrlong longSpecial type for pointer arithmetic.
GLsizeiptrlong longSpecial type for pointer arithmetic.
GLubyteoctet8-bit twos complement unsigned integer.
GLushortunsigned short16-bit twos complement unsigned integer.
GLuintunsigned long32-bit twos complement unsigned integer.
GLfloatunrestricted float32-bit IEEE floating point number.
GLclampfunrestricted floatClamped 32-bit IEEE floating point number.
- -

WebGL 2

- -

These types are used within a {{domxref("WebGL2RenderingContext")}}. All WebGL 1 types are used as well.

- - - - - - - - - - - - - - -
TipoTipo IDL WebDescrição
GLint64long longSigned 64-bit integer number.
- -

WebGL extensions

- -

Estes tipos são utilziados dentro das extensões de WebGL.

- - - - - - - - - - - - - - -
TipoTipo de IDL WebDescrição
GLuint64EXTlong longUnsigned 64-bit integer number.
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('WebGL', "#5.1", "Types")}}{{Spec2('WebGL')}}Initial definition
{{SpecName('WebGL2', "#3.1", "Types")}}{{Spec2('WebGL2')}}Defines additional types.
{{SpecName('EXT_disjoint_timer_query', "", "GLuint64EXT")}}{{Spec2('EXT_disjoint_timer_query')}}Adds GLuint64EXT
- -

Consulte também

- - - -
- - - - - -
diff --git a/files/pt-pt/web/api/webgl_api/types/index.html b/files/pt-pt/web/api/webgl_api/types/index.html new file mode 100644 index 0000000000..a1762958ae --- /dev/null +++ b/files/pt-pt/web/api/webgl_api/types/index.html @@ -0,0 +1,242 @@ +--- +title: Tipos de WebGL +slug: Web/API/WebGL_API/Tipos +translation_of: Web/API/WebGL_API/Types +--- +
{{WebGLSidebar}}
+ +

Os seguintes tipos são utilizados nas interfaces de WebGL.

+ +

WebGL 1

+ +

These types are used within a {{domxref("WebGLRenderingContext")}}.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TipoTipo de IDL WebDescrição
GLenumunsigned longUsed for enums. See also the list of constants.
GLbooleanbooleanA {{jsxref("Boolean")}}.
GLbitfieldunsigned longA bit field that stores multiple, logical bits. Used for example in {{domxref("WebGLRenderingContext.clear()")}}.
GLbytebyte8-bit twos complement signed integer.
GLshortshort16-bit twos complement signed integer.
GLintlong32-bit twos complement signed integer.
GLsizeilongUsed for sizes (e.g. width and height of the drawing buffer).
GLintptrlong longSpecial type for pointer arithmetic.
GLsizeiptrlong longSpecial type for pointer arithmetic.
GLubyteoctet8-bit twos complement unsigned integer.
GLushortunsigned short16-bit twos complement unsigned integer.
GLuintunsigned long32-bit twos complement unsigned integer.
GLfloatunrestricted float32-bit IEEE floating point number.
GLclampfunrestricted floatClamped 32-bit IEEE floating point number.
+ +

WebGL 2

+ +

These types are used within a {{domxref("WebGL2RenderingContext")}}. All WebGL 1 types are used as well.

+ + + + + + + + + + + + + + +
TipoTipo IDL WebDescrição
GLint64long longSigned 64-bit integer number.
+ +

WebGL extensions

+ +

Estes tipos são utilziados dentro das extensões de WebGL.

+ + + + + + + + + + + + + + +
TipoTipo de IDL WebDescrição
GLuint64EXTlong longUnsigned 64-bit integer number.
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('WebGL', "#5.1", "Types")}}{{Spec2('WebGL')}}Initial definition
{{SpecName('WebGL2', "#3.1", "Types")}}{{Spec2('WebGL2')}}Defines additional types.
{{SpecName('EXT_disjoint_timer_query', "", "GLuint64EXT")}}{{Spec2('EXT_disjoint_timer_query')}}Adds GLuint64EXT
+ +

Consulte também

+ + + +
+ + + + + +
diff --git a/files/pt-pt/web/api/webgl_api/using_extensions/index.html b/files/pt-pt/web/api/webgl_api/using_extensions/index.html new file mode 100644 index 0000000000..a8bbe535d2 --- /dev/null +++ b/files/pt-pt/web/api/webgl_api/using_extensions/index.html @@ -0,0 +1,718 @@ +--- +title: Utilizar extensões de WebGL +slug: Web/API/WebGL_API/Utilizar_Extensões +tags: + - Avançado + - WebGL +translation_of: Web/API/WebGL_API/Using_Extensions +--- +
{{WebGLSidebar}}
+ +

WebGL, like its sister APIs (OpenGL and OpenGL ES), supports extensions. A complete list of extensions is available in the khronos webgl extension registry.

+ +
Nota: In WebGL, unlike in other GL APIs, extensions are only available if explicitly requested.
+ +

Nomes de extensão canónica, prefixos e preferências da empresa

+ +

Extensions may be supported by browser vendors before being officially ratified (but only when they are in draft stage). In that case, their name can be prefixed by the vendor prefix (MOZ_, WEBKIT_, etc.) or the extension is only available once a browser preference has been toggled.

+ +

If you wish to work with the bleeding edge of extensions, and want to keep working on upon ratification (assuming, of course, that the extension doesn't change in incompatible ways), that you query the canonical extension name as well as the vendor extension name. For instance:

+ +
var ext = (
+  gl.getExtension('OES_vertex_array_object') ||
+  gl.getExtension('MOZ_OES_vertex_array_object') ||
+  gl.getExtension('WEBKIT_OES_vertex_array_object')
+);
+
+ +

Note that, vendor prefix have been discouraged more and more and thus most browser implement experimental extensions behind a feature flag rather than vendor prefix.

+ +

The feature flags are:

+ + + +

Convenções de nomeação

+ +

WebGL extensions are prefixed with "ANGLE", "OES", "EXT" or "WEBGL". These prefixes reflect origin and intent:

+ + + +

Extensões de consulta disponíveis

+ +

O contexto de WebGL suporta a consulta de quais as extensões que estão disponíveis.

+ +
var available_extensions = gl.getSupportedExtensions();
+ +

The {{domxref("WebGLRenderingContext.getSupportedExtensions()")}} method returns an array of strings, one for each supported extension.

+ +

Lista de extensões

+ +

As extensões atuais são:

+ +

{{page("pt-PT/docs/Web/API/WebGL_API", "Extensões")}}

+ +

Ativar uma extensão

+ +

Before an extension can be used it has to be enabled using {{domxref("WebGLRenderingContext.getExtension()")}}. For example:

+ +
var float_texture_ext = gl.getExtension('OES_texture_float');
+ +

The return value is null if the extension is not supported, or an extension object otherwise.

+ +

Objetos de extensão

+ +

If an extension defines specific symbols or functions that are not available in the core specification of WebGL, they will be available on the extension object returned by the call to gl.getExtension().

+ +

Compatibilidade de navegador

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support9{{CompatGeckoDesktop("2.0")}}11125.1
ANGLE_instanced_arrays{{CompatUnknown}}{{CompatGeckoDesktop("33.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_blend_minmax{{CompatUnknown}}{{CompatGeckoDesktop("33.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_color_buffer_float{{CompatUnknown}}{{CompatGeckoDesktop("49.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_color_buffer_half_float{{CompatUnknown}}{{CompatGeckoDesktop("30.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_disjoint_timer_query{{CompatUnknown}}{{CompatGeckoDesktop("41.0")}} [1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_frag_depth{{CompatUnknown}}{{CompatGeckoDesktop("30.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_sRGB{{CompatUnknown}}{{CompatGeckoDesktop("28.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_shader_texture_lod{{CompatUnknown}}{{CompatGeckoDesktop("50.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_texture_filter_anisotropic{{CompatUnknown}}{{CompatGeckoDesktop("17.0")}} [2]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_element_index_uint{{CompatUnknown}}{{CompatGeckoDesktop("24.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_standard_derivatives{{CompatUnknown}}{{CompatGeckoDesktop("10.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_float{{CompatUnknown}}{{CompatGeckoDesktop("6.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_float_linear{{CompatUnknown}}{{CompatGeckoDesktop("24.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_half_float{{CompatUnknown}}{{CompatGeckoDesktop("29.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_half_float_linear{{CompatUnknown}}{{CompatGeckoDesktop("30.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_vertex_array_object{{CompatUnknown}}{{CompatGeckoDesktop("25.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_color_buffer_float{{CompatUnknown}}{{CompatGeckoDesktop("30.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_astc{{CompatUnknown}}{{CompatGeckoDesktop("53.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_atc{{CompatUnknown}}{{CompatGeckoDesktop("18.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_etc{{CompatUnknown}}{{CompatGeckoDesktop("51.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_etc1{{CompatUnknown}}{{CompatGeckoDesktop("30.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_pvrtc{{CompatUnknown}}{{CompatGeckoDesktop("18.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_s3tc{{CompatUnknown}}{{CompatGeckoDesktop("22.0")}} [2]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_s3tc_srgb{{CompatUnknown}}{{CompatGeckoDesktop("55.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_debug_renderer_info{{CompatUnknown}}{{CompatGeckoDesktop("19.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_debug_shaders{{CompatUnknown}}{{CompatGeckoDesktop("30.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_depth_texture{{CompatUnknown}}{{CompatGeckoDesktop("22.0")}} [2]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_draw_buffers{{CompatUnknown}}{{CompatGeckoDesktop("28.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_lose_context{{CompatUnknown}}{{CompatGeckoDesktop("22.0")}} [2]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FuncionalidadesAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}25{{CompatGeckoMobile("2.0")}}{{CompatVersionUnknown}}128.0
ANGLE_instanced_arrays{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_blend_minmax{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_color_buffer_float{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_color_buffer_half_float{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_disjoint_timer_query{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_frag_depth{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_sRGB{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_shader_texture_lod{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_texture_filter_anisotropic{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_element_index_uint{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_standard_derivatives{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_float{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_float_linear{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_half_float{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_half_float_linear{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_vertex_array_object{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_color_buffer_float{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_astc{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_atc{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_etc{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_etc1{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_s3tc{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_pvrtc{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_s3tc{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_s3tc_srgb{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_debug_renderer_info{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_debug_shaders{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_depth_texture{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_draw_buffers{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_lose_context{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Toggling the webgl.enable-draft-extensions preference in about:config is required.

+ +

[2] This extension was prefixed with MOZ_ in prior versions.

+ +

Consulte também

+ + + +
+ + + + + +
diff --git "a/files/pt-pt/web/api/webgl_api/utilizar_extens\303\265es/index.html" "b/files/pt-pt/web/api/webgl_api/utilizar_extens\303\265es/index.html" deleted file mode 100644 index a8bbe535d2..0000000000 --- "a/files/pt-pt/web/api/webgl_api/utilizar_extens\303\265es/index.html" +++ /dev/null @@ -1,718 +0,0 @@ ---- -title: Utilizar extensões de WebGL -slug: Web/API/WebGL_API/Utilizar_Extensões -tags: - - Avançado - - WebGL -translation_of: Web/API/WebGL_API/Using_Extensions ---- -
{{WebGLSidebar}}
- -

WebGL, like its sister APIs (OpenGL and OpenGL ES), supports extensions. A complete list of extensions is available in the khronos webgl extension registry.

- -
Nota: In WebGL, unlike in other GL APIs, extensions are only available if explicitly requested.
- -

Nomes de extensão canónica, prefixos e preferências da empresa

- -

Extensions may be supported by browser vendors before being officially ratified (but only when they are in draft stage). In that case, their name can be prefixed by the vendor prefix (MOZ_, WEBKIT_, etc.) or the extension is only available once a browser preference has been toggled.

- -

If you wish to work with the bleeding edge of extensions, and want to keep working on upon ratification (assuming, of course, that the extension doesn't change in incompatible ways), that you query the canonical extension name as well as the vendor extension name. For instance:

- -
var ext = (
-  gl.getExtension('OES_vertex_array_object') ||
-  gl.getExtension('MOZ_OES_vertex_array_object') ||
-  gl.getExtension('WEBKIT_OES_vertex_array_object')
-);
-
- -

Note that, vendor prefix have been discouraged more and more and thus most browser implement experimental extensions behind a feature flag rather than vendor prefix.

- -

The feature flags are:

- - - -

Convenções de nomeação

- -

WebGL extensions are prefixed with "ANGLE", "OES", "EXT" or "WEBGL". These prefixes reflect origin and intent:

- - - -

Extensões de consulta disponíveis

- -

O contexto de WebGL suporta a consulta de quais as extensões que estão disponíveis.

- -
var available_extensions = gl.getSupportedExtensions();
- -

The {{domxref("WebGLRenderingContext.getSupportedExtensions()")}} method returns an array of strings, one for each supported extension.

- -

Lista de extensões

- -

As extensões atuais são:

- -

{{page("pt-PT/docs/Web/API/WebGL_API", "Extensões")}}

- -

Ativar uma extensão

- -

Before an extension can be used it has to be enabled using {{domxref("WebGLRenderingContext.getExtension()")}}. For example:

- -
var float_texture_ext = gl.getExtension('OES_texture_float');
- -

The return value is null if the extension is not supported, or an extension object otherwise.

- -

Objetos de extensão

- -

If an extension defines specific symbols or functions that are not available in the core specification of WebGL, they will be available on the extension object returned by the call to gl.getExtension().

- -

Compatibilidade de navegador

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support9{{CompatGeckoDesktop("2.0")}}11125.1
ANGLE_instanced_arrays{{CompatUnknown}}{{CompatGeckoDesktop("33.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_blend_minmax{{CompatUnknown}}{{CompatGeckoDesktop("33.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_color_buffer_float{{CompatUnknown}}{{CompatGeckoDesktop("49.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_color_buffer_half_float{{CompatUnknown}}{{CompatGeckoDesktop("30.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_disjoint_timer_query{{CompatUnknown}}{{CompatGeckoDesktop("41.0")}} [1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_frag_depth{{CompatUnknown}}{{CompatGeckoDesktop("30.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_sRGB{{CompatUnknown}}{{CompatGeckoDesktop("28.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_shader_texture_lod{{CompatUnknown}}{{CompatGeckoDesktop("50.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_texture_filter_anisotropic{{CompatUnknown}}{{CompatGeckoDesktop("17.0")}} [2]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_element_index_uint{{CompatUnknown}}{{CompatGeckoDesktop("24.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_standard_derivatives{{CompatUnknown}}{{CompatGeckoDesktop("10.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_float{{CompatUnknown}}{{CompatGeckoDesktop("6.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_float_linear{{CompatUnknown}}{{CompatGeckoDesktop("24.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_half_float{{CompatUnknown}}{{CompatGeckoDesktop("29.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_half_float_linear{{CompatUnknown}}{{CompatGeckoDesktop("30.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_vertex_array_object{{CompatUnknown}}{{CompatGeckoDesktop("25.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_color_buffer_float{{CompatUnknown}}{{CompatGeckoDesktop("30.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_astc{{CompatUnknown}}{{CompatGeckoDesktop("53.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_atc{{CompatUnknown}}{{CompatGeckoDesktop("18.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_etc{{CompatUnknown}}{{CompatGeckoDesktop("51.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_etc1{{CompatUnknown}}{{CompatGeckoDesktop("30.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_pvrtc{{CompatUnknown}}{{CompatGeckoDesktop("18.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_s3tc{{CompatUnknown}}{{CompatGeckoDesktop("22.0")}} [2]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_s3tc_srgb{{CompatUnknown}}{{CompatGeckoDesktop("55.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_debug_renderer_info{{CompatUnknown}}{{CompatGeckoDesktop("19.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_debug_shaders{{CompatUnknown}}{{CompatGeckoDesktop("30.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_depth_texture{{CompatUnknown}}{{CompatGeckoDesktop("22.0")}} [2]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_draw_buffers{{CompatUnknown}}{{CompatGeckoDesktop("28.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_lose_context{{CompatUnknown}}{{CompatGeckoDesktop("22.0")}} [2]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FuncionalidadesAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}25{{CompatGeckoMobile("2.0")}}{{CompatVersionUnknown}}128.0
ANGLE_instanced_arrays{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_blend_minmax{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_color_buffer_float{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_color_buffer_half_float{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_disjoint_timer_query{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_frag_depth{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_sRGB{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_shader_texture_lod{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_texture_filter_anisotropic{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_element_index_uint{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_standard_derivatives{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_float{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_float_linear{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_half_float{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_half_float_linear{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_vertex_array_object{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_color_buffer_float{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_astc{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_atc{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_etc{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_etc1{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_s3tc{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_pvrtc{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_s3tc{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_s3tc_srgb{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_debug_renderer_info{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_debug_shaders{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_depth_texture{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_draw_buffers{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_lose_context{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

[1] Toggling the webgl.enable-draft-extensions preference in about:config is required.

- -

[2] This extension was prefixed with MOZ_ in prior versions.

- -

Consulte também

- - - -
- - - - - -
diff --git a/files/pt-pt/web/api/webrtc_api/index.html b/files/pt-pt/web/api/webrtc_api/index.html new file mode 100644 index 0000000000..8e1b31898b --- /dev/null +++ b/files/pt-pt/web/api/webrtc_api/index.html @@ -0,0 +1,287 @@ +--- +title: API de WebRTC +slug: Web/API/API_WebRTC +tags: + - API + - API de WebRTC + - API de WebRTCÁudio + - Multimedia + - Rede + - Video + - WebRTC + - emissão + - transmissão +translation_of: Web/API/WebRTC_API +--- +
{{APIRef("WebRTC")}}
+ +

WebRTC (Comunicações da Web em Tempo Real) é uma tecnologia que permite às aplicações e sites da Web capturar e opcionalmente transmitir multimédia de áudio e/ou vídeo, bem como trocar dados arbitrariamente entre navegadores sem a necessidade de um intermediário. O conjunto de normas que compreende WebRTC torna possível a partilha de dados e realizar teleconferência peer-to-peer, sem precisar que o utilizador instale plug-ins ou qualquer outro software de terceiros.

+ +

WebRTC consiste em diversos protocolos e APIs inter-relacionadas que trabalham em conjunto para obter isto. A documentação que irá encontrar aqui irá ajudá-lo a compreender o essencial de WebRTC, como configurar e utilizar ligações de dados e multimédia, e muito mais.

+ +

Conceitos e utilização de WebRTC

+ +

O WebRTC atende múltiplos propósitos e se destaca consideravelmente com Media Capture e Streams API. Juntos, eles fornecem recursos multimídia poderosos para a Web, incluindo suporte para conferências de áudio e vídeo, troca de arquivos, gerenciamento de identidade e interface com sistemas telefônicos legados, enviando sinais  {{Glossary("DTMF")}} . As conexões entre pares podem ser feitas sem exigir drivers especiais ou plug-ins, e muitas vezes podem ser feitas sem nenhum servidor intermediário.

+ +

As conexões entre dois pares são criadas usando - e representadas pela interface - {{domxref("RTCPeerConnection")}} . Uma vez que uma conexão foi estabelecida e aberta, os fluxos de mídia ({{domxref("MediaStream")}}s) e / ou canais de dados ({{domxref("RTCDataChannel")}}s) podem ser adicionados à conexão.

+ +

Os fluxos de mídia podem ser constituídos de qualquer número de faixas de informações de mídia; As faixas, que são representadas por objetos com base na interface {{domxref("MediaStreamTrack")}} , podem conter um dos vários tipos de dados de mídia, incluindo áudio, vídeo e texto (como legendas ou nomes de capítulos) . A maioria dos fluxos consistem em pelo menos uma faixa de áudio e provavelmente também uma faixa de vídeo, e pode ser usados para enviar e receber mídia ao vivo ou informações de mídia armazenada (como um filme transmitido).

+ +

Você também pode usar a conexão entre dois pares para trocar dados binários arbitrários usando a interface {{domxref("RTCDataChannel")}} . Isso pode ser usado para informações back-channel, troca de metadados, pacotes com status de jogos, transferências de arquivos ou mesmo como um canal primário para transferência de dados.

+ +

Mais detalhes e links para guias relevantes e tutoriais necessários

+ +

Interfaces de WebRTC

+ +

Como a WebRTC fornece interfaces que trabalham juntas para realizar uma variedade de tarefas, dividimos as interfaces na lista abaixo por categoria. Veja a barra lateral para uma lista alfabética.

+ +

Gestão e configuração de ligação

+ +

Essas interfaces são usadas para configurar, abrir e gerenciar conexões WebRTC.

+ +
+
{{domxref("RTCPeerConnection")}}
+
Representa uma conexão WebRTC entre o computador local e um ponto remoto. Ele é usado para lidar com transmissão eficiente de dados entre os dois pares.
+
{{domxref("RTCDataChannel")}}
+
Representa um canal de dados bidirecional entre dois pares de uma conexão.
+
{{domxref("RTCDataChannelEvent")}}
+
Representa eventos que ocorrem ao anexar um {{domxref("RTCDataChannel")}} a um {{domxref("RTCPeerConnection")}} . O único evento enviado com esta interface é {{event("datachannel")}} .
+
{{domxref("RTCSessionDescription")}}
+
Representa os parâmetros de uma sessão. Cada RTCSessionDescription consiste em um tipo de descrição que indica qual parte do processo de negociação de oferta(offer) / resposta(answer) isso descreve e do SDP descritor da sessão.
+
{{domxref("RTCStatsReport")}}
+
Fornece informações detalhando estatísticas para uma conexão ou para uma faixa individual na conexão; O relatório pode ser obtido chamando {{domxref("RTCPeerConnection.getStats()")}} .
+
{{domxref("RTCIceCandidate")}}
+
Representa um servidor candidato que estabelece a conectividade de internet (ICE -internet connectivity establishment) para estabelecer um {{domxref("RTCPeerConnection")}} .
+
{{domxref("RTCIceTransport")}}
+
Representa informações sobre o transporte referentes ao estabelecimento de conectividade de internet (ICE - internet connectivity establishment).
+
{{domxref("RTCPeerConnectionIceEvent")}}
+
Representa eventos que ocorrem em relação aos candidatos ICE com o destino, geralmente um {{domxref("RTCPeerConnection")}} . Apenas um evento é deste tipo: {{event("icecandidate")}} .
+
{{domxref("RTCRtpSender")}}
+
Gerencia a codificação e a transmissão de dados para um {{domxref("MediaStreamTrack")}} em {{domxref("RTCPeerConnection")}}.
+
{{domxref("RTCRtpReceiver")}}
+
Gerencia a recepção e decodificação de dados para um {{domxref("MediaStreamTrack")}} em um {{domxref("RTCPeerConnection")}}.
+
{{domxref("RTCTrackEvent")}}
+
Indica que uma nova entrada {{domxref("MediaStreamTrack")}} foi criada e um objeto associado {{domxref("RTCRtpReceiver")}} foi adicionado ao objeto {{domxref("RTCPeerConnection")}} .
+
+ +

Identidade e segurança

+ +

A API WebRTC inclui uma série de interfaces para gerenciar segurança e identidade.

+ +
+
{{domxref("RTCIdentityProvider")}}
+
Permite que um agente do usuário possa solicitar que uma confirmação de identidade seja gerada ou validada.
+
{{domxref("RTCIdentityAssertion")}}
+
Representa a identidade de um ponto remoto da conexão atual. Caso nenhum par (peer) seja configurado e verificado, esta interface retorna null. Uma vez configurado, este não poderá ser alterado.
+
{{domxref("RTCIdentityProviderRegistrar")}}
+
Registra um provedor de identidade (idP).
+
{{domxref("RTCIdentityEvent")}}
+
Representa uma confirmação de identidade gerada por um provedor de identidade (idP). Isso geralmente é para um {{domxref("RTCPeerConnection")}}. O único evento enviado com este tipo é {{event("identityresult")}}.
+
{{domxref("RTCIdentityErrorEvent")}}
+
Representa um erro associado ao provedor de identidade (idP). Isso geralmente é para um {{domxref("RTCPeerConnection")}} . Dois eventos são enviados com este tipo: {{event("idpassertionerror")}} e {{event("idpvalidationerror")}} .
+
{{domxref("RTCCertificate")}}
+
Representa um certificado que um {{domxref("RTCPeerConnection")}} usa para autenticar.
+
+ +

Telefonia

+ +

Essas interfaces estão relacionadas à interatividade com redes telefônicas de comutação pública (PTSNs).

+ +
+
{{domxref("RTCDTMFSender")}}
+
Gerencia a codificação e a transmissão da sinalização multi-frequência de dois tons (DTMF) para um {{domxref("RTCPeerConnection")}}.
+
{{domxref("RTCDTMFToneChangeEvent")}}
+
Indica uma ocorrência de uma multi-frequência de dois tons (DTMF). Este evento não faz bolha (bubble) (exceto quando indicado de outra forma) e não é cancelável (exceto quando indicado de outra forma).
+
+ +

Outros

+ +
+
{{domxref("RTCIceServer")}}
+
Define como ligar a um único servidor de ICE (tais como um servidor STUN ou TURN).
+
+ +

 

+ +

Guias

+ +
+
Introduction to WebRTC protocols
+
This article introduces the protocols on top of which the WebRTC API is built.
+
WebRTC connectivity
+
A guide to how WebRTC connections work and how the various protocols and interfaces can be used together to build powerful communication apps.
+
Lifetime of a WebRTC session
+
WebRTC lets you build peer-to-peer communication of arbitrary data, audio, or video—or any combination thereof—into a browser application. In this article, we'll look at the lifetime of a WebRTC session, from establishing the connection all the way through closing the connection when it's no longer needed.
+
Signaling and two-way video calling
+
A tutorial and example which turbs a WebSocket-based chat system created for a previous example and adds support for opening video calls among participants. The chat server's WebSocket connection is used for WebRTC signaling.
+
Using WebRTC data channels
+
This guide covers how you can use a peer connection and an associated {{domxref("RTCDataChannel")}} to exchange arbitrary data between two peers.
+
Using DTMF with WebRTC
+
WebRTC's support for interacting with gateways that link to old-school telephone systems includes support for sending DTMF tones using the {{domxref("RTCDTMFSender")}} interface. This guide shows how to do so.
+
+ +

Tutoriais

+ +
+
Improving compatibility using WebRTC adapter.js
+
The WebRTC organization provides on GitHub the WebRTC adapter to work around compatibility issues in different browsers' WebRTC implementations. The adapter is a JavaScript shim which lets your code to be written to the specification so that it will "just work" in all browsers with WebRTC support.
+
Taking still photos with WebRTC
+
This article shows how to use WebRTC to access the camera on a computer or mobile phone with WebRTC support and take a photo with it.
+
A simple RTCDataChannel sample
+
The {{domxref("RTCDataChannel")}} interface is a feature which lets you open a channel between two peers over which you may send and receive arbitrary data. The API is intentionally similar to the WebSocket API, so that the same programming model can be used for each.
+
+ +

Recursos

+ +

Protocolos

+ +

WebRTC-proper protocols

+ + + + + + + +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('WebRTC 1.0')}}{{Spec2('WebRTC 1.0')}}A definição inicial da API do WebRTC.
{{SpecName('Media Capture')}}{{Spec2('Media Capture')}}A definição inicial do objeto que transmite o fluxo de conteúdo de mídia.
{{SpecName('Media Capture DOM Elements')}}{{Spec2('Media Capture DOM Elements')}}A definição inicial sobre como obter fluxo de conteúdo de Elementos DOM
+ +

Em adição a estas especificações que definem a API necessária para usar o WebRTC, existem vários protocolos, listados em recursos.

+ + + + + +
+ + + + + +
diff --git a/files/pt-pt/web/api/webrtc_api/taking_still_photos/index.html b/files/pt-pt/web/api/webrtc_api/taking_still_photos/index.html new file mode 100644 index 0000000000..203ebfab5b --- /dev/null +++ b/files/pt-pt/web/api/webrtc_api/taking_still_photos/index.html @@ -0,0 +1,222 @@ +--- +title: Tirar fotografias com a câmara da Web +slug: Web/API/API_WebRTC/Tirar_fotografias +tags: + - API + - Avançado + - Código amostra + - Exemplo + - Vídeo(2) + - WebRTC + - cãmara da Web +translation_of: Web/API/WebRTC_API/Taking_still_photos +--- +

{{WebRTCSidebar}}

+ +

This article shows how to use WebRTC to access the camera on a computer or mobile phone with WebRTC support and take a photo with it. Try this sample then read on to learn how it works.

+ +

You can also jump straight to the code on Github if you like.

+ +

The HTML markup

+ +

Our HTML interface has two main operational sections: the stream and capture panel and the presentation panel. Each of these is presented side-by-side in its own {{HTMLElement("div")}} to facilitate styling and control.

+ +

The first panel on the left contains two components: a {{HTMLElement("video")}} element, which will receive the stream from WebRTC, and a {{HTMLElement("button")}} the user clicks to capture a video frame.

+ +
  <div class="camera">
+    <video id="video">Video stream not available.</video>
+    <button id="startbutton">Take photo</button>
+  </div>
+ +

This is straightforward, and we'll see how it ties together when we get into the JavaScript code.

+ +

Next, we have a {{HTMLElement("canvas")}} element into which the captured frames are stored, potentially manipulated in some way, and then converted into an output image file. This canvas is kept hidden by styling the canvas with {{cssxref("display")}}:none, to avoid cluttering up the screen — the user does not need to see this intermediate stage.

+ +

We also have an {{HTMLElement("img")}} element into which we will draw the image — this is the final display shown to the user.

+ +
  <canvas id="canvas">
+  </canvas>
+  <div class="output">
+    <img id="photo" alt="The screen capture will appear in this box.">
+  </div>
+ +

That's all of the relevant HTML. The rest is just some page layout fluff and a bit of text offering a link back to this page.

+ +

O código de JavaScript

+ +

Now let's take a look at the JavaScript code. We'll break it up into a few bite-sized pieces to make it easier to explain.

+ +

Initialização

+ +

We start by wrapping the whole script in an anonymous function to avoid global variables, then setting up various variables we'll be using.

+ +
(function() {
+  var width = 320;    // We will scale the photo width to this
+  var height = 0;     // This will be computed based on the input stream
+
+  var streaming = false;
+
+  var video = null;
+  var canvas = null;
+  var photo = null;
+  var startbutton = null;
+ +

Those variables are:

+ +
+
largura
+
Whatever size the incoming video is, we're going to scale the resulting image to be 320 pixels wide.
+
altura
+
The output height of the image will be computed given the width and the aspect ratio of the stream.
+
transmissão
+
Indicates whether or not there is currently an active stream of video running.
+
vídeo
+
This will be a reference to the {{HTMLElement("video")}} element after the page is done loading.
+
canvas
+
This will be a reference to the {{HTMLElement("canvas")}} element after the page is done loading.
+
foto
+
This will be a reference to the {{HTMLElement("img")}} element after the page is done loading.
+
startbutton
+
This will be a reference to the {{HTMLElement("button")}} element that's used to trigger capture. We'll get that after the page is done loading.
+
+ +

The startup() function

+ +

The startup() function is run when the page has finished loading, courtesy of {{domxref("window.addEventListener()")}}. This function's job is to request access to the user's webcam, initialize the output {{HTMLElement("img")}} to a default state, and to establish the event listeners needed to receive each frame of video from the camera and react when the button is clicked to capture an image.

+ +

Getting element references

+ +

First, we grab references to the major elements we need to be able to access.

+ +
  function startup() {
+    video = document.getElementById('video');
+    canvas = document.getElementById('canvas');
+    photo = document.getElementById('photo');
+    startbutton = document.getElementById('startbutton');
+ +

Get the media stream

+ +

The next task is to get the media stream:

+ +
    navigator.mediaDevices.getUserMedia({ video: true, audio: false })
+    .then(function(stream) {
+        video.srcObject = stream;
+        video.play();
+    })
+    .catch(function(err) {
+        console.log("An error occured! " + err);
+    });
+
+ +

Here, we're calling {{domxref("MediaDevices.getUserMedia()")}} and requesting a video stream (without audio). It returns a promise which we attach success and failure callbacks to.

+ +

The success callback receives a stream object as input. It the {{HTMLElement("video")}} element's source to our new stream.

+ +

Once the stream is linked to the <video> element, we start it playing by calling HTMLMediaElement.play().

+ +

The error callback is called if opening the stream doesn't work. This will happen for example if there's no compatible camera connected, or the user denied access.

+ +

Listen for the video to start playing

+ +

After calling HTMLMediaElement.play() on the {{HTMLElement("video")}}, there's a (hopefully brief) period of time that elapses before the stream of video begins to flow. To avoid blocking until that happens, we add an event listener to video, canplay, which is delivered when the video playback actually begins. At that point, all the properties in the video object have been configured based on the stream's format.

+ +
    video.addEventListener('canplay', function(ev){
+      if (!streaming) {
+        height = video.videoHeight / (video.videoWidth/width);
+
+        video.setAttribute('width', width);
+        video.setAttribute('height', height);
+        canvas.setAttribute('width', width);
+        canvas.setAttribute('height', height);
+        streaming = true;
+      }
+    }, false);
+ +

This callback does nothing unless it's the first time it's been called; this is tested by looking at the value of our streaming variable, which is false the first time this method is run.

+ +

If this is indeed the first run, we set the video's height based on the size difference between the video's actual size, video.videoWidth, and the width at which we're going to render it, width.

+ +

Finally, the width and height of both the video and the canvas are set to match each other by calling {{domxref("Element.setAttribute()")}} on each of the two properties on each element, and setting widths and heights as appropriate. Finally, we set the streaming variable to true to prevent us from inadvertently running this setup code again.

+ +

Handle clicks on the button

+ +

To capture a still photo each time the user clicks the startbutton, we need to add an event listener to the button, to be called when the click event is issued:

+ +
    startbutton.addEventListener('click', function(ev){
+      takepicture();
+      ev.preventDefault();
+    }, false);
+ +

This method is simple enough: it just calls our takepicture() function, defined below in the section {{anch("Capturing a frame from the stream")}}, then calls {{domxref("Event.preventDefault()")}} on the received event to prevent the click from being handled more than once.

+ +

Wrapping up the startup() method

+ +

There are only two more lines of code in the startup() method:

+ +
    clearphoto();
+  }
+ +

This is where we call the clearphoto() method we'll describe below in the section {{anch("Clearing the photo box")}}.

+ +

Clearing the photo box

+ +

Clearing the photo box involves creating an image, then converting it into a format usable by the {{HTMLElement("img")}} element that displays the most recently captured frame. That code looks like this:

+ +
  function clearphoto() {
+    var context = canvas.getContext('2d');
+    context.fillStyle = "#AAA";
+    context.fillRect(0, 0, canvas.width, canvas.height);
+
+    var data = canvas.toDataURL('image/png');
+    photo.setAttribute('src', data);
+  }
+ +

We start by getting a reference to the hidden {{HTMLElement("canvas")}} element that we use for offscreen rendering.  Next we set the fillStyle to #AAA (a fairly light grey), and fill the entire canvas with that color by calling {{domxref("CanvasRenderingContext2D.fillRect()","fillRect()")}}.

+ +

Last in this function, we convert the canvas into a PNG image and call {{domxref("Element.setAttribute", "photo.setAttribute()")}} to make our captured still box display the image.

+ +

Capturing a frame from the stream

+ +

There's one last function to define, and it's the point to the entire exercise: the takepicture() function, whose job it is to capture the currently displayed video frame, convert it into a PNG file, and display it in the captured frame box. The code looks like this:

+ +
  function takepicture() {
+    var context = canvas.getContext('2d');
+    if (width && height) {
+      canvas.width = width;
+      canvas.height = height;
+      context.drawImage(video, 0, 0, width, height);
+
+      var data = canvas.toDataURL('image/png');
+      photo.setAttribute('src', data);
+    } else {
+      clearphoto();
+    }
+  }
+ +

As is the case any time we need to work with the contents of a canvas, we start by getting the {{domxref("CanvasRenderingContext2D","2D drawing context")}} for the hidden canvas.

+ +

Then, if the width and height are both non-zero (meaning that there's at least potentially valid image data), we set the width and height of the canvas to match that of the captured frame, then call {{domxref("CanvasRenderingContext2D.drawImage()", "drawImage()")}} to draw the current frame of the video into the context, filling the entire canvas with the frame image.

+ +
+

Note: This takes advantage of the fact that the {{domxref("HTMLVideoElement")}} interface looks like a {{domxref("HTMLImageElement")}} to any API that accepts an HTMLImageElement as a parameter, with the video's current frame presented as the image's contents.

+
+ +

Once the canvas contains the captured image, we convert it to PNG format by calling {{domxref("HTMLCanvasElement.toDataURL()")}} on it; finally, we call {{domxref("Element.setAttribute", "photo.setAttribute()")}} to make our captured still box display the image.

+ +

If there isn't a valid image available (that is, the width and height are both 0), we clear the contents of the captured frame box by calling clearphoto().

+ +

Fun with filters

+ +

Since we're capturing images from the user's webcam by grabbing frames from a {{HTMLElement("video")}} element, we can very easily apply filters and fun effects to the video. As it turns out, any CSS filters you apply to the element using the {{cssxref("filter")}} property affect the captured photo. These filters can range from the simple (making the image black and white)  to the extreme (gaussian blurs and hue rotation).

+ +

You can play with this effect using, for example, the Firefox developer tools' style editor; see Edit CSS filters for details on how to do so.

+ +

Consultar também

+ + diff --git "a/files/pt-pt/web/api/websockets_api/escrever_aplica\303\247\303\243o_cliente_de_websocket/index.html" "b/files/pt-pt/web/api/websockets_api/escrever_aplica\303\247\303\243o_cliente_de_websocket/index.html" deleted file mode 100644 index c66e10ceaf..0000000000 --- "a/files/pt-pt/web/api/websockets_api/escrever_aplica\303\247\303\243o_cliente_de_websocket/index.html" +++ /dev/null @@ -1,180 +0,0 @@ ---- -title: Escrever aplicação cliente de WebSocket -slug: Web/API/WebSockets_API/Escrever_aplicação_cliente_de_WebSocket -tags: - - Client - - Exemplo - - Guía - - Networking - - Web Sockets API - - WebSocket - - WebSocket API - - WebSockets -translation_of: Web/API/WebSockets_API/Writing_WebSocket_client_applications ---- -
{{APIRef("Websockets API")}}
- -

WebSocket client applications use the WebSocket API to communicate with WebSocket servers using the WebSocket protocol.

- -

{{AvailableInWorkers}}

- -
-

Note: The example snippets in this article are taken from our WebSocket chat client/server sample. See the code, then try out the example for yourself.

-
- -

Creating a WebSocket object

- -

In order to communicate using the WebSocket protocol, you need to create a {{domxref("WebSocket")}} object; this will automatically attempt to open the connection to the server.

- -

The WebSocket constructor accepts one required and one optional parameter:

- -
webSocket = new WebSocket(url, protocols);
-
- -
-
url
-
The URL to which to connect; this should be the URL to which the WebSocket server will respond. This should use the URL scheme wss://, although some software may allow you to use the insecure ws:// for local connections.
-
protocols {{ optional_inline() }}
-
Either a single protocol string or an array of protocol strings. These strings are used to indicate sub-protocols, so that a single server can implement multiple WebSocket sub-protocols (for example, you might want one server to be able to handle different types of interactions depending on the specified protocol). If you don't specify a protocol string, an empty string is assumed.
-
- -

The constructor will throw a SecurityError if the destination doesn't allow access. This may happen if you attempt to use an insecure connection (most {{Glossary("user agent", "user agents")}} now require a secure link for all WebSocket connections unless they're on the same device or possibly on the same network).

- -

Connection errors

- -

If an error occurs while attempting to connect, first a simple event with the name error is sent to the {{domxref("WebSocket")}} object (thereby invoking its {{domxref("WebSocket.onerror", "onerror")}} handler), and then the {{domxref("CloseEvent")}} is sent to the WebSocket object (thereby invoking its {{domxref("WebSocket.onclose", "onclose")}} handler) to indicate the reason for the connection's closing.

- -

The browser may also output to its console a more descriptive error message as well as a closing code as defined in RFC 6455, Section 7.4 through the {{domxref("CloseEvent")}}.

- -

Examples

- -

This simple example creates a new WebSocket, connecting to the server at wss://www.example.com/socketserver. A custom protocol of "protocolOne" is named in the request for the socket in this example, though this can be omitted.

- -
var exampleSocket = new WebSocket("wss://www.example.com/socketserver", "protocolOne");
-
- -

On return, {{domxref("WebSocket.readyState", "exampleSocket.readyState")}} is CONNECTING. The readyState will become OPEN once the connection is ready to transfer data.

- -

If you want to open a connection and are flexible about the protocols you support, you can specify an array of protocols:

- -
var exampleSocket = new WebSocket("wss://www.example.com/socketserver", ["protocolOne", "protocolTwo"]);
-
- -

Once the connection is established (that is, readyState is OPEN), {{domxref("WebSocket.protocol", "exampleSocket.protocol")}} will tell you which protocol the server selected.

- -

Establishing a WebSocket relies on the HTTP Upgrade mechanism, so the request for the protocol upgrade is implicit when we address the web server as ws://www.example.com or wss://www.example.com.

- -

Sending data to the server

- -

Once you've opened your connection, you can begin transmitting data to the server. To do this, simply call the WebSocket object's {{domxref("WebSocket.send", "send()")}} method for each message you want to send:

- -
exampleSocket.send("Here's some text that the server is urgently awaiting!");
-
- -

You can send data as a string, {{ domxref("Blob") }}, or {{jsxref("ArrayBuffer")}}.

- -

As establishing a connection is asynchronous and prone to failure there is no guarantee that calling the send() method immediately after creating a WebSocket object will be successful. We can at least be sure that attempting to send data only takes place once a connection is established by defining an {{domxref("WebSocket.onopen", "onopen")}} event handler to do the work:

- -
exampleSocket.onopen = function (event) {
-  exampleSocket.send("Here's some text that the server is urgently awaiting!");
-};
-
- -

Using JSON to transmit objects

- -

One handy thing you can do is use {{glossary("JSON")}} to send reasonably complex data to the server. For example, a chat program can interact with a server using a protocol implemented using packets of JSON-encapsulated data:

- -
// Send text to all users through the server
-function sendText() {
-  // Construct a msg object containing the data the server needs to process the message from the chat client.
-  var msg = {
-    type: "message",
-    text: document.getElementById("text").value,
-    id:   clientID,
-    date: Date.now()
-  };
-
-  // Send the msg object as a JSON-formatted string.
-  exampleSocket.send(JSON.stringify(msg));
-
-  // Blank the text input element, ready to receive the next line of text from the user.
-  document.getElementById("text").value = "";
-}
-
- -

Receiving messages from the server

- -

WebSockets is an event-driven API; when messages are received, a message event is sent to the WebSocket object. To handle it, add an event listener for the message event, or use the {{domxref("WebSocket.onmessage", "onmessage")}} event handler. To begin listening for incoming data, you can do something like this:

- -
exampleSocket.onmessage = function (event) {
-  console.log(event.data);
-}
-
- -

Receiving and interpreting JSON objects

- -

Let's consider the chat client application first alluded to in {{ anch("Using JSON to transmit objects") }}. There are assorted types of data packets the client might receive, such as:

- - - -

The code that interprets these incoming messages might look like this:

- -
exampleSocket.onmessage = function(event) {
-  var f = document.getElementById("chatbox").contentDocument;
-  var text = "";
-  var msg = JSON.parse(event.data);
-  var time = new Date(msg.date);
-  var timeStr = time.toLocaleTimeString();
-
-  switch(msg.type) {
-    case "id":
-      clientID = msg.id;
-      setUsername();
-      break;
-    case "username":
-      text = "<b>User <em>" + msg.name + "</em> signed in at " + timeStr + "</b><br>";
-      break;
-    case "message":
-      text = "(" + timeStr + ") <b>" + msg.name + "</b>: " + msg.text + "<br>";
-      break;
-    case "rejectusername":
-      text = "<b>Your username has been set to <em>" + msg.name + "</em> because the name you chose is in use.</b><br>"
-      break;
-    case "userlist":
-      var ul = "";
-      for (i=0; i < msg.users.length; i++) {
-        ul += msg.users[i] + "<br>";
-      }
-      document.getElementById("userlistbox").innerHTML = ul;
-      break;
-  }
-
-  if (text.length) {
-    f.write(text);
-    document.getElementById("chatbox").contentWindow.scrollByPages(1);
-  }
-};
-
- -

Here we use {{jsxref("JSON.parse()")}} to convert the JSON object back into the original object, then examine and act upon its contents.

- -

Text data format

- -

Text received over a WebSocket connection is in UTF-8 format.

- -

Closing the connection

- -

When you've finished using the WebSocket connection, call the WebSocket method {{domxref("WebSocket.close", "close()")}}:

- -
exampleSocket.close();
-
- -

It may be helpful to examine the socket's {{domxref("WebSocket.bufferedAmount", "bufferedAmount")}} attribute before attempting to close the connection to determine if any data has yet to be transmitted on the network. If this value isn't 0, there's pending data still, so you may wish to wait before closing the connection.

- -

Security considerations

- -

WebSockets should not be used in a mixed content environment; that is, you shouldn't open a non-secure WebSocket connection from a page loaded using HTTPS or vice-versa. Most browsers now only allow secure WebSocket connections, and no longer support using them in insecure contexts.

diff --git a/files/pt-pt/web/api/websockets_api/escrever_servidores_de_websocket/index.html b/files/pt-pt/web/api/websockets_api/escrever_servidores_de_websocket/index.html deleted file mode 100644 index 7f3b996573..0000000000 --- a/files/pt-pt/web/api/websockets_api/escrever_servidores_de_websocket/index.html +++ /dev/null @@ -1,257 +0,0 @@ ---- -title: Escrever servidores de WebSocket -slug: Web/API/WebSockets_API/Escrever_servidores_de_WebSocket -tags: - - Guía - - HTML5 - - Tutorial - - WebSocket - - WebSocket API - - WebSockets -translation_of: Web/API/WebSockets_API/Writing_WebSocket_servers ---- -
{{APIRef("Websockets API")}}
- -

Um servidor WebSocket não é nada mais que uma aplicação que escuta qualquer porta de um servidor TCP que possui um protocolo específico. A tarefa de criar um servidor personalizado é uma tarefa complexa para a maioria; no entanto, é simples implementar um servidor simples de WebSocket numa plataforma á sua escolha.

- -

Um servidor WebSocket pode ser escrito em qualquer linguagem de servidor que suporte Berkeley sockets, como C(++), Python, PHP, ou server-side JavaScript. Este tutorial não se foca em nenhuma linguagem em específico, mas serve como guia para facilitar o desenvolver do seu próprio server.

- -

A WebSocket server can be written in any server-side programming language that is capable of Berkeley sockets, such as C(++), Python, PHP, or server-side JavaScript. This is not a tutorial in any specific language, but serves as a guide to facilitate writing your own server.

- -

This article assumes you're already familiar with how {{Glossary("HTTP")}} works, and that you have a moderate level of programming experience. Depending on language support, knowledge of TCP sockets may be required. The scope of this guide is to present the minimum knowledge you need to write a WebSocket server.

- -
-

Note: Read the latest official WebSockets specification, RFC 6455. Sections 1 and 4-7 are especially interesting to server implementors. Section 10 discusses security and you should definitely peruse it before exposing your server.

-
- -

A WebSocket server is explained on a very low level here. WebSocket servers are often separate and specialized servers (for load-balancing or other practical reasons), so you will often use a reverse proxy (such as a regular HTTP server) to detect WebSocket handshakes, pre-process them, and send those clients to a real WebSocket server. This means that you don't have to bloat your server code with cookie and authentication handlers (for example).

- -

The WebSocket handshake

- -

First, the server must listen for incoming socket connections using a standard TCP socket. Depending on your platform, this may be handled for you automatically. For example, let's assume that your server is listening on example.com, port 8000, and your socket server responds to {{HTTPMethod("GET")}} requests at example.com/chat.

- -
-

Warning: The server may listen on any port it chooses, but if it chooses any port other than 80 or 443, it may have problems with firewalls and/or proxies. Browsers generally require a secure connection for WebSockets, although they may offer an exception for local devices.

-
- -

The handshake is the "Web" in WebSockets. It's the bridge from HTTP to WebSockets. In the handshake, details of the connection are negotiated, and either party can back out before completion if the terms are unfavorable. The server must be careful to understand everything the client asks for, otherwise security issues can occur.

- -
-

Tip: The request-uri (/chat here) has no defined meaning in the spec. So, many people  use it to let one server handle multiple WebSocket applications. For example, example.com/chat could invoke a multiuser chat app, while /game on the same server might invoke a multiplayer game.

-
- -

Client handshake request

- -

Even though you're building a server, a client still has to start the WebSocket handshake process by contacting the server and requesting a WebSocket connection. So, you must know how to interpret the client's request. The client will send a pretty standard HTTP request with headers that looks like this (the HTTP version must be 1.1 or greater, and the method must be GET):

- -
GET /chat HTTP/1.1
-Host: example.com:8000
-Upgrade: websocket
-Connection: Upgrade
-Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
-Sec-WebSocket-Version: 13
-
-
- -

The client can solicit extensions and/or subprotocols here; see Miscellaneous for details. Also, common headers like {{HTTPHeader("User-Agent")}}, {{HTTPHeader("Referer")}}, {{HTTPHeader("Cookie")}}, or authentication headers might be there as well. Do whatever you want with those; they don't directly pertain to the WebSocket. It's also safe to ignore them. In many common setups, a reverse proxy has already dealt with them.

- -
-

Tip: All browsers send an Origin header. You can use this header for security (checking for same origin, automatically allowing or denying, etc.) and send a 403 Forbidden if you don't like what you see. However, be warned that non-browser agents can send a faked Origin. Most applications reject requests without this header.

-
- -

If any header is not understood or has an incorrect value, the server should send a {{HTTPStatus("400")}} ("Bad Request")} response and immediately close the socket. As usual, it may also give the reason why the handshake failed in the HTTP response body, but the message may never be displayed (browsers do not display it). If the server doesn't understand that version of WebSockets, it should send a {{HTTPHeader("Sec-WebSocket-Version")}} header back that contains the version(s) it does understand.  In the example above, it indicates version 13 of the WebSocket protocol.

- -

The most interesting header here is {{HTTPHeader("Sec-WebSocket-Key")}}. Let's look at that next.

- -
-

Note: Regular HTTP status codes can be used only before the handshake. After the handshake succeeds, you have to use a different set of codes (defined in section 7.4 of the spec).

-
- -

Server handshake response

- -

When the server receives the handshake request, it should send back a special response that indicates that the protocol will be changing from HTTP to WebSocket. That header looks something like the following (remember each header line ends with \r\n and put an extra \r\n after the last one to indicate the end of the header):

- -
HTTP/1.1 101 Switching Protocols
-Upgrade: websocket
-Connection: Upgrade
-Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
-
-
- -

Additionally, the server can decide on extension/subprotocol requests here; see Miscellaneous for details. The Sec-WebSocket-Accept header is important in that the server must derive it from the {{HTTPHeader("Sec-WebSocket-Key")}} that the client sent to it. To get it, concatenate the client's Sec-WebSocket-Key and the string "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" together (it's a "magic string"), take the SHA-1 hash of the result, and return the base64 encoding of that hash.

- -
-

Note: This seemingly overcomplicated process exists so that it's obvious to the client whether the server supports WebSockets. This is important because security issues might arise if the server accepts a WebSockets connection but interprets the data as a HTTP request.

-
- -

So if the Key was "dGhlIHNhbXBsZSBub25jZQ==", the Sec-WebSocket-Accept header's value is "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=". Once the server sends these headers, the handshake is complete and you can start swapping data!

- -
-

Note: The server can send other headers like {{HTTPHeader("Set-Cookie")}}, or ask for authentication or redirects via other status codes, before sending the reply handshake.

-
- -

Keeping track of clients

- -

This doesn't directly relate to the WebSocket protocol, but it's worth mentioning here: your server must keep track of clients' sockets so you don't keep handshaking again with clients who have already completed the handshake. The same client IP address can try to connect multiple times. However, the server can deny them if they attempt too many connections in order to save itself from Denial-of-Service attacks.

- -

For example, you might keep a table of usernames or ID numbers along with the corresponding {{domxref("WebSocket")}} and other data that you need to associate with that connection.

- -

Exchanging data frames

- -

Either the client or the server can choose to send a message at any time — that's the magic of WebSockets. However, extracting information from these so-called "frames" of data is a not-so-magical experience. Although all frames follow the same specific format, data going from the client to the server is masked using XOR encryption (with a 32-bit key). Section 5 of the specification describes this in detail.

- -

Format

- -

Each data frame (from the client to the server or vice-versa) follows this same format:

- -
Frame format:
-​​
-      0                   1                   2                   3
-      0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
-     +-+-+-+-+-------+-+-------------+-------------------------------+
-     |F|R|R|R| opcode|M| Payload len |    Extended payload length    |
-     |I|S|S|S|  (4)  |A|     (7)     |             (16/64)           |
-     |N|V|V|V|       |S|             |   (if payload len==126/127)   |
-     | |1|2|3|       |K|             |                               |
-     +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
-     |     Extended payload length continued, if payload len == 127  |
-     + - - - - - - - - - - - - - - - +-------------------------------+
-     |                               |Masking-key, if MASK set to 1  |
-     +-------------------------------+-------------------------------+
-     | Masking-key (continued)       |          Payload Data         |
-     +-------------------------------- - - - - - - - - - - - - - - - +
-     :                     Payload Data continued ...                :
-     + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
-     |                     Payload Data continued ...                |
-     +---------------------------------------------------------------+
- -

The MASK bit tells whether the message is encoded. Messages from the client must be masked, so your server must expect this to be 1. (In fact, section 5.1 of the spec says that your server must disconnect from a client if that client sends an unmasked message.) When sending a frame back to the client, do not mask it and do not set the mask bit. We'll explain masking later. Note: You must mask messages even when using a secure socket. RSV1-3 can be ignored, they are for extensions.

- -

The opcode field defines how to interpret the payload data: 0x0 for continuation, 0x1 for text (which is always encoded in UTF-8), 0x2 for binary, and other so-called "control codes" that will be discussed later. In this version of WebSockets, 0x3 to 0x7 and 0xB to 0xF have no meaning.

- -

The FIN bit tells whether this is the last message in a series. If it's 0, then the server keeps listening for more parts of the message; otherwise, the server should consider the message delivered. More on this later.

- -

Decoding Payload Length

- -

To read the payload data, you must know when to stop reading. That's why the payload length is important to know. Unfortunately, this is somewhat complicated. To read it, follow these steps:

- -
    -
  1. Read bits 9-15 (inclusive) and interpret that as an unsigned integer. If it's 125 or less, then that's the length; you're done. If it's 126, go to step 2. If it's 127, go to step 3.
  2. -
  3. Read the next 16 bits and interpret those as an unsigned integer. You're done.
  4. -
  5. Read the next 64 bits and interpret those as an unsigned integer. (The most significant bit must be 0.) You're done.
  6. -
- -

Reading and Unmasking the Data

- -

If the MASK bit was set (and it should be, for client-to-server messages), read the next 4 octets (32 bits); this is the masking key. Once the payload length and masking key is decoded, you can read that number of bytes from the socket. Let's call the data ENCODED, and the key MASK. To get DECODED, loop through the octets (bytes a.k.a. characters for text data) of ENCODED and XOR the octet with the (i modulo 4)th octet of MASK. In pseudo-code (that happens to be valid JavaScript):

- -
var DECODED = "";
-for (var i = 0; i < ENCODED.length; i++) {
-    DECODED[i] = ENCODED[i] ^ MASK[i % 4];
-}
- -

Now you can figure out what DECODED means depending on your application.

- -

Message Fragmentation

- -

The FIN and opcode fields work together to send a message split up into separate frames.  This is called message fragmentation. Fragmentation is only available on opcodes 0x0 to 0x2.

- -

Recall that the opcode tells what a frame is meant to do. If it's 0x1, the payload is text. If it's 0x2, the payload is binary data. However, if it's 0x0, the frame is a continuation frame; this means the server should concatenate the frame's payload to the last frame it received from that client. Here is a rough sketch, in which a server reacts to a client sending text messages. The first message is sent in a single frame, while the second message is sent across three frames. FIN and opcode details are shown only for the client:

- -
Client: FIN=1, opcode=0x1, msg="hello"
-Server: (process complete message immediately) Hi.
-Client: FIN=0, opcode=0x1, msg="and a"
-Server: (listening, new message containing text started)
-Client: FIN=0, opcode=0x0, msg="happy new"
-Server: (listening, payload concatenated to previous message)
-Client: FIN=1, opcode=0x0, msg="year!"
-Server: (process complete message) Happy new year to you too!
- -

Notice the first frame contains an entire message (has FIN=1 and opcode!=0x0), so the server can process or respond as it sees fit. The second frame sent by the client has a text payload (opcode=0x1), but the entire message has not arrived yet (FIN=0). All remaining parts of that message are sent with continuation frames (opcode=0x0), and the final frame of the message is marked by FIN=1. Section 5.4 of the spec describes message fragmentation.

- -

Pings and Pongs: The Heartbeat of WebSockets

- -

At any point after the handshake, either the client or the server can choose to send a ping to the other party. When the ping is received, the recipient must send back a pong as soon as possible. You can use this to make sure that the client is still connected, for example.

- -

A ping or pong is just a regular frame, but it's a control frame. Pings have an opcode of 0x9, and pongs have an opcode of 0xA. When you get a ping, send back a pong with the exact same Payload Data as the ping (for pings and pongs, the max payload length is 125). You might also get a pong without ever sending a ping; ignore this if it happens.

- -
-

If you have gotten more than one ping before you get the chance to send a pong, you only send one pong.

-
- -

Closing the connection

- -

To close a connection either the client or server can send a control frame with data containing a specified control sequence to begin the closing handshake (detailed in Section 5.5.1). Upon receiving such a frame, the other peer sends a Close frame in response. The first peer then closes the connection. Any further data received after closing of connection is then discarded. 

- -

Miscellaneous

- -
-

WebSocket codes, extensions, subprotocols, etc. are registered at the IANA WebSocket Protocol Registry.

-
- -

WebSocket extensions and subprotocols are negotiated via headers during the handshake. Sometimes extensions and subprotocols very similar, but there is a clear distinction. Extensions control the WebSocket frame and modify the payload, while subprotocols structure the WebSocket payload and never modify anything. Extensions are optional and generalized (like compression); subprotocols are mandatory and localized (like ones for chat and for MMORPG games).

- -

Extensions

- -
-

This section needs expansion. Please edit if you are equipped to do so.

-
- -

Think of an extension as compressing a file before e-mailing it to someone. Whatever you do, you're sending the same data in different forms. The recipient will eventually be able to get the same data as your local copy, but it is sent differently. That's what an extension does. WebSockets defines a protocol and a simple way to send data, but an extension such as compression could allow sending the same data but in a shorter format.

- -
-

Extensions are explained in sections 5.8, 9, 11.3.2, and 11.4 of the spec.

-
- -

TODO

- -

Subprotocols

- -

Think of a subprotocol as a custom XML schema or doctype declaration. You're still using XML and its syntax, but you're additionally restricted by a structure you agreed on. WebSocket subprotocols are just like that. They do not introduce anything fancy, they just establish structure. Like a doctype or schema, both parties must agree on the subprotocol; unlike a doctype or schema, the subprotocol is implemented on the server and cannot be externally refered to by the client.

- -
-

Subprotocols are explained in sections 1.9, 4.2, 11.3.4, and 11.5 of the spec.

-
- -

A client has to ask for a specific subprotocol. To do so, it will send something like this as part of the original handshake:

- -
GET /chat HTTP/1.1
-...
-Sec-WebSocket-Protocol: soap, wamp
-
-
- -

or, equivalently:

- -
...
-Sec-WebSocket-Protocol: soap
-Sec-WebSocket-Protocol: wamp
-
-
- -

Now the server must pick one of the protocols that the client suggested and it supports. If there is more than one, send the first one the client sent. Imagine our server can use both soap and wamp. Then, in the response handshake, it sends:

- -
Sec-WebSocket-Protocol: soap
-
-
- -
-

The server can't send more than one Sec-Websocket-Protocol header.
- If the server doesn't want to use any subprotocol, it shouldn't send any Sec-WebSocket-Protocol header. Sending a blank header is incorrect. The client may close the connection if it doesn't get the subprotocol it wants.

-
- -

If you want your server to obey certain subprotocols, then naturally you'll need extra code on the server. Let's imagine we're using a subprotocol json. In this subprotocol, all data is passed as JSON. If the client solicits this protocol and the server wants to use it, the server needs to have a JSON parser. Practically speaking, this will be part of a library, but the server needs to pass the data around.

- -
-

Tip: To avoid name conflict, it's recommended to make your subprotocol name part of a domain string. If you are building a custom chat app that uses a proprietary format exclusive to Example Inc., then you might use this: Sec-WebSocket-Protocol: chat.example.com. Note that this isn't required, it's just an optional convention, and you can use any string you wish.

-
- - - - diff --git a/files/pt-pt/web/api/websockets_api/escrever_um_servidor_websocket_em_c/index.html b/files/pt-pt/web/api/websockets_api/escrever_um_servidor_websocket_em_c/index.html deleted file mode 100644 index a76f81d660..0000000000 --- a/files/pt-pt/web/api/websockets_api/escrever_um_servidor_websocket_em_c/index.html +++ /dev/null @@ -1,441 +0,0 @@ ---- -title: Escrever um servidor WebSocket em C# -slug: Web/API/WebSockets_API/Escrever_um_servidor_WebSocket_em_C -tags: - - HTML5 - - Tutorial - - WebSockets -translation_of: Web/API/WebSockets_API/Writing_WebSocket_server ---- -

Introdução

- -

Se desejar utilizar o WebSocket API, é útil dispor de um servidor. Neste artigo pode ver como escrever um em C#. Pode fazê-lo em qualquer língua do lado do servidor, mas para manter as coisas simples e mais compreensíveis, vamos usar a linguagem da Microsoft.

- -

Este servidor está em conformidade com o RFC 6455, pelo que só tratará de ligações a partir das versões de navegadores; Chrome 16, Firefox 11, e IE 10 ou superior.

- -

Primeiros passos

- -

Os WebSockets comunicam através de uma ligação interwiki("wikipedia","Transmission_Control_Protocol","TCP (Transmission Control Protocol)"). Felizmente, C# tem uma classe TcpListener que serve para escutar ligações de TCP. Encontra-se no espaço de nomes System.Net.Sockets.

- -
-

Nota: É aconselhável incluir o namespace com using a fim de escrever menos. Permite a utilização das classes de um namespace sem escrever sempre o namespace completo.

-
- -

TcpListener

- -

Construtor

- -
-
TcpListener(System.Net.IPAddress localaddr, int port)
-
localaddr indica o endereço IP do ouvinte e port indica a porta.
-
- -
-

Nota: Para criar um objeto IPAddress a partir de uma string, use o método static Parse de IPAddress.

-
- -

Métodos

- -
-
Start()
-
Começa a escutar os pedidos de ligação recebidos.
-
- -
-
AcceptTcpClient()
-
Espera por uma ligação TCP, aceita-a e devolve-a como um objeto TcpClient.
-
- -

Exemplo

- -

Aqui tem uma implementação básica do servidor:

- -
​using System.Net.Sockets;
-using System.Net;
-using System;
-
-class Server {
-    public static void Main() {
-        TcpListener server = new TcpListener(IPAddress.Parse("127.0.0.1"), 80);
-
-        server.Start();
-        Console.WriteLine("O servidor começou com endreço 127.0.0.1:80.{0}Esperando por uma conexão...", Environment.NewLine);
-
-        TcpClient client = server.AcceptTcpClient();
-
-        Console.WriteLine("Um cliente está conectado.");
-    }
-}
-
- -

TcpClient

- -

Métodos

- -
-
GetStream()
-
Obtém o stream que é o canal de comunicação. Ambos os lados do canal têm capacidade de leitura e escrita.
-
- -

Propriedades

- -
-
int Available
-
Esta propriedade indica quantos bytes de dados foram enviados. O valor é zero até que a propriedade NetworkStream.DataAvailable seja true.
-
- -

NetworkStream

- -

Métodos

- -
-
Write(Byte[] buffer, int offset, int size)
-
Escreve bytes vindos do buffer. offset e size determinam o comprimento da mensagem.
-
Read(Byte[] buffer, int offset, int size)
-
Lê bytes do buffer. offset e size determinam o comprimento da mensagem.
-
- -

Exemplo

- -

Vamos continuar o nosso exemplo:

- -
TcpClient client = server.AcceptTcpClient();
-
-Console.WriteLine("Um cliente está conectado.");
-
-NetworkStream stream = client.GetStream();
-
-// entrar num ciclo infinito para poder processar qualquer mudança no stream
-while (true) {
-    while (!stream.DataAvailable);
-
-    Byte[] bytes = new Byte[client.Available];
-
-    stream.Read(bytes, 0, bytes.Length);
-}
- -

Handshaking (aperto de mão)

- -

Quando um cliente se liga a um servidor, envia um pedido GET para atualizar a ligação do protocolo HTTP a uma ligação WebSocket. Isto é conhecido como aperto de mão.

- -

Este código de amostra pode detetar um GET do cliente. Note que isto irá bloquear até que os primeiros 3 bytes de uma mensagem estejam disponíveis. Deverão ser investigadas soluções alternativas para ambientes de produção.

- -
using System.Text;
-using System.Text.RegularExpressions;
-
-while(client.Available < 3)
-{
-   // esperar para que hajam bytes suficientes disponiveis
-}
-
-Byte[] bytes = new Byte[client.Available];
-
-stream.Read(bytes, 0, bytes.Length);
-
-//traduzir bytes do pedido para uma string
-String data = Encoding.UTF8.GetString(bytes);
-
-if (Regex.IsMatch(data, "^GET")) {
-
-} else {
-
-}
- -

A resposta é fácil de construir, mas pode ser um pouco difícil de compreender. A explicação completa do aperto de mão do servidor pode ser encontrada em RFC 6455, secção 4.2.2. Para os nossos propósitos, vamos apenas construir uma resposta simples.

- -

Deve:

- -
    -
  1. Obter o valor do cabeçalho de pedido da Sec-WebSocket-Key sem qualquer espaço em branco
  2. -
  3. Combine esse valor com "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" (um GUID especificado pela RFC 6455)
  4. -
  5. Calcule o código SHA-1 e Base64 do mesmo
  6. -
  7. Devolve-o como o valor do cabeçalho de resposta Sec-WebSocket-Accept numa resposta HTTP.
  8. -
- -

-if (new System.Text.RegularExpressions.Regex("^GET").IsMatch(data))
-{
-    const string eol = "\r\n"; // HTTP/1.1 define a sequencia "CR LF" como o marcador de fim de linha
-
-    Byte[] response = Encoding.UTF8.GetBytes("HTTP/1.1 101 Switching Protocols" + eol
-        + "Connection: Upgrade" + eol
-        + "Upgrade: websocket" + eol
-        + "Sec-WebSocket-Accept: " + Convert.ToBase64String(
-            System.Security.Cryptography.SHA1.Create().ComputeHash(
-                Encoding.UTF8.GetBytes(
-                    new System.Text.RegularExpressions.Regex("Sec-WebSocket-Key: (.*)").Match(data).Groups[1].Value.Trim() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
-                )
-            )
-        ) + eol
-        + eol);
-
-    stream.Write(response, 0, response.Length);
-}
-
- -

Descodificar mensagens

- -

Após um aperto de mão bem-sucedido, o cliente pode enviar mensagens para o servidor, mas agora estas estão codificadas.

- -

Se enviarmos "MDN", recebemos estes bytes:

- - - - - - - - - - - - - - - -
129131618435611216109
- -

Vejamos o que significam estes bytes.

- -

O primeiro byte, que tem actualmente um valor de 129, é um bitfield que se decompõe da seguinte forma:

- - - - - - - - - - - - - - - - - - - - -
FIN (Bit 0)RSV1 (Bit 1)RSV2 (Bit 2)RSV3 (Bit 3)Opcode (Bit 4:7)
10000x1=0001
- - - -

O segundo byte, que tem atualmente um valor de 131, é outro campo de bits que se decompõe assim:

- - - - - - - - - - - - - - -
MASK (Bit 0)Comprimento do conteúdo da mensagem (Bit 1:7)
10x83=0000011
- - - -
-

Porque o primeiro bit é sempre 1 para mensagens cliente-servidor, pode subtrair 128 deste byte para se livrar do bit MASK.

-
- -

Note que o bit MASK está definido na nossa mensagem. Isto significa que os quatro bytes seguintes (61, 84, 35, e 6) são os bytes de máscara utilizados para descodificar a mensagem. Estes bytes mudam com cada mensagem.

- -

Os restantes bytes são a payload da mensagem codificada.

- -

Algoritmo para descodificar

- -

Di = Ei XOR M(i mod 4)

- -

onde D é a série de bytes da mensagem descodificados, E é a série de bytes da mensagem codificados, M é a série de bytes da chave, e i é o índice do byte da mensagem a ser descodificado.

- -

Exemplo em C#:

- -
Byte[] decoded = new Byte[3];
-Byte[] encoded = new Byte[3] {112, 16, 109};
-Byte[] mask = new Byte[4] {61, 84, 35, 6};
-
-for (int i = 0; i < encoded.Length; i++) {
-    decoded[i] = (Byte)(encoded[i] ^ mask[i % 4]);
-}
- -

Exemplo completo

- -

Aqui tem o código, que foi explorado, na sua totalidade; isto inclui o código do cliente e do servidor.

- -

wsserver.cs

- -
//
-// csc wsserver.cs
-// wsserver.exe
-
-using System;
-using System.Net;
-using System.Net.Sockets;
-using System.Text;
-using System.Text.RegularExpressions;
-
-class Server {
-    public static void Main() {
-        string ip = "127.0.0.1";
-        int port = 80;
-        var server = new TcpListener(IPAddress.Parse(ip), port);
-
-        server.Start();
-        Console.WriteLine("Server has started on {0}:{1}, Waiting for a connection...", ip, port);
-
-        TcpClient client = server.AcceptTcpClient();
-        Console.WriteLine("A client connected.");
-
-        NetworkStream stream = client.GetStream();
-
-        // enter to an infinite cycle to be able to handle every change in stream
-        while (true) {
-            while (!stream.DataAvailable);
-            while (client.Available < 3); // match against "get"
-
-            byte[] bytes = new byte[client.Available];
-            stream.Read(bytes, 0, client.Available);
-            string s = Encoding.UTF8.GetString(bytes);
-
-            if (Regex.IsMatch(s, "^GET", RegexOptions.IgnoreCase)) {
-                Console.WriteLine("=====Handshaking from client=====\n{0}", s);
-
-                // 1. Obtain the value of the "Sec-WebSocket-Key" request header without any leading or trailing whitespace
-                // 2. Concatenate it with "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" (a special GUID specified by RFC 6455)
-                // 3. Compute SHA-1 and Base64 hash of the new value
-                // 4. Write the hash back as the value of "Sec-WebSocket-Accept" response header in an HTTP response
-                string swk = Regex.Match(s, "Sec-WebSocket-Key: (.*)").Groups[1].Value.Trim();
-                string swka = swk + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
-                byte[] swkaSha1 = System.Security.Cryptography.SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(swka));
-                string swkaSha1Base64 = Convert.ToBase64String(swkaSha1);
-
-                // HTTP/1.1 defines the sequence CR LF as the end-of-line marker
-                byte[] response = Encoding.UTF8.GetBytes(
-                    "HTTP/1.1 101 Switching Protocols\r\n" +
-                    "Connection: Upgrade\r\n" +
-                    "Upgrade: websocket\r\n" +
-                    "Sec-WebSocket-Accept: " + swkaSha1Base64 + "\r\n\r\n");
-
-                stream.Write(response, 0, response.Length);
-            } else {
-                bool fin = (bytes[0] & 0b10000000) != 0,
-                    mask = (bytes[1] & 0b10000000) != 0; // must be true, "All messages from the client to the server have this bit set"
-
-                int opcode = bytes[0] & 0b00001111, // expecting 1 - text message
-                    msglen = bytes[1] - 128, // & 0111 1111
-                    offset = 2;
-
-                if (msglen == 126) {
-                    // was ToUInt16(bytes, offset) but the result is incorrect
-                    msglen = BitConverter.ToUInt16(new byte[] { bytes[3], bytes[2] }, 0);
-                    offset = 4;
-                } else if (msglen == 127) {
-                    Console.WriteLine("TODO: msglen == 127, needs qword to store msglen");
-                    // i don't really know the byte order, please edit this
-                    // msglen = BitConverter.ToUInt64(new byte[] { bytes[5], bytes[4], bytes[3], bytes[2], bytes[9], bytes[8], bytes[7], bytes[6] }, 0);
-                    // offset = 10;
-                }
-
-                if (msglen == 0)
-                    Console.WriteLine("msglen == 0");
-                else if (mask) {
-                    byte[] decoded = new byte[msglen];
-                    byte[] masks = new byte[4] { bytes[offset], bytes[offset + 1], bytes[offset + 2], bytes[offset + 3] };
-                    offset += 4;
-
-                    for (int i = 0; i < msglen; ++i)
-                        decoded[i] = (byte)(bytes[offset + i] ^ masks[i % 4]);
-
-                    string text = Encoding.UTF8.GetString(decoded);
-                    Console.WriteLine("{0}", text);
-                } else
-                    Console.WriteLine("mask bit not set");
-
-                Console.WriteLine();
-            }
-        }
-    }
-}
- -

client.html

- -
<!doctype html>
-<style>
-    textarea { vertical-align: bottom; }
-    #output { overflow: auto; }
-    #output > p { overflow-wrap: break-word; }
-    #output span { color: blue; }
-    #output span.error { color: red; }
-</style>
-<h2>WebSocket Test</h2>
-<textarea cols=60 rows=6></textarea>
-<button>send</button>
-<div id=output></div>
-<script>
-    // http://www.websocket.org/echo.html
-
-    var button = document.querySelector("button"),
-        output = document.querySelector("#output"),
-        textarea = document.querySelector("textarea"),
-        // wsUri = "ws://echo.websocket.org/",
-        wsUri = "ws://127.0.0.1/",
-        websocket = new WebSocket(wsUri);
-
-    button.addEventListener("click", onClickButton);
-
-    websocket.onopen = function (e) {
-        writeToScreen("CONNECTED");
-        doSend("WebSocket rocks");
-    };
-
-    websocket.onclose = function (e) {
-        writeToScreen("DISCONNECTED");
-    };
-
-    websocket.onmessage = function (e) {
-        writeToScreen("<span>RESPONSE: " + e.data + "</span>");
-    };
-
-    websocket.onerror = function (e) {
-        writeToScreen("<span class=error>ERROR:</span> " + e.data);
-    };
-
-    function doSend(message) {
-        writeToScreen("SENT: " + message);
-        websocket.send(message);
-    }
-
-    function writeToScreen(message) {
-        output.insertAdjacentHTML("afterbegin", "<p>" + message + "</p>");
-    }
-
-    function onClickButton() {
-        var text = textarea.value;
-
-        text && doSend(text);
-        textarea.value = "";
-        textarea.focus();
-    }
-</script>
- -

Ver também

- - - -
 
diff --git a/files/pt-pt/web/api/websockets_api/escrever_um_servidor_websocket_em_java/index.html b/files/pt-pt/web/api/websockets_api/escrever_um_servidor_websocket_em_java/index.html deleted file mode 100644 index 4181a1cd37..0000000000 --- a/files/pt-pt/web/api/websockets_api/escrever_um_servidor_websocket_em_java/index.html +++ /dev/null @@ -1,220 +0,0 @@ ---- -title: Escrever um servidor WebSocket em Java -slug: Web/API/WebSockets_API/Escrever_um_servidor_WebSocket_em_Java -tags: - - HTML5 - - Handshaking - - Tutorial - - WebSockets -translation_of: Web/API/WebSockets_API/Writing_a_WebSocket_server_in_Java ---- -

Introdução

- -

Este exemplo mostra-lhe como criar um servidor com API de WebSocket utilizando Oracle Java.
-
- Embora outras linguagens do lado do servidor possam ser utilizadas para criar um servidor WebSocket, este exemplo utiliza Oracle Java para simplificar o código do exemplo.

- -

Este servidor está em conformidade com o RFC 6455, pelo que apenas trata de ligações a partir das seguintes versões dos navegadores; Chrome 16, Firefox 11, IE 10 e superior.

- -

Primeiros passos

- -

Os WebSockets comunicam através de uma ligação {{interwiki("wikipedia", "Transmission_Control_Protocol", "TCP (Transmission Control Protocol)")}}. A classe ServerSocket do Java está localizada no pacote java.net.

- -

ServerSocket

- -

Construtor

- -
-
ServerSocket(int port)
-
Quando se instância a classe ServerSocket, esta é ligada ao número da porta que se especificou pelo argumento port.
-
- Aqui está uma implementação dividida em partes:
-
- -
import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.ServerSocket;
-import java.net.Socket;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import java.util.Base64;
-import java.util.Scanner;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-public class WebSocket {
-	public static void main(String[] args) throws IOException, NoSuchAlgorithmException {
-		ServerSocket server = new ServerSocket(80);
-		try {
-			System.out.println("Server has started on 127.0.0.1:80.\r\nWaiting for a connection...");
-			Socket client = server.accept();
-			System.out.println("A client connected.");
- -

Socket

- -

Métodos

- -
-
getInputStream()
-
Devolve uma input stream para este socket.
-
getOutputStream()
-
Devolve uma output stream para este socket.
-
- -

OutputStream

- -

Métodos

- -
-
write(byte[] b, int off, int len)
-
Escreve o número de bytes especificado por len a partir da matriz de bytes especificada por b, começando no índice indicado por off para este output stream.
-
- -

InputStream

- -

Métodos

- -
-
read(byte[] b, int off, int len)
-
Lê até um número de bytes especificado por len da matriz de bytes especificada por b, começando no índice indicado por off para este input stream.
-
- -

Vamos continuar o nosso exemplo.

- -
			InputStream in = client.getInputStream();
-			OutputStream out = client.getOutputStream();
-			Scanner s = new Scanner(in, "UTF-8");
- -

Handshaking (aperto de mão)

- -

Quando um cliente se liga a um servidor, envia um pedido GET para actualizar a ligação do protocolo HTTP a uma ligação WebSocket. Isto é conhecido como aperto de mão.

- -
			try {
-				String data = s.useDelimiter("\\r\\n\\r\\n").next();
-				Matcher get = Pattern.compile("^GET").matcher(data);
- -

Criar a resposta é mais fácil do que compreender porque o deve fazer desta forma.

- -

Você deve,

- -
    -
  1. Obter o valor do cabeçalho de pedido da Sec-WebSocket-Key sem qualquer espaço em branco
  2. -
  3. Combine esse valor com "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
  4. -
  5. Calcule o código SHA-1 e Base64 do mesmo
  6. -
  7. Devolve-o como o valor do cabeçalho de resposta Sec-WebSocket-Accept numa resposta HTTP.
  8. -
- -
				if (get.find()) {
-					Matcher match = Pattern.compile("Sec-WebSocket-Key: (.*)").matcher(data);
-					match.find();
-					byte[] response = ("HTTP/1.1 101 Switching Protocols\r\n"
-						+ "Connection: Upgrade\r\n"
-						+ "Upgrade: websocket\r\n"
-						+ "Sec-WebSocket-Accept: "
-						+ Base64.getEncoder().encodeToString(MessageDigest.getInstance("SHA-1").digest((match.group(1) + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").getBytes("UTF-8")))
-						+ "\r\n\r\n").getBytes("UTF-8");
-					out.write(response, 0, response.length);
-
- -

Descodificar mensagens

- -

Após um aperto de mão bem-sucedido, o cliente pode enviar mensagens para o servidor, mas agora estas estão codificadas.
-
- Se enviarmos "abcdef", recebemos estes bytes:

- - - - - - - - - - - - - - - - - - -
129134167225225210198131130182194135
- -

129 (FIN, RSV1, RSV2, RSV3, opcode)

- -

Pode enviar a sua mensagem em fragmentos, mas por enquanto o FIN é 1 indicando que a mensagem está toda num fragmento. RSV1, RSV2 e RSV3 são sempre 0, a não ser que um significado para os bytes é negociado. Opcode 0x1 significa que isto é um texto (ver lista completa de opcodes).

- - - - - - - - - - - - - - - - - - - - -
FIN (É o último fragmento da mensagem?)RSV1RSV2RSV3Opcode
10000x1=0001
- -

134 (comprimento da mensagem)

- -

O comprimento da mensagem é indicada das seguintes formas:

- - - -

167, 225, 225 e 210 (chave para descodificar)

- -

Estes são os bytes da chave para descodificar. A chave muda para cada mensagem.

- -

198, 131, 130, 182, 194, 135 (conteúdo da mensagem)

- -

Os restantes bytes codificados são a mensagem.

- -

Algoritmo para descodificar

- -

O algoritmo usado para descodificar a mensagem é o seguinte:

- -

Di = Ei XOR M(i mod 4)

- -

onde D é a série de bytes da mensagem descodificados, E é a série de bytes da mensagem codificados, M é a série de bytes da chave, e i é o índice do byte da mensagem a ser descodificado.

- -

Exemplo em Java:

- -
					byte[] decoded = new byte[6];
-					byte[] encoded = new byte[] { (byte) 198, (byte) 131, (byte) 130, (byte) 182, (byte) 194, (byte) 135 };
-					byte[] key = new byte[] { (byte) 167, (byte) 225, (byte) 225, (byte) 210 };
-					for (int i = 0; i < encoded.length; i++) {
-						decoded[i] = (byte) (encoded[i] ^ key[i & 0x3]);
-					}
-				}
-			} finally {
-				s.close();
-			}
-		} finally {
-			server.close();
-		}
-	}
-}
- -

Ver também

- - - -
diff --git a/files/pt-pt/web/api/websockets_api/writing_a_websocket_server_in_java/index.html b/files/pt-pt/web/api/websockets_api/writing_a_websocket_server_in_java/index.html new file mode 100644 index 0000000000..4181a1cd37 --- /dev/null +++ b/files/pt-pt/web/api/websockets_api/writing_a_websocket_server_in_java/index.html @@ -0,0 +1,220 @@ +--- +title: Escrever um servidor WebSocket em Java +slug: Web/API/WebSockets_API/Escrever_um_servidor_WebSocket_em_Java +tags: + - HTML5 + - Handshaking + - Tutorial + - WebSockets +translation_of: Web/API/WebSockets_API/Writing_a_WebSocket_server_in_Java +--- +

Introdução

+ +

Este exemplo mostra-lhe como criar um servidor com API de WebSocket utilizando Oracle Java.
+
+ Embora outras linguagens do lado do servidor possam ser utilizadas para criar um servidor WebSocket, este exemplo utiliza Oracle Java para simplificar o código do exemplo.

+ +

Este servidor está em conformidade com o RFC 6455, pelo que apenas trata de ligações a partir das seguintes versões dos navegadores; Chrome 16, Firefox 11, IE 10 e superior.

+ +

Primeiros passos

+ +

Os WebSockets comunicam através de uma ligação {{interwiki("wikipedia", "Transmission_Control_Protocol", "TCP (Transmission Control Protocol)")}}. A classe ServerSocket do Java está localizada no pacote java.net.

+ +

ServerSocket

+ +

Construtor

+ +
+
ServerSocket(int port)
+
Quando se instância a classe ServerSocket, esta é ligada ao número da porta que se especificou pelo argumento port.
+
+ Aqui está uma implementação dividida em partes:
+
+ +
import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.Base64;
+import java.util.Scanner;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public class WebSocket {
+	public static void main(String[] args) throws IOException, NoSuchAlgorithmException {
+		ServerSocket server = new ServerSocket(80);
+		try {
+			System.out.println("Server has started on 127.0.0.1:80.\r\nWaiting for a connection...");
+			Socket client = server.accept();
+			System.out.println("A client connected.");
+ +

Socket

+ +

Métodos

+ +
+
getInputStream()
+
Devolve uma input stream para este socket.
+
getOutputStream()
+
Devolve uma output stream para este socket.
+
+ +

OutputStream

+ +

Métodos

+ +
+
write(byte[] b, int off, int len)
+
Escreve o número de bytes especificado por len a partir da matriz de bytes especificada por b, começando no índice indicado por off para este output stream.
+
+ +

InputStream

+ +

Métodos

+ +
+
read(byte[] b, int off, int len)
+
Lê até um número de bytes especificado por len da matriz de bytes especificada por b, começando no índice indicado por off para este input stream.
+
+ +

Vamos continuar o nosso exemplo.

+ +
			InputStream in = client.getInputStream();
+			OutputStream out = client.getOutputStream();
+			Scanner s = new Scanner(in, "UTF-8");
+ +

Handshaking (aperto de mão)

+ +

Quando um cliente se liga a um servidor, envia um pedido GET para actualizar a ligação do protocolo HTTP a uma ligação WebSocket. Isto é conhecido como aperto de mão.

+ +
			try {
+				String data = s.useDelimiter("\\r\\n\\r\\n").next();
+				Matcher get = Pattern.compile("^GET").matcher(data);
+ +

Criar a resposta é mais fácil do que compreender porque o deve fazer desta forma.

+ +

Você deve,

+ +
    +
  1. Obter o valor do cabeçalho de pedido da Sec-WebSocket-Key sem qualquer espaço em branco
  2. +
  3. Combine esse valor com "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
  4. +
  5. Calcule o código SHA-1 e Base64 do mesmo
  6. +
  7. Devolve-o como o valor do cabeçalho de resposta Sec-WebSocket-Accept numa resposta HTTP.
  8. +
+ +
				if (get.find()) {
+					Matcher match = Pattern.compile("Sec-WebSocket-Key: (.*)").matcher(data);
+					match.find();
+					byte[] response = ("HTTP/1.1 101 Switching Protocols\r\n"
+						+ "Connection: Upgrade\r\n"
+						+ "Upgrade: websocket\r\n"
+						+ "Sec-WebSocket-Accept: "
+						+ Base64.getEncoder().encodeToString(MessageDigest.getInstance("SHA-1").digest((match.group(1) + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").getBytes("UTF-8")))
+						+ "\r\n\r\n").getBytes("UTF-8");
+					out.write(response, 0, response.length);
+
+ +

Descodificar mensagens

+ +

Após um aperto de mão bem-sucedido, o cliente pode enviar mensagens para o servidor, mas agora estas estão codificadas.
+
+ Se enviarmos "abcdef", recebemos estes bytes:

+ + + + + + + + + + + + + + + + + + +
129134167225225210198131130182194135
+ +

129 (FIN, RSV1, RSV2, RSV3, opcode)

+ +

Pode enviar a sua mensagem em fragmentos, mas por enquanto o FIN é 1 indicando que a mensagem está toda num fragmento. RSV1, RSV2 e RSV3 são sempre 0, a não ser que um significado para os bytes é negociado. Opcode 0x1 significa que isto é um texto (ver lista completa de opcodes).

+ + + + + + + + + + + + + + + + + + + + +
FIN (É o último fragmento da mensagem?)RSV1RSV2RSV3Opcode
10000x1=0001
+ +

134 (comprimento da mensagem)

+ +

O comprimento da mensagem é indicada das seguintes formas:

+ + + +

167, 225, 225 e 210 (chave para descodificar)

+ +

Estes são os bytes da chave para descodificar. A chave muda para cada mensagem.

+ +

198, 131, 130, 182, 194, 135 (conteúdo da mensagem)

+ +

Os restantes bytes codificados são a mensagem.

+ +

Algoritmo para descodificar

+ +

O algoritmo usado para descodificar a mensagem é o seguinte:

+ +

Di = Ei XOR M(i mod 4)

+ +

onde D é a série de bytes da mensagem descodificados, E é a série de bytes da mensagem codificados, M é a série de bytes da chave, e i é o índice do byte da mensagem a ser descodificado.

+ +

Exemplo em Java:

+ +
					byte[] decoded = new byte[6];
+					byte[] encoded = new byte[] { (byte) 198, (byte) 131, (byte) 130, (byte) 182, (byte) 194, (byte) 135 };
+					byte[] key = new byte[] { (byte) 167, (byte) 225, (byte) 225, (byte) 210 };
+					for (int i = 0; i < encoded.length; i++) {
+						decoded[i] = (byte) (encoded[i] ^ key[i & 0x3]);
+					}
+				}
+			} finally {
+				s.close();
+			}
+		} finally {
+			server.close();
+		}
+	}
+}
+ +

Ver também

+ + + +
diff --git a/files/pt-pt/web/api/websockets_api/writing_websocket_client_applications/index.html b/files/pt-pt/web/api/websockets_api/writing_websocket_client_applications/index.html new file mode 100644 index 0000000000..c66e10ceaf --- /dev/null +++ b/files/pt-pt/web/api/websockets_api/writing_websocket_client_applications/index.html @@ -0,0 +1,180 @@ +--- +title: Escrever aplicação cliente de WebSocket +slug: Web/API/WebSockets_API/Escrever_aplicação_cliente_de_WebSocket +tags: + - Client + - Exemplo + - Guía + - Networking + - Web Sockets API + - WebSocket + - WebSocket API + - WebSockets +translation_of: Web/API/WebSockets_API/Writing_WebSocket_client_applications +--- +
{{APIRef("Websockets API")}}
+ +

WebSocket client applications use the WebSocket API to communicate with WebSocket servers using the WebSocket protocol.

+ +

{{AvailableInWorkers}}

+ +
+

Note: The example snippets in this article are taken from our WebSocket chat client/server sample. See the code, then try out the example for yourself.

+
+ +

Creating a WebSocket object

+ +

In order to communicate using the WebSocket protocol, you need to create a {{domxref("WebSocket")}} object; this will automatically attempt to open the connection to the server.

+ +

The WebSocket constructor accepts one required and one optional parameter:

+ +
webSocket = new WebSocket(url, protocols);
+
+ +
+
url
+
The URL to which to connect; this should be the URL to which the WebSocket server will respond. This should use the URL scheme wss://, although some software may allow you to use the insecure ws:// for local connections.
+
protocols {{ optional_inline() }}
+
Either a single protocol string or an array of protocol strings. These strings are used to indicate sub-protocols, so that a single server can implement multiple WebSocket sub-protocols (for example, you might want one server to be able to handle different types of interactions depending on the specified protocol). If you don't specify a protocol string, an empty string is assumed.
+
+ +

The constructor will throw a SecurityError if the destination doesn't allow access. This may happen if you attempt to use an insecure connection (most {{Glossary("user agent", "user agents")}} now require a secure link for all WebSocket connections unless they're on the same device or possibly on the same network).

+ +

Connection errors

+ +

If an error occurs while attempting to connect, first a simple event with the name error is sent to the {{domxref("WebSocket")}} object (thereby invoking its {{domxref("WebSocket.onerror", "onerror")}} handler), and then the {{domxref("CloseEvent")}} is sent to the WebSocket object (thereby invoking its {{domxref("WebSocket.onclose", "onclose")}} handler) to indicate the reason for the connection's closing.

+ +

The browser may also output to its console a more descriptive error message as well as a closing code as defined in RFC 6455, Section 7.4 through the {{domxref("CloseEvent")}}.

+ +

Examples

+ +

This simple example creates a new WebSocket, connecting to the server at wss://www.example.com/socketserver. A custom protocol of "protocolOne" is named in the request for the socket in this example, though this can be omitted.

+ +
var exampleSocket = new WebSocket("wss://www.example.com/socketserver", "protocolOne");
+
+ +

On return, {{domxref("WebSocket.readyState", "exampleSocket.readyState")}} is CONNECTING. The readyState will become OPEN once the connection is ready to transfer data.

+ +

If you want to open a connection and are flexible about the protocols you support, you can specify an array of protocols:

+ +
var exampleSocket = new WebSocket("wss://www.example.com/socketserver", ["protocolOne", "protocolTwo"]);
+
+ +

Once the connection is established (that is, readyState is OPEN), {{domxref("WebSocket.protocol", "exampleSocket.protocol")}} will tell you which protocol the server selected.

+ +

Establishing a WebSocket relies on the HTTP Upgrade mechanism, so the request for the protocol upgrade is implicit when we address the web server as ws://www.example.com or wss://www.example.com.

+ +

Sending data to the server

+ +

Once you've opened your connection, you can begin transmitting data to the server. To do this, simply call the WebSocket object's {{domxref("WebSocket.send", "send()")}} method for each message you want to send:

+ +
exampleSocket.send("Here's some text that the server is urgently awaiting!");
+
+ +

You can send data as a string, {{ domxref("Blob") }}, or {{jsxref("ArrayBuffer")}}.

+ +

As establishing a connection is asynchronous and prone to failure there is no guarantee that calling the send() method immediately after creating a WebSocket object will be successful. We can at least be sure that attempting to send data only takes place once a connection is established by defining an {{domxref("WebSocket.onopen", "onopen")}} event handler to do the work:

+ +
exampleSocket.onopen = function (event) {
+  exampleSocket.send("Here's some text that the server is urgently awaiting!");
+};
+
+ +

Using JSON to transmit objects

+ +

One handy thing you can do is use {{glossary("JSON")}} to send reasonably complex data to the server. For example, a chat program can interact with a server using a protocol implemented using packets of JSON-encapsulated data:

+ +
// Send text to all users through the server
+function sendText() {
+  // Construct a msg object containing the data the server needs to process the message from the chat client.
+  var msg = {
+    type: "message",
+    text: document.getElementById("text").value,
+    id:   clientID,
+    date: Date.now()
+  };
+
+  // Send the msg object as a JSON-formatted string.
+  exampleSocket.send(JSON.stringify(msg));
+
+  // Blank the text input element, ready to receive the next line of text from the user.
+  document.getElementById("text").value = "";
+}
+
+ +

Receiving messages from the server

+ +

WebSockets is an event-driven API; when messages are received, a message event is sent to the WebSocket object. To handle it, add an event listener for the message event, or use the {{domxref("WebSocket.onmessage", "onmessage")}} event handler. To begin listening for incoming data, you can do something like this:

+ +
exampleSocket.onmessage = function (event) {
+  console.log(event.data);
+}
+
+ +

Receiving and interpreting JSON objects

+ +

Let's consider the chat client application first alluded to in {{ anch("Using JSON to transmit objects") }}. There are assorted types of data packets the client might receive, such as:

+ + + +

The code that interprets these incoming messages might look like this:

+ +
exampleSocket.onmessage = function(event) {
+  var f = document.getElementById("chatbox").contentDocument;
+  var text = "";
+  var msg = JSON.parse(event.data);
+  var time = new Date(msg.date);
+  var timeStr = time.toLocaleTimeString();
+
+  switch(msg.type) {
+    case "id":
+      clientID = msg.id;
+      setUsername();
+      break;
+    case "username":
+      text = "<b>User <em>" + msg.name + "</em> signed in at " + timeStr + "</b><br>";
+      break;
+    case "message":
+      text = "(" + timeStr + ") <b>" + msg.name + "</b>: " + msg.text + "<br>";
+      break;
+    case "rejectusername":
+      text = "<b>Your username has been set to <em>" + msg.name + "</em> because the name you chose is in use.</b><br>"
+      break;
+    case "userlist":
+      var ul = "";
+      for (i=0; i < msg.users.length; i++) {
+        ul += msg.users[i] + "<br>";
+      }
+      document.getElementById("userlistbox").innerHTML = ul;
+      break;
+  }
+
+  if (text.length) {
+    f.write(text);
+    document.getElementById("chatbox").contentWindow.scrollByPages(1);
+  }
+};
+
+ +

Here we use {{jsxref("JSON.parse()")}} to convert the JSON object back into the original object, then examine and act upon its contents.

+ +

Text data format

+ +

Text received over a WebSocket connection is in UTF-8 format.

+ +

Closing the connection

+ +

When you've finished using the WebSocket connection, call the WebSocket method {{domxref("WebSocket.close", "close()")}}:

+ +
exampleSocket.close();
+
+ +

It may be helpful to examine the socket's {{domxref("WebSocket.bufferedAmount", "bufferedAmount")}} attribute before attempting to close the connection to determine if any data has yet to be transmitted on the network. If this value isn't 0, there's pending data still, so you may wish to wait before closing the connection.

+ +

Security considerations

+ +

WebSockets should not be used in a mixed content environment; that is, you shouldn't open a non-secure WebSocket connection from a page loaded using HTTPS or vice-versa. Most browsers now only allow secure WebSocket connections, and no longer support using them in insecure contexts.

diff --git a/files/pt-pt/web/api/websockets_api/writing_websocket_server/index.html b/files/pt-pt/web/api/websockets_api/writing_websocket_server/index.html new file mode 100644 index 0000000000..a76f81d660 --- /dev/null +++ b/files/pt-pt/web/api/websockets_api/writing_websocket_server/index.html @@ -0,0 +1,441 @@ +--- +title: Escrever um servidor WebSocket em C# +slug: Web/API/WebSockets_API/Escrever_um_servidor_WebSocket_em_C +tags: + - HTML5 + - Tutorial + - WebSockets +translation_of: Web/API/WebSockets_API/Writing_WebSocket_server +--- +

Introdução

+ +

Se desejar utilizar o WebSocket API, é útil dispor de um servidor. Neste artigo pode ver como escrever um em C#. Pode fazê-lo em qualquer língua do lado do servidor, mas para manter as coisas simples e mais compreensíveis, vamos usar a linguagem da Microsoft.

+ +

Este servidor está em conformidade com o RFC 6455, pelo que só tratará de ligações a partir das versões de navegadores; Chrome 16, Firefox 11, e IE 10 ou superior.

+ +

Primeiros passos

+ +

Os WebSockets comunicam através de uma ligação interwiki("wikipedia","Transmission_Control_Protocol","TCP (Transmission Control Protocol)"). Felizmente, C# tem uma classe TcpListener que serve para escutar ligações de TCP. Encontra-se no espaço de nomes System.Net.Sockets.

+ +
+

Nota: É aconselhável incluir o namespace com using a fim de escrever menos. Permite a utilização das classes de um namespace sem escrever sempre o namespace completo.

+
+ +

TcpListener

+ +

Construtor

+ +
+
TcpListener(System.Net.IPAddress localaddr, int port)
+
localaddr indica o endereço IP do ouvinte e port indica a porta.
+
+ +
+

Nota: Para criar um objeto IPAddress a partir de uma string, use o método static Parse de IPAddress.

+
+ +

Métodos

+ +
+
Start()
+
Começa a escutar os pedidos de ligação recebidos.
+
+ +
+
AcceptTcpClient()
+
Espera por uma ligação TCP, aceita-a e devolve-a como um objeto TcpClient.
+
+ +

Exemplo

+ +

Aqui tem uma implementação básica do servidor:

+ +
​using System.Net.Sockets;
+using System.Net;
+using System;
+
+class Server {
+    public static void Main() {
+        TcpListener server = new TcpListener(IPAddress.Parse("127.0.0.1"), 80);
+
+        server.Start();
+        Console.WriteLine("O servidor começou com endreço 127.0.0.1:80.{0}Esperando por uma conexão...", Environment.NewLine);
+
+        TcpClient client = server.AcceptTcpClient();
+
+        Console.WriteLine("Um cliente está conectado.");
+    }
+}
+
+ +

TcpClient

+ +

Métodos

+ +
+
GetStream()
+
Obtém o stream que é o canal de comunicação. Ambos os lados do canal têm capacidade de leitura e escrita.
+
+ +

Propriedades

+ +
+
int Available
+
Esta propriedade indica quantos bytes de dados foram enviados. O valor é zero até que a propriedade NetworkStream.DataAvailable seja true.
+
+ +

NetworkStream

+ +

Métodos

+ +
+
Write(Byte[] buffer, int offset, int size)
+
Escreve bytes vindos do buffer. offset e size determinam o comprimento da mensagem.
+
Read(Byte[] buffer, int offset, int size)
+
Lê bytes do buffer. offset e size determinam o comprimento da mensagem.
+
+ +

Exemplo

+ +

Vamos continuar o nosso exemplo:

+ +
TcpClient client = server.AcceptTcpClient();
+
+Console.WriteLine("Um cliente está conectado.");
+
+NetworkStream stream = client.GetStream();
+
+// entrar num ciclo infinito para poder processar qualquer mudança no stream
+while (true) {
+    while (!stream.DataAvailable);
+
+    Byte[] bytes = new Byte[client.Available];
+
+    stream.Read(bytes, 0, bytes.Length);
+}
+ +

Handshaking (aperto de mão)

+ +

Quando um cliente se liga a um servidor, envia um pedido GET para atualizar a ligação do protocolo HTTP a uma ligação WebSocket. Isto é conhecido como aperto de mão.

+ +

Este código de amostra pode detetar um GET do cliente. Note que isto irá bloquear até que os primeiros 3 bytes de uma mensagem estejam disponíveis. Deverão ser investigadas soluções alternativas para ambientes de produção.

+ +
using System.Text;
+using System.Text.RegularExpressions;
+
+while(client.Available < 3)
+{
+   // esperar para que hajam bytes suficientes disponiveis
+}
+
+Byte[] bytes = new Byte[client.Available];
+
+stream.Read(bytes, 0, bytes.Length);
+
+//traduzir bytes do pedido para uma string
+String data = Encoding.UTF8.GetString(bytes);
+
+if (Regex.IsMatch(data, "^GET")) {
+
+} else {
+
+}
+ +

A resposta é fácil de construir, mas pode ser um pouco difícil de compreender. A explicação completa do aperto de mão do servidor pode ser encontrada em RFC 6455, secção 4.2.2. Para os nossos propósitos, vamos apenas construir uma resposta simples.

+ +

Deve:

+ +
    +
  1. Obter o valor do cabeçalho de pedido da Sec-WebSocket-Key sem qualquer espaço em branco
  2. +
  3. Combine esse valor com "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" (um GUID especificado pela RFC 6455)
  4. +
  5. Calcule o código SHA-1 e Base64 do mesmo
  6. +
  7. Devolve-o como o valor do cabeçalho de resposta Sec-WebSocket-Accept numa resposta HTTP.
  8. +
+ +

+if (new System.Text.RegularExpressions.Regex("^GET").IsMatch(data))
+{
+    const string eol = "\r\n"; // HTTP/1.1 define a sequencia "CR LF" como o marcador de fim de linha
+
+    Byte[] response = Encoding.UTF8.GetBytes("HTTP/1.1 101 Switching Protocols" + eol
+        + "Connection: Upgrade" + eol
+        + "Upgrade: websocket" + eol
+        + "Sec-WebSocket-Accept: " + Convert.ToBase64String(
+            System.Security.Cryptography.SHA1.Create().ComputeHash(
+                Encoding.UTF8.GetBytes(
+                    new System.Text.RegularExpressions.Regex("Sec-WebSocket-Key: (.*)").Match(data).Groups[1].Value.Trim() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
+                )
+            )
+        ) + eol
+        + eol);
+
+    stream.Write(response, 0, response.Length);
+}
+
+ +

Descodificar mensagens

+ +

Após um aperto de mão bem-sucedido, o cliente pode enviar mensagens para o servidor, mas agora estas estão codificadas.

+ +

Se enviarmos "MDN", recebemos estes bytes:

+ + + + + + + + + + + + + + + +
129131618435611216109
+ +

Vejamos o que significam estes bytes.

+ +

O primeiro byte, que tem actualmente um valor de 129, é um bitfield que se decompõe da seguinte forma:

+ + + + + + + + + + + + + + + + + + + + +
FIN (Bit 0)RSV1 (Bit 1)RSV2 (Bit 2)RSV3 (Bit 3)Opcode (Bit 4:7)
10000x1=0001
+ + + +

O segundo byte, que tem atualmente um valor de 131, é outro campo de bits que se decompõe assim:

+ + + + + + + + + + + + + + +
MASK (Bit 0)Comprimento do conteúdo da mensagem (Bit 1:7)
10x83=0000011
+ + + +
+

Porque o primeiro bit é sempre 1 para mensagens cliente-servidor, pode subtrair 128 deste byte para se livrar do bit MASK.

+
+ +

Note que o bit MASK está definido na nossa mensagem. Isto significa que os quatro bytes seguintes (61, 84, 35, e 6) são os bytes de máscara utilizados para descodificar a mensagem. Estes bytes mudam com cada mensagem.

+ +

Os restantes bytes são a payload da mensagem codificada.

+ +

Algoritmo para descodificar

+ +

Di = Ei XOR M(i mod 4)

+ +

onde D é a série de bytes da mensagem descodificados, E é a série de bytes da mensagem codificados, M é a série de bytes da chave, e i é o índice do byte da mensagem a ser descodificado.

+ +

Exemplo em C#:

+ +
Byte[] decoded = new Byte[3];
+Byte[] encoded = new Byte[3] {112, 16, 109};
+Byte[] mask = new Byte[4] {61, 84, 35, 6};
+
+for (int i = 0; i < encoded.Length; i++) {
+    decoded[i] = (Byte)(encoded[i] ^ mask[i % 4]);
+}
+ +

Exemplo completo

+ +

Aqui tem o código, que foi explorado, na sua totalidade; isto inclui o código do cliente e do servidor.

+ +

wsserver.cs

+ +
//
+// csc wsserver.cs
+// wsserver.exe
+
+using System;
+using System.Net;
+using System.Net.Sockets;
+using System.Text;
+using System.Text.RegularExpressions;
+
+class Server {
+    public static void Main() {
+        string ip = "127.0.0.1";
+        int port = 80;
+        var server = new TcpListener(IPAddress.Parse(ip), port);
+
+        server.Start();
+        Console.WriteLine("Server has started on {0}:{1}, Waiting for a connection...", ip, port);
+
+        TcpClient client = server.AcceptTcpClient();
+        Console.WriteLine("A client connected.");
+
+        NetworkStream stream = client.GetStream();
+
+        // enter to an infinite cycle to be able to handle every change in stream
+        while (true) {
+            while (!stream.DataAvailable);
+            while (client.Available < 3); // match against "get"
+
+            byte[] bytes = new byte[client.Available];
+            stream.Read(bytes, 0, client.Available);
+            string s = Encoding.UTF8.GetString(bytes);
+
+            if (Regex.IsMatch(s, "^GET", RegexOptions.IgnoreCase)) {
+                Console.WriteLine("=====Handshaking from client=====\n{0}", s);
+
+                // 1. Obtain the value of the "Sec-WebSocket-Key" request header without any leading or trailing whitespace
+                // 2. Concatenate it with "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" (a special GUID specified by RFC 6455)
+                // 3. Compute SHA-1 and Base64 hash of the new value
+                // 4. Write the hash back as the value of "Sec-WebSocket-Accept" response header in an HTTP response
+                string swk = Regex.Match(s, "Sec-WebSocket-Key: (.*)").Groups[1].Value.Trim();
+                string swka = swk + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
+                byte[] swkaSha1 = System.Security.Cryptography.SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(swka));
+                string swkaSha1Base64 = Convert.ToBase64String(swkaSha1);
+
+                // HTTP/1.1 defines the sequence CR LF as the end-of-line marker
+                byte[] response = Encoding.UTF8.GetBytes(
+                    "HTTP/1.1 101 Switching Protocols\r\n" +
+                    "Connection: Upgrade\r\n" +
+                    "Upgrade: websocket\r\n" +
+                    "Sec-WebSocket-Accept: " + swkaSha1Base64 + "\r\n\r\n");
+
+                stream.Write(response, 0, response.Length);
+            } else {
+                bool fin = (bytes[0] & 0b10000000) != 0,
+                    mask = (bytes[1] & 0b10000000) != 0; // must be true, "All messages from the client to the server have this bit set"
+
+                int opcode = bytes[0] & 0b00001111, // expecting 1 - text message
+                    msglen = bytes[1] - 128, // & 0111 1111
+                    offset = 2;
+
+                if (msglen == 126) {
+                    // was ToUInt16(bytes, offset) but the result is incorrect
+                    msglen = BitConverter.ToUInt16(new byte[] { bytes[3], bytes[2] }, 0);
+                    offset = 4;
+                } else if (msglen == 127) {
+                    Console.WriteLine("TODO: msglen == 127, needs qword to store msglen");
+                    // i don't really know the byte order, please edit this
+                    // msglen = BitConverter.ToUInt64(new byte[] { bytes[5], bytes[4], bytes[3], bytes[2], bytes[9], bytes[8], bytes[7], bytes[6] }, 0);
+                    // offset = 10;
+                }
+
+                if (msglen == 0)
+                    Console.WriteLine("msglen == 0");
+                else if (mask) {
+                    byte[] decoded = new byte[msglen];
+                    byte[] masks = new byte[4] { bytes[offset], bytes[offset + 1], bytes[offset + 2], bytes[offset + 3] };
+                    offset += 4;
+
+                    for (int i = 0; i < msglen; ++i)
+                        decoded[i] = (byte)(bytes[offset + i] ^ masks[i % 4]);
+
+                    string text = Encoding.UTF8.GetString(decoded);
+                    Console.WriteLine("{0}", text);
+                } else
+                    Console.WriteLine("mask bit not set");
+
+                Console.WriteLine();
+            }
+        }
+    }
+}
+ +

client.html

+ +
<!doctype html>
+<style>
+    textarea { vertical-align: bottom; }
+    #output { overflow: auto; }
+    #output > p { overflow-wrap: break-word; }
+    #output span { color: blue; }
+    #output span.error { color: red; }
+</style>
+<h2>WebSocket Test</h2>
+<textarea cols=60 rows=6></textarea>
+<button>send</button>
+<div id=output></div>
+<script>
+    // http://www.websocket.org/echo.html
+
+    var button = document.querySelector("button"),
+        output = document.querySelector("#output"),
+        textarea = document.querySelector("textarea"),
+        // wsUri = "ws://echo.websocket.org/",
+        wsUri = "ws://127.0.0.1/",
+        websocket = new WebSocket(wsUri);
+
+    button.addEventListener("click", onClickButton);
+
+    websocket.onopen = function (e) {
+        writeToScreen("CONNECTED");
+        doSend("WebSocket rocks");
+    };
+
+    websocket.onclose = function (e) {
+        writeToScreen("DISCONNECTED");
+    };
+
+    websocket.onmessage = function (e) {
+        writeToScreen("<span>RESPONSE: " + e.data + "</span>");
+    };
+
+    websocket.onerror = function (e) {
+        writeToScreen("<span class=error>ERROR:</span> " + e.data);
+    };
+
+    function doSend(message) {
+        writeToScreen("SENT: " + message);
+        websocket.send(message);
+    }
+
+    function writeToScreen(message) {
+        output.insertAdjacentHTML("afterbegin", "<p>" + message + "</p>");
+    }
+
+    function onClickButton() {
+        var text = textarea.value;
+
+        text && doSend(text);
+        textarea.value = "";
+        textarea.focus();
+    }
+</script>
+ +

Ver também

+ + + +
 
diff --git a/files/pt-pt/web/api/websockets_api/writing_websocket_servers/index.html b/files/pt-pt/web/api/websockets_api/writing_websocket_servers/index.html new file mode 100644 index 0000000000..7f3b996573 --- /dev/null +++ b/files/pt-pt/web/api/websockets_api/writing_websocket_servers/index.html @@ -0,0 +1,257 @@ +--- +title: Escrever servidores de WebSocket +slug: Web/API/WebSockets_API/Escrever_servidores_de_WebSocket +tags: + - Guía + - HTML5 + - Tutorial + - WebSocket + - WebSocket API + - WebSockets +translation_of: Web/API/WebSockets_API/Writing_WebSocket_servers +--- +
{{APIRef("Websockets API")}}
+ +

Um servidor WebSocket não é nada mais que uma aplicação que escuta qualquer porta de um servidor TCP que possui um protocolo específico. A tarefa de criar um servidor personalizado é uma tarefa complexa para a maioria; no entanto, é simples implementar um servidor simples de WebSocket numa plataforma á sua escolha.

+ +

Um servidor WebSocket pode ser escrito em qualquer linguagem de servidor que suporte Berkeley sockets, como C(++), Python, PHP, ou server-side JavaScript. Este tutorial não se foca em nenhuma linguagem em específico, mas serve como guia para facilitar o desenvolver do seu próprio server.

+ +

A WebSocket server can be written in any server-side programming language that is capable of Berkeley sockets, such as C(++), Python, PHP, or server-side JavaScript. This is not a tutorial in any specific language, but serves as a guide to facilitate writing your own server.

+ +

This article assumes you're already familiar with how {{Glossary("HTTP")}} works, and that you have a moderate level of programming experience. Depending on language support, knowledge of TCP sockets may be required. The scope of this guide is to present the minimum knowledge you need to write a WebSocket server.

+ +
+

Note: Read the latest official WebSockets specification, RFC 6455. Sections 1 and 4-7 are especially interesting to server implementors. Section 10 discusses security and you should definitely peruse it before exposing your server.

+
+ +

A WebSocket server is explained on a very low level here. WebSocket servers are often separate and specialized servers (for load-balancing or other practical reasons), so you will often use a reverse proxy (such as a regular HTTP server) to detect WebSocket handshakes, pre-process them, and send those clients to a real WebSocket server. This means that you don't have to bloat your server code with cookie and authentication handlers (for example).

+ +

The WebSocket handshake

+ +

First, the server must listen for incoming socket connections using a standard TCP socket. Depending on your platform, this may be handled for you automatically. For example, let's assume that your server is listening on example.com, port 8000, and your socket server responds to {{HTTPMethod("GET")}} requests at example.com/chat.

+ +
+

Warning: The server may listen on any port it chooses, but if it chooses any port other than 80 or 443, it may have problems with firewalls and/or proxies. Browsers generally require a secure connection for WebSockets, although they may offer an exception for local devices.

+
+ +

The handshake is the "Web" in WebSockets. It's the bridge from HTTP to WebSockets. In the handshake, details of the connection are negotiated, and either party can back out before completion if the terms are unfavorable. The server must be careful to understand everything the client asks for, otherwise security issues can occur.

+ +
+

Tip: The request-uri (/chat here) has no defined meaning in the spec. So, many people  use it to let one server handle multiple WebSocket applications. For example, example.com/chat could invoke a multiuser chat app, while /game on the same server might invoke a multiplayer game.

+
+ +

Client handshake request

+ +

Even though you're building a server, a client still has to start the WebSocket handshake process by contacting the server and requesting a WebSocket connection. So, you must know how to interpret the client's request. The client will send a pretty standard HTTP request with headers that looks like this (the HTTP version must be 1.1 or greater, and the method must be GET):

+ +
GET /chat HTTP/1.1
+Host: example.com:8000
+Upgrade: websocket
+Connection: Upgrade
+Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
+Sec-WebSocket-Version: 13
+
+
+ +

The client can solicit extensions and/or subprotocols here; see Miscellaneous for details. Also, common headers like {{HTTPHeader("User-Agent")}}, {{HTTPHeader("Referer")}}, {{HTTPHeader("Cookie")}}, or authentication headers might be there as well. Do whatever you want with those; they don't directly pertain to the WebSocket. It's also safe to ignore them. In many common setups, a reverse proxy has already dealt with them.

+ +
+

Tip: All browsers send an Origin header. You can use this header for security (checking for same origin, automatically allowing or denying, etc.) and send a 403 Forbidden if you don't like what you see. However, be warned that non-browser agents can send a faked Origin. Most applications reject requests without this header.

+
+ +

If any header is not understood or has an incorrect value, the server should send a {{HTTPStatus("400")}} ("Bad Request")} response and immediately close the socket. As usual, it may also give the reason why the handshake failed in the HTTP response body, but the message may never be displayed (browsers do not display it). If the server doesn't understand that version of WebSockets, it should send a {{HTTPHeader("Sec-WebSocket-Version")}} header back that contains the version(s) it does understand.  In the example above, it indicates version 13 of the WebSocket protocol.

+ +

The most interesting header here is {{HTTPHeader("Sec-WebSocket-Key")}}. Let's look at that next.

+ +
+

Note: Regular HTTP status codes can be used only before the handshake. After the handshake succeeds, you have to use a different set of codes (defined in section 7.4 of the spec).

+
+ +

Server handshake response

+ +

When the server receives the handshake request, it should send back a special response that indicates that the protocol will be changing from HTTP to WebSocket. That header looks something like the following (remember each header line ends with \r\n and put an extra \r\n after the last one to indicate the end of the header):

+ +
HTTP/1.1 101 Switching Protocols
+Upgrade: websocket
+Connection: Upgrade
+Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
+
+
+ +

Additionally, the server can decide on extension/subprotocol requests here; see Miscellaneous for details. The Sec-WebSocket-Accept header is important in that the server must derive it from the {{HTTPHeader("Sec-WebSocket-Key")}} that the client sent to it. To get it, concatenate the client's Sec-WebSocket-Key and the string "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" together (it's a "magic string"), take the SHA-1 hash of the result, and return the base64 encoding of that hash.

+ +
+

Note: This seemingly overcomplicated process exists so that it's obvious to the client whether the server supports WebSockets. This is important because security issues might arise if the server accepts a WebSockets connection but interprets the data as a HTTP request.

+
+ +

So if the Key was "dGhlIHNhbXBsZSBub25jZQ==", the Sec-WebSocket-Accept header's value is "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=". Once the server sends these headers, the handshake is complete and you can start swapping data!

+ +
+

Note: The server can send other headers like {{HTTPHeader("Set-Cookie")}}, or ask for authentication or redirects via other status codes, before sending the reply handshake.

+
+ +

Keeping track of clients

+ +

This doesn't directly relate to the WebSocket protocol, but it's worth mentioning here: your server must keep track of clients' sockets so you don't keep handshaking again with clients who have already completed the handshake. The same client IP address can try to connect multiple times. However, the server can deny them if they attempt too many connections in order to save itself from Denial-of-Service attacks.

+ +

For example, you might keep a table of usernames or ID numbers along with the corresponding {{domxref("WebSocket")}} and other data that you need to associate with that connection.

+ +

Exchanging data frames

+ +

Either the client or the server can choose to send a message at any time — that's the magic of WebSockets. However, extracting information from these so-called "frames" of data is a not-so-magical experience. Although all frames follow the same specific format, data going from the client to the server is masked using XOR encryption (with a 32-bit key). Section 5 of the specification describes this in detail.

+ +

Format

+ +

Each data frame (from the client to the server or vice-versa) follows this same format:

+ +
Frame format:
+​​
+      0                   1                   2                   3
+      0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+     +-+-+-+-+-------+-+-------------+-------------------------------+
+     |F|R|R|R| opcode|M| Payload len |    Extended payload length    |
+     |I|S|S|S|  (4)  |A|     (7)     |             (16/64)           |
+     |N|V|V|V|       |S|             |   (if payload len==126/127)   |
+     | |1|2|3|       |K|             |                               |
+     +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
+     |     Extended payload length continued, if payload len == 127  |
+     + - - - - - - - - - - - - - - - +-------------------------------+
+     |                               |Masking-key, if MASK set to 1  |
+     +-------------------------------+-------------------------------+
+     | Masking-key (continued)       |          Payload Data         |
+     +-------------------------------- - - - - - - - - - - - - - - - +
+     :                     Payload Data continued ...                :
+     + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
+     |                     Payload Data continued ...                |
+     +---------------------------------------------------------------+
+ +

The MASK bit tells whether the message is encoded. Messages from the client must be masked, so your server must expect this to be 1. (In fact, section 5.1 of the spec says that your server must disconnect from a client if that client sends an unmasked message.) When sending a frame back to the client, do not mask it and do not set the mask bit. We'll explain masking later. Note: You must mask messages even when using a secure socket. RSV1-3 can be ignored, they are for extensions.

+ +

The opcode field defines how to interpret the payload data: 0x0 for continuation, 0x1 for text (which is always encoded in UTF-8), 0x2 for binary, and other so-called "control codes" that will be discussed later. In this version of WebSockets, 0x3 to 0x7 and 0xB to 0xF have no meaning.

+ +

The FIN bit tells whether this is the last message in a series. If it's 0, then the server keeps listening for more parts of the message; otherwise, the server should consider the message delivered. More on this later.

+ +

Decoding Payload Length

+ +

To read the payload data, you must know when to stop reading. That's why the payload length is important to know. Unfortunately, this is somewhat complicated. To read it, follow these steps:

+ +
    +
  1. Read bits 9-15 (inclusive) and interpret that as an unsigned integer. If it's 125 or less, then that's the length; you're done. If it's 126, go to step 2. If it's 127, go to step 3.
  2. +
  3. Read the next 16 bits and interpret those as an unsigned integer. You're done.
  4. +
  5. Read the next 64 bits and interpret those as an unsigned integer. (The most significant bit must be 0.) You're done.
  6. +
+ +

Reading and Unmasking the Data

+ +

If the MASK bit was set (and it should be, for client-to-server messages), read the next 4 octets (32 bits); this is the masking key. Once the payload length and masking key is decoded, you can read that number of bytes from the socket. Let's call the data ENCODED, and the key MASK. To get DECODED, loop through the octets (bytes a.k.a. characters for text data) of ENCODED and XOR the octet with the (i modulo 4)th octet of MASK. In pseudo-code (that happens to be valid JavaScript):

+ +
var DECODED = "";
+for (var i = 0; i < ENCODED.length; i++) {
+    DECODED[i] = ENCODED[i] ^ MASK[i % 4];
+}
+ +

Now you can figure out what DECODED means depending on your application.

+ +

Message Fragmentation

+ +

The FIN and opcode fields work together to send a message split up into separate frames.  This is called message fragmentation. Fragmentation is only available on opcodes 0x0 to 0x2.

+ +

Recall that the opcode tells what a frame is meant to do. If it's 0x1, the payload is text. If it's 0x2, the payload is binary data. However, if it's 0x0, the frame is a continuation frame; this means the server should concatenate the frame's payload to the last frame it received from that client. Here is a rough sketch, in which a server reacts to a client sending text messages. The first message is sent in a single frame, while the second message is sent across three frames. FIN and opcode details are shown only for the client:

+ +
Client: FIN=1, opcode=0x1, msg="hello"
+Server: (process complete message immediately) Hi.
+Client: FIN=0, opcode=0x1, msg="and a"
+Server: (listening, new message containing text started)
+Client: FIN=0, opcode=0x0, msg="happy new"
+Server: (listening, payload concatenated to previous message)
+Client: FIN=1, opcode=0x0, msg="year!"
+Server: (process complete message) Happy new year to you too!
+ +

Notice the first frame contains an entire message (has FIN=1 and opcode!=0x0), so the server can process or respond as it sees fit. The second frame sent by the client has a text payload (opcode=0x1), but the entire message has not arrived yet (FIN=0). All remaining parts of that message are sent with continuation frames (opcode=0x0), and the final frame of the message is marked by FIN=1. Section 5.4 of the spec describes message fragmentation.

+ +

Pings and Pongs: The Heartbeat of WebSockets

+ +

At any point after the handshake, either the client or the server can choose to send a ping to the other party. When the ping is received, the recipient must send back a pong as soon as possible. You can use this to make sure that the client is still connected, for example.

+ +

A ping or pong is just a regular frame, but it's a control frame. Pings have an opcode of 0x9, and pongs have an opcode of 0xA. When you get a ping, send back a pong with the exact same Payload Data as the ping (for pings and pongs, the max payload length is 125). You might also get a pong without ever sending a ping; ignore this if it happens.

+ +
+

If you have gotten more than one ping before you get the chance to send a pong, you only send one pong.

+
+ +

Closing the connection

+ +

To close a connection either the client or server can send a control frame with data containing a specified control sequence to begin the closing handshake (detailed in Section 5.5.1). Upon receiving such a frame, the other peer sends a Close frame in response. The first peer then closes the connection. Any further data received after closing of connection is then discarded. 

+ +

Miscellaneous

+ +
+

WebSocket codes, extensions, subprotocols, etc. are registered at the IANA WebSocket Protocol Registry.

+
+ +

WebSocket extensions and subprotocols are negotiated via headers during the handshake. Sometimes extensions and subprotocols very similar, but there is a clear distinction. Extensions control the WebSocket frame and modify the payload, while subprotocols structure the WebSocket payload and never modify anything. Extensions are optional and generalized (like compression); subprotocols are mandatory and localized (like ones for chat and for MMORPG games).

+ +

Extensions

+ +
+

This section needs expansion. Please edit if you are equipped to do so.

+
+ +

Think of an extension as compressing a file before e-mailing it to someone. Whatever you do, you're sending the same data in different forms. The recipient will eventually be able to get the same data as your local copy, but it is sent differently. That's what an extension does. WebSockets defines a protocol and a simple way to send data, but an extension such as compression could allow sending the same data but in a shorter format.

+ +
+

Extensions are explained in sections 5.8, 9, 11.3.2, and 11.4 of the spec.

+
+ +

TODO

+ +

Subprotocols

+ +

Think of a subprotocol as a custom XML schema or doctype declaration. You're still using XML and its syntax, but you're additionally restricted by a structure you agreed on. WebSocket subprotocols are just like that. They do not introduce anything fancy, they just establish structure. Like a doctype or schema, both parties must agree on the subprotocol; unlike a doctype or schema, the subprotocol is implemented on the server and cannot be externally refered to by the client.

+ +
+

Subprotocols are explained in sections 1.9, 4.2, 11.3.4, and 11.5 of the spec.

+
+ +

A client has to ask for a specific subprotocol. To do so, it will send something like this as part of the original handshake:

+ +
GET /chat HTTP/1.1
+...
+Sec-WebSocket-Protocol: soap, wamp
+
+
+ +

or, equivalently:

+ +
...
+Sec-WebSocket-Protocol: soap
+Sec-WebSocket-Protocol: wamp
+
+
+ +

Now the server must pick one of the protocols that the client suggested and it supports. If there is more than one, send the first one the client sent. Imagine our server can use both soap and wamp. Then, in the response handshake, it sends:

+ +
Sec-WebSocket-Protocol: soap
+
+
+ +
+

The server can't send more than one Sec-Websocket-Protocol header.
+ If the server doesn't want to use any subprotocol, it shouldn't send any Sec-WebSocket-Protocol header. Sending a blank header is incorrect. The client may close the connection if it doesn't get the subprotocol it wants.

+
+ +

If you want your server to obey certain subprotocols, then naturally you'll need extra code on the server. Let's imagine we're using a subprotocol json. In this subprotocol, all data is passed as JSON. If the client solicits this protocol and the server wants to use it, the server needs to have a JSON parser. Practically speaking, this will be part of a library, but the server needs to pass the data around.

+ +
+

Tip: To avoid name conflict, it's recommended to make your subprotocol name part of a domain string. If you are building a custom chat app that uses a proprietary format exclusive to Example Inc., then you might use this: Sec-WebSocket-Protocol: chat.example.com. Note that this isn't required, it's just an optional convention, and you can use any string you wish.

+
+ + + + diff --git a/files/pt-pt/web/api/window/barra_lateral/index.html b/files/pt-pt/web/api/window/barra_lateral/index.html deleted file mode 100644 index d35750364d..0000000000 --- a/files/pt-pt/web/api/window/barra_lateral/index.html +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: Window.sidebar -slug: Web/API/Window/barra_lateral -tags: - - DOM - - Janela - - Não Padrão - - Propriedade - - Referencia -translation_of: Web/API/Window/sidebar ---- -
{{APIRef}} {{Non-standard_header}}
- -

Devolve um objeto da barra lateral, que contém vários métodos para registar extras com o navegador.

- -

Notas

- -

O objeto da barra lateral devolvido tem os seguintes métodos:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
MétodoDescrição (SeaMonkey)Descrição (Firefox)
addPanel(title, contentURL, "")Adiciona um painel de barra lateral.Obsoleto desde o Firefox 23 (apresentado apenas no SeaMonkey).
- Em vez disso, os utilizadores finais podem utilizar a opção "carregar este marcador na barra lateral". Consulte também Criação de uma barra lateral do Firefox.
addPersistentPanel(title, contentURL, "")Adiciona um painel de barra lateral, que consegue funcionar em segundo plano.
AddSearchProvider(descriptionURL)Installs a search provider (OpenSearch). Adding OpenSearch search engines contains more details. Added in Firefox 2.
addSearchEngine(engineURL, iconURL, suggestedTitle, suggestedCategory) {{Obsolete_inline(44)}} -

Installs a search engine (Sherlock). Adding Sherlock search engines contains more details.

- -
-

Note: This was made obsolete in Firefox 44, and has been removed completely in Firefox 59. You should use AddSearchProvider instead.

-
-
IsSearchProviderInstalled(descriptionURL)Indicates if a specific search provider (OpenSearch) is installed.
- -

Especificação

- -

Específico da Mozilla. Não faz parte de qualquer padrão.

diff --git a/files/pt-pt/web/api/window/sidebar/index.html b/files/pt-pt/web/api/window/sidebar/index.html new file mode 100644 index 0000000000..d35750364d --- /dev/null +++ b/files/pt-pt/web/api/window/sidebar/index.html @@ -0,0 +1,60 @@ +--- +title: Window.sidebar +slug: Web/API/Window/barra_lateral +tags: + - DOM + - Janela + - Não Padrão + - Propriedade + - Referencia +translation_of: Web/API/Window/sidebar +--- +
{{APIRef}} {{Non-standard_header}}
+ +

Devolve um objeto da barra lateral, que contém vários métodos para registar extras com o navegador.

+ +

Notas

+ +

O objeto da barra lateral devolvido tem os seguintes métodos:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MétodoDescrição (SeaMonkey)Descrição (Firefox)
addPanel(title, contentURL, "")Adiciona um painel de barra lateral.Obsoleto desde o Firefox 23 (apresentado apenas no SeaMonkey).
+ Em vez disso, os utilizadores finais podem utilizar a opção "carregar este marcador na barra lateral". Consulte também Criação de uma barra lateral do Firefox.
addPersistentPanel(title, contentURL, "")Adiciona um painel de barra lateral, que consegue funcionar em segundo plano.
AddSearchProvider(descriptionURL)Installs a search provider (OpenSearch). Adding OpenSearch search engines contains more details. Added in Firefox 2.
addSearchEngine(engineURL, iconURL, suggestedTitle, suggestedCategory) {{Obsolete_inline(44)}} +

Installs a search engine (Sherlock). Adding Sherlock search engines contains more details.

+ +
+

Note: This was made obsolete in Firefox 44, and has been removed completely in Firefox 59. You should use AddSearchProvider instead.

+
+
IsSearchProviderInstalled(descriptionURL)Indicates if a specific search provider (OpenSearch) is installed.
+ +

Especificação

+ +

Específico da Mozilla. Não faz parte de qualquer padrão.

-- cgit v1.2.3-54-g00ecf