From 4f0e1ec1c2772904c033f747dc38a08223e8d661 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Thu, 15 Jul 2021 13:42:10 -0400 Subject: delete pages that were never translated from en-US (es, part 2) (#1550) --- files/es/web/api/audionode/index.html | 154 ---- .../hit_regions_and_accessibility/index.html | 100 --- files/es/web/api/filesystem/index.html | 118 --- files/es/web/api/headers/index.html | 135 --- .../recommended_drag_types/index.html | 145 ---- .../es/web/api/htmlcanvaselement/toblob/index.html | 261 ------ files/es/web/api/mediasource/index.html | 182 ----- files/es/web/api/webvtt_api/index.html | 903 --------------------- .../api/window/domcontentloaded_event/index.html | 149 ---- files/es/web/api/worker/postmessage/index.html | 206 ----- .../index.html | 232 ------ 11 files changed, 2585 deletions(-) delete mode 100644 files/es/web/api/audionode/index.html delete mode 100644 files/es/web/api/canvas_api/tutorial/hit_regions_and_accessibility/index.html delete mode 100644 files/es/web/api/filesystem/index.html delete mode 100644 files/es/web/api/headers/index.html delete mode 100644 files/es/web/api/html_drag_and_drop_api/recommended_drag_types/index.html delete mode 100644 files/es/web/api/htmlcanvaselement/toblob/index.html delete mode 100644 files/es/web/api/mediasource/index.html delete mode 100644 files/es/web/api/webvtt_api/index.html delete mode 100644 files/es/web/api/window/domcontentloaded_event/index.html delete mode 100644 files/es/web/api/worker/postmessage/index.html delete mode 100644 files/es/web/api/xmlhttprequest/synchronous_and_asynchronous_requests/index.html (limited to 'files/es/web/api') diff --git a/files/es/web/api/audionode/index.html b/files/es/web/api/audionode/index.html deleted file mode 100644 index ea6ff34406..0000000000 --- a/files/es/web/api/audionode/index.html +++ /dev/null @@ -1,154 +0,0 @@ ---- -title: AudioNode -slug: Web/API/AudioNode -translation_of: Web/API/AudioNode ---- -
{{APIRef("Web Audio API")}}
- -

La interfaz AudioNode es una interfaz genérica para representar un módulo de procesamiento de audio. Ejemplos:

- - - -

{{InheritanceDiagram}}

- -

Note: An AudioNode can be target of events, por lo tanto este implementa  {{domxref("EventTarget")}} interface.

- -

Descripción

- -

The audio routing graph

- -

AudioNodes participating in an AudioContext create a audio routing graph.

- -

Cada AudioNode posee entradas y salidas, y múltiples nodos de audio son conectados para construir un processing graph. Este graph es contenido en {{domxref("AudioContext")}}, y cada nodo de audio solo puede pertecener a un audio context.

- -

Un source node tiene cero entradas pero una o muchas salidas, y puede ser usado para generar sonido. Por otro lado, un destination node no tiene salidas; instead, all its inputs are directly played back on the speakers (or whatever audio output device the audio context uses). In addition, there are processing nodes which have inputs and outputs. The exact processing done varies from one AudioNode to another but, in general, a node reads its inputs, does some audio-related processing, and generates new values for its outputs, or simply lets the audio pass through (for example in the {{domxref("AnalyserNode")}}, where the result of the processing is accessed separately).

- -

The more nodes in a graph, the higher the latency will be. Por ejemplo, si tu graph tiene una latencia de 500ms, Cuando el source node reproduzca un sonido, este va a tomar la mitad de un segundo hasta que el sonido pueda ser escuchado en tus altavoces. (or even longer because of latency in the underlying audio device). Por lo tanto, si tu necesitas tener un audio interactivo, keep the graph as small as possible, and put user-controlled audio nodes at the end of a graph. For example, a volume control (GainNode) should be the last node so that volume changes take immediate effect.

- -

Each input and output has a given amount of channels. For example, mono audio has one channel, while stereo audio has two channels. The Web Audio API will up-mix or down-mix the number of channels as required; check the Web Audio spec for details.

- -

For a list of all audio nodes, see the Web Audio API homepage.

- -

Creating an AudioNode

- -

There are two ways to create an AudioNode: via the constuctor and via the factory method.

- -
// constructor
-const analyserNode = new AnalyserNode(audioCtx, {
-  fftSize: 2048,
-  maxDecibels: -25,
-  minDecibels: -60,
-  smoothingTimeConstant: 0.5,
-});
-
-// factory method
-const analyserNode = audioCtx.createAnalyser();
-analyserNode.fftSize = 2048;
-analyserNode.maxDecibels = -25;
-analyserNode.minDecibels = -60;
-analyserNode.smoothingTimeConstant = 0.5;
- -

Eres libre de usar cualquiera de los constructors o factory methods, o una mezcla de ambos, sin embargo hay ventajas al usar contructores:

- - - -

Tener en cuenta que Microsoft Edge does not yet appear to support the constructors; it will throw a "Function expected" error when you use the constructors.

- -

Brief history: The first version of the Web Audio spec only defined the factory methods. After a design review in October 2013, it was decided to add constructors because they have numerous benefits over factory methods. The constructors were added to the spec from August to October 2016. Factory methods continue to be included in the spec and are not deprecated.

- -

Properties

- -
-
{{domxref("AudioNode.context")}} {{readonlyInline}}
-
Returns the associated {{domxref("BaseAudioContext")}}, that is the object representing the processing graph the node is participating in.
-
- -
-
{{domxref("AudioNode.numberOfInputs")}} {{readonlyInline}}
-
Returns the number of inputs feeding the node. Source nodes are defined as nodes having a numberOfInputs property with a value of 0.
-
- -
-
{{domxref("AudioNode.numberOfOutputs")}} {{readonlyInline}}
-
Returns the number of outputs coming out of the node. Destination nodes — like {{ domxref("AudioDestinationNode") }} — have a value of 0 for this attribute.
-
- -
-
{{domxref("AudioNode.channelCount")}}
-
Represents an integer used to determine how many channels are used when up-mixing and down-mixing connections to any inputs to the node. Its usage and precise definition depend on the value of {{domxref("AudioNode.channelCountMode")}}.
-
- -
-
{{domxref("AudioNode.channelCountMode")}}
-
Represents an enumerated value describing the way channels must be matched between the node's inputs and outputs.
-
{{domxref("AudioNode.channelInterpretation")}}
-
Represents an enumerated value describing the meaning of the channels. This interpretation will define how audio up-mixing and down-mixing will happen.
- The possible values are "speakers" or "discrete".
-
- -

Methods

- -

Also implements methods from the interface {{domxref("EventTarget")}}.

- -
-
{{domxref("AudioNode.connect()")}}
-
Allows us to connect the output of this node to be input into another node, either as audio data or as the value of an {{domxref("AudioParam")}}.
-
{{domxref("AudioNode.disconnect()")}}
-
Allows us to disconnect the current node from another one it is already connected to.
-
- -

Example

- -

This simple snippet of code shows the creation of some audio nodes, and how the AudioNode properties and methods can be used. You can find examples of such usage on any of the examples linked to on the Web Audio API landing page (for example Violent Theremin.)

- -
const audioCtx = new AudioContext();
-
-const oscillator = new OscillatorNode(audioCtx);
-const gainNode = new GainNode(audioCtx);
-
-oscillator.connect(gainNode).connect(audioCtx.destination);
-
-oscillator.context;
-oscillator.numberOfInputs;
-oscillator.numberOfOutputs;
-oscillator.channelCount;
- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Web Audio API', '#the-audionode-interface', 'AudioNode')}}{{Spec2('Web Audio API')}} 
- -

Browser compatibility

- -
- - -

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

-
- -

See also

- - diff --git a/files/es/web/api/canvas_api/tutorial/hit_regions_and_accessibility/index.html b/files/es/web/api/canvas_api/tutorial/hit_regions_and_accessibility/index.html deleted file mode 100644 index 1f2a93dbae..0000000000 --- a/files/es/web/api/canvas_api/tutorial/hit_regions_and_accessibility/index.html +++ /dev/null @@ -1,100 +0,0 @@ ---- -title: Hit regions and accessibility -slug: Web/API/Canvas_API/Tutorial/Hit_regions_and_accessibility -translation_of: Web/API/Canvas_API/Tutorial/Hit_regions_and_accessibility -original_slug: Web/Guide/HTML/Canvas_tutorial/Hit_regions_and_accessibility ---- -
{{CanvasSidebar}} {{ PreviousNext("Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas", "Web/API/Canvas_API/Tutorial/Optimizing_canvas") }}
- -
The {{HTMLElement("canvas")}} element on its own is just a bitmap and does not provide information about any drawn objects. Canvas content is not exposed to accessibility tools like semantic HTML is. In general, you should avoid using canvas in an accessible website or app. The following guidelines can help to make it more accessible.
- -
El elemento {{HTMLElement ("canvas")}} por sí solo es solo un mapa de bits y no proporciona información sobre ningún objeto dibujado. El contenido del lienzo no está expuesto a herramientas de accesibilidad como el HTML semántico. En general, debe evitar usar canvas en un sitio web o aplicación accesible. Las siguientes pautas pueden ayudar a que sea más accesible.
- -

Fallback content

- -

The content inside the <canvas> ... </canvas> tags can be used as a fallback for browsers which don't support canvas rendering. It's also very useful for assistive technology users (like screen readers) which can read and interpret the sub DOM in it. A good example at html5accessibility.com demonstrates how this can be done:

- -
<canvas>
-  <h2>Shapes</h2>
-  <p>A rectangle with a black border.
-   In the background is a pink circle.
-   Partially overlaying the <a href="http://en.wikipedia.org/wiki/Circle" onfocus="drawCircle();" onblur="drawPicture();">circle</a>.
-   Partially overlaying the circle is a green
-   <a href="http://en.wikipedia.org/wiki/Square" onfocus="drawSquare();" onblur="drawPicture();">square</a>
-   and a purple <a href="http://en.wikipedia.org/wiki/Triangle" onfocus="drawTriangle();" onblur="drawPicture();">triangle</a>,
-   both of which are semi-opaque, so the full circle can be seen underneath.</p>
-</canvas> 
- -

See the video how NVDA reads this example by Steve Faulkner.

- -

ARIA rules

- -

Accessible Rich Internet Applications (ARIA) defines ways to make Web content and Web applications more accessible to people with disabilities. You can use ARIA attributes to describe the behavior and purpose of the canvas element. See ARIA and ARIA techniques for more information.

- -
<canvas id="button" tabindex="0" role="button" aria-pressed="false" aria-label="Start game"></canvas>
-
- -

Hit regions

- -

Whether the mouse coordinates are within a particular area on the canvas, is a common problem to solve. The hit region API allows you to define an area of your canvas and provides another possibility to expose interactive content on a canvas to accessibility tools. It allows you to make hit detection easier and lets you route events to DOM elements. The API has the following three methods (which are still experimental in current web browsers; check the browser compatibility tables).

- -
-
{{domxref("CanvasRenderingContext2D.addHitRegion()")}} {{experimental_inline}}
-
Adds a hit region to the canvas.
-
{{domxref("CanvasRenderingContext2D.removeHitRegion()")}} {{experimental_inline}}
-
Removes the hit region with the specified id from the canvas.
-
{{domxref("CanvasRenderingContext2D.clearHitRegions()")}} {{experimental_inline}}
-
Removes all hit regions from the canvas.
-
- -

You can add a hit region to your path and check for the {{domxref("MouseEvent.region")}} property to test if your mouse is hitting your region, for example.

- -
<canvas id="canvas"></canvas>
-<script>
-var canvas = document.getElementById('canvas');
-var ctx = canvas.getContext('2d');
-
-ctx.beginPath();
-ctx.arc(70, 80, 10, 0, 2 * Math.PI, false);
-ctx.fill();
-ctx.addHitRegion({id: 'circle'});
-
-canvas.addEventListener('mousemove', function(event) {
-  if (event.region) {
-    alert('hit region: ' + event.region);
-  }
-});
-</script>
- -

The addHitRegion() method also takes a control option to route events to an element (that is a descendant of the canvas):

- -
ctx.addHitRegion({control: element});
- -

This can be useful for routing to {{HTMLElement("input")}} elements, for example. See also this codepen demo.

- -

Focus rings

- -

When working with the keyboard, focus rings are a handy indicator to help navigating on a page. To draw focus rings on a canvas drawing, the drawFocusIfNeeded property can be used.

- -
-
{{domxref("CanvasRenderingContext2D.drawFocusIfNeeded()")}} {{experimental_inline}}
-
If a given element is focused, this method draws a focus ring around the current path.
-
- -

Additionally, the scrollPathIntoView() method can be used to make an element visible on the screen if focused, for example.

- -
-
{{domxref("CanvasRenderingContext2D.scrollPathIntoView()")}} {{experimental_inline}}
-
Scrolls the current path or a given path into the view.
-
- -

See also

- - - -
{{ PreviousNext("Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas", "Web/API/Canvas_API/Tutorial/Optimizing_canvas") }}
diff --git a/files/es/web/api/filesystem/index.html b/files/es/web/api/filesystem/index.html deleted file mode 100644 index 62f5e91b4b..0000000000 --- a/files/es/web/api/filesystem/index.html +++ /dev/null @@ -1,118 +0,0 @@ ---- -title: FileSystem -slug: Web/API/FileSystem -translation_of: Web/API/FileSystem ---- -

{{APIRef("File System API")}} {{non-standard_header}}

- -

La interfaz de la API FileSystem  para la entrada de archivos y directorios es usada para representar un sistema de archivos.  Estos objetos pueden ser obtenidos desde la propiedad {{domxref("FileSystemEntry.filesystem", "filesystem")}} en cualquier entrada del sistema de archivos . Algunos navegadores ofrecen APIs adicionales para crear y administrar el sistema de archivos , como el metodo de Chrome {{domxref("Window.requestFileSystem", "requestFileSystem()")}}.

- -

This interface will not grant you access to the users filesystem. Instead you will have a "virtual drive" within the browser sandbox. If you want to gain access to the users filesystem you need to invoke the user by eg. installing a Chrome extension. The relevant Chrome API can be found here.

- -
-

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.

-
- -

Conceptos Basicos

- -

Hay dos formas de acceder a un objeto FileSystem :

- -
    -
  1. You can directly ask for one representing a sandboxed file system created just for your web app directly by calling window.requestFileSystem().  If that call is successful, it executes a callback handler, which receives as a parameter a FileSystem object describing the file system.
  2. -
  3. You can get it from a file system entry object, through its {{domxref("FileSystemEntry.filesystem", "filesystem")}} property.
  4. -
- -

Propiedades

- -
-
{{domxref("FileSystem.name")}} {{ReadOnlyInline}}
-
A {{domxref("USVString")}} representing the file system's name. This name is unique among the entire list of exposed file systems.
-
{{domxref("FileSystem.root")}} {{ReadOnlyInline}}
-
A {{domxref("FileSystemDirectoryEntry")}} object which represents the file system's root directory. Through this object, you can gain access to all files and directories in the file system.
-
- -

Especificaciones

- - - - - - - - - - - - - - - - -
EspecificaciónEstadoComentario
{{SpecName('File System API')}}{{Spec2('File System API')}}Draft of proposed API
- -

This API has no official W3C or WHATWG specification.

- -

Compatibilidad entre navegadores 

- -

{{ CompatibilityTable }}

- -
- - - - - - - - - - - - - - - - - - - - - -
CaracteristicaChromeFirefox (Gecko)Internet ExplorerMicrosoft EdgeOperaSafari (WebKit)
Soporte basico13{{ property_prefix("webkit") }}{{ CompatGeckoDesktop(50) }}{{ CompatNo }}{{CompatVersionUnknown}}[1]{{CompatVersionUnknown}} {{ property_prefix("webkit") }}{{ CompatNo }}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatNo }}0.16{{ property_prefix("webkit") }}{{ CompatGeckoMobile(50) }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
-
- -

[1] Microsoft Edge implements this interface under the name WebKitFileSystem, and supports its use only in drag-and-drop scenarios using the {{domxref("DataTransferItem.webkitGetAsEntry()")}} method. It's not available for use in file or folder picker panels (such as when you use an {{HTMLElement("input")}} element with the {{domxref("HTMLInputElement.webkitdirectory")}} attribute.

- -

See also

- - diff --git a/files/es/web/api/headers/index.html b/files/es/web/api/headers/index.html deleted file mode 100644 index cb65b6aa11..0000000000 --- a/files/es/web/api/headers/index.html +++ /dev/null @@ -1,135 +0,0 @@ ---- -title: Headers -slug: Web/API/Headers -tags: - - API - - Experimental - - Fetch - - Headers - - Interface - - Reference -translation_of: Web/API/Headers ---- -
{{ APIRef("Fetch") }}
- -
La interfaz Headers de la Fetch API permite realizar diversas acciones en los Headers de solicitud y respuesta HTTP.Estas acciones incluyen recuperar, establecer, agregar y eliminar. Un objeto Header tiene una lista  asociada que inicialmente está vacía, y consta de cero o más pares de nombre y valor.
- -
Es posible añadir metodos de uso como {{domxref("Headers.append","append()")}} (ver{{anch(" ejemplos")}}.) En todos los métodos de esta interfaz, los nombres de los encabezados se relacionan con una secuencia de bytes sensible a mayúsculas y minúsculas.
- -
Por razones de seguridad, algunos headers pueden ser controlados unicamente por el user agent. Estos headers incluyen los {{Glossary("Forbidden_header_name", "nombres prohibidos para headers", 1)}}  y {{Glossary("Forbidden_response_header_name", "nombres prohibidos de Headers response", 1)}}.
- -

A Headers object also has an associated guard, which takes a value of immutable, request, request-no-cors, response, or none. This affects whether the {{domxref("Headers.set","set()")}}, {{domxref("Headers.delete","delete()")}}, and {{domxref("Headers.append","append()")}} methods will mutate the header. For more information see {{Glossary("Guard")}}.

- -

You can retrieve a Headers object via the {{domxref("Request.headers")}} and {{domxref("Response.headers")}} properties, and create a new Headers object using the {{domxref("Headers.Headers()")}} constructor.

- -

An object implementing Headers can directly be used in a {{jsxref("Statements/for...of", "for...of")}} structure, instead of {{domxref('Headers.entries()', 'entries()')}}: for (var p of myHeaders) is equivalent to for (var p of myHeaders.entries()).

- -
-

Note: you can find more out about the available headers by reading our HTTP headers reference.

-
- -

Constructor

- -
-
{{domxref("Headers.Headers()")}}
-
Creates a new Headers object.
-
- -

Methods

- -
-
{{domxref("Headers.append()")}}
-
Appends a new value onto an existing header inside a Headers object, or adds the header if it does not already exist.
-
{{domxref("Headers.delete()")}}
-
Deletes a header from a Headers object.
-
{{domxref("Headers.entries()")}}
-
Returns an {{jsxref("Iteration_protocols","iterator")}} allowing to go through all key/value pairs contained in this object.
-
{{domxref("Headers.forEach()")}}
-
Executes a provided function once for each array element.
-
{{domxref("Headers.get()")}}
-
Returns a {{domxref("ByteString")}} sequence of all the values of a header within a Headers object with a given name.
-
{{domxref("Headers.has()")}}
-
Returns a boolean stating whether a Headers object contains a certain header.
-
{{domxref("Headers.keys()")}}
-
Returns an {{jsxref("Iteration_protocols", "iterator")}} allowing you to go through all keys of the key/value pairs contained in this object.
-
{{domxref("Headers.set()")}}
-
Sets a new value for an existing header inside a Headers object, or adds the header if it does not already exist.
-
{{domxref("Headers.values()")}}
-
Returns an {{jsxref("Iteration_protocols", "iterator")}} allowing you to go through all values of the key/value pairs contained in this object.
-
- -
-

Note: To be clear, the difference between {{domxref("Headers.set()")}} and {{domxref("Headers.append()")}} is that if the specified header does already exist and does accept multiple values, {{domxref("Headers.set()")}} will overwrite the existing value with the new one, whereas {{domxref("Headers.append()")}} will append the new value onto the end of the set of values. See their dedicated pages for example code.

-
- -
-

Note: All of the Headers methods will throw a TypeError if you try to pass in a reference to a name that isn't a valid HTTP Header name. The mutation operations will throw a TypeError if the header has an immutable {{Glossary("Guard")}}. In any other failure case they fail silently.

-
- -
-

Note: When Header values are iterated over, they are automatically sorted in lexicographical order, and values from duplicate header names are combined.

-
- -

Obsolete methods

- -
-
{{domxref("Headers.getAll()")}}
-
Used to return an array of all the values of a header within a Headers object with a given name; this method has now been deleted from the spec, and {{domxref("Headers.get()")}} now returns all values instead of just one.
-
- -

Examples

- -

In the following snippet, we create a new header using the Headers() constructor, add a new header to it using append(), then return that header value using get():

- -
var myHeaders = new Headers();
-
-myHeaders.append('Content-Type', 'text/xml');
-myHeaders.get('Content-Type') // should return 'text/xml'
-
- -

The same can be achieved by passing an array of arrays or an object literal to the constructor:

- -
var myHeaders = new Headers({
-    'Content-Type': 'text/xml'
-});
-
-// or, using an array of arrays:
-myHeaders = new Headers([
-    ['Content-Type', 'text/xml']
-]);
-
-myHeaders.get('Content-Type') // should return 'text/xml'
-
- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Fetch','#headers-class','Headers')}}{{Spec2('Fetch')}} 
- -

Browser compatibility

- - - -

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

- -

See also

- - - -

 

diff --git a/files/es/web/api/html_drag_and_drop_api/recommended_drag_types/index.html b/files/es/web/api/html_drag_and_drop_api/recommended_drag_types/index.html deleted file mode 100644 index 84b04854fa..0000000000 --- a/files/es/web/api/html_drag_and_drop_api/recommended_drag_types/index.html +++ /dev/null @@ -1,145 +0,0 @@ ---- -title: Tipos de Drag recomendados -slug: Web/API/HTML_Drag_and_Drop_API/Recommended_drag_types -translation_of: Web/API/HTML_Drag_and_Drop_API/Recommended_drag_types -original_slug: DragDrop/Recommended_Drag_Types ---- -

A continuación se describe la mejor practica para utilizar los datos a ser arrastrado.

-

Arrastramdo Texto

-

Al arrastrar el texto, utilice el texto / texto normal. Los datos deben ser la cadena de arrastre. Por ejemplo:

-
event.dataTransfer.setData("text/plain", "This is text to drag")
-
-

Arrastrar texto en cuadros de texto y las selecciones de las páginas web se realiza de forma automática, por lo que no es necesario para manejar dragging.

-

Se recomienda que siempre se agrega datos del tipo  text/plain  como un mensaje para las aplicaciones o los destinos que no soportan otros tipos, a menos que no hay alternativa de texto lógico. Siempre agregue el tipo de texto sin formato pasado, ya que es el menos específico.

-

En códigos más viejo, encontrara text/unicode o el tipo Text.Estos equivalen text/plain,que guardara y recibia los datos del texto plano en ese lugar.

- -

Los enlaces deben incluir los datos de los dos tipos, el primero debe ser  URL utilizando el tipo text/uri-list,y el segundo es URL utilizando el tipo text/plain. Ambos tipos deben utilizar los mismos datos, la URL del enlace. Por ejemplo:

-
var dt = event.dataTransfer;
-dt.setData("text/uri-list", "http://www.mozilla.org");
-dt.setData("text/plain", "http://www.mozilla.org");
-
-

Es constumbre, establecer el tipo text/plain de ultimo, , ya que es menos específico que el tipo de URI.

-

Note que el tipo de URL uri-list es con una "i", no una "L"

-

Note that the URL type is uri-list with an 'I', not with an 'L'.

-

To drag multiple links, you can also separate each link with a linebreak. A line that begins with a number sign (#) is a comment and should not be considered a valid URL. You can use a comment to indicate the purpose of a link, or to hold the title associated with a link. The text/plain version of the drag data should include all links but should not include the comments.

-

For example:

-
http://www.mozilla.org
-#A second link
-http://www.xulplanet.com
-
-

This sample text/uri-list data contains two links and a comment.

-

When retrieving a dropped link, you should ensure you handle the case where multiple links may have been dragged, and any comments that appear in the data. For convenience, the special type URL may be used to refer to the first valid link within the data for the text/uri-list type. You should not add data using the URL type; attempting to do so will just set the value of the text/uri-list type instead.

-
var url = event.dataTransfer.getData("URL");
-
-

You may also see data using the text/x-moz-url type which is a Mozilla specific type. If it appears, it should be used before the text/uri-list type. It holds the URL of the link followed by the title of the link, separated by a linebreak. For example:

-
http://www.mozilla.org
-Mozilla
-http://www.xulplanet.com
-XUL Planet
-
-

Dragging HTML and XML

-

HTML content may use the text/html type. The data for this type should be the serialized HTML to drag. For instance, it would be suitable to set the data value for this type to the value of the innerHTML property of an element.

-

XML content may use the text/xml type, but you should ensure that the data value is well-formed XML.

-

You may also include a plain text representation of the HTML or XML data using the text/plain type. The data should be just the text and should not include any of the source tags or attributes. For instance:

-
var dt = event.dataTransfer;
-dt.setData("text/html", "Hello there, <strong>stranger</strong>");
-dt.setData("text/plain", "Hello there, stranger");
-
-

Dragging Files

-

A local file is dragged using the application/x-moz-file type with a data value that is an nsIFile object. Non-privileged web pages are not able to retrieve or modify data of this type. Because a file is not a string, you must use the mozSetDataAt method to assign the data. Similarly, when retrieving the data, you must use the mozGetDataAt method.

-
event.dataTransfer.mozSetDataAt("application/x-moz-file", file, 0);
-
-

If possible, you may also include the file URL of the file using both the text/uri-list and/or text/plain types. These types should be added last so that the more specific application/x-moz-file type has higher priority.

-

Multiple files will be received during a drop as mutliple items in the data transfer. See Dragging and Dropping Multiple Items for more details about this.

-

The following example shows how to create an area for receiving dropped files:

-
<listbox ondragenter="return checkDrag(event)"
-         ondragover="return checkDrag(event)"
-         ondrop="doDrop(event)"/>
-
-<script>
-function checkDrag(event)
-{
-  return event.dataTransfer.types.contains("application/x-moz-file");
-}
-
-function doDrop(event)
-{
-  var file = event.dataTransfer.mozGetDataAt("application/x-moz-file", 0);
-  if (file instanceof Components.interfaces.nsIFile)
-    event.currentTarget.appendItem(file.leafName);
-}
-</script>
-
-

In this example, the event returns false only if the data transfer contains the application/x-moz-file type. During the drop event, the data associated with the file type is retrieved, and the filename of the file is added to the listbox. Note that the instanceof operator is used here as the mozGetDataAt method will return an nsISupports that needs to be checked and converted into an nsIFile. This is also a good extra check in case someone made a mistake and added a non-file for this type.

-

Dragging Images

-

Direct image dragging is not commonly done. In fact, Mozilla does not support direct image dragging on Mac or Linux platforms. Instead, images are usually dragged only by their URLs. To do this, use the text/uri-list type as with other URL links. The data should be the URL of the image or a data URL if the image is not stored on a web site or disk. For more information about data URLs, see the data URL scheme.

-

As with other links, the data for the text/plain type should also contain the URL. However, a data URL is not usually as useful in a text context, so you may wish to exclude the text/plain data in this situation.

-

In chrome or other privileged code, you may also use the image/jpeg, image/png or image/gif types, depending on the type of image. The data should be an object which implements the nsIInputStream interface. When this stream is read, it should provide the data bits for the image, as if the image was a file of that type.

-

You should also include the application/x-moz-file type if the image is located on disk. In fact, this a common way in which image files are dragged.

-

It is important to set the data in the right order, from most specific to least specific. The image type such as image/jpeg should come first, followed by the application/x-moz-file type. Next, you should set the text/uri-list data and finally the text/plain data. For example:

-
var dt = event.dataTransfer;
-dt.mozSetDataAt("image/png", stream, 0);
-dt.mozSetDataAt("application/x-moz-file", file, 0);
-dt.setData("text/uri-list", imageurl);
-dt.setData("text/plain", imageurl);
-
-

Note that the mozGetDataAt method is used for non-text data. As some contexts may only include some of these types, it is important to check which type is made available when receiving dropped images.

-

Dragging Nodes

-

Nodes and elements in a document may be dragged using the application/x-moz-node type. This data for the type should be a DOM node. This allows the drop target to receive the actual node where the drag was started from. Note that callers from a different domain will not be able to access the node even when it has been dropped.

-

You should always include a plain text alternative for the node.

-

Dragging Custom Data

-

You can also use other types that you make up for custom purposes. You should strive to always include a plain text alternative unless that object being dragged is specific to a particular site or application. In this case, the custom type ensures that the data cannot be dropped elsewhere.

-

Dragging files to an operating system folder

-

There are cases in which you may want to add a file to an existing drag event session, and you may also want to write the file to disk when the drop operation happens over a folder in the operating system when your code receives notification of the target folder's location. This only works in extensions (or other privileged code) and the data flavor "application/moz-file-promise" should be used. The following sample offers an overview of this advanced case:

-
// currentEvent is a given existing drag operation event
-
-currentEvent.dataTransfer.setData("text/x-moz-url", URL);
-currentEvent.dataTransfer.setData("application/x-moz-file-promise-url", URL);
-currentEvent.dataTransfer.setData("application/x-moz-file-promise-filename", leafName);
-currentEvent.dataTransfer.mozSetDataAt('application/x-moz-file-promise',
-                  new dataProvider(success,error),
-                  0, Components.interfaces.nsISupports);
-
-function dataProvider(){}
-
-dataProvider.prototype = {
-  QueryInterface : function(iid) {
-    if (iid.equals(Components.interfaces.nsIFlavorDataProvider)
-                  || iid.equals(Components.interfaces.nsISupports))
-      return this;
-    throw Components.results.NS_NOINTERFACE;
-  },
-  getFlavorData : function(aTransferable, aFlavor, aData, aDataLen) {
-    if (aFlavor == 'application/x-moz-file-promise') {
-
-       var urlPrimitive = {};
-       var dataSize = {};
-
-       aTransferable.getTransferData('application/x-moz-file-promise-url', urlPrimitive, dataSize);
-       var url = new String(urlPrimitive.value.QueryInterface(Components.interfaces.nsISupportsString));
-       console.log("URL file orignal is = " + url);
-
-       var namePrimitive = {};
-       aTransferable.getTransferData('application/x-moz-file-promise-filename', namePrimitive, dataSize);
-       var name = new String(namePrimitive.value.QueryInterface(Components.interfaces.nsISupportsString));
-
-       console.log("target filename is = " + name);
-
-       var dirPrimitive = {};
-       aTransferable.getTransferData('application/x-moz-file-promise-dir', dirPrimitive, dataSize);
-       var dir = dirPrimitive.value.QueryInterface(Components.interfaces.nsILocalFile);
-
-       console.log("target folder is = " + dir.path);
-
-       var file = Cc['@mozilla.org/file/local;1'].createInstance(Components.interfaces.nsILocalFile);
-       file.initWithPath(dir.path);
-       file.appendRelativePath(name);
-
-       console.log("output final path is =" + file.path);
-
-       // now you can write or copy the file yourself...
-    }
-  }
-}
-
-

{{ languages( { "ja": "Ja/DragDrop/Recommended_Drag_Types" } ) }}

diff --git a/files/es/web/api/htmlcanvaselement/toblob/index.html b/files/es/web/api/htmlcanvaselement/toblob/index.html deleted file mode 100644 index 4759cd6250..0000000000 --- a/files/es/web/api/htmlcanvaselement/toblob/index.html +++ /dev/null @@ -1,261 +0,0 @@ ---- -title: HTMLCanvasElement.toBlob() -slug: Web/API/HTMLCanvasElement/toBlob -translation_of: Web/API/HTMLCanvasElement/toBlob ---- -
-
-
{{APIRef("Canvas API")}}
-
-
- -

EL metodo HTMLCanvasElement.toBlob() crea un objeto {{domxref("Blob")}} que representa la imagen contenida en el canvas; este archivo puede ser cacheado en el disco oo guardado en la memoria a desicion del  user agent. Si la propiedad type no se especifica el tipo de la imagen será image/png. La imagen creada tiene una resolución de 96dpi.
- El tercer argumento es usado con las imagenes  image/jpeg para especificar la calidad de salida.

- -

Syntax

- -
void canvas.toBlob(callback, type, encoderOptions);
-
- -

Parameters

- -
-
callback
-
A callback function with the resulting {{domxref("Blob")}} object as a single argument.
-
type {{optional_inline}}
-
A {{domxref("DOMString")}} indicating the image format. The default type is image/png.
-
encoderOptions {{optional_inline}}
-
A {{jsxref("Number")}} between 0 and 1 indicating image quality if the requested type is image/jpeg or image/webp. If this argument is anything else, the default value for image quality is used. Other arguments are ignored.
-
- -

Return value

- -

None.

- -

Examples

- -

Getting a file representing the canvas

- -

Once you have drawn content into a canvas, you can convert it into a file of any supported image format. The code snippet below, for example, takes the image in the {{HTMLElement("canvas")}} element whose ID is "canvas", obtains a copy of it as a PNG image, then appends a new {{HTMLElement("img")}} element to the document, whose source image is the one created using the canvas.

- -
var canvas = document.getElementById("canvas");
-
-canvas.toBlob(function(blob) {
-  var newImg = document.createElement("img"),
-      url = URL.createObjectURL(blob);
-
-  newImg.onload = function() {
-    // no longer need to read the blob so it's revoked
-    URL.revokeObjectURL(url);
-  };
-
-  newImg.src = url;
-  document.body.appendChild(newImg);
-});
-
- -

Note that here we're creating a PNG image; if you add a second parameter to the toBlob() call, you can specify the image type. For example, to get the image in JPEG format:

- -
 canvas.toBlob(function(blob){...}, "image/jpeg", 0.95); // JPEG at 95% quality
- -
-

A way to convert a canvas to an ico (Mozilla only)

- -

This uses -moz-parse to convert the canvas to ico. Windows XP doesn't support converting from PNG to ico, so it uses bmp instead. A download link is created by setting the download attribute. The value of the download attribute is the name it will use as the file name.

- -
var canvas = document.getElementById("canvas");
-var d = canvas.width;
-ctx = canvas.getContext("2d");
-ctx.beginPath();
-ctx.moveTo(d / 2, 0);
-ctx.lineTo(d, d);
-ctx.lineTo(0, d);
-ctx.closePath();
-ctx.fillStyle = "yellow";
-ctx.fill();
-
-function blobCallback(iconName) {
-  return function(b) {
-    var a = document.createElement("a");
-    a.textContent = "Download";
-    document.body.appendChild(a);
-    a.style.display = "block";
-    a.download = iconName + ".ico";
-    a.href = window.URL.createObjectURL(b);
-  }
-}
-canvas.toBlob(blobCallback('passThisString'), 'image/vnd.microsoft.icon',
-              '-moz-parse-options:format=bmp;bpp=32');
-
- -

Save toBlob to disk with OS.File (chrome/add-on context only)

- -
-

This technique saves it to the desktop and is only useful in Firefox chrome context or add-on code as OS APIs are not present on web sites.

-
- -
var canvas = document.getElementById("canvas");
-var d = canvas.width;
-ctx = canvas.getContext("2d");
-ctx.beginPath();
-ctx.moveTo(d / 2, 0);
-ctx.lineTo(d, d);
-ctx.lineTo(0, d);
-ctx.closePath();
-ctx.fillStyle = "yellow";
-ctx.fill();
-
-function blobCallback(iconName) {
-  return function(b) {
-    var r = new FileReader();
-    r.onloadend = function () {
-    // r.result contains the ArrayBuffer.
-    Cu.import('resource://gre/modules/osfile.jsm');
-    var writePath = OS.Path.join(OS.Constants.Path.desktopDir,
-                                 iconName + '.ico');
-    var promise = OS.File.writeAtomic(writePath, new Uint8Array(r.result),
-                                      {tmpPath:writePath + '.tmp'});
-    promise.then(
-      function() {
-        console.log('successfully wrote file');
-      },
-      function() {
-        console.log('failure writing file')
-      }
-    );
-  };
-  r.readAsArrayBuffer(b);
-  }
-}
-
-canvas.toBlob(blobCallback('passThisString'), 'image/vnd.microsoft.icon',
-              '-moz-parse-options:format=bmp;bpp=32');
- -

Polyfill

- -

A low performance polyfill based on toDataURL.

- -
if (!HTMLCanvasElement.prototype.toBlob) {
- Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
-  value: function (callback, type, quality) {
-
-    var binStr = atob( this.toDataURL(type, quality).split(',')[1] ),
-        len = binStr.length,
-        arr = new Uint8Array(len);
-
-    for (var i=0; i<len; i++ ) {
-     arr[i] = binStr.charCodeAt(i);
-    }
-
-    callback( new Blob( [arr], {type: type || 'image/png'} ) );
-  }
- });
-}
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', "scripting.html#dom-canvas-toblob", "HTMLCanvasElement.toBlob")}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5.1', "scripting-1.html#dom-canvas-toblob", "HTMLCanvasElement.toBlob")}}{{Spec2('HTML5.1')}}No change
{{SpecName('HTML5 W3C', "scripting-1.html#dom-canvas-toblob", "HTMLCanvasElement.toBlob")}}{{Spec2('HTML5 W3C')}}Snapshot of the {{SpecName('HTML WHATWG')}} containing the initial definition.
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}[1]{{CompatGeckoDesktop('19')}}{{CompatIE(10)}}{{property_prefix("ms")}}{{CompatNo}}{{CompatNo}}[2]
Image quality parameter (jpeg){{CompatNo}}{{CompatGeckoDesktop('25')}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("19")}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}
Image quality parameter (jpeg){{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("25")}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}
-
- -

