diff options
author | Peter Bengtsson <mail@peterbe.com> | 2021-07-15 13:42:10 -0400 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-07-15 13:42:10 -0400 |
commit | 4f0e1ec1c2772904c033f747dc38a08223e8d661 (patch) | |
tree | 6212d976fd9f708d4f13e7d472bd765341661c1b /files/es/web/api | |
parent | d79f316e1c617b165487da0198765d992cce2fff (diff) | |
download | translated-content-4f0e1ec1c2772904c033f747dc38a08223e8d661.tar.gz translated-content-4f0e1ec1c2772904c033f747dc38a08223e8d661.tar.bz2 translated-content-4f0e1ec1c2772904c033f747dc38a08223e8d661.zip |
delete pages that were never translated from en-US (es, part 2) (#1550)
Diffstat (limited to 'files/es/web/api')
-rw-r--r-- | files/es/web/api/audionode/index.html | 154 | ||||
-rw-r--r-- | files/es/web/api/canvas_api/tutorial/hit_regions_and_accessibility/index.html | 100 | ||||
-rw-r--r-- | files/es/web/api/filesystem/index.html | 118 | ||||
-rw-r--r-- | files/es/web/api/headers/index.html | 135 | ||||
-rw-r--r-- | files/es/web/api/html_drag_and_drop_api/recommended_drag_types/index.html | 145 | ||||
-rw-r--r-- | files/es/web/api/htmlcanvaselement/toblob/index.html | 261 | ||||
-rw-r--r-- | files/es/web/api/mediasource/index.html | 182 | ||||
-rw-r--r-- | files/es/web/api/webvtt_api/index.html | 903 | ||||
-rw-r--r-- | files/es/web/api/window/domcontentloaded_event/index.html | 149 | ||||
-rw-r--r-- | files/es/web/api/worker/postmessage/index.html | 206 | ||||
-rw-r--r-- | files/es/web/api/xmlhttprequest/synchronous_and_asynchronous_requests/index.html | 232 |
11 files changed, 0 insertions, 2585 deletions
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 ---- -<div>{{APIRef("Web Audio API")}}</div> - -<p>La interfaz <strong><code>AudioNode</code></strong> es una interfaz genérica para representar un módulo de procesamiento de audio. Ejemplos:</p> - -<ul> - <li>En un recurso de audio (e.g. an HTML {{HTMLElement("audio")}} or {{HTMLElement("video")}} element, an {{domxref("OscillatorNode")}}, etc.),</li> - <li>the audio destination,</li> - <li>intermediate processing module (e.g. a filter like {{domxref("BiquadFilterNode")}} or {{domxref("ConvolverNode")}}), or</li> - <li>volume control (like {{domxref("GainNode")}})</li> -</ul> - -<p>{{InheritanceDiagram}}</p> - -<p class="note"><strong>Note</strong>: An <code>AudioNode</code> can be target of events, por lo tanto este implementa {{domxref("EventTarget")}} interface.</p> - -<h2 id="Descripción">Descripción</h2> - -<h3 id="The_audio_routing_graph">The audio routing graph</h3> - -<p><img alt="AudioNodes participating in an AudioContext create a audio routing graph." src="https://mdn.mozillademos.org/files/9713/WebAudioBasics.png" style="display: block; height: 230px; margin: 0px auto; width: 677px;"></p> - -<p>Cada <code>AudioNode</code> posee entradas y salidas, y múltiples nodos de audio son conectados para construir un <em>processing graph</em>. Este graph es contenido en {{domxref("AudioContext")}}, y cada nodo de audio solo puede pertecener a un audio context.</p> - -<p>Un <em>source node</em> tiene cero entradas pero una o muchas salidas, y puede ser usado para generar sonido. Por otro lado, un <em>destination node</em> 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 <em>processing nodes</em> which have inputs and outputs. The exact processing done varies from one <code>AudioNode</code> 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).</p> - -<p>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 (<code>GainNode</code>) should be the last node so that volume changes take immediate effect.</p> - -<p>Each input and output has a given amount of <em>channels</em>. 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.</p> - -<p>For a list of all audio nodes, see the <a href="/en-US/docs/Web/API/Web_Audio_API">Web Audio API</a> homepage.</p> - -<h3 id="Creating_an_AudioNode">Creating an <code>AudioNode</code></h3> - -<p>There are two ways to create an <code>AudioNode</code>: via the <em>constuctor</em> and via the <em>factory method</em>.</p> - -<pre class="brush: js;">// 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;</pre> - -<p>Eres libre de usar cualquiera de los constructors o factory methods, o una mezcla de ambos, sin embargo hay ventajas al usar contructores:</p> - -<ul> - <li>All parameters can be set during construction time and don't need to be set individually.</li> - <li>You can <a href="https://github.com/WebAudio/web-audio-api/issues/251">sub-class an audio node</a>. While the actual processing is done internally by the browser and cannot be altered, you could write a wrapper around an audio node to provide custom properties and methods.</li> - <li>Slightly better performance: In both Chrome and Firefox, the factory methods call the constructors internally.</li> -</ul> - -<p>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.</p> - -<p><em>Brief history:</em> The first version of the Web Audio spec only defined the factory methods. After a <a href="https://github.com/WebAudio/web-audio-api/issues/250">design review in October 2013</a>, 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.</p> - -<h2 id="Properties" style="">Properties</h2> - -<dl> - <dt>{{domxref("AudioNode.context")}} {{readonlyInline}}</dt> - <dd>Returns the associated {{domxref("BaseAudioContext")}}, that is the object representing the processing graph the node is participating in.</dd> -</dl> - -<dl> - <dt>{{domxref("AudioNode.numberOfInputs")}} {{readonlyInline}}</dt> - <dd>Returns the number of inputs feeding the node. Source nodes are defined as nodes having a <code>numberOfInputs</code> property with a value of <code>0</code>.</dd> -</dl> - -<dl> - <dt>{{domxref("AudioNode.numberOfOutputs")}} {{readonlyInline}}</dt> - <dd>Returns the number of outputs coming out of the node. Destination nodes — like {{ domxref("AudioDestinationNode") }} — have a value of <code>0</code> for this attribute.</dd> -</dl> - -<dl> - <dt>{{domxref("AudioNode.channelCount")}}</dt> - <dd>Represents an integer used to determine how many channels are used when <a href="/en-US/docs/Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API#Up-mixing_and_down-mixing">up-mixing and down-mixing</a> connections to any inputs to the node. Its usage and precise definition depend on the value of {{domxref("AudioNode.channelCountMode")}}.</dd> -</dl> - -<dl> - <dt>{{domxref("AudioNode.channelCountMode")}}</dt> - <dd>Represents an enumerated value describing the way channels must be matched between the node's inputs and outputs.</dd> - <dt>{{domxref("AudioNode.channelInterpretation")}}</dt> - <dd>Represents an enumerated value describing the meaning of the channels. This interpretation will define how audio <a href="/en-US/docs/Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API#Up-mixing_and_down-mixing">up-mixing and down-mixing</a> will happen.<br> - The possible values are <code>"speakers"</code> or <code>"discrete"</code>.</dd> -</dl> - -<h2 id="Methods">Methods</h2> - -<p><em>Also implements methods from the interface </em>{{domxref("EventTarget")}}.</p> - -<dl> - <dt>{{domxref("AudioNode.connect()")}}</dt> - <dd>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")}}.</dd> - <dt>{{domxref("AudioNode.disconnect()")}}</dt> - <dd>Allows us to disconnect the current node from another one it is already connected to.</dd> -</dl> - -<h2 id="Example">Example</h2> - -<p>This simple snippet of code shows the creation of some audio nodes, and how the <code>AudioNode</code> properties and methods can be used. You can find examples of such usage on any of the examples linked to on the <a href="/en-US/docs/Web/API/Web_Audio_API">Web Audio API</a> landing page (for example <a href="https://github.com/mdn/violent-theremin">Violent Theremin</a>.)<span class="p"> </span></p> - -<pre class="brush: js;">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;</pre> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('Web Audio API', '#the-audionode-interface', 'AudioNode')}}</td> - <td>{{Spec2('Web Audio API')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<div> - - -<p>{{Compat("api.AudioNode")}}</p> -</div> - -<h2 id="See_also">See also</h2> - -<ul> - <li><a href="/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API">Using the Web Audio API</a></li> -</ul> 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 ---- -<div>{{CanvasSidebar}} {{ PreviousNext("Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas", "Web/API/Canvas_API/Tutorial/Optimizing_canvas") }}</div> - -<div class="summary">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.</div> - -<div class="summary">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.</div> - -<h2 id="Fallback_content">Fallback content</h2> - -<p>The content inside the <code><canvas> ... </canvas></code> 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 <a href="http://www.html5accessibility.com/tests/canvas.html">html5accessibility.com</a> demonstrates how this can be done:</p> - -<pre class="brush: html"><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> </pre> - -<p>See the <a href="https://www.youtube.com/watch?v=ABeIFlqYiMQ">video how NVDA reads this example by Steve Faulkner</a>.</p> - -<h2 id="ARIA_rules">ARIA rules</h2> - -<p>Accessible Rich Internet Applications <strong>(<a href="/en-US/docs/Web/Accessibility/ARIA">ARIA</a>)</strong> 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 <a href="/en-US/docs/Web/Accessibility/ARIA">ARIA</a> and <a href="/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques">ARIA techniques</a> for more information.</p> - -<pre class="brush: html"><canvas id="button" tabindex="0" role="button" aria-pressed="false" aria-label="Start game"></canvas> -</pre> - -<h2 id="Hit_regions">Hit regions</h2> - -<p>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).</p> - -<dl> - <dt>{{domxref("CanvasRenderingContext2D.addHitRegion()")}} {{experimental_inline}}</dt> - <dd>Adds a hit region to the canvas.</dd> - <dt>{{domxref("CanvasRenderingContext2D.removeHitRegion()")}} {{experimental_inline}}</dt> - <dd>Removes the hit region with the specified <code>id</code> from the canvas.</dd> - <dt>{{domxref("CanvasRenderingContext2D.clearHitRegions()")}} {{experimental_inline}}</dt> - <dd>Removes all hit regions from the canvas.</dd> -</dl> - -<p>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.</p> - -<pre class="brush: html"><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></pre> - -<p>The <code>addHitRegion()</code> method also takes a <code>control</code> option to route events to an element (that is a descendant of the canvas):</p> - -<pre class="brush: js">ctx.addHitRegion({control: element});</pre> - -<p>This can be useful for routing to {{HTMLElement("input")}} elements, for example. See also this <a href="https://codepen.io/peterj35/pen/PEdLKx">codepen demo</a>.</p> - -<h2 id="Focus_rings">Focus rings</h2> - -<p>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 <code>drawFocusIfNeeded</code> property can be used.</p> - -<dl> - <dt>{{domxref("CanvasRenderingContext2D.drawFocusIfNeeded()")}} {{experimental_inline}}</dt> - <dd>If a given element is focused, this method draws a focus ring around the current path.</dd> -</dl> - -<p>Additionally, the <code>scrollPathIntoView()</code> method can be used to make an element visible on the screen if focused, for example.</p> - -<dl> - <dt>{{domxref("CanvasRenderingContext2D.scrollPathIntoView()")}} {{experimental_inline}}</dt> - <dd>Scrolls the current path or a given path into the view.</dd> -</dl> - -<h2 id="See_also">See also</h2> - -<ul> - <li><a href="https://www.w3.org/WAI/PF/HTML/wiki/Canvas_Accessibility_Use_Cases">Canvas accessibility use cases</a></li> - <li><a href="https://www.w3.org/html/wg/wiki/AddedElementCanvas">Canvas element accessibility issues</a></li> - <li><a href="http://www.paciellogroup.com/blog/2012/06/html5-canvas-accessibility-in-firefox-13/">HTML5 Canvas Accessibility in Firefox 13 – by Steve Faulkner</a></li> - <li><a href="https://html.spec.whatwg.org/multipage/scripting.html#best-practices">Best practices for interactive canvas elements</a></li> -</ul> - -<div>{{ PreviousNext("Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas", "Web/API/Canvas_API/Tutorial/Optimizing_canvas") }}</div> 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 ---- -<p>{{APIRef("File System API")}} {{non-standard_header}}</p> - -<p>La interfaz de la API <strong><code>FileSystem</code></strong> 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()")}}.</p> - -<p>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 <a href="https://developer.chrome.com/apps/fileSystem">here</a>.</p> - -<div class="note"> -<p>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.</p> -</div> - -<h2 id="Conceptos_Basicos">Conceptos Basicos</h2> - -<p>Hay dos formas de acceder a un objeto <code>FileSystem</code> :</p> - -<ol> - <li>You can directly ask for one representing a sandboxed file system created just for your web app directly by calling <code>window.requestFileSystem()</code>. If that call is successful, it executes a callback handler, which receives as a parameter a <code>FileSystem</code> object describing the file system.</li> - <li>You can get it from a file system entry object, through its {{domxref("FileSystemEntry.filesystem", "filesystem")}} property.</li> -</ol> - -<h2 id="Propiedades">Propiedades</h2> - -<dl> - <dt>{{domxref("FileSystem.name")}} {{ReadOnlyInline}}</dt> - <dd>A {{domxref("USVString")}} representing the file system's name. This name is unique among the entire list of exposed file systems.</dd> - <dt>{{domxref("FileSystem.root")}} {{ReadOnlyInline}}</dt> - <dd>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.</dd> -</dl> - -<h2 id="Especificaciones">Especificaciones</h2> - -<table class="standard-table"> - <thead> - <tr> - <th scope="col">Especificación</th> - <th scope="col">Estado</th> - <th scope="col">Comentario</th> - </tr> - </thead> - <tbody> - <tr> - <td>{{SpecName('File System API')}}</td> - <td>{{Spec2('File System API')}}</td> - <td>Draft of proposed API</td> - </tr> - </tbody> -</table> - -<p>This API has no official W3C or WHATWG specification.</p> - -<h2 id="Browser_compatibility" name="Browser_compatibility">Compatibilidad entre navegadores </h2> - -<p>{{ CompatibilityTable }}</p> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Caracteristica</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Microsoft Edge</th> - <th>Opera</th> - <th>Safari (WebKit)</th> - </tr> - <tr> - <td>Soporte basico</td> - <td>13{{ property_prefix("webkit") }}</td> - <td>{{ CompatGeckoDesktop(50) }}</td> - <td>{{ CompatNo }}</td> - <td>{{CompatVersionUnknown}}<sup>[1]</sup></td> - <td>{{CompatVersionUnknown}} {{ property_prefix("webkit") }}</td> - <td>{{ CompatNo }}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Phone</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{ CompatNo }}</td> - <td>0.16{{ property_prefix("webkit") }}</td> - <td>{{ CompatGeckoMobile(50) }}</td> - <td>{{ CompatNo }}</td> - <td>{{ CompatNo }}</td> - <td>{{ CompatNo }}</td> - </tr> - </tbody> -</table> -</div> - -<p>[1] Microsoft Edge implements this interface under the name <code>WebKitFileSystem</code>, 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.</p> - -<h2 id="See_also">See also</h2> - -<ul> - <li><a href="/en-US/docs/Web/API/File_and_Directory_Entries_API">File and Directory Entries API</a></li> - <li><a href="/en-US/docs/Web/API/File_and_Directory_Entries_API/Introduction">Introduction to the File System API</a></li> - <li>{{domxref("FileSystemEntry")}}, {{domxref("FileSystemFileEntry")}}, and {{domxref("FileSystemDirectoryEntry")}}</li> - <li>MSDN article: <a href="https://msdn.microsoft.com/library/mt732564">WebKitFileSystem object</a></li> -</ul> 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 ---- -<div>{{ APIRef("Fetch") }}</div> - -<div>La interfaz <strong><code>Headers</code></strong> de la <a href="/en-US/docs/Web/API/Fetch_API">Fetch API</a> permite realizar diversas acciones en los Headers de solicitud y respuesta HTTP.Estas acciones incluyen recuperar, establecer, agregar y eliminar. Un objeto <code>Header</code> tiene una lista asociada que inicialmente está vacía, y consta de cero o más pares de nombre y valor.</div> - -<div>Es posible añadir metodos de uso como <span style="line-height: 19.0909080505371px;">{{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.</span></div> - -<div>Por razones de seguridad, algunos headers pueden ser controlados unicamente por el <strong>user agent</strong>. 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)}}.</div> - -<p>A Headers object also has an associated guard, which takes a value of <code>immutable</code>, <code>request</code>, <code>request-no-cors</code>, <code>response</code>, or <code>none</code>. 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")}}.</p> - -<p>You can retrieve a <code>Headers</code> object via the {{domxref("Request.headers")}} and {{domxref("Response.headers")}} properties, and create a new <code>Headers</code> object using the {{domxref("Headers.Headers()")}} constructor.</p> - -<p>An object implementing <code>Headers</code> can directly be used in a {{jsxref("Statements/for...of", "for...of")}} structure, instead of {{domxref('Headers.entries()', 'entries()')}}: <code>for (var p of myHeaders)</code> is equivalent to <code>for (var p of myHeaders.entries())</code>.</p> - -<div class="note"> -<p><strong>Note</strong>: you can find more out about the available headers by reading our <a href="/en-US/docs/Web/HTTP/Headers">HTTP headers</a> reference.</p> -</div> - -<h2 id="Constructor">Constructor</h2> - -<dl> - <dt>{{domxref("Headers.Headers()")}}</dt> - <dd>Creates a new <code>Headers</code> object.</dd> -</dl> - -<h2 id="Methods">Methods</h2> - -<dl> - <dt>{{domxref("Headers.append()")}}</dt> - <dd>Appends a new value onto an existing header inside a <code>Headers</code> object, or adds the header if it does not already exist.</dd> - <dt>{{domxref("Headers.delete()")}}</dt> - <dd>Deletes a header from a <code>Headers</code> object.</dd> - <dt>{{domxref("Headers.entries()")}}</dt> - <dd>Returns an {{jsxref("Iteration_protocols","iterator")}} allowing to go through all key/value pairs contained in this object.</dd> - <dt>{{domxref("Headers.forEach()")}}</dt> - <dd>Executes a provided function once for each array element.</dd> - <dt>{{domxref("Headers.get()")}}</dt> - <dd>Returns a {{domxref("ByteString")}} sequence of all the values of a header within a <code>Headers</code> object with a given name.</dd> - <dt>{{domxref("Headers.has()")}}</dt> - <dd>Returns a boolean stating whether a <code>Headers</code> object contains a certain header.</dd> - <dt>{{domxref("Headers.keys()")}}</dt> - <dd>Returns an {{jsxref("Iteration_protocols", "iterator")}} allowing you to go through all keys of the key/value pairs contained in this object.</dd> - <dt>{{domxref("Headers.set()")}}</dt> - <dd>Sets a new value for an existing header inside a <code>Headers</code> object, or adds the header if it does not already exist.</dd> - <dt>{{domxref("Headers.values()")}}</dt> - <dd>Returns an {{jsxref("Iteration_protocols", "iterator")}} allowing you to go through all values of the key/value pairs contained in this object.</dd> -</dl> - -<div class="note"> -<p><strong>Note</strong>: 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.</p> -</div> - -<div class="note"> -<p><strong>Note</strong>: All of the Headers methods will throw a <code>TypeError</code> if you try to pass in a reference to a name that isn't a <a href="https://fetch.spec.whatwg.org/#concept-header-name">valid HTTP Header name</a>. The mutation operations will throw a <code>TypeError</code> if the header has an immutable {{Glossary("Guard")}}. In any other failure case they fail silently.</p> -</div> - -<div class="note"> -<p><strong>Note</strong>: When Header values are iterated over, they are automatically sorted in lexicographical order, and values from duplicate header names are combined.</p> -</div> - -<h3 id="Obsolete_methods">Obsolete methods</h3> - -<dl> - <dt>{{domxref("Headers.getAll()")}}</dt> - <dd>Used to return an array of all the values of a header within a <code>Headers</code> 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.</dd> -</dl> - -<h2 id="Examples">Examples</h2> - -<p>In the following snippet, we create a new header using the <code>Headers()</code> constructor, add a new header to it using <code>append()</code>, then return that header value using <code>get()</code>:</p> - -<pre class="brush: js">var myHeaders = new Headers(); - -myHeaders.append('Content-Type', 'text/xml'); -myHeaders.get('Content-Type') // should return 'text/xml' -</pre> - -<p>The same can be achieved by passing an array of arrays or an object literal to the constructor:</p> - -<pre class="brush: js">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' -</pre> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('Fetch','#headers-class','Headers')}}</td> - <td>{{Spec2('Fetch')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - - - -<p>{{Compat("api.Headers")}}</p> - -<h2 id="See_also">See also</h2> - -<ul> - <li><a href="/en-US/docs/Web/API/ServiceWorker_API">ServiceWorker API</a></li> - <li><a href="/en-US/docs/Web/HTTP/Access_control_CORS">HTTP access control (CORS)</a></li> - <li><a href="/en-US/docs/Web/HTTP">HTTP</a></li> -</ul> - -<p> </p> 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 ---- -<p>A continuación se describe la mejor practica para utilizar los datos a ser arrastrado.</p> -<h2 id="text" name="text">Arrastramdo Texto</h2> -<p>Al arrastrar el texto, utilice el texto / texto normal. Los datos deben ser la cadena de arrastre. Por ejemplo:</p> -<pre>event.dataTransfer.setData("text/plain", "This is text to drag") -</pre> -<p>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.</p> -<p><span style="line-height: 1.5;">Se recomienda que siempre se agrega datos del tipo </span><code style="font-size: 14px;">text/plain</code><span style="line-height: 1.5;"> </span><span style="line-height: 1.5;">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.</span></p> -<p><span style="line-height: 1.5;">En códigos más viejo, encontrara </span><span style="font-family: 'Courier New', 'Andale Mono', monospace; line-height: normal;">text/unicode o </span>el tipo<span style="font-family: 'Courier New', 'Andale Mono', monospace; line-height: normal;"> </span><span style="font-family: 'Courier New', 'Andale Mono', monospace; line-height: normal;">Text.</span><span style="line-height: 1.5;">Estos equivalen </span><span style="font-family: 'Courier New', 'Andale Mono', monospace; line-height: normal;">text/plain,</span><span style="line-height: 1.5;">que </span><span style="line-height: 1.5;">guardara y recibia los datos del texto plano en ese lugar</span><font face="Courier New, Andale Mono, monospace"><span style="line-height: normal;">.</span></font></p> -<h2 id="link" name="link">Arrastrando Enlaces</h2> -<p>Los enlaces deben incluir los datos de los dos tipos, el primero debe ser URL utilizando el tipo <span style="font-family: 'Courier New', 'Andale Mono', monospace; line-height: normal;">text/uri-list,</span><span style="line-height: 1.5;">y el segundo es URL utilizando el tipo </span><span style="font-family: 'Courier New', 'Andale Mono', monospace; line-height: normal;">text/plain. </span><span style="line-height: 1.5;">Ambos tipos deben utilizar los mismos datos, la URL del enlace. Por ejemplo:</span></p> -<pre>var dt = event.dataTransfer; -dt.setData("text/uri-list", "http://www.mozilla.org"); -dt.setData("text/plain", "http://www.mozilla.org"); -</pre> -<p>Es constumbre, establecer el tipo <span style="font-family: 'Courier New', 'Andale Mono', monospace; line-height: normal;">text/plain de ultimo, </span><span style="line-height: 1.5;">, ya que es menos específico que el tipo de URI.</span></p> -<p>Note que el tipo de URL <span style="font-family: 'Courier New', 'Andale Mono', monospace; line-height: normal;">uri-list </span><span style="line-height: 1.5;">es con una "i", no una "L"</span></p> -<p><span style="line-height: 1.5;">Note that the URL type is </span><code style="font-size: 14px;">uri-list</code><span style="line-height: 1.5;"> with an 'I', not with an 'L'.</span></p> -<p>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 <code>text/plain</code> version of the drag data should include all links but should not include the comments.</p> -<p>For example:</p> -<pre>http://www.mozilla.org -#A second link -http://www.xulplanet.com -</pre> -<p>This sample <code>text/uri-list</code> data contains two links and a comment.</p> -<p>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 <code>URL</code> may be used to refer to the first valid link within the data for the <code>text/uri-list</code> type. You should not add data using the <code>URL</code> type; attempting to do so will just set the value of the <code>text/uri-list</code> type instead.</p> -<pre>var url = event.dataTransfer.getData("URL"); -</pre> -<p>You may also see data using the <code>text/x-moz-url</code> type which is a Mozilla specific type. If it appears, it should be used before the <code>text/uri-list</code> type. It holds the URL of the link followed by the title of the link, separated by a linebreak. For example:</p> -<pre>http://www.mozilla.org -Mozilla -http://www.xulplanet.com -XUL Planet -</pre> -<h2 id="html" name="html">Dragging HTML and XML</h2> -<p>HTML content may use the <code>text/html</code> 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 <code>innerHTML</code> property of an element.</p> -<p>XML content may use the <code>text/xml</code> type, but you should ensure that the data value is well-formed XML.</p> -<p>You may also include a plain text representation of the HTML or XML data using the <code>text/plain</code> type. The data should be just the text and should not include any of the source tags or attributes. For instance:</p> -<pre>var dt = event.dataTransfer; -dt.setData("text/html", "Hello there, <strong>stranger</strong>"); -dt.setData("text/plain", "Hello there, stranger"); -</pre> -<h2 id="file" name="file">Dragging Files</h2> -<p>A local file is dragged using the <code>application/x-moz-file</code> type with a data value that is an <a href="/en/XPCOM_Interface_Reference/nsIFile" title="nsIFile">nsIFile</a> 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 <a href="/En/DragDrop/DataTransfer#mozSetDataAt.28.29" title="mozSetDataAt">mozSetDataAt</a> method to assign the data. Similarly, when retrieving the data, you must use the <a href="/En/DragDrop/DataTransfer#mozGetDataAt.28.29" title="mozGetDataAt">mozGetDataAt</a> method.</p> -<pre>event.dataTransfer.mozSetDataAt("application/x-moz-file", file, 0); -</pre> -<p>If possible, you may also include the file URL of the file using both the <code>text/uri-list</code> and/or <code>text/plain</code> types. These types should be added last so that the more specific <code>application/x-moz-file</code> type has higher priority.</p> -<p>Multiple files will be received during a drop as mutliple items in the data transfer. See <a href="/En/DragDrop/Dragging_and_Dropping_Multiple_Items" title="Dragging and Dropping Multiple Items">Dragging and Dropping Multiple Items</a> for more details about this.</p> -<p>The following example shows how to create an area for receiving dropped files:</p> -<pre><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> -</pre> -<p>In this example, the event returns false only if the data transfer contains the <code>application/x-moz-file</code> 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 <code>instanceof</code> operator is used here as the <a href="/En/DragDrop/DataTransfer#mozGetDataAt.28.29" title="mozGetDataAt">mozGetDataAt</a> method will return an <code>nsISupports</code> 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.</p> -<h2 id="image" name="image">Dragging Images</h2> -<p>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 <code>text/uri-list</code> 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 <a class="internal" href="/en/data_URIs" title="en/The data URL scheme">the data URL scheme</a>.</p> -<p>As with other links, the data for the <code>text/plain</code> 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 <code>text/plain</code> data in this situation.</p> -<p>In chrome or other privileged code, you may also use the <code>image/jpeg</code>, <code>image/png</code> or <code>image/gif</code> types, depending on the type of image. The data should be an object which implements the <a href="/en/XPCOM_Interface_Reference/nsIInputStream" title="nsIInputStream">nsIInputStream</a> 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.</p> -<p>You should also include the <code>application/x-moz-file</code> type if the image is located on disk. In fact, this a common way in which image files are dragged.</p> -<p>It is important to set the data in the right order, from most specific to least specific. The image type such as <code>image/jpeg</code> should come first, followed by the <code>application/x-moz-file</code> type. Next, you should set the <code>text/uri-list</code> data and finally the <code>text/plain</code> data. For example:</p> -<pre>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); -</pre> -<p>Note that the <a href="/En/DragDrop/DataTransfer#mozGetDataAt.28.29" title="mozGetDataAt">mozGetDataAt</a> 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.</p> -<h2 id="node" name="node">Dragging Nodes</h2> -<p>Nodes and elements in a document may be dragged using the <code>application/x-moz-node</code> 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.</p> -<p>You should always include a plain text alternative for the node.</p> -<h2 id="custom" name="custom">Dragging Custom Data</h2> -<p>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.</p> -<h2 id="filestoos" name="filestoos">Dragging files to an operating system folder</h2> -<p>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:</p> -<pre class="brush: js">// 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... - } - } -} -</pre> -<p>{{ languages( { "ja": "Ja/DragDrop/Recommended_Drag_Types" } ) }}</p> 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 ---- -<div> -<div> -<div>{{APIRef("Canvas API")}}</div> -</div> -</div> - -<p>EL metodo <strong><code>HTMLCanvasElement.toBlob()</code></strong> 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 <code>type</code> no se especifica el tipo de la imagen será <code>image/png</code>. La imagen creada tiene una resolución de 96dpi.<br> - El tercer argumento es usado con las imagenes <code>image/jpeg</code> para especificar la calidad de salida.</p> - -<h2 id="Syntax">Syntax</h2> - -<pre class="syntaxbox"><var>void <em>canvas</em>.toBlob(<em>callback</em>, <em>type</em>, <em>encoderOptions</em>);</var> -</pre> - -<h3 id="Parameters">Parameters</h3> - -<dl> - <dt>callback</dt> - <dd>A callback function with the resulting {{domxref("Blob")}} object as a single argument.</dd> - <dt><code>type</code> {{optional_inline}}</dt> - <dd>A {{domxref("DOMString")}} indicating the image format. The default type is <code>image/png</code>.</dd> - <dt><code>encoderOptions</code> {{optional_inline}}</dt> - <dd>A {{jsxref("Number")}} between <code>0</code> and <code>1</code> indicating image quality if the requested type is <code>image/jpeg </code>or <code>image/webp</code>. If this argument is anything else, the default value for image quality is used. Other arguments are ignored.</dd> -</dl> - -<h3 id="Return_value">Return value</h3> - -<p>None.</p> - -<h2 id="Examples">Examples</h2> - -<h3 id="Getting_a_file_representing_the_canvas">Getting a file representing the canvas</h3> - -<p>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.</p> - -<pre class="brush: js">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); -}); -</pre> - -<p>Note that here we're creating a PNG image; if you add a second parameter to the <code>toBlob()</code> call, you can specify the image type. For example, to get the image in JPEG format:</p> - -<pre class="brush: js"> canvas.toBlob(function(blob){...}, "image/jpeg", 0.95); // JPEG at 95% quality</pre> - -<div> -<h3 id="A_way_to_convert_a_canvas_to_an_ico_(Mozilla_only)">A way to convert a canvas to an ico (Mozilla only)</h3> - -<p>This uses <code>-moz-parse</code> 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.</p> - -<pre class="brush: js">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');</pre> -</div> - -<h3 id="Save_toBlob_to_disk_with_OS.File_(chromeadd-on_context_only)">Save toBlob to disk with OS.File (chrome/add-on context only)</h3> - -<div class="note"> -<p>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.</p> -</div> - -<pre class="brush: js">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');</pre> - -<h2 id="Polyfill">Polyfill</h2> - -<p>A low performance polyfill based on toDataURL.</p> - -<pre class="brush: js">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'} ) ); - } - }); -} -</pre> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('HTML WHATWG', "scripting.html#dom-canvas-toblob", "HTMLCanvasElement.toBlob")}}</td> - <td>{{Spec2('HTML WHATWG')}}</td> - <td>No change since the latest snapshot, {{SpecName('HTML5 W3C')}}</td> - </tr> - <tr> - <td>{{SpecName('HTML5.1', "scripting-1.html#dom-canvas-toblob", "HTMLCanvasElement.toBlob")}}</td> - <td>{{Spec2('HTML5.1')}}</td> - <td>No change</td> - </tr> - <tr> - <td>{{SpecName('HTML5 W3C', "scripting-1.html#dom-canvas-toblob", "HTMLCanvasElement.toBlob")}}</td> - <td>{{Spec2('HTML5 W3C')}}</td> - <td>Snapshot of the {{SpecName('HTML WHATWG')}} containing the initial definition.</td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<p>{{CompatibilityTable}}</p> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatNo}}<sup>[1]</sup></td> - <td>{{CompatGeckoDesktop('19')}}</td> - <td>{{CompatIE(10)}}{{property_prefix("ms")}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}<sup>[2]</sup></td> - </tr> - <tr> - <td>Image quality parameter (jpeg)</td> - <td>{{CompatNo}}</td> - <td>{{CompatGeckoDesktop('25')}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatGeckoMobile("19")}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatUnknown}}</td> - </tr> - <tr> - <td>Image quality parameter (jpeg)</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatGeckoMobile("25")}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<p>[1] Chrome does not implement this feature yet. See <a href="http://crbug.com/67587">bug 67587</a>.</p> - -<p>[2] WebKit does not implement this feature yet. See {{WebKitBug("71270")}}.</p> - -<h2 id="See_also">See also</h2> - -<ul> - <li>The interface defining it, {{domxref("HTMLCanvasElement")}}.</li> - <li>{{domxref("Blob")}}</li> -</ul> 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 ---- -<p>{{APIRef("Media Source Extensions")}}{{SeeCompatTable}}</p> - -<p>El <strong><code>MediaSource</code></strong> interfaz representa un recurso de media en datos por un {{domxref("HTMLMediaElement")}} objeto. Un <code>MediaSource</code> objeto puede ser atribuido a un {{domxref("HTMLMediaElement")}} para ser reproducido por el usuario.</p> - -<h2 id="Constructor">Constructor</h2> - -<dl> - <dt>{{domxref("MediaSource.MediaSource", "MediaSource()")}}</dt> - <dd>construye y retorna un <code>MediaSource</code> objeto sin asociar un recurso con buffers.</dd> -</dl> - -<h2 id="Propiedades">Propiedades</h2> - -<p><em>Inherits properties from its parent interface, {{domxref("EventTarget")}}.</em></p> - -<dl> - <dt>{{domxref("MediaSource.sourceBuffers")}} {{readonlyInline}}</dt> - <dd>Returns a {{domxref("SourceBufferList")}} object containing the list of {{domxref("SourceBuffer")}} objects associated with this <code>MediaSource</code>.</dd> - <dt>{{domxref("MediaSource.activeSourceBuffers")}} {{readonlyInline}}</dt> - <dd>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.</dd> - <dt>{{domxref("MediaSource.readyState")}} {{readonlyInline}}</dt> - <dd>Returns an enum representing the state of the current <code>MediaSource</code>, whether it is not currently attached to a media element (<code>closed</code>), attached and ready to receive {{domxref("SourceBuffer")}} objects (<code>open</code>), or attached but the stream has been ended via {{domxref("MediaSource.endOfStream()")}} (<code>ended</code>.)</dd> - <dt>{{domxref("MediaSource.duration")}}</dt> - <dd>Gets and sets the duration of the current media being presented.</dd> -</dl> - -<dl> -</dl> - -<dl> -</dl> - -<h2 id="Methods">Methods</h2> - -<p><em>Inherits properties from its parent interface, {{domxref("EventTarget")}}.</em></p> - -<dl> - <dt>{{domxref("MediaSource.addSourceBuffer()")}}</dt> - <dd>Creates a new {{domxref("SourceBuffer")}} of the given MIME type and adds it to the <code>MediaSource</code>'s {{domxref("SourceBuffers")}} list.</dd> - <dt>{{domxref("MediaSource.removeSourceBuffer()")}}</dt> - <dd>Removes the given {{domxref("SourceBuffer")}} from the {{domxref("SourceBuffers")}} list associated with this <code>MediaSource</code> object.</dd> - <dt>{{domxref("MediaSource.endOfStream()")}}</dt> - <dd>Signals the end of the stream.</dd> - <dt> - <h2 id="Static_methods">Static methods</h2> - </dt> - <dt>{{domxref("MediaSource.isTypeSupported()")}}</dt> - <dd>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.</dd> -</dl> - -<h2 id="Examples">Examples</h2> - -<p>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 <a href="http://nickdesaulniers.github.io/netfix/demo/bufferAll.html">viewed live here</a> (you can also <a href="https://github.com/nickdesaulniers/netfix/blob/gh-pages/demo/bufferAll.html">download the source</a> for further investigation.)</p> - -<pre class="brush: js">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(); -};</pre> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('Media Source Extensions', '#mediasource', 'MediaSource')}}</td> - <td>{{Spec2('Media Source Extensions')}}</td> - <td>Initial definition.</td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<div>{{CompatibilityTable}}</div> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari (WebKit)</th> - </tr> - <tr> - <td>Basic support</td> - <td>23</td> - <td>{{CompatGeckoDesktop("25.0")}}<sup>[1]</sup><br> - {{CompatGeckoDesktop("42.0")}}</td> - <td>11<sup>[2]</sup></td> - <td>15</td> - <td>8</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>Firefox OS (Gecko)</th> - <th>IE Phone</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>4.4.4</td> - <td> - <p>{{CompatNo}}</p> - </td> - <td>{{CompatNo}}</td> - <td>11</td> - <td>30</td> - <td>{{CompatNo}}</td> - </tr> - </tbody> -</table> -</div> - -<p>[1] Available after switching the <code>about:config</code> preference <code>media.mediasource.enabled</code> to <code>true</code>. 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.</p> - -<p>[2] Only works on Windows 8+.</p> - -<h2 id="See_also">See also</h2> - -<ul> - <li>{{domxref("SourceBuffer")}}</li> - <li>{{domxref("SourceBufferList")}}</li> -</ul> 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 ---- -<div>{{DefaultAPISidebar("WebVTT")}}</div> - -<p><span class="seoSummary"><strong>El formato de pistas de texto para la web (WebVTT)</strong> es un formato para mostrar pistas de texto en le tiempo (como subtítulos) usando el elemento {{HTMLElement("track")}}.</span> 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.</p> - -<h2 id="Archivos_WebVTT">Archivos WebVTT</h2> - -<p>El tipo MIME de los archivos WebVTT es <code>text/vtt</code>.</p> - -<p>Un archivo WebVTT (<code>.vtt</code>) contiene apuntes, que pueden ser tanto de una línea como de varias, como se muestra debajo:</p> - -<pre class="notranslate">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 -</pre> - -<h2 id="Estructura_WebVTT">Estructura WebVTT</h2> - -<p>La estructura de un archivo WevWTT consiste de los siguientes componentes, algunos de ellos opcionales, en este orden:</p> - -<ul> - <li>Una marca de orden de bytes (BOM) opcional.</li> - <li>La cadena de texto "<code>WEBVTT</code>".</li> - <li>Un encabezado de texto opcional a la derecha de <code>WEBVTT</code>. - <ul> - <li>Debe haber al menos un espacio después de <code>WEBVTT</code>.</li> - <li>Podrías usarlo para añadir una descripción al archivo.</li> - <li>Puedes usar cualquier cosa en el encabezado de texto excepto saltos de línea o la cadena "<code>--></code>".</li> - </ul> - </li> - <li>Una línea en blanco, que es equivalente a dos saltos de línea consecutivos.</li> - <li>Cero o más apuntes o comentarios.</li> - <li>Cero o más líneas en blanco.</li> -</ul> - -<h5 id="Ejemplo_1_-_El_archivo_WebVTT_más_simple_posible">Ejemplo 1 - El archivo WebVTT más simple posible</h5> - -<pre class="eval notranslate">WEBVTT -</pre> - -<h5 id="Ejemplo_2_-_Archivo_WebVTT_muy_simple_con_un_encabezado_de_texto">Ejemplo 2 - Archivo WebVTT muy simple con un encabezado de texto</h5> - -<pre class="eval notranslate">WEBVTT - Este archivo no tiene anotaciones. -</pre> - -<h5 id="Ejemplo_3_-_Ejemplo_de_un_archivo_WebVTT_común_con_encabezado_y_anotaciones">Ejemplo 3 - Ejemplo de un archivo WebVTT común con encabezado y anotaciones</h5> - -<pre class="eval notranslate">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. -</pre> - -<h3 id="Estructura_interna_de_un_archivo_WebVTT">Estructura interna de un archivo WebVTT</h3> - -<p>Vamos a reexaminar uno de nuestros ejemplos previos, y mirar la estructura de las anotaciones con un poco más de detalle.</p> - -<pre class="notranslate">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</pre> - -<p>En el caso de cada anotación:</p> - -<ul> - <li>La primera línea se empieza con un tiempo, que es el tiempo en el que se empieza a mostrar el téxto que aparece debajo.</li> - <li>En la misma línea, tenemos una cadena de texto "<code>--></code>".</li> - <li>Acabamos la línea con un segundo tiempo, que es el tiempo en el que se termina de mostrar el texto asociado.</li> - <li>Nosotros podemos entonces tener una o más líneas que empiezan con un guión, cada una de ellas conteniendo parte de la pista de texto para mostrar.</li> -</ul> - -<p>También podemos poner comentarios en nuestro archivo <code>.vtt</code>, para ayudarnos a recorddar información importante sobre las partes de nuestro archivo. Estas deben estar en líneas separadas empezando con la cadena <code>NOTE</code>. Aprenderas más sobre eso en la siguiente sección.</p> - -<p>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.</p> - -<h2 id="Comentarios_en_WebVTT">Comentarios en WebVTT</h2> - -<p>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.</p> - -<p>Un comentario no puede contener la cadena de texto "<code>--></code>", el símbolo &, o el signo de menor que (<). Si quisieses usar esos caracteres necesitarías hacer un escape usando por ejemplo <code>&amp;</code> para el símbolo &, y &lt; para menor que (<). Tambien es recomendado que uses la secuencia de escape de mayor que <code>&gt;</code> en vez de el simbo de mayor que (<code>></code>) para evitar la confusión con etiquetas.</p> - -<p>Un comentario consiste en tres partes:</p> - -<ul> - <li>La cadena de texto <code>NOTE</code>.</li> - <li>Un espacio o un salto de línea.</li> - <li>Cero o más caracteres que no sean los indicados arriba.</li> -</ul> - -<h5 id="Ejemplo_4_-_Ejemplo_común_de_WebVTT">Ejemplo 4 - Ejemplo común de WebVTT</h5> - -<pre class="eval notranslate">NOTE Esto es un comentario -</pre> - -<h5 id="Ejemplo_5_-_Comentario_multilínea">Ejemplo 5 - Comentario multilínea</h5> - -<pre class="eval notranslate">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. -</pre> - -<h5 id="Ejemplo_6_-_Uso_común_de_comentarios">Ejemplo 6 - Uso común de comentarios</h5> - -<pre class="eval notranslate">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 -</pre> - -<h2 id="Estilizando_anotaciones_WebVTT">Estilizando anotaciones WebVTT</h2> - -<p>Tu puedes estilizar anotaciones WebVTT buscado elementos que coincidan con el pseudoelemento {{cssxref("::cue")}}.</p> - -<h3 id="Dentro_del_CSS_del_sitio">Dentro del CSS del sitio</h3> - -<pre class="brush: css notranslate">video::cue { - background-image: linear-gradient(to bottom, dimgray, lightgray); - color: papayawhip; -} - -video::cue(b) { - color: peachpuff; -} -</pre> - -<p>Aquí, todos los elementos de video estan estilizados para usar un gradiente gris como fondo, con <code>"papayawhip"</code> como color principal. Además el texto en negrita usando el elemento {{HTMLElement("b")}} tiene el color <code>"peachpuff"</code>.</p> - -<p>El ejemplo HTML de abajo actualemte se encarga de mostrar los archivos multimedia él solo.</p> - -<pre class="brush: html notranslate"><video controls autoplay src="video.webm"> - <track default src="track.vtt"> -</video> -</pre> - -<h3 id="Within_the_WebVTT_file_itself">Within the WebVTT file itself</h3> - -<p>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 <code>"STYLE"</code> all by itelf on a line of text, as shown below:</p> - -<pre class="notranslate">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.</pre> - -<p>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:</p> - -<pre class="notranslate">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™ -</pre> - -<pre class="brush: css notranslate">::cue(#\31) { color: lime; } -::cue(#crédit\ de\ transcription) { color: red; }</pre> - -<p>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):</p> - -<pre class="notranslate">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?</pre> - -<h2 id="WebVTT_cues">WebVTT cues</h2> - -<p>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:</p> - -<ul> - <li>An optional cue identifier followed by a newline.</li> - <li>Cue timings.</li> - <li>Optional cue settings with at least one space before the first and between each setting.</li> - <li>One or more newlines.</li> - <li>The cue payload text.</li> -</ul> - -<h5 id="Example_7_-_Example_of_a_cue">Example 7 - Example of a cue</h5> - -<pre class="eval notranslate">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....</pre> - -<h3 id="Cue_identifier">Cue identifier</h3> - -<p>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 "<code>-->"</code>. 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, ...).</p> - -<h5 id="Example_8_-_Cue_identifier_from_Example_7">Example 8 - Cue identifier from Example 7</h5> - -<pre class="eval notranslate">1 - Title Crawl</pre> - -<h5 id="Example_9_-_Common_usage_of_identifiers">Example 9 - Common usage of identifiers</h5> - -<pre class="eval notranslate">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 -</pre> - -<h3 id="Cue_timings">Cue timings</h3> - -<p>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.</p> - -<p>If the WebVTT file is being used for chapters ({{HTMLElement("track")}} {{htmlattrxref("kind")}} is <code>chapters</code>) then the file cannot have overlapping timings.</p> - -<p>Each cue timing contains five components:</p> - -<ul> - <li>Timestamp for start time.</li> - <li>At least one space.</li> - <li>The string "<code>-->".</code></li> - <li>At least one space.</li> - <li>Timestamp for end time. - <ul> - <li>Which must be greater than the start time.</li> - </ul> - </li> -</ul> - -<p>The timestamps must be in one of two formats:</p> - -<ul> - <li><code>mm:ss.ttt</code></li> - <li><code>hh:mm:ss.ttt</code></li> -</ul> - -<p>Where the components are defined as follows:</p> - -<ul> - <li><code>hh</code> is hours. - - <ul> - <li>Must be at least two digits.</li> - <li>Hours can be greater than two digits (e.g., 9999:00:00.000).</li> - </ul> - </li> - <li><code>mm</code> is minutes. - <ul> - <li>Must be between 00 and 59 inclusive.</li> - </ul> - </li> - <li><code>ss</code> is seconds. - <ul> - <li>Must be between 00 and 59 inclusive.</li> - </ul> - </li> - <li><code>ttt</code> is miliseconds. - <ul> - <li>Must be between 000 and 999 inclusive.</li> - </ul> - </li> -</ul> - -<h5 id="Example_10_-_Basic_cue_timing_examples">Example 10 - Basic cue timing examples</h5> - -<pre class="eval notranslate">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</pre> - -<h5 id="Example_11_-_Overlapping_cue_timing_examples">Example 11 - Overlapping cue timing examples</h5> - -<pre class="eval notranslate">00:00:00.000 --> 00:00:10.000 -00:00:05.000 --> 00:01:00.000 -00:00:30.000 --> 00:00:50.000</pre> - -<h5 id="Example_12_-_Non-overlapping_cue_timing_examples">Example 12 - Non-overlapping cue timing examples</h5> - -<pre class="eval notranslate">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</pre> - -<h3 id="Cue_settings">Cue settings</h3> - -<p>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.</p> - -<p>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:</p> - -<ul> - <li><strong>vertical</strong> - - <ul> - <li>Indicates that the text will be displayed vertically rather than horizontally, such as in some Asian languages.</li> - </ul> - - <table> - <thead> - <tr> - <th colspan="2">Table 1 - vertical values</th> - </tr> - </thead> - <tbody> - <tr> - <th><code>vertical:rl</code></th> - <td>writing direction is right to left</td> - </tr> - <tr> - <th><code>vertical:lr</code></th> - <td>writing direction is left to right</td> - </tr> - </tbody> - </table> - </li> - <li><strong>line</strong> - <ul> - <li>Specifies where text appears vertically. If vertical is set, line specifies where text appears horizontally.</li> - <li>Value can be a line number. - <ul> - <li>The line height is the height of the first line of the cue as it appears on the video.</li> - <li>Positive numbers indicate top down.</li> - <li>Negative numbers indicate bottom up.</li> - </ul> - </li> - <li>Or value can be a percentage. - <ul> - <li>Must be an integer (i.e., no decimals) between 0 and 100 inclusive.</li> - <li>Must be followed by a percent sign (%).</li> - </ul> - </li> - </ul> - - <table> - <thead> - <tr> - <th colspan="4">Table 2 - line examples</th> - </tr> - </thead> - <tbody> - <tr> - <th></th> - <th><code>vertical</code> omitted</th> - <th><code>vertical:rl</code></th> - <th><code>vertical:lr</code></th> - </tr> - <tr> - <th><code>line:0</code></th> - <td>top</td> - <td>right</td> - <td>left</td> - </tr> - <tr> - <th><code>line:-1</code></th> - <td>bottom</td> - <td>left</td> - <td>right</td> - </tr> - <tr> - <th><code>line:0%</code></th> - <td>top</td> - <td>right</td> - <td>left</td> - </tr> - <tr> - <th><code>line:100%</code></th> - <td>bottom</td> - <td>left</td> - <td>right</td> - </tr> - </tbody> - </table> - </li> - <li><strong>position</strong> - <ul> - <li>Specifies where the text will appear horizontally. If vertical is set, position specifies where the text will appear vertically.</li> - <li>Value is a percentage.</li> - <li>Must be an integer (no decimals) between 0 and 100 inclusive.</li> - <li>Must be followed by a percent sign (%).</li> - </ul> - - <table> - <thead> - <tr> - <th colspan="4">Table 3 - position examples</th> - </tr> - </thead> - <tbody> - <tr> - <th></th> - <th><code>vertical</code> omitted</th> - <th><code>vertical:rl</code></th> - <th><code>vertical:lr</code></th> - </tr> - <tr> - <th><code>position:0%</code></th> - <td>left</td> - <td>top</td> - <td>top</td> - </tr> - <tr> - <th><code>position:100%</code></th> - <td>right</td> - <td>bottom</td> - <td>bottom</td> - </tr> - </tbody> - </table> - </li> - <li><strong>size</strong> - <ul> - <li>Specifies the width of the text area. If vertical is set, size specifies the height of the text area.</li> - <li>Value is a percentage.</li> - <li>Must be an integer (i.e., no decimals) between 0 and 100 inclusive.</li> - <li>Must be followed by a percent sign (%).</li> - </ul> - - <table> - <thead> - <tr> - <th colspan="4">Table 4 - size examples</th> - </tr> - </thead> - <tbody> - <tr> - <th></th> - <th><code>vertical</code> omitted</th> - <th><code>vertical:rl</code></th> - <th><code>vertical:lr</code></th> - </tr> - <tr> - <th><code>size:100%</code></th> - <td>full width</td> - <td>full height</td> - <td>full height</td> - </tr> - <tr> - <th><code>size:50%</code></th> - <td>half width</td> - <td>half height</td> - <td>half height</td> - </tr> - </tbody> - </table> - </li> - <li><strong>align</strong> - <ul> - <li>Specifies the alignment of the text. Text is aligned within the space given by the size cue setting if it is set.</li> - </ul> - - <table> - <thead> - <tr> - <th colspan="4">Table 5 - align values</th> - </tr> - </thead> - <tbody> - <tr> - <th></th> - <th><code>vertical</code> omitted</th> - <th><code>vertical:rl</code></th> - <th><code>vertical:lr</code></th> - </tr> - <tr> - <th><code>align:start</code></th> - <td>left</td> - <td>top</td> - <td>top</td> - </tr> - <tr> - <th><code>align:middle</code></th> - <td>centred horizontally</td> - <td>centred vertically</td> - <td>centred vertically</td> - </tr> - <tr> - <th><code>align:end</code></th> - <td>right</td> - <td>bottom</td> - <td>bottom</td> - </tr> - </tbody> - </table> - </li> -</ul> - -<h5 id="Example_13_-_Cue_setting_examples">Example 13 - Cue setting examples</h5> - -<p>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.</p> - -<pre class="eval notranslate">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 -</pre> - -<h3 id="Cue_payload">Cue payload</h3> - -<p>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.</p> - -<p>A cue text payload cannot contain the string "<code>-->"</code>, 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.</p> - -<p>In addition to the three escape sequences mentioned above, there are fours others. They are listed in the table below.</p> - -<table> - <thead> - <tr> - <th colspan="3">Table 6 - Escape sequences</th> - </tr> - </thead> - <tbody> - <tr> - <th>Name</th> - <th>Character</th> - <th>Escape Sequence</th> - </tr> - <tr> - <td>Ampersand</td> - <td>&</td> - <td><code>&amp;</code></td> - </tr> - <tr> - <td>Less-than</td> - <td><</td> - <td><code>&lt;</code></td> - </tr> - <tr> - <td>Greater-than</td> - <td>></td> - <td><code>&gt;</code></td> - </tr> - <tr> - <td>Left-to-right mark</td> - <td></td> - <td><code>&lrm;</code></td> - </tr> - <tr> - <td>Right-to-left mark</td> - <td></td> - <td><code>&rlm;</code></td> - </tr> - <tr> - <td>Non-breaking space</td> - <td><code> </code></td> - <td><code>&nbsp;</code></td> - </tr> - </tbody> -</table> - -<h3 id="Cue_payload_text_tags">Cue payload text tags</h3> - -<p>There are a number of tags, such as <code><bold></code>, that can be used. However, if the WebVTT file is used in a {{HTMLElement("track")}} element where the attribute {{htmlattrxref("kind")}} is <code>chapters</code> then you cannot use tags.</p> - -<ul> - <li><strong>Timestamp tag</strong> - - <ul> - <li>The timestamp must be greater that the cue's start timestamp, greater than any previous timestamp in the cue payload, and less than the cue's end timestamp. The <em>active text</em> is the text between the timestamp and the next timestamp or to the end of the payload if there is not another timestamp in the payload. Any text before the <em>active text</em> in the payload is <em>previous text</em> . Any text beyond the <em>active text</em> is <em>future text</em> . This enables karaoke style captions.</li> - </ul> - - <div> - <h5 id="Example_12_-_Karaoke_style_text">Example 12 - Karaoke style text</h5> - - <pre class="eval notranslate">1 -00:16.500 --> 00:18.500 -When the moon <00:17.500>hits your eye - -1 -00:00:18.500 --> 00:00:20.500 -Like a <00:19.000>big-a <00:19.500>pizza <00:20.000>pie - -1 -00:00:20.500 --> 00:00:21.500 -That's <00:00:21.000>amore -</pre> - </div> - </li> -</ul> - -<p>The following tags are the HTML tags allowed in a cue and require opening and closing tags (e.g., <code><b>text</b></code>).</p> - -<ul> - <li><strong>Class tag</strong> (<code><c></c></code>) - - <ul> - <li>Style the contained text using a CSS class.</li> - </ul> - - <div> - <h5 id="Example_14_-_Class_tag">Example 14 - Class tag</h5> - - <pre class="notranslate"><c.classname>text</c></pre> - </div> - </li> - <li><strong>Italics tag</strong> (<code><i></i></code>) - <ul> - <li>Italicize the contained text.</li> - </ul> - - <div> - <h5 id="Example_15_-_Italics_tag">Example 15 - Italics tag</h5> - - <pre class="notranslate"><i>text</i></pre> - </div> - </li> - <li><strong>Bold tag</strong> (<code><b></b></code>) - <ul> - <li>Bold the contained text.</li> - </ul> - - <div> - <h5 id="Example_16_-_Bold_tag">Example 16 - Bold tag</h5> - - <pre class="notranslate"><b>text</b></pre> - </div> - </li> - <li><strong>Underline tag</strong> (<code><u></u></code>) - <ul> - <li>Underline the contained text.</li> - </ul> - - <div> - <h5 id="Example_17_-_Underline_tag">Example 17 - Underline tag</h5> - - <pre class="notranslate"><u>text</u></pre> - </div> - </li> - <li><strong>Ruby tag</strong> (<code><ruby></ruby></code>) - <ul> - <li>Used with ruby text tags to display <a href="http://en.wikipedia.org/wiki/Ruby_character">ruby characters</a> (i.e., small annotative characters above other characters).</li> - </ul> - - <div> - <h5 id="Example_18_-_Ruby_tag">Example 18 - Ruby tag</h5> - - <pre class="notranslate"><ruby>WWW<rt>World Wide Web</rt>oui<rt>yes</rt></ruby></pre> - </div> - </li> - <li><strong>Ruby text tag</strong> (<code><rt></rt></code>) - <ul> - <li>Used with ruby tags to display <a href="http://en.wikipedia.org/wiki/Ruby_character">ruby characters</a> (i.e., small annotative characters above other characters).</li> - </ul> - - <div> - <h5 id="Example_19_-_Ruby_text_tag">Example 19 - Ruby text tag</h5> - - <pre class="notranslate"><ruby>WWW<rt>World Wide Web</rt>oui<rt>yes</rt></ruby></pre> - </div> - </li> - <li><strong>Voice tag</strong> (<code><v></v></code>) - <ul> - <li>Similar to class tag, also used to style the contained text using CSS.</li> - </ul> - - <div> - <h5 id="Example_20_-_Voice_tag">Example 20 - Voice tag</h5> - - <pre class="notranslate"><v Bob>text</v></pre> - </div> - </li> -</ul> - -<h2 id="Interfaces">Interfaces</h2> - -<p>There are two interfaces or APIs used in WebVTT which are:</p> - -<h3 id="VTTCue_interface">VTTCue interface</h3> - -<p>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.</p> - -<p>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:</p> - -<pre class="idl def notranslate">enum <dfn>AutoKeyword</dfn> { <dfn>"auto"</dfn> }; -enum <dfn>DirectionSetting</dfn> { <dfn>""</dfn> /* horizontal */, <dfn>"rl"</dfn>, <dfn>"lr"</dfn> }; -enum <dfn>LineAlignSetting</dfn> { <dfn>"start"</dfn>, <dfn>"center"</dfn>, <dfn>"end"</dfn> }; -enum <dfn>PositionAlignSetting</dfn> { <dfn>"line-left"</dfn>, <dfn>"center"</dfn>, <dfn>"line-right"</dfn>, <dfn>"auto"</dfn> }; -enum <dfn>AlignSetting</dfn> { <dfn>"start"</dfn>, <dfn>"center"</dfn>, <dfn>"end"</dfn>, <dfn>"left"</dfn>, <dfn>"right"</dfn> }; -[<a class="idl-code" href="https://w3c.github.io/webvtt/#dom-vttcue-vttcue" id="ref-for-dom-vttcue-vttcue-1">Constructor</a>(double <dfn>startTime</dfn>, double <dfn>endTime</dfn>, DOMString <dfn>text</dfn>)] -interface <dfn>VTTCue</dfn> : <a href="https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackcue">TextTrackCue</a> { - attribute <a href="https://w3c.github.io/webvtt/#vttregion" id="ref-for-vttregion-1">VTTRegion</a>? <a class="idl-code" href="https://w3c.github.io/webvtt/#dom-vttcue-region" id="ref-for-dom-vttcue-region-1">region</a>; - attribute <a href="https://w3c.github.io/webvtt/#enumdef-directionsetting" id="ref-for-enumdef-directionsetting-1">DirectionSetting</a> <a class="idl-code" href="https://w3c.github.io/webvtt/#dom-vttcue-vertical" id="ref-for-dom-vttcue-vertical-1">vertical</a>; - attribute boolean <a class="idl-code" href="https://w3c.github.io/webvtt/#dom-vttcue-snaptolines" id="ref-for-dom-vttcue-snaptolines-2">snapToLines</a>; - attribute (double or <a href="https://w3c.github.io/webvtt/#enumdef-autokeyword" id="ref-for-enumdef-autokeyword-1">AutoKeyword</a>) <a class="idl-code" href="https://w3c.github.io/webvtt/#dom-vttcue-line" id="ref-for-dom-vttcue-line-2">line</a>; - attribute <a href="https://w3c.github.io/webvtt/#enumdef-linealignsetting" id="ref-for-enumdef-linealignsetting-1">LineAlignSetting</a> <a class="idl-code" href="https://w3c.github.io/webvtt/#dom-vttcue-linealign" id="ref-for-dom-vttcue-linealign-1">lineAlign</a>; - attribute (double or <a href="https://w3c.github.io/webvtt/#enumdef-autokeyword" id="ref-for-enumdef-autokeyword-2">AutoKeyword</a>) <a class="idl-code" href="https://w3c.github.io/webvtt/#dom-vttcue-position" id="ref-for-dom-vttcue-position-1">position</a>; - attribute <a href="https://w3c.github.io/webvtt/#enumdef-positionalignsetting" id="ref-for-enumdef-positionalignsetting-1">PositionAlignSetting</a> <a class="idl-code" href="https://w3c.github.io/webvtt/#dom-vttcue-positionalign" id="ref-for-dom-vttcue-positionalign-1">positionAlign</a>; - attribute double <a class="idl-code" href="https://w3c.github.io/webvtt/#dom-vttcue-size" id="ref-for-dom-vttcue-size-1">size</a>; - attribute <a href="https://w3c.github.io/webvtt/#enumdef-alignsetting" id="ref-for-enumdef-alignsetting-1">AlignSetting</a> <a class="idl-code" href="https://w3c.github.io/webvtt/#dom-vttcue-align" id="ref-for-dom-vttcue-align-1">align</a>; - attribute DOMString <a class="idl-code" href="https://w3c.github.io/webvtt/#dom-vttcue-text" id="ref-for-dom-vttcue-text-1">text</a>; - <a href="https://dom.spec.whatwg.org/#documentfragment">DocumentFragment</a> <a class="idl-code" href="https://w3c.github.io/webvtt/#dom-vttcue-getcueashtml" id="ref-for-dom-vttcue-getcueashtml-2">getCueAsHTML</a>(); -};</pre> - -<h3 id="VTT_Region_interface">VTT Region interface</h3> - -<p>This is the second interface in WebVTT API.</p> - -<p>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:</p> - -<pre class="idl def notranslate">enum <dfn>ScrollSetting</dfn> { <dfn>""</dfn> /* none */, <dfn>"up"</dfn> }; -[<a class="idl-code" href="https://w3c.github.io/webvtt/#dom-vttregion-vttregion" id="ref-for-dom-vttregion-vttregion-1">Constructor</a>] -interface <dfn>VTTRegion</dfn> { - attribute double <a class="idl-code" href="https://w3c.github.io/webvtt/#dom-vttregion-width" id="ref-for-dom-vttregion-width-1">width</a>; - attribute long <a class="idl-code" href="https://w3c.github.io/webvtt/#dom-vttregion-lines" id="ref-for-dom-vttregion-lines-1">lines</a>; - attribute double <a class="idl-code" href="https://w3c.github.io/webvtt/#dom-vttregion-regionanchorx" id="ref-for-dom-vttregion-regionanchorx-1">regionAnchorX</a>; - attribute double <a class="idl-code" href="https://w3c.github.io/webvtt/#dom-vttregion-regionanchory" id="ref-for-dom-vttregion-regionanchory-1">regionAnchorY</a>; - attribute double <a class="idl-code" href="https://w3c.github.io/webvtt/#dom-vttregion-viewportanchorx" id="ref-for-dom-vttregion-viewportanchorx-1">viewportAnchorX</a>; - attribute double <a class="idl-code" href="https://w3c.github.io/webvtt/#dom-vttregion-viewportanchory" id="ref-for-dom-vttregion-viewportanchory-1">viewportAnchorY</a>; - attribute <a href="https://w3c.github.io/webvtt/#enumdef-scrollsetting" id="ref-for-enumdef-scrollsetting-1">ScrollSetting</a> <a class="idl-code" href="https://w3c.github.io/webvtt/#dom-vttregion-scroll" id="ref-for-dom-vttregion-scroll-1">scroll</a>; -};</pre> - -<h2 id="Methods_and_properties">Methods and properties</h2> - -<p>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:</p> - -<ul style="list-style-type: circle;"> - <li> - <h3 id="VTTCue">VTTCue</h3> - - <ul> - <li>The methods which are available in this interface are: - <ul style="list-style-type: circle;"> - <li>GetCueAsHTML to get the HTML of that Cue.</li> - <li>VTT Constructor for creating new objects of Cues.</li> - <li>Autokeyword.</li> - <li>DirectionSetting: to set the direction of caption or text in a file.</li> - <li>LineAlignment: to adjust the line alignment.</li> - <li>PositionAlignSetting: to adjust the position of text.</li> - </ul> - </li> - </ul> - </li> - <li> - <h3 id="VTTRegion">VTTRegion</h3> - - <ul> - <li>The methods used for region are listed below along with description of their functionality: - <ul style="list-style-type: circle;"> - <li>ScrollSetting: For adjusting the scrolling setting of all nodes present in given region.</li> - <li>VTT Region Constructor: for construction of new VTT Regions.</li> - </ul> - </li> - </ul> - </li> -</ul> - -<h2 id="Tutorial_on_how_to_write_a_WebVTT_file">Tutorial on how to write a WebVTT file</h2> - -<p>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:</p> - -<ol> - <li>Open a notepad.</li> - <li>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:</li> -</ol> - -<pre class="notranslate">WEBVTT</pre> - -<p> 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:</p> - -<pre class="notranslate">00:01.000 --> 00:05.000</pre> - -<ol> - <li>On the next line you can write the caption for this cue which will run from 1<sup>st</sup> second to the 5<sup>th</sup> second, inclusive.</li> - <li>Following the similar steps, a complete WebVTT file for specific video or audio file can be made.</li> -</ol> - -<h2 id="CSS_pseudo-classes">CSS pseudo-classes</h2> - -<p>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.</p> - -<p>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:</p> - -<pre class="notranslate">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</pre> - -<p>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 <code><i></code> tag is for italics.</p> - -<p>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:</p> - -<ul> - <li>Lang (Lanugage): e.g., p:lang(it).</li> - <li>Link: e.g., a:link.</li> - <li>Nth-last-child: e.g., p:nth-last-child(2).</li> - <li>Nth-child(n): e.g., p:nth-child(2).</li> -</ul> - -<p>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.</p> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th>Specification</th> - <th>Status</th> - <th>Comment</th> - </tr> - <tr> - <td>{{SpecName("WebVTT")}}</td> - <td>{{Spec2("WebVTT")}}</td> - <td>Initial definition</td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<h3 id="VTTCue_interface_2"><code>VTTCue</code> interface</h3> - -<div> - - -<p>{{Compat("api.VTTCue", 0)}}</p> - -<h3 id="TextTrack_interface"><code>TextTrack</code> interface</h3> - -<div> - - -<p>{{Compat("api.TextTrack", 0)}}</p> - -<h3 id="Notes">Notes</h3> -</div> -</div> - -<p>Prior to Firefox 50, the <code>AlignSetting</code> enum (representing possible values for {{domxref("VTTCue.align")}}) incorrectly included the value <code>"middle"</code> instead of <code>"center"</code>. This has been corrected.</p> - -<p>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 <code>true</code>. WebVTT is enabled by default starting in Firefox 31 and can be disabled by setting the preference to <code>false</code>.</p> - -<p>Prior to Firefox 58, the <code>REGION</code> keyword was creating {{domxref("VTTRegion")}} objects, but they were not being used. Firefox 58 now fully supports <code>VTTRegion</code> and its use; however, this feature is disabled by default behind the preference <code>media.webvtt.regions.enabled</code>; set it to <code>true</code> to enable region support in Firefox 58. Regions are enabled by default starting in Firefox 59 (see bugs {{bug(1338030)}} and {{bug(1415805)}}).</p> 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 ---- -<p>El evento <code>DOMContentLoaded</code> 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 - <a href="/en-US/docs/Mozilla_event_reference/load"><code>load</code></a> - debería ser usado solo para detectar una carga completa de la página. Es un error increíblemente popular usar <a href="/en-US/docs/Mozilla_event_reference/load"><code>load</code></a> cuando <code>DOMContentLoaded</code> sería mucho más apropiado, así que úsalo con cuidado.</p> - -<p>JavaScript síncrono pausa el parseo del DOM.</p> - -<p>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.</p> - -<h2 id="Speeding_up">Speeding up</h2> - -<p>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 <a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests">JavaScript asynchronous</a> and to <a href="https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery">optimize loading of stylesheets</a> which if used as usual, slow down page load due to being loaded in parallel, "stealing" traffic from the main html document.</p> - -<h2 id="General_info">General info</h2> - -<dl> - <dt style="width: 120px; text-align: right; float: left;">Specification</dt> - <dd style="margin: 0px 0px 0px 120px;"><a class="external" href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-end.html#the-end">HTML5</a></dd> - <dt style="width: 120px; text-align: right; float: left;">Interface</dt> - <dd style="margin: 0px 0px 0px 120px;">Event</dd> - <dt style="width: 120px; text-align: right; float: left;">Bubbles</dt> - <dd style="margin: 0px 0px 0px 120px;">Yes</dd> - <dt style="width: 120px; text-align: right; float: left;">Cancelable</dt> - <dd style="margin: 0px 0px 0px 120px;">Yes (although specified as a simple event that isn't cancelable)</dd> - <dt style="width: 120px; text-align: right; float: left;">Target</dt> - <dd style="margin: 0px 0px 0px 120px;">Document</dd> - <dt style="width: 120px; text-align: right; float: left;">Default Action</dt> - <dd style="margin: 0px 0px 0px 120px;">None.</dd> -</dl> - -<h2 id="Properties">Properties</h2> - -<table class="standard-table"> - <thead> - <tr> - <th scope="col">Property</th> - <th scope="col">Type</th> - <th scope="col">Description</th> - </tr> - </thead> - <tbody> - <tr> - <td><code>target</code> {{readonlyInline}}</td> - <td>{{domxref("EventTarget")}}</td> - <td>The event target (the topmost target in the DOM tree).</td> - </tr> - <tr> - <td><code>type</code> {{readonlyInline}}</td> - <td>{{domxref("DOMString")}}</td> - <td>The type of event.</td> - </tr> - <tr> - <td><code>bubbles</code> {{readonlyInline}}</td> - <td>{{jsxref("Boolean")}}</td> - <td>Whether the event normally bubbles or not.</td> - </tr> - <tr> - <td><code>cancelable</code> {{readonlyInline}}</td> - <td>{{jsxref("Boolean")}}</td> - <td>Whether the event is cancellable or not.</td> - </tr> - </tbody> -</table> - -<h2 id="Example">Example</h2> - -<pre class="brush: html"><script> - document.addEventListener("DOMContentLoaded", function(event) { - console.log("DOM fully loaded and parsed"); - }); -</script> -</pre> - -<pre class="brush: html"><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> -</pre> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<p>{{CompatibilityTable}}</p> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Basic support</td> - <td>1.0<sup>[1]</sup></td> - <td>{{CompatGeckoDesktop("1")}}<sup>[1]</sup></td> - <td>9.0<sup>[2]</sup></td> - <td>9.0</td> - <td>3.1<sup>[1]</sup></td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatVersionUnknown}}<sup>[1]</sup></td> - <td>{{CompatGeckoMobile("1")}}<sup>[1]</sup></td> - <td>{{CompatUnknown}}<sup>[2]</sup></td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}<sup>[1]</sup></td> - </tr> - </tbody> -</table> -</div> - -<p>[1] Bubbling for this event is supported by at least Gecko 1.9.2, Chrome 6, and Safari 4.</p> - -<p>[2] Internet Explorer 8 supports the <code>readystatechange</code> 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 <code>document.documentElement.doScroll("left");</code>, as this snippet will throw an error until the DOM is ready.</p> - -<h2 id="Related_Events">Related Events</h2> - -<ul> - <li>{{event("DOMContentLoaded")}}</li> - <li>{{event("readystatechange")}}</li> - <li>{{event("load")}}</li> - <li>{{event("beforeunload")}}</li> - <li>{{event("unload")}}</li> -</ul> 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 ---- -<p>{{APIRef("Web Workers API")}}</p> - -<p><a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API">Web Workers API</a> posee un metodo llamado <code><strong>postMessage()</strong></code> 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).</p> - -<p>El Worker puede enviar de vuelta información al hilo que lo genero usando el metodo {{domxref("DedicatedWorkerGlobalScope.postMessage")}}.</p> - -<h2 id="Syntax">Syntax</h2> - -<pre class="brush: js">myWorker.postMessage(aMessage, transferList);</pre> - -<h3 id="Parameters">Parameters</h3> - -<dl> - <dt><em>aMessage</em></dt> - <dd>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 <a href="/en-US/docs/Web/Guide/DOM/The_structured_clone_algorithm" title="http://www.whatwg.org/specs/web-apps/current-work/multipage/common-dom-interfaces.html#transferable">structured clone</a> algorithm, which includes cyclical references.</dd> - <dt><em>transferList</em> {{optional_inline}}</dt> - <dd>An optional <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" title="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array">array</a> of {{domxref("Transferable")}} objects to transfer ownership of. If the ownership of an object is transferred, it becomes unusable (<em>neutered</em>) in the context it was sent from and it becomes available only to the worker it was sent to.</dd> - <dd>Only {{domxref("MessagePort")}} and {{domxref("ArrayBuffer")}} objects can be transferred.</dd> -</dl> - -<h3 id="Returns">Returns</h3> - -<p>Void.</p> - -<h2 id="Example">Example</h2> - -<p>The following code snippet shows creation of a {{domxref("Worker")}} object using the {{domxref("Worker.Worker", "Worker()")}} constructor. When either of two form inputs (<code>first</code> and <code>second</code>) have their values changed, {{event("change")}} events invoke <code>postMessage()</code> to send the value of both inputs to the current worker.</p> - -<pre class="brush: js">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'); -} -</pre> - -<p>For a full example, see our<a class="external external-icon" href="https://github.com/mdn/simple-web-worker">Basic dedicated worker example</a> (<a class="external external-icon" dir="ltr" href="mailto:aguilahorus@gmail.com">run dedicated worker</a>).</p> - -<div class="note"> -<p><strong>Note</strong>: <code>postMessage()</code> can only send a single object at once. As seen above, if you want to pass multiple values you can send an array.</p> -</div> - -<h2 id="Transfer_Example">Transfer Example</h2> - -<p>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.</p> - -<h4 id="Main_thread_code">Main thread code:</h4> - -<pre class="brush: js">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); -</pre> - -<h4 id="Worker_code">Worker code</h4> - -<pre class="brush: js">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); -} -</pre> - -<h4 id="Output_logged">Output logged</h4> - -<pre>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</pre> - -<p>We see that byteLength goes to 0 as it is trasnferred. To see a fully working example of this Firefox demo addon see here: <a href="https://github.com/Noitidart/ChromeWorker/tree/aca57d9cadc4e68af16201bdecbfb6f9a6f9ca6b">GitHub :: ChromeWorker - demo-transfer-arraybuffer</a></p> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('HTML WHATWG', "#dom-worker-postmessage", "Worker.postMessage()")}}</td> - <td>{{Spec2('HTML WHATWG')}}</td> - <td>No change from {{SpecName("Web Workers")}}.</td> - </tr> - <tr> - <td>{{SpecName('Web Workers', "#dom-worker-postmessage", "Worker.postMessage()")}}</td> - <td>{{Spec2('Web Workers')}}</td> - <td>Initial definition.</td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<div>{{CompatibilityTable}}</div> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari (WebKit)</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>10.0 [1]</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>Firefox OS (Gecko)</th> - <th>IE Phone</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>10.0 [1]</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<p>[1] Internet Explorer does not support {{domxref("Transferable")}} objects.</p> - -<h2 id="See_also">See also</h2> - -<ul> - <li>The {{domxref("Worker")}} interface it belongs to.</li> -</ul> 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 ---- -<p><code>XMLHttpRequest</code> soporta solicitudes síncronas y asíncronas, pero la mas preferida es la asíncrona por razones de rendimiento</p> - -<p><span id="result_box" lang="es"><span>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</span></span></p> - -<h2 id="Peticiones_asíncronas">Peticiones asíncronas</h2> - -<p><span id="result_box" lang="es"><span>Si se utiliza <code>XMLHttpRequest</code> de forma asíncrona, recibirá una devolución de llamada cuando los datos se hayan recibido .</span> <span>Esto permite que el navegador continúe funcionando de forma normal mientras se procesa la solicitud.</span></span></p> - -<h3 id="Ejemplo_Enviar_un_archivo_a_la_consola"><span id="result_box" lang="es"><span>Ejemplo: Enviar un archivo a la consola</span></span></h3> - -<p><span class="short_text" id="result_box" lang="es"><span>Este es el uso más simple de la asíncronia </span></span><code>XMLHttpRequest</code>.</p> - -<pre class="brush: js">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); </pre> - -<p>En la linea 2, el ultimo parametro de <code>open()</code> , especifica <code>true</code> para indicar que la solicitud se tratara de forma asíncrona</p> - -<p>Line 3 creates an event handler function object and assigns it to the request's <code>onload</code> attribute. This handler looks at the request's <code>readyState</code> 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.</p> - -<p>Line 15 actually initiates the request. The callback routine is called whenever the state of the request changes.</p> - -<h3 id="Ejemplo_Creando_una_funcion_estandar_para_leer_archivos_externos.">Ejemplo: Creando una funcion estandar para leer archivos externos.</h3> - -<p>In some cases you must read many external files. This is a standard function which uses the <code>XMLHttpRequest</code> object asynchronously in order to switch the content of the read file to a specified listener.</p> - -<pre class="brush: js">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); -} -</pre> - -<p>Usage:</p> - -<pre class="brush: js">function showMessage (sMsg) { - alert(sMsg + this.responseText); -} - -loadFile("message.txt", showMessage, "New message!\n\n"); -</pre> - -<p>The signature of the utility function <em><strong>loadFile</strong></em> 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.</p> - -<p>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.</p> - -<p>Line 3 declares a function invoked when the XHR operation fails to complete successfully.</p> - -<p>Line 7 stores on the XHR object the success callback function given as the second argument to loadFile.</p> - -<p>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.</p> - -<p>Line 9 designates the function xhrSuccess as the callback to be invoked when the onload event fires, that is, when the XHR sucessfully completes. </p> - -<p>Line 10 designates the function xhrError as the callback to be invoked when the XHR requests fails to complete.</p> - -<p>Line 11 specifies <code>true</code> for its third parameter to indicate that the request should be handled asynchronously.</p> - -<p>Line 12 actually initiates the request.</p> - -<h3 id="Example_using_a_timeout">Example: using a timeout</h3> - -<p>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 <code>timeout</code> property on the <code>XMLHttpRequest</code> object, as shown in the code below:</p> - -<pre class="brush: js">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); -}</pre> - -<p>Notice the addition of code to handle the "timeout" event by setting the <code>ontimeout</code> handler.</p> - -<p>Usage:</p> - -<pre class="brush: js">function showMessage (sMsg) { - alert(sMsg + this.responseText); -} - -loadFile("message.txt", 2000, showMessage, "New message!\n"); -</pre> - -<p>Here, we're specifying a timeout of 2000 ms.</p> - -<div class="note"> -<p><strong>Note:</strong> Support for <code>timeout</code> was added in {{Gecko("12.0")}}.</p> -</div> - -<h2 id="Synchronous_request">Synchronous request</h2> - -<div class="note"><strong>Note:</strong> 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.</div> - -<p>In rare cases, the use of a synchronous method is preferable to an asynchronous one.</p> - -<h3 id="Example_HTTP_synchronous_request">Example: HTTP synchronous request</h3> - -<p>This example demonstrates how to make a simple synchronous request.</p> - -<pre class="brush: js">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); -} -</pre> - -<p>Line 3 sends the request. The <code>null</code> parameter indicates that no body content is needed for the <code>GET</code> request.</p> - -<p>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.</p> - -<h3 id="Example_Synchronous_HTTP_request_from_a_Worker">Example: Synchronous HTTP request from a <code>Worker</code></h3> - -<p>One of the few cases in which a synchronous request does not usually block execution is the use of <code>XMLHttpRequest</code> within a <code><a href="/en/DOM/Worker" title="/en/DOM/Worker">Worker</a></code>.</p> - -<p><code><strong>example.html</strong></code> (the main page):</p> - -<pre class="brush: html"><!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> -</pre> - -<p><code><strong>myFile.txt</strong></code> (the target of the synchronous <code><a href="/en/DOM/XMLHttpRequest" title="/en/XMLHttpRequest">XMLHttpRequest</a></code> invocation):</p> - -<pre>Hello World!! -</pre> - -<p><code><strong>myTask.js</strong></code> (the <code><a href="/en/DOM/Worker" title="/en/DOM/Worker">Worker</a></code>):</p> - -<pre class="brush: js">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); - } -}; -</pre> - -<div class="note"><strong>Note:</strong> The effect, because of the use of the <code>Worker</code>, is however asynchronous.</div> - -<p>It could be useful in order to interact in background with the server or to preload some content. See <a class="internal" href="/En/DOM/Using_web_workers" title="en/Using DOM workers">Using web workers</a> for examples and details.</p> - -<h3 id="Adapting_Sync_XHR_usecases_to_the_Beacon_API">Adapting Sync XHR usecases to the Beacon API</h3> - -<p>There are some cases in which the synchronous usage of XMLHttpRequest was not replaceable, like during the <a class="internal" href="/en/DOM/window.onunload" title="en/DOM/window.onunload"><code>window.onunload</code></a> and <a class="internal" href="/en/DOM/window.onbeforeunload" title="en/DOM/window.onbeforeunload"><code>window.onbeforeunload</code></a> events. The <a href="/en-US/docs/Web/API/Navigator/sendBeacon">navigator.sendBeacon</a> API can support these usecases typically while delivering a good UX.</p> - -<p><span>The following example (from the <a href="/en-US/docs/Web/API/Navigator/sendBeacon">sendBeacon docs</a>) 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.</span></p> - -<pre class="brush: js">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); -} -</pre> - -<p>Using the <strong><code>sendBeacon()</code></strong> method, the data will be transmitted asynchronously to the web server when the User Agent has had an opportunity to do so, <strong>without delaying the unload or affecting the performance of the next navigation.</strong></p> - -<p>The following example shows a theoretical analytics code pattern that submits data to a server using the by using the <strong><code>sendBeacon()</code></strong> method.</p> - -<pre class="brush: js">window.addEventListener('unload', logData, false); - -function logData() { - navigator.sendBeacon("/log", analyticsData); -} -</pre> - -<h2 id="See_also">See also</h2> - -<ul> - <li><a href="/en-US/docs/Web/API/XMLHttpRequest" title="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest"><code>XMLHttpRequest</code></a></li> - <li><a href="/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest" title="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest">Using XMLHttpRequest</a></li> - <li><a href="/en-US/docs/AJAX" title="/en-US/docs/AJAX">AJAX</a></li> - <li><code><a href="/en-US/docs/Web/API/Navigator/sendBeacon">navigator.sendBeacon</a></code></li> -</ul> - -<p>{{ languages( {"zh-cn": "zh-cn/DOM/XMLHttpRequest/Synchronous_and_Asynchronous_Requests" } ) }}</p> |