[1] Chrome does not implement this feature yet. See bug 67587.

- -

[2] WebKit does not implement this feature yet. See {{WebKitBug("71270")}}.

- -

See also

- - diff --git a/files/es/web/api/mediasource/index.html b/files/es/web/api/mediasource/index.html deleted file mode 100644 index 2f5ff914c9..0000000000 --- a/files/es/web/api/mediasource/index.html +++ /dev/null @@ -1,182 +0,0 @@ ---- -title: MediaSource -slug: Web/API/MediaSource -translation_of: Web/API/MediaSource ---- -

{{APIRef("Media Source Extensions")}}{{SeeCompatTable}}

- -

El MediaSource interfaz representa un recurso de media en datos por un {{domxref("HTMLMediaElement")}} objeto. Un MediaSource objeto puede ser atribuido a un {{domxref("HTMLMediaElement")}} para ser reproducido por el usuario.

- -

Constructor

- -
-
{{domxref("MediaSource.MediaSource", "MediaSource()")}}
-
construye y retorna un MediaSource objeto sin asociar un recurso con buffers.
-
- -

Propiedades

- -

Inherits properties from its parent interface, {{domxref("EventTarget")}}.

- -
-
{{domxref("MediaSource.sourceBuffers")}} {{readonlyInline}}
-
Returns a {{domxref("SourceBufferList")}} object containing the list of {{domxref("SourceBuffer")}} objects associated with this MediaSource.
-
{{domxref("MediaSource.activeSourceBuffers")}} {{readonlyInline}}
-
Returns a {{domxref("SourceBufferList")}} object containing a subset of the {{domxref("SourceBuffer")}} objects contained within {{domxref("SourceBuffers")}} — the list of objects providing the selected video track,  enabled audio tracks, and shown/hidden text tracks.
-
{{domxref("MediaSource.readyState")}} {{readonlyInline}}
-
Returns an enum representing the state of the current MediaSource, whether it is not currently attached to a media element (closed), attached and ready to receive {{domxref("SourceBuffer")}} objects (open), or attached but the stream has been ended via {{domxref("MediaSource.endOfStream()")}} (ended.)
-
{{domxref("MediaSource.duration")}}
-
Gets and sets the duration of the current media being presented.
-
- -
-
- -
-
- -

Methods

- -

Inherits properties from its parent interface, {{domxref("EventTarget")}}.

- -
-
{{domxref("MediaSource.addSourceBuffer()")}}
-
Creates a new {{domxref("SourceBuffer")}} of the given MIME type and adds it to the MediaSource's {{domxref("SourceBuffers")}} list.
-
{{domxref("MediaSource.removeSourceBuffer()")}}
-
Removes the given {{domxref("SourceBuffer")}} from the {{domxref("SourceBuffers")}} list associated with this MediaSource object.
-
{{domxref("MediaSource.endOfStream()")}}
-
Signals the end of the stream.
-
-

Static methods

-
-
{{domxref("MediaSource.isTypeSupported()")}}
-
Returns a {{domxref("Boolean")}} value indicating if the given MIME type is supported by the current user agent — this is, if it can successfully create {{domxref("SourceBuffer")}} objects for that MIME type.
-
- -

Examples

- -

The following simple example loads a video chunk by chunk as fast as possible, playing it as soon as it can. This example was written by Nick Desaulniers and can be viewed live here (you can also download the source for further investigation.)

- -
var video = document.querySelector('video');
-
-var assetURL = 'frag_bunny.mp4';
-// Need to be specific for Blink regarding codecs
-// ./mp4info frag_bunny.mp4 | grep Codec
-var mimeCodec = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"';
-
-if ('MediaSource' in window && MediaSource.isTypeSupported(mimeCodec)) {
-  var mediaSource = new MediaSource;
-  //console.log(mediaSource.readyState); // closed
-  video.src = URL.createObjectURL(mediaSource);
-  mediaSource.addEventListener('sourceopen', sourceOpen);
-} else {
-  console.error('Unsupported MIME type or codec: ', mimeCodec);
-}
-
-function sourceOpen (_) {
-  //console.log(this.readyState); // open
-  var mediaSource = this;
-  var sourceBuffer = mediaSource.addSourceBuffer(mimeCodec);
-  fetchAB(assetURL, function (buf) {
-    sourceBuffer.addEventListener('updateend', function (_) {
-      mediaSource.endOfStream();
-      video.play();
-      //console.log(mediaSource.readyState); // ended
-    });
-    sourceBuffer.appendBuffer(buf);
-  });
-};
-
-function fetchAB (url, cb) {
-  console.log(url);
-  var xhr = new XMLHttpRequest;
-  xhr.open('get', url);
-  xhr.responseType = 'arraybuffer';
-  xhr.onload = function () {
-    cb(xhr.response);
-  };
-  xhr.send();
-};
- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Media Source Extensions', '#mediasource', 'MediaSource')}}{{Spec2('Media Source Extensions')}}Initial definition.
- -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support23{{CompatGeckoDesktop("25.0")}}[1]
- {{CompatGeckoDesktop("42.0")}}
11[2]158
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support4.4.4 -

{{CompatNo}}

-
{{CompatNo}}1130{{CompatNo}}
-
- -

[1] Available after switching the about:config preference media.mediasource.enabled to true. In addition, support was limited to a whitelist of sites, for example YouTube, Netflix, and other popular streaming sites. The whitelist was removed and Media Source Extensions was enabled by default in 42+ for all sites.

- -

[2] Only works on Windows 8+.

- -

See also

- - diff --git a/files/es/web/api/webvtt_api/index.html b/files/es/web/api/webvtt_api/index.html deleted file mode 100644 index 7a54969a31..0000000000 --- a/files/es/web/api/webvtt_api/index.html +++ /dev/null @@ -1,903 +0,0 @@ ---- -title: Formato de pistas de texto para la web (WebVTT) -slug: Web/API/WebVTT_API -translation_of: Web/API/WebVTT_API ---- -
{{DefaultAPISidebar("WebVTT")}}
- -

El formato de pistas de texto para la web (WebVTT) es un formato para mostrar pistas de texto en le tiempo (como subtítulos) usando el elemento {{HTMLElement("track")}}. El propósito principal de los archivos de WebVTT es superponer pistas de texto a un elemento {{HTMLElement("video")}}. WebVTT es un formato basado en el texto, que debe de ser codificado usando {{Glossary("UTF-8")}}. Donde puedes usar espacios también puedes usar tabulaciones. También hay una pequeña API disponible para representar y manejar estas pistas de texto y los datos necesarios para realizar la reproducción del texto en los momentos correctos.

- -

Archivos WebVTT

- -

El tipo MIME de los archivos WebVTT es text/vtt.

- -

Un archivo WebVTT (.vtt) contiene apuntes, que pueden ser tanto de una línea como de varias, como se muestra debajo:

- -
WEBVTT
-
-00:01.000 --> 00:04.000
-- Nunca bebas nitrógeno líquido.
-
-00:05.000 --> 00:09.000
-- Podría perforar tu estómago.
-- Podrías morir.
-
-NOTE Esta es la última línea en el archivo
-
- -

Estructura WebVTT

- -

La estructura de un archivo WevWTT consiste de los siguientes componentes, algunos de ellos opcionales, en este orden:

- - - -
Ejemplo 1 - El archivo WebVTT más simple posible
- -
WEBVTT
-
- -
Ejemplo 2 - Archivo WebVTT muy simple con un encabezado de texto
- -
WEBVTT - Este archivo no tiene anotaciones.
-
- -
Ejemplo 3 - Ejemplo de un archivo WebVTT común con encabezado y anotaciones
- -
WEBVTT - Este archivo tiene anotaciones.
-
-14
-00:01:14.815 --> 00:01:18.114
-- ¿Qué?
-- ¿Dónde estamos ahora?
-
-15
-00:01:18.171 --> 00:01:20.991
-- Este es el país de los murciélagos grandes.
-
-16
-00:01:21.058 --> 00:01:23.868
-- [ Murciélagos chillando ]
-- Ellos no se pondrán entu pelo. Ellos están persiguiendo a los bichos.
-
- -

Estructura interna de un archivo WebVTT

- -

Vamos a reexaminar uno de nuestros ejemplos previos, y mirar la estructura de las anotaciones con un poco más de detalle.

- -
WEBVTT
-
-00:01.000 --> 00:04.000
-- Nunca bebas nitrógeno líquido.
-
-00:05.000 --> 00:09.000
-- Podría perforar tu estómago.
-- Podrías morir.
-
-NOTE Esta es la última línea en el archivo
- -

En el caso de cada anotación:

- - - -

También podemos poner comentarios en nuestro archivo .vtt, para ayudarnos a recorddar información importante sobre las partes de nuestro archivo. Estas deben estar en líneas separadas empezando con la cadena NOTE. Aprenderas más sobre eso en la siguiente sección.

- -

Es importante no usar líneas en blanco extras dentro de una anotación, por ejemplo entre las líneas de tiempo y las anotaciones. WebVTT está basado en líneas, una línea en blanco finalizará la anotación.

- -

Comentarios en WebVTT

- -

Los comentarios son un componente opcional que se puede usar para añadir informacion a un archivo WebVTT. Los comentarios estan pensados para aquellos que leen el archivo y no se muestran con las pistas de texto. Los comentarios pueden contener saltos de línea pero no una línea en blanco, que es equivalente a dos saltos de línea consecutivos. Una línea en blanco indica el fin de un comentario.

- -

Un comentario no puede contener la cadena de texto "-->", el símbolo &, o el signo de menor que (<). Si quisieses usar esos caracteres necesitarías hacer un escape usando por ejemplo &amp; para el símbolo &, y &lt; para menor que (<). Tambien es recomendado que uses la secuencia de escape de mayor que &gt; en vez de el simbo de mayor que (>) para evitar la confusión con etiquetas.

- -

Un comentario consiste en tres partes:

- - - -
Ejemplo 4 - Ejemplo común de WebVTT
- -
NOTE Esto es un comentario
-
- -
Ejemplo 5 - Comentario multilínea
- -
NOTE
-Un comentario que está ocupando
-más de una línea.
-
-NOTE También puedes hacer un comentario
-que ocupe más de una línea de esta manera.
-
- -
Ejemplo 6 - Uso común de comentarios
- -
WEBVTT - Traducción de la película que me gusta
-
-NOTE
-Esta traducción esta hecha por Kyle para que
-Algunos amigos puedan verla con sus padres.
-
-1
-00:02:15.000 --> 00:02:20.000
-- Ta en kopp varmt te.
-- Det är inte varmt.
-
-2
-00:02:20.000 --> 00:02:25.000
-- Har en kopp te.
-- Det smakar som te.
-
-NOTE Esta ultima línea puede no estar bien traducida.
-
-3
-00:02:25.000 --> 00:02:30.000
-- Ta en kopp
-
- -

Estilizando anotaciones WebVTT

- -

Tu puedes estilizar anotaciones WebVTT buscado elementos que coincidan con el pseudoelemento {{cssxref("::cue")}}.

- -

Dentro del CSS del sitio

- -
video::cue {
-  background-image: linear-gradient(to bottom, dimgray, lightgray);
-  color: papayawhip;
-}
-
-video::cue(b) {
-  color: peachpuff;
-}
-
- -

Aquí, todos los elementos de video estan estilizados para usar un gradiente gris como fondo, con "papayawhip" como color principal. Además el texto en negrita usando el elemento {{HTMLElement("b")}} tiene el color "peachpuff".

- -

El ejemplo HTML de abajo actualemte se encarga de mostrar los archivos multimedia él solo.

- -
<video controls autoplay src="video.webm">
- <track default src="track.vtt">
-</video>
-
- -

Within the WebVTT file itself

- -

You can also define the style directly in the WebVTT file. In this case, you insert your CSS rules into the file with each rule preceded by the string "STYLE" all by itelf on a line of text, as shown below:

- -
WEBVTT
-
-STYLE
-::cue {
-  background-image: linear-gradient(to bottom, dimgray, lightgray);
-  color: papayawhip;
-}
-/* Style blocks cannot use blank lines nor "dash dash greater than" */
-
-NOTE comment blocks can be used between style blocks.
-
-STYLE
-::cue(b) {
-  color: peachpuff;
-}
-
-00:00:00.000 --> 00:00:10.000
-- Hello <b>world</b>.
-
-NOTE style blocks cannot appear after the first cue.
- -

We can also use identifiers inside WebVTT file, which can be used for defining a new style for some particular cues in the file. The example where we wanted the transcription text to be red highlighted and the other part to remain normal, we can define it as follows using CSS. Where it must be noted that the CSS uses escape sequences the way they are used in HTML pages:

- -
WEBVTT
-
-1
-00:00.000 --> 00:02.000
-That’s an, an, that’s an L!
-
-crédit de transcription
-00:04.000 --> 00:05.000
-Transcrit par Célestes™
-
- -
::cue(#\31) { color: lime; }
-::cue(#crédit\ de\ transcription) { color: red; }
- -

Positioning of text tracks is also supported, by including positioning information after the timings in a cue, as seen below (see {{anch("Cue settings")}} for more information):

- -
WEBVTT
-
-00:00:00.000 --> 00:00:04.000 position:10%,line-left align:left size:35%
-Where did he go?
-
-00:00:03.000 --> 00:00:06.500 position:90% align:right size:35%
-I think he went down this lane.
-
-00:00:04.000 --> 00:00:06.500 position:45%,line-right align:center size:35%
-What are you waiting for?
- -

WebVTT cues

- -

A cue is a single subtitle block that has a single start time, end time, and textual payload. Example 6 consists of the header, a blank line, and then five cues separated by blank lines. A cue consists of five components:

- - - -
Example 7 - Example of a cue
- -
1 - Title Crawl
-00:00:05.000 --> 00:00:10.000 line:0 position:20% size:60% align:start
-Some time ago in a place rather distant....
- -

Cue identifier

- -

The identifier is a name that identifies the cue. It can be used to reference the cue from a script. It must not contain a newline and cannot contain the string "-->". It must end with a single newline. They do not have to be unique, although it is common to number them (e.g., 1, 2, 3, ...).

- -
Example 8 - Cue identifier from Example 7
- -
1 - Title Crawl
- -
Example 9 - Common usage of identifiers
- -
WEBVTT
-
-1
-00:00:22.230 --> 00:00:24.606
-This is the first subtitle.
-
-2
-00:00:30.739 --> 00:00:34.074
-This is the second.
-
-3
-00:00:34.159 --> 00:00:35.743
-Third
-
- -

Cue timings

- -

A cue timing indicates when the cue is shown. It has a start and end time which are represented by timestamps. The end time must be greater than the start time, and the start time must be greater than or equal to all previous start times. Cues may have overlapping timings.

- -

If the WebVTT file is being used for chapters ({{HTMLElement("track")}} {{htmlattrxref("kind")}} is chapters) then the file cannot have overlapping timings.

- -

Each cue timing contains five components:

- - - -

The timestamps must be in one of two formats:

- - - -

Where the components are defined as follows:

- - - -
Example 10 - Basic cue timing examples
- -
00:00:22.230 --> 00:00:24.606
-00:00:30.739 --> 00:00:34.074
-00:00:34.159 --> 00:00:35.743
-00:00:35.827 --> 00:00:40.122
- -
Example 11 - Overlapping cue timing examples
- -
00:00:00.000 --> 00:00:10.000
-00:00:05.000 --> 00:01:00.000
-00:00:30.000 --> 00:00:50.000
- -
Example 12 - Non-overlapping cue timing examples
- -
00:00:00.000 --> 00:00:10.000
-00:00:10.000 --> 00:01:00.581
-00:01:00.581 --> 00:02:00.100
-00:02:01.000 --> 00:02:01.000
- -

Cue settings

- -

Cue settings are optional components used to position where the cue payload text will be displayed over the video. This includes whether the text is displayed horizontally or vertically. There can be zero or more of them, and they can be used in any order so long as each setting is used no more than once.

- -

The cue settings are added to the right of the cue timings. There must be one or more spaces between the cue timing and the first setting and between each setting. A setting's name and value are separated by a colon. The settings are case sensitive so use lower case as shown. There are five cue settings:

- - - -
Example 13 - Cue setting examples
- -

The first line demonstrates no settings. The second line might be used to overlay text on a sign or label. The third line might be used for a title. The last line might be used for an Asian language.

- -
00:00:05.000 --> 00:00:10.000
-00:00:05.000 --> 00:00:10.000 line:63% position:72% align:start
-00:00:05.000 --> 00:00:10.000 line:0 position:20% size:60% align:start
-00:00:05.000 --> 00:00:10.000 vertical:rt line:-1 align:end
-
- -

Cue payload

- -

The payload is where the main information or content is located. In normal usage the payload contains the subtitles to be displayed. The payload text may contain newlines but it cannot contain a blank line, which is equivalent to two consecutive newlines. A blank line signifies the end of a cue.

- -

A cue text payload cannot contain the string "-->", the ampersand character (&), or the less-than sign (<). Instead use the escape sequence "&amp;" for ampersand and "&lt;" for less-than. It is also recommended that you use the greater-than escape sequence "&gt;" instead of the greater-than character (>) to avoid confusion with tags. If you are using the WebVTT file for metadata these restrictions do not apply.

- -

In addition to the three escape sequences mentioned above, there are fours others. They are listed in the table below.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Table 6 - Escape sequences
NameCharacterEscape Sequence
Ampersand&&amp;
Less-than<&lt;
Greater-than>&gt;
Left-to-right mark&lrm;
Right-to-left mark&rlm;
Non-breaking space &nbsp;
- -

Cue payload text tags

- -

There are a number of tags, such as <bold>, that can be used. However, if the WebVTT file is used in a {{HTMLElement("track")}} element where the attribute {{htmlattrxref("kind")}} is chapters then you cannot use tags.

- - - -

The following tags are the HTML tags allowed in a cue and require opening and closing tags (e.g., <b>text</b>).

- - - -

Interfaces

- -

There are two interfaces or APIs used in WebVTT which are:

- -

VTTCue interface

- -

It is used for providing an interface in Document Object Model API, where different attributes supported by it can be used to prepare and alter the cues in number of ways.

- -

Constructor is the first point for starting the Cue which is defined using the default constructor VTTCue(startTime, endTime, text) where starting time, ending time and text for cue can be adjusted. After that we can set the region for that particular cue to which this cue belongs using cue.region. Vertical, horizontal, line, lineAlign, Position, positionAlign, text, size and Align can be used to alter the cue and its formation, just like we can alter the objects form, shape and visibility in HTML using CSS. But the VTTCue interface is within the WebVTT provides the vast range of adjustment variables which can be used directly to alter the Cue. Following interface can be used to expose WebVTT cues in DOM API:

- -
enum AutoKeyword { "auto" };
-enum DirectionSetting { "" /* horizontal */, "rl", "lr" };
-enum LineAlignSetting { "start", "center", "end" };
-enum PositionAlignSetting { "line-left", "center", "line-right", "auto" };
-enum AlignSetting { "start", "center", "end", "left", "right" };
-[Constructor(double startTime, double endTime, DOMString text)]
-interface VTTCue : TextTrackCue {
-  attribute VTTRegion? region;
-  attribute DirectionSetting vertical;
-  attribute boolean snapToLines;
-  attribute (double or AutoKeyword) line;
-  attribute LineAlignSetting lineAlign;
-  attribute (double or AutoKeyword) position;
-  attribute PositionAlignSetting positionAlign;
-  attribute double size;
-  attribute AlignSetting align;
-  attribute DOMString text;
-  DocumentFragment getCueAsHTML();
-};
- -

VTT Region interface

- -

This is the second interface in WebVTT API.

- -

The new keyword can be used for defining a new VTTRegion object which can then be used for containing the multiple cues. There are several properties of VTTRegion which are width, lines, regionAnchorX, RegionAnchorY, viewportAnchorX, viewportAnchorY and scroll that can be used to specify the look and feel of this VTT region. The interface code is given below which can be used to expose the WebVTT regions in DOM API:

- -
enum ScrollSetting { "" /* none */, "up" };
-[Constructor]
-interface VTTRegion {
-  attribute double width;
-  attribute long lines;
-  attribute double regionAnchorX;
-  attribute double regionAnchorY;
-  attribute double viewportAnchorX;
-  attribute double viewportAnchorY;
-  attribute ScrollSetting scroll;
-};
- -

Methods and properties

- -

The methods used in WebVTT are those which are used to alter the cue or region as the attributes for both interfaces are different. We can categorize them for better understanding relating to each interface in WebVTT:

- - - -

Tutorial on how to write a WebVTT file

- -

There are few steps that can be followed to write a simple webVTT file. Before start, it must be noted that you can make use of a notepad and then save the file as ‘.vtt’ file. Steps are given below:

- -
    -
  1. Open a notepad.
  2. -
  3. The first line of WebVTT is standardized similar to the way some other languages require you to put headers as the file starts to indicate the file type. On the very first line you have to write:
  4. -
- -
WEBVTT
- -

      3. Leave the second line blank, and on the third line the time for first cue is to be specified. For example, for a first cue starting at time 1 second and ending at 5 seconds, it is written as:

- -
00:01.000 --> 00:05.000
- -
    -
  1. On the next line you can write the caption for this cue which will run from 1st second to the 5th second, inclusive.
  2. -
  3. Following the similar steps, a complete WebVTT file for specific video or audio file can be made.
  4. -
- -

CSS pseudo-classes

- -

CSS pseudo classes allow us to classify the type of object which we want to differentiate from other types of objects. It works in similar manner in WebVTT files as it works in HTML file.

- -

It is one of the good features supported by WebVTT is the localization and use of class elements which can be used in same way they are used in HTML and CSS to classify the style for particular type of objects, but here these are used for styling and classifying the Cues as shown below:

- -
WEBVTT
-
-04:02.500 --> 04:05.000
-J’ai commencé le basket à l'âge de 13, 14 ans
-
-04:05.001 --> 04:07.800
-Sur les <i.foreignphrase><lang en>playground</lang></i>, ici à Montpellier
- -

In the above example it can be observed that we can use the identifier and pseudo class name for defining the language of caption, where <i> tag is for italics.

- -

The type of pseudo class is determined by the selector it is using and working is similar in nature as it works in HTML. Following CSS pseudo classes can be used:

- - - -

Where p and a are the tags which are used in HTML for paragraph and link, respectively and they can be replaced by identifiers which are used for Cues in WebVTT file.

- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName("WebVTT")}}{{Spec2("WebVTT")}}Initial definition
- -

Browser compatibility

- -

VTTCue interface

- -
- - -

{{Compat("api.VTTCue", 0)}}

- -

TextTrack interface

- -
- - -

{{Compat("api.TextTrack", 0)}}

- -

Notes

-
-
- -

Prior to Firefox 50, the AlignSetting enum (representing possible values for {{domxref("VTTCue.align")}}) incorrectly included the value "middle" instead of "center". This has been corrected.

- -

WebVTT was implemented in Firefox 24 behind the preference {{pref("media.webvtt.enabled")}}, which is disabled by default; you can enable it by setting this preference to true. WebVTT is enabled by default starting in Firefox 31 and can be disabled by setting the preference to false.

- -

Prior to Firefox 58, the REGION keyword was creating {{domxref("VTTRegion")}} objects, but they were not being used. Firefox 58 now fully supports VTTRegion and its use; however, this feature is disabled by default behind the preference media.webvtt.regions.enabled; set it to true to enable region support in Firefox 58. Regions are enabled by default starting in Firefox 59 (see bugs {{bug(1338030)}} and {{bug(1415805)}}).

diff --git a/files/es/web/api/window/domcontentloaded_event/index.html b/files/es/web/api/window/domcontentloaded_event/index.html deleted file mode 100644 index 0659abde6f..0000000000 --- a/files/es/web/api/window/domcontentloaded_event/index.html +++ /dev/null @@ -1,149 +0,0 @@ ---- -title: DOMContentLoaded -slug: Web/API/Window/DOMContentLoaded_event -translation_of: Web/API/Window/DOMContentLoaded_event -original_slug: Web/Events/DOMContentLoaded ---- -

El evento DOMContentLoaded es disparado cuando el documento HTML ha sido completamente cargado y parseado, sin esperar hojas de estilo, images y subframes para  finalizar la carga. Un evento muy diferente - load - debería ser usado solo para detectar una carga completa de la página. Es un error increíblemente popular usar load cuando DOMContentLoaded sería mucho más apropiado, así que úsalo con cuidado.

- -

JavaScript síncrono pausa el parseo del DOM.

- -

También hay mucho propósito general y bibliotecas autónomas que ofrecen métodos de navegador cruzado para detectar que el DOM está preparado.

- -

Speeding up

- -

If you want DOM to get parsed as fast as possible after the user had requested the page, some things you could do is turn your JavaScript asynchronous and to optimize loading of stylesheets which if used as usual, slow down page load due to being loaded in parallel, "stealing" traffic from the main html document.

- -

General info

- -
-
Specification
-
HTML5
-
Interface
-
Event
-
Bubbles
-
Yes
-
Cancelable
-
Yes (although specified as a simple event that isn't cancelable)
-
Target
-
Document
-
Default Action
-
None.
-
- -

Properties

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PropertyTypeDescription
target {{readonlyInline}}{{domxref("EventTarget")}}The event target (the topmost target in the DOM tree).
type {{readonlyInline}}{{domxref("DOMString")}}The type of event.
bubbles {{readonlyInline}}{{jsxref("Boolean")}}Whether the event normally bubbles or not.
cancelable {{readonlyInline}}{{jsxref("Boolean")}}Whether the event is cancellable or not.
- -

Example

- -
<script>
-  document.addEventListener("DOMContentLoaded", function(event) {
-    console.log("DOM fully loaded and parsed");
-  });
-</script>
-
- -
<script>
-  document.addEventListener("DOMContentLoaded", function(event) {
-    console.log("DOM fully loaded and parsed");
-  });
-
-for(var i=0; i<1000000000; i++)
-{} // this synchronous script is going to delay parsing of the DOM. So the DOMContentLoaded event is going to launch later.
-</script>
-
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0[1]{{CompatGeckoDesktop("1")}}[1]9.0[2]9.03.1[1]
-
- -
- - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}[1]{{CompatGeckoMobile("1")}}[1]{{CompatUnknown}}[2]{{CompatVersionUnknown}}{{CompatVersionUnknown}}[1]
-
- -

[1] Bubbling for this event is supported by at least Gecko 1.9.2, Chrome 6, and Safari 4.

- -

[2] Internet Explorer 8 supports the readystatechange event, which can be used to detect when the DOM is ready. In earlier versions of Internet Explorer, this state can be detected by repeatedly trying to execute document.documentElement.doScroll("left");, as this snippet will throw an error until the DOM is ready.

- - - - diff --git a/files/es/web/api/worker/postmessage/index.html b/files/es/web/api/worker/postmessage/index.html deleted file mode 100644 index c47fe400fc..0000000000 --- a/files/es/web/api/worker/postmessage/index.html +++ /dev/null @@ -1,206 +0,0 @@ ---- -title: Worker.postMessage() -slug: Web/API/Worker/postMessage -translation_of: Web/API/Worker/postMessage ---- -

{{APIRef("Web Workers API")}}

- -

Web Workers API posee un metodo llamado postMessage() el cual envia un mensaje al ambito del worker. Este metodo acepta un parametro, el cual es un dato enviado al worker. El dato puede ser un valor o objeto controlado por el algoritmo strctured clone (incluye referencias ciclicas).

- -

El Worker puede enviar de vuelta información al hilo que lo genero usando el metodo {{domxref("DedicatedWorkerGlobalScope.postMessage")}}.

- -

Syntax

- -
myWorker.postMessage(aMessage, transferList);
- -

Parameters

- -
-
aMessage
-
The object to deliver to the worker; this will be in the data field in the event delivered to the {{domxref("DedicatedWorkerGlobalScope.onmessage")}} handler. This may be any value or JavaScript object handled by the structured clone algorithm, which includes cyclical references.
-
transferList {{optional_inline}}
-
An optional array of {{domxref("Transferable")}} objects to transfer ownership of. If the ownership of an object is transferred, it becomes unusable (neutered) in the context it was sent from and it becomes available only to the worker it was sent to.
-
Only {{domxref("MessagePort")}} and {{domxref("ArrayBuffer")}} objects can be transferred.
-
- -

Returns

- -

Void.

- -

Example

- -

The following code snippet shows creation of a {{domxref("Worker")}} object using the {{domxref("Worker.Worker", "Worker()")}} constructor. When either of two form inputs (first and second) have their values changed, {{event("change")}} events invoke postMessage() to send the value of both inputs to the current worker.

- -
var myWorker = new Worker("worker.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');
-}
-
- -

For a full example, see ourBasic dedicated worker example (run dedicated worker).

- -
-

Note: postMessage() can only send a single object at once. As seen above, if you want to pass multiple values you can send an array.

-
- -

Transfer Example

- -

This example is of a Firefox addon that transfers an ArrayBuffer from the main thread to the ChromeWorker, and then the ChromeWorker trasnfers it back to the main thread.

- -

Main thread code:

- -
var myWorker = new ChromeWorker(self.path + 'myWorker.js');
-
-function handleMessageFromWorker(msg) {
-    console.log('incoming message from worker, msg:', msg);
-    switch (msg.data.aTopic) {
-        case 'do_sendMainArrBuff':
-            sendMainArrBuff(msg.data.aBuf)
-            break;
-        default:
-            throw 'no aTopic on incoming message to ChromeWorker';
-    }
-}
-
-myWorker.addEventListener('message', handleMessageFromWorker);
-
-// Ok lets create the buffer and send it
-var arrBuf = new ArrayBuffer(8);
-console.info('arrBuf.byteLength pre transfer:', arrBuf.byteLength);
-
-myWorker.postMessage(
-    {
-        aTopic: 'do_sendWorkerArrBuff',
-        aBuf: arrBuf // The array buffer that we passed to the transferrable section 3 lines below
-    },
-    [
-        arrBuf // The array buffer we created 9 lines above
-    ]
-);
-
-console.info('arrBuf.byteLength post transfer:', arrBuf.byteLength);
-
- -

Worker code

- -
self.onmessage = function (msg) {
-    switch (msg.data.aTopic) {
-        case 'do_sendWorkerArrBuff':
-                sendWorkerArrBuff(msg.data.aBuf)
-            break;
-        default:
-            throw 'no aTopic on incoming message to ChromeWorker';
-    }
-}
-
-function sendWorkerArrBuff(aBuf) {
-    console.info('from worker, PRE send back aBuf.byteLength:', aBuf.byteLength);
-
-    self.postMessage({aTopic:'do_sendMainArrBuff', aBuf:aBuf}, [aBuf]);
-
-    console.info('from worker, POST send back aBuf.byteLength:', aBuf.byteLength);
-}
-
- -

Output logged

- -
arrBuf.byteLength pre transfer: 8                              bootstrap.js:40
-arrBuf.byteLength post transfer: 0                             bootstrap.js:42
-
-from worker, PRE send back aBuf.byteLength: 8                  myWorker.js:5:2
-
-incoming message from worker, msg: message { ... }             bootstrap.js:20
-got back buf in main thread, aBuf.byteLength: 8                bootstrap.js:12
-
-from worker, POST send back aBuf.byteLength: 0                 myWorker.js:7:2
- -

We see that byteLength goes to 0 as it is trasnferred. To see a fully working example of this Firefox demo addon see here: GitHub :: ChromeWorker - demo-transfer-arraybuffer

- -

Specifications

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#dom-worker-postmessage", "Worker.postMessage()")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName("Web Workers")}}.
{{SpecName('Web Workers', "#dom-worker-postmessage", "Worker.postMessage()")}}{{Spec2('Web Workers')}}Initial definition.
- -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}10.0 [1]{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}10.0 [1]{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

[1] Internet Explorer does not support {{domxref("Transferable")}} objects.

- -

See also

- - diff --git a/files/es/web/api/xmlhttprequest/synchronous_and_asynchronous_requests/index.html b/files/es/web/api/xmlhttprequest/synchronous_and_asynchronous_requests/index.html deleted file mode 100644 index 28675abd79..0000000000 --- a/files/es/web/api/xmlhttprequest/synchronous_and_asynchronous_requests/index.html +++ /dev/null @@ -1,232 +0,0 @@ ---- -title: Solicitudes síncronas y asíncronas -slug: Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests -translation_of: Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests ---- -

XMLHttpRequest soporta solicitudes síncronas y asíncronas, pero la mas preferida es la asíncrona por razones de rendimiento

- -

Las solicitudes síncronas bloquean la ejecución del código, mientras se procesa la solicitud, dejando a la pantalla congelada y dando una experiencia de usuario poco agradable

- -

Peticiones asíncronas

- -

Si se utiliza XMLHttpRequest de forma asíncrona, recibirá una devolución de llamada cuando los datos se hayan recibido . Esto permite que el navegador continúe funcionando de forma normal mientras se procesa la solicitud.

- -

Ejemplo: Enviar un archivo a la consola

- -

Este es el uso más simple de la asíncronia XMLHttpRequest.

- -
var xhr = new XMLHttpRequest();
-xhr.open("GET", "/bar/foo.txt", true);
-xhr.onload = function (e) {
-  if (xhr.readyState === 4) {
-    if (xhr.status === 200) {
-      console.log(xhr.responseText);
-    } else {
-      console.error(xhr.statusText);
-    }
-  }
-};
-xhr.onerror = function (e) {
-  console.error(xhr.statusText);
-};
-xhr.send(null); 
- -

En la linea 2, el ultimo parametro de open() , especifica true para indicar que la solicitud se tratara de forma asíncrona

- -

Line 3 creates an event handler function object and assigns it to the request's onload attribute.  This handler looks at the request's readyState to see if the transaction is complete in line 4, and if it is, and the HTTP status is 200, dumps the received content.  If an error occurred, an error message is displayed.

- -

Line 15 actually initiates the request.  The callback routine is called whenever the state of the request changes.

- -

Ejemplo: Creando una funcion estandar para leer archivos externos.

- -

In some cases you must read many external files. This is a standard function which uses the XMLHttpRequest object asynchronously in order to switch the content of the read file to a specified listener.

- -
function xhrSuccess () { this.callback.apply(this, this.arguments); }
-
-function xhrError () { console.error(this.statusText); }
-
-function loadFile (sURL, fCallback /*, argumentToPass1, argumentToPass2, etc. */) {
-  var oReq = new XMLHttpRequest();
-  oReq.callback = fCallback;
-  oReq.arguments = Array.prototype.slice.call(arguments, 2);
-  oReq.onload = xhrSuccess;
-  oReq.onerror = xhrError;
-  oReq.open("get", sURL, true);
-  oReq.send(null);
-}
-
- -

Usage:

- -
function showMessage (sMsg) {
-  alert(sMsg + this.responseText);
-}
-
-loadFile("message.txt", showMessage, "New message!\n\n");
-
- -

The signature of the utility function loadFile declares (i) a target URL to read (via HTTP GET), (ii) a function to execute on successful completion of the XHR operation, and (iii) an arbitrary list of additional arguments that are "passed through" the XHR object to the success callback function.

- -

Line 1 declares a function invoked when the XHR operation completes successfully.  It, in turn, invokes the callback function specified in the invocation of the loadFile function (in this case, the function showMessage) which has been assigned to a property of the XHR object (Line 7). The additional arguments (if any) supplied to the invocation of function loadFile are "applied" to the running of the callback function.

- -

Line 3 declares a function invoked when the XHR operation fails to complete successfully.

- -

Line 7 stores on the XHR object the success callback function given as the second argument to loadFile.

- -

Line 8 slices the arguments array given to the invocation of loadFile. Starting with the third argument, all remaining arguments are collected, assigned to the arguments property of the variable oReq, passed to the success callback function xhrSuccess., and ultimately supplied to the callback function (in this case, showMessage) which is invoked by function xhrSuccess.

- -

Line 9 designates the function xhrSuccess as the callback to be invoked when the onload event fires, that is, when the XHR sucessfully completes.  

- -

Line 10 designates the function xhrError as the callback to be invoked when the XHR requests fails to complete.

- -

Line 11 specifies true for its third parameter to indicate that the request should be handled asynchronously.

- -

Line 12 actually initiates the request.

- -

Example: using a timeout

- -

You can use a timeout to prevent hanging your code forever while waiting for a read to occur. This is done by setting the value of the timeout property on the XMLHttpRequest object, as shown in the code below:

- -
function loadFile(sUrl, timeout, callback){
-
-    var args = arguments.slice(3);
-    var xhr = new XMLHttpRequest();
-    xhr.ontimeout = function () {
-        console.error("The request for " + url + " timed out.");
-    };
-    xhr.onload = function() {
-        if (xhr.readyState === 4) {
-            if (xhr.status === 200) {
-                callback.apply(xhr, args);
-            } else {
-                console.error(xhr.statusText);
-            }
-        }
-    };
-    xhr.open("GET", url, true);
-    xhr.timeout = timeout;
-    xhr.send(null);
-}
- -

Notice the addition of code to handle the "timeout" event by setting the ontimeout handler.

- -

Usage:

- -
function showMessage (sMsg) {
-  alert(sMsg + this.responseText);
-}
-
-loadFile("message.txt", 2000, showMessage, "New message!\n");
-
- -

Here, we're specifying a timeout of 2000 ms.

- -
-

Note: Support for timeout was added in {{Gecko("12.0")}}.

-
- -

Synchronous request

- -
Note: Starting with Gecko 30.0 {{ geckoRelease("30.0") }}, synchronous requests on the main thread have been deprecated due to the negative effects to the user experience.
- -

In rare cases, the use of a synchronous method is preferable to an asynchronous one.

- -

Example: HTTP synchronous request

- -

This example demonstrates how to make a simple synchronous request.

- -
var request = new XMLHttpRequest();
-request.open('GET', '/bar/foo.txt', false);  // `false` makes the request synchronous
-request.send(null);
-
-if (request.status === 200) {
-  console.log(request.responseText);
-}
-
- -

Line 3 sends the request.  The null parameter indicates that no body content is needed for the GET request.

- -

Line 5 checks the status code after the transaction is completed.  If the result is 200 -- HTTP's "OK" result -- the document's text content is output to the console.

- -

Example: Synchronous HTTP request from a Worker

- -

One of the few cases in which a synchronous request does not usually block execution is the use of XMLHttpRequest within a Worker.

- -

example.html (the main page):

- -
<!doctype html>
-<html>
-<head>
-<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
-<title>MDN Example</title>
-<script type="text/javascript">
-  var worker = new Worker("myTask.js");
-  worker.onmessage = function(event) {
-    alert("Worker said: " + event.data);
-  };
-
-  worker.postMessage("Hello");
-</script>
-</head>
-<body></body>
-</html>
-
- -

myFile.txt (the target of the synchronous XMLHttpRequest invocation):

- -
Hello World!!
-
- -

myTask.js (the Worker):

- -
self.onmessage = function (event) {
-  if (event.data === "Hello") {
-    var xhr = new XMLHttpRequest();
-    xhr.open("GET", "myFile.txt", false);  // synchronous request
-    xhr.send(null);
-    self.postMessage(xhr.responseText);
-  }
-};
-
- -
Note: The effect, because of the use of the Worker, is however asynchronous.
- -

It could be useful in order to interact in background with the server or to preload some content. See Using web workers for examples and details.

- -

Adapting Sync XHR usecases to the Beacon API

- -

There are some cases in which the synchronous usage of XMLHttpRequest was not replaceable, like during the window.onunload and window.onbeforeunload events.  The navigator.sendBeacon API can support these usecases typically while delivering a good UX.

- -

The following example (from the sendBeacon docs) shows a theoretical analytics code that attempts to submit data to a server by using a synchronous XMLHttpRequest in an unload handler. This results in the unload of the page to be delayed.

- -
window.addEventListener('unload', logData, false);
-
-function logData() {
-    var client = new XMLHttpRequest();
-    client.open("POST", "/log", false); // third parameter indicates sync xhr. :(
-    client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
-    client.send(analyticsData);
-}
-
- -

Using the sendBeacon() method, the data will be transmitted asynchronously to the web server when the User Agent has had an opportunity to do so, without delaying the unload or affecting the performance of the next navigation.

- -

The following example shows a theoretical analytics code pattern that submits data to a server using the by using the sendBeacon() method.

- -
window.addEventListener('unload', logData, false);
-
-function logData() {
-    navigator.sendBeacon("/log", analyticsData);
-}
-
- -

See also

- - - -

{{ languages( {"zh-cn": "zh-cn/DOM/XMLHttpRequest/Synchronous_and_Asynchronous_Requests" } ) }}

-- cgit v1.2.3-54-g00ecf