diff options
author | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:41:45 -0500 |
---|---|---|
committer | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:41:45 -0500 |
commit | 1109132f09d75da9a28b649c7677bb6ce07c40c0 (patch) | |
tree | 0dd8b084480983cf9f9680e8aedb92782a921b13 /files/es/web/api | |
parent | 4b1a9203c547c019fc5398082ae19a3f3d4c3efe (diff) | |
download | translated-content-1109132f09d75da9a28b649c7677bb6ce07c40c0.tar.gz translated-content-1109132f09d75da9a28b649c7677bb6ce07c40c0.tar.bz2 translated-content-1109132f09d75da9a28b649c7677bb6ce07c40c0.zip |
initial commit
Diffstat (limited to 'files/es/web/api')
658 files changed, 82469 insertions, 0 deletions
diff --git a/files/es/web/api/abstractworker/index.html b/files/es/web/api/abstractworker/index.html new file mode 100644 index 0000000000..f3f50ecf38 --- /dev/null +++ b/files/es/web/api/abstractworker/index.html @@ -0,0 +1,130 @@ +--- +title: AbstractWorker +slug: Web/API/AbstractWorker +translation_of: Web/API/AbstractWorker +--- +<p>{{ APIRef("Web Workers API") }}</p> + +<p>La interfaz <strong><code>AbstractWorker</code></strong> de la <a href="/en-US/docs/Web/API/Web_Workers_API">API de Web Workers</a> es una interfaz abstracta que define propiedades métodos comunes a toda clase de workers, no sólo al {{domxref("Worker")}} básico sino también el {{domxref("ServiceWorker")}} y el {{domxref("SharedWorker")}}.<br> + Al ser una clase abstracta, usted no interactúa directamente con el <code>AbstractWorker</code>.</p> + +<h2 id="Propiedades">Propiedades</h2> + +<p><em>La interfaz <code>AbstractWorker</code></em><em> no hereda ninguna propiedad.</em></p> + +<h3 id="Gestor_de_eventos">Gestor de eventos</h3> + +<dl> + <dt>{{domxref("AbstractWorker.onerror")}}</dt> + <dd>Es un {{ domxref("EventListener") }} el cual es invocado siempre que un {{domxref("ErrorEvent")}} de tipo <code>error</code> se gatilla através del worker.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<p><em>La interfaz <code>AbstractWorker</code></em><em> no implementa o hereda ningún método.</em></p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>Note que usted no estará usando la interfaz <code>AbstractWorker</code> diractamente en su código — cuando es invocada, {{domxref("Worker")}} y {{domxref("SharedWorker")}} heredan sus propiedades.</p> + +<p>El siguiente fragmento de código muestra la creación de un objeto {{domxref("Worker")}} usando el constructor {{domxref("Worker.Worker", "Worker()")}} , junto con la forma de uso del objeto creado:</p> + +<pre class="brush: js">var myWorker = new Worker("worker.js"); + +first.onchange = function() { + myWorker.postMessage([first.value,second.value]); + console.log('Mensaje enviado al worker'); +}</pre> + +<p>El código del worker se carga desde el archivo <code>"worker.js"</code>. Éste código asume que hay un elemento del tipo {{HTMLElement("input")}} representado como <code>first</code>; un gestor de evento para el evento {{domxref("change")}} se define para que cuando el usuario cambie el valor de <code>first</code>, un mensaje se enviará al worker haciendoselo saber.</p> + +<p>Para ejemplos completos, visitar:</p> + +<ul> + <li><a class="external external-icon" href="https://github.com/mdn/simple-web-worker">Basic dedicated worker example</a> (<a class="external external-icon" href="http://mdn.github.io/simple-web-worker/">run dedicated worker</a>).</li> + <li><a class="external external-icon" href="https://github.com/mdn/simple-shared-worker">Basic shared worker example</a> (<a class="external external-icon" href="http://mdn.github.io/simple-shared-worker/">run shared worker</a>).</li> +</ul> + +<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("HTML WHATWG", "#the-abstractworker-abstract-interface", "AbstractWorker")}}</td> + <td>{{Spec2("HTML WHATWG")}}</td> + <td>No existen cambios para {{SpecName("Web Workers")}}.</td> + </tr> + <tr> + <td>{{SpecName("Web Workers", "#the-abstractworker-abstract-interface", "AbstractWorker")}}</td> + <td>{{Spec2("Web Workers")}}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_Navegadores">Compatibilidad en Navegadores</h2> + +<div>{{CompatibilityTable()}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatChrome(4)}}</td> + <td>{{CompatGeckoDesktop("1.9.1")}}</td> + <td>10</td> + <td>10.6</td> + <td>4</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</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>Soporte básico</td> + <td>4.4</td> + <td>{{CompatGeckoMobile("1.9.1")}}</td> + <td>1.0.1</td> + <td>10</td> + <td>11.5</td> + <td>5.1</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Vease_también">Vease también</h2> + +<ul> + <li>Las interfaces de {{domxref("Worker")}}, {{domxref("ServiceWorker")}} y {{domxref("SharedWorker")}}, que están basadas en el <code>AbstractWorker</code> .</li> + <li><a href="https://wiki.developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API">Web Workers API</a></li> + <li><a href="https://wiki.developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers">Usando Web Workers</a></li> +</ul> diff --git a/files/es/web/api/ambient_light_events/index.html b/files/es/web/api/ambient_light_events/index.html new file mode 100644 index 0000000000..4ea45847c0 --- /dev/null +++ b/files/es/web/api/ambient_light_events/index.html @@ -0,0 +1,114 @@ +--- +title: Luz Ambiental Eventos +slug: Web/API/Ambient_Light_Events +translation_of: Web/API/Ambient_Light_Events +--- +<div>{{DefaultAPISidebar("Ambient Light Events")}}{{SeeCompatTable}}</div> + +<p>Los eventos de luz ambiental son una forma práctica de hacer una página web o una aplicación al tanto de cualquier cambio en la intensidad de la luz. Se les permite reaccionar a un cambio de este tipo, por ejemplo, cambiando el contraste de color de la interfaz de usuario (UI) o cambiando la exposición necesaria para tomar una foto.</p> + +<h2 id="Eventos_de_luz"><span class="short_text" id="result_box" lang="es"><span>Eventos</span> <span>de luz</span></span></h2> + +<p>Cuando el sensor de luz de un dispositivo detecta un cambio en el nivel de luz, notifica al navegador de ese cambio. Cuando el navegador recibe dicha notificación, se dispara un {{domxref ( "DeviceLightEvent")}} evento que proporciona información sobre la intensidad de la luz exacta.</p> + +<p>Este evento puede ser capturado en el plano objeto de la ventana mediante el uso de la {{domxref ( "EventTarget.addEventListener", "addEventListener")}} El método (usando el {{event( "devicelight")}} nombre del evento) o adjuntando una controlador de eventos al {{domxref ( "window.ondevicelight")}} propiedad.</p> + +<p>Una vez capturado, el objeto de evento da acceso a la intensidad de la luz expresada en lux a través de la {{domxref ( "DeviceLightEvent.value")}} propiedad.</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush: js">if ('ondevicelight' in window) { + window.addEventListener('devicelight', function(event) { + var body = document.querySelector('body'); + if (event.value < 50) { + body.classList.add('darklight'); + body.classList.remove('brightlight'); + } else { + body.classList.add('brightlight'); + body.classList.remove('darklight'); + } + }); +} else { + console.log('devicelight event not supported'); +} +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <thead> + <tr> + <td>Especificaciones</td> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("AmbientLight", "", "Ambient Light Events")}}</td> + <td>{{Spec2("AmbientLight")}}</td> + <td>definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_del_Navegador">Compatibilidad del Navegador</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>{{domxref("DeviceLightEvent")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop("22.0")}}<sup>[1]</sup></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>{{domxref("DeviceLightEvent")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoMobile("15.0")}}<sup>[1]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] The {{event("devicelight")}} event is implemented and preference enabled by default in Firefox Mobile for Android (15.0) and in Firefox OS (B2G). Starting with Gecko 22.0 {{geckoRelease("22.0")}} a desktop implementation for Mac OS X is also available. Support for Windows 7 is in progress (see {{bug(754199)}}).</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{domxref("DeviceLightEvent")}}</li> + <li>{{event("devicelight")}}</li> +</ul> diff --git a/files/es/web/api/analysernode/index.html b/files/es/web/api/analysernode/index.html new file mode 100644 index 0000000000..73a51adba8 --- /dev/null +++ b/files/es/web/api/analysernode/index.html @@ -0,0 +1,218 @@ +--- +title: AnalyserNode +slug: Web/API/AnalyserNode +translation_of: Web/API/AnalyserNode +--- +<p>{{APIRef("Web Audio API")}}</p> + +<p>La interfaz <strong><code>AnalyserNode</code></strong><strong> </strong>representa un nodo habilitado para proveer frecuencia en tiempo real y analisis de tiempo-dominio. Es un {{domxref("AudioNode")}} que pasa el flujo de audio sin modificación desde el origen de entrada a la salida, pero, te permite obtener los datos generados, procesarlos, y crear visualizaciones de audio.</p> + +<p>Un <code>AnalyzerNode</code> tiene exactamente una entrada y una salida. El nodo trabaja incluso si la salida no se encuentra conectada.</p> + +<p><img alt="Without modifying the audio stream, the node allows to get the frequency and time-domain data associated to it, using a FFT." src="https://mdn.mozillademos.org/files/9707/WebAudioFFT.png" style="height: 174px; width: 661px;"></p> + +<table class="properties"> + <tbody> + <tr> + <th scope="row"><dfn>Numero de entradas</dfn></th> + <td><code>1</code></td> + </tr> + <tr> + <th scope="row"><dfn>Numero de salidas</dfn></th> + <td><code>1</code> (puede estar desconectada)</td> + </tr> + <tr> + <th scope="row"><dfn>Modo de conteo de canal</dfn></th> + <td><code>"explicit"</code></td> + </tr> + <tr> + <th scope="row"><dfn>Conteo de cana</dfn></th> + <td><code>1</code></td> + </tr> + <tr> + <th scope="row"><dfn>Interpretación de canal</dfn></th> + <td><code>"speakers"</code></td> + </tr> + </tbody> +</table> + +<h2 id="Herencia">Herencia</h2> + +<p>Esta interfaz hereda de las siguientes interfaces padre:</p> + +<p>{{InheritanceDiagram}}</p> + +<h2 id="Propiedades">Propiedades</h2> + +<p><em>Inherits properties from its parent, </em><em>{{domxref("AudioNode")}}</em>.</p> + +<dl> + <dt>{{domxref("AnalyserNode.fftSize")}}</dt> + <dd>Is an unsigned long value representing the size of the FFT (<a href="http://en.wikipedia.org/wiki/Fast_Fourier_transform" title="/en-US/docs/">Fast Fourier Transform</a>) to be used to determine the frequency domain.</dd> + <dt>{{domxref("AnalyserNode.frequencyBinCount")}} {{readonlyInline}}</dt> + <dd>Is an unsigned long value half that of the FFT size. This generally equates to the number of data values you will have to play with for the visualization.</dd> + <dt>{{domxref("AnalyserNode.minDecibels")}}</dt> + <dd>Is a double value representing the minimum power value in the scaling range for the FFT analysis data, for conversion to unsigned byte values — basically, this specifies the minimum value for the range of results when using <code>getByteFrequencyData()</code>.</dd> + <dt>{{domxref("AnalyserNode.maxDecibels")}}</dt> + <dd>Is a double value representing the maximum power value in the scaling range for the FFT analysis data, for conversion to unsigned byte values — basically, this specifies the maximum value for the range of results when using <code>getByteFrequencyData()</code>.</dd> + <dt>{{domxref("AnalyserNode.smoothingTimeConstant")}}</dt> + <dd>Is a double value representing the averaging constant with the last analysis frame — basically, it makes the transition between values over time smoother.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<p><em>Inherits methods from its parent, </em><em>{{domxref("AudioNode")}}</em>.</p> + +<dl> + <dt>{{domxref("AnalyserNode.getFloatFrequencyData()")}}</dt> + <dd>Copies the current frequency data into a {{domxref("Float32Array")}} array passed into it.</dd> +</dl> + +<dl> + <dt>{{domxref("AnalyserNode.getByteFrequencyData()")}}</dt> + <dd>Copies the current frequency data into a {{domxref("Uint8Array")}} (unsigned byte array) passed into it.</dd> +</dl> + +<dl> + <dt>{{domxref("AnalyserNode.getFloatTimeDomainData()")}}</dt> + <dd>Copies the current waveform, or time-domain, data into a {{domxref("Float32Array")}} array passed into it.</dd> + <dt>{{domxref("AnalyserNode.getByteTimeDomainData()")}}</dt> + <dd>Copies the current waveform, or time-domain, data into a {{domxref("Uint8Array")}} (unsigned byte array) passed into it.</dd> +</dl> + +<h2 id="Examples">Examples</h2> + +<div class="note"> +<p><strong>Note</strong>: See the guide <a href="/en-US/docs/Web/API/Web_Audio_API/Visualizations_with_Web_Audio_API">Visualizations with Web Audio API</a> for more information on creating audio visualizations.</p> +</div> + +<h3 id="Basic_usage">Basic usage</h3> + +<p>The following example shows basic usage of an {{domxref("AudioContext")}} to create an <code>AnalyserNode</code>, then {{domxref("window.requestAnimationFrame()","requestAnimationFrame")}} and {{htmlelement("canvas")}} to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input. For more complete applied examples/information, check out our <a href="http://mdn.github.io/voice-change-o-matic/">Voice-change-O-matic</a> demo (see <a href="https://github.com/mdn/voice-change-o-matic/blob/gh-pages/scripts/app.js#L128-L205">app.js lines 128–205</a> for relevant code).</p> + +<pre class="brush: js">var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); +var analyser = audioCtx.createAnalyser(); + + ... + +analyser.fftSize = 2048; +var bufferLength = analyser.frequencyBinCount; +var dataArray = new Uint8Array(bufferLength); +analyser.getByteTimeDomainData(dataArray); + +// draw an oscilloscope of the current audio source + +function draw() { + + drawVisual = requestAnimationFrame(draw); + + analyser.getByteTimeDomainData(dataArray); + + canvasCtx.fillStyle = 'rgb(200, 200, 200)'; + canvasCtx.fillRect(0, 0, WIDTH, HEIGHT); + + canvasCtx.lineWidth = 2; + canvasCtx.strokeStyle = 'rgb(0, 0, 0)'; + + canvasCtx.beginPath(); + + var sliceWidth = WIDTH * 1.0 / bufferLength; + var x = 0; + + for(var i = 0; i < bufferLength; i++) { + + var v = dataArray[i] / 128.0; + var y = v * HEIGHT/2; + + if(i === 0) { + canvasCtx.moveTo(x, y); + } else { + canvasCtx.lineTo(x, y); + } + + x += sliceWidth; + } + + canvasCtx.lineTo(canvas.width, canvas.height/2); + canvasCtx.stroke(); + }; + + draw();</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-analysernode-interface', 'AnalyserNode')}}</td> + <td>{{Spec2('Web Audio API')}}</td> + <td> </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>{{CompatChrome(10.0)}}{{property_prefix("webkit")}}</td> + <td>{{CompatGeckoDesktop(25.0)}} </td> + <td>{{CompatNo}}</td> + <td>15.0 {{property_prefix("webkit")}}<br> + 22</td> + <td>6.0{{property_prefix("webkit")}}</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</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatUnknown}}</td> + <td>26.0</td> + <td>1.2</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>33.0</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web_Audio_API/Using_Web_Audio_API">Using the Web Audio API</a></li> +</ul> diff --git a/files/es/web/api/animation/animación/index.html b/files/es/web/api/animation/animación/index.html new file mode 100644 index 0000000000..770036b76d --- /dev/null +++ b/files/es/web/api/animation/animación/index.html @@ -0,0 +1,106 @@ +--- +title: Animation() +slug: Web/API/Animation/Animación +tags: + - Animacion +translation_of: Web/API/Animation/Animation +--- +<p>{{ SeeCompatTable() }}{{ APIRef("Web Animations API") }}</p> + +<p>El constructor <strong><code>Animation()</code></strong> de <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API">Web Animations API</a> devuelve una instancia del objeto <code>Animation</code>.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var <em>animation</em> = new Animation([<em>effect</em>][, <em>timeline</em>]);</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code>effect</code> {{optional_inline}}</dt> + <dd>El efecto objetivo, es un objeto de la interfaz {{domxref("AnimationEffectReadOnly")}} ,para asignarlo a la animación. Aunque en el futuro podrían ser asignados otros efectos como <code>SequenceEffect</code> o <code>GroupEffect</code>, el único efecto disponible actualmente es {{domxref("KeyframeEffect")}}. Este puede ser <code>null</code> (valor por defecto) para indicar que no debe aplicarse ningún efecto.</dd> + <dt><code>timeline</code> {{optional_inline}}</dt> + <dd>Especifica el <code>timeline</code> con el que asociar la animación, como un objeto de tipo basado en la interfaz {{domxref("AnimationTimeline")}} . Actualmente el único tipo de línea de tiempo disponible es {{domxref("DocumentTimeline")}}, pero en el futuro habrá lineas de tiempo asociadas , por ejemplo, con gestos o desplazamiento. El valor por defecto es {{domxref("Document.timeline")}}, pero puede ser establecido en <code>null</code>.</dd> +</dl> + +<h2 id="Ejemplos">Ejemplos</h2> + +<p>En el ejemplo <a href="http://codepen.io/rachelnabors/pen/eJyWzm/?editors=0010">Follow the White Rabbit </a>, el constructor <code>Animation()</code> es usado para crear una <code>Animation</code> para el <code>rabbitDownKeyframes</code> utilizando el <code>timeline</code> del documento:</p> + +<pre class="brush: js">var rabbitDownAnimation = new Animation(rabbitDownKeyframes, document.timeline); +</pre> + +<h2 id="Especificaciones">Especificaciones</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 Animations', '#dom-animation-animation', 'Animation()' )}}</td> + <td>{{Spec2('Web Animations')}}</td> + <td>Editor's draft.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_del_navegador">Compatibilidad del navegador</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>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop(48)}}<sup>[1]</sup></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>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>{{CompatGeckoMobile(48)}} <sup>[1]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] La Web Animations API solo está habilitada de manera predeterminada en Firefox Developer Edition y Nightly builds. Puedes habilitarla en compilaciones de lanzamiento estableciendo la preferencia de <code>dom.animations-api.core.enabled</code> en <code>true</code>, y puede desactivarse en cualquier versión de Firefox estableciendo esta preferencia en <code>false</code>.</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Web_Animations_API">Web Animations API</a></li> + <li>{{domxref("Animation")}}</li> +</ul> diff --git a/files/es/web/api/animation/cancel/index.html b/files/es/web/api/animation/cancel/index.html new file mode 100644 index 0000000000..e08956221a --- /dev/null +++ b/files/es/web/api/animation/cancel/index.html @@ -0,0 +1,119 @@ +--- +title: Animation.cancel() +slug: Web/API/Animation/cancel +tags: + - API + - Animacion + - Animaciones Web + - Experimental + - Reference + - cancel + - metodo + - waapi +translation_of: Web/API/Animation/cancel +--- +<p>{{ SeeCompatTable() }}{{ APIRef("Web Animations") }}</p> + +<p>El método <code><strong>cancel()</strong></code> de la Web Animations API de la interfaz {{domxref("Animation")}} borra todos los {{domxref("KeyframeEffect")}} causados por esta animación y aborta su reproducción.</p> + +<div class="note"> +<p>Cuando se cancela una animación, su {{domxref("Animation.startTime", "startTime")}} y su {{domxref("Animation.currentTime", "currentTime")}} se establecen en <code>null</code>.</p> +</div> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><em>Animation</em>.cancel();</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<p>None.</p> + +<h3 id="Valor_devuelto">Valor devuelto</h3> + +<p>None.</p> + +<h3 id="Excepciones">Excepciones</h3> + +<p>Este método no arroja excepciones directamente; sin embargo, si la animación {{domxref ("Animation.playState", "playState")}} no está <code>"idle"</code>"inactiva" cuando se cancela, el {{domxref ("Animation.finished", "current finished promise", "", 1)}} se rechaza con un {{domxref ("DOMException")}} llamado <code>AbortError</code>.</p> + +<dl> +</dl> + +<h2 id="Especificaciones">Especificaciones</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 Animations', '#dom-animation-cancel', 'Animation.cancel()' )}}</td> + <td>{{Spec2('Web Animations')}}</td> + <td>Editor's draft.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_del_navegador">Compatibilidad del navegador</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>{{CompatChrome(39.0)}}</td> + <td>{{CompatGeckoDesktop(48)}}<sup>[1]</sup></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>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile(48)}}<sup>[1]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] La Web Animations API solo está habilitada por defecto en Firefox Developer Edition y Nightly builds. Puedes habilitarlo en versiones Beta y de lanzamiento estableciendo la preferencia <code>dom.animations-api.core.enabled</code> en <code>true</code>, y puedes deshabilitarlo en cualquier versión de Firefox estableciendo esta propiedad en <code>false</code>.</p> + +<h2 id="Ver_también" style="line-height: 30px; font-size: 2.14285714285714rem;">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Web_Animations_API">Web Animations API</a></li> + <li>{{domxref("KeyframeEffect")}}</li> + <li>{{domxref("Animation")}}</li> + <li>{{domxref("Animation.playState")}}</li> + <li>{{domxref("Animation.finished")}} devuelve la promesa que esta acción rechazará si la animación de <code>playState</code> no está <code>"idle"</code> ("inactiva") .</li> +</ul> diff --git a/files/es/web/api/animation/effect/index.html b/files/es/web/api/animation/effect/index.html new file mode 100644 index 0000000000..f4283c52c4 --- /dev/null +++ b/files/es/web/api/animation/effect/index.html @@ -0,0 +1,104 @@ +--- +title: Animation.effect +slug: Web/API/Animation/effect +tags: + - API + - Animacion + - Animaciones Web + - Experimental + - Reference + - efecto +translation_of: Web/API/Animation/effect +--- +<div>{{ SeeCompatTable() }} {{ APIRef("Web Animations") }}</div> + +<p>La propiedad <code><strong>Animation</strong></code><strong><code>.effect</code></strong> de la <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API">Web Animations API</a> obtiene y establece el efecto objetivo de una animación. El efecto objetivo puede ser un objeto efecto de un tipo basado en {{domxref("AnimationEffectReadOnly")}}, como {{domxref("KeyframeEffect")}}, o <code>null</code>.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var <em>effect</em> = <em>Animation</em>.effect; + +<em>Animation</em>.effect = <em>{{domxref("AnimationEffectReadOnly")}}</em></pre> + +<h3 id="Valor">Valor</h3> + +<p>Un objeto {{domxref("AnimationEffectReadOnly")}} que describe el efecto de animación objetivo para la animación, o <code>null</code> para indicar que el efecto no está activo.</p> + +<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 Animations', '#dom-animation-effect', 'Animation.effect' )}}</td> + <td>{{Spec2('Web Animations')}}</td> + <td>Editor's draft.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</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>Microsoft Edge</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop(48)}}<sup>[1][2]</sup></td> + <td>{{CompatUnknown}}</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>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>{{CompatGeckoMobile(48)}}<sup>[1][2]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] La Web Animations API solo está habilitada por defecto en Firefox Developer Edition y Nightly builds. Puedes habilitarlo en versiones Beta y de lanzamiento estableciendo la preferencia <code>dom.animations-api.core.enabled</code>en <code>true</code>, y puedes deshabilitarlo en cualquier versión de Firefox estableciendo esta propiedad en <code>false</code>.</p> + +<p>[2] Esta propiedad es compatible con Firefox 48 pero es de solo-lectura. La versión Firefox 51 admite también escritura.</p> + +<h2 id="Ver_también" style="line-height: 30px; font-size: 2.14285714285714rem;">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Web_Animations_API">Web Animations API</a></li> + <li>{{domxref("AnimationEffectReadOnly")}}</li> + <li>{{domxref("Animation")}}</li> +</ul> diff --git a/files/es/web/api/animation/finish/index.html b/files/es/web/api/animation/finish/index.html new file mode 100644 index 0000000000..69ed0e4a68 --- /dev/null +++ b/files/es/web/api/animation/finish/index.html @@ -0,0 +1,147 @@ +--- +title: Animation.finish() +slug: Web/API/Animation/finish +tags: + - API + - Animacion + - Animaciones Web + - Experimental + - Finish + - Reference + - metodo + - waapi +translation_of: Web/API/Animation/finish +--- +<p>{{APIRef("Web Animations")}}{{SeeCompatTable}}</p> + +<div> +<p><span class="seoSummary">El método <strong><code>finish()</code> </strong>de la interfaz {{domxref("Animation")}} de la <a href="/en-US/docs/Web/API/Web_Animations_API">Web Animations API</a> </span>establece el tiempo de reproducción actual hasta el final de la animación correspondiente a la dirección de reproducción actual. Es decir, si la animación se está reproduciendo hacia adelante, establece el tiempo de reproducción a la longitud de la secuencia de animación, y si la animación se reproduce hacia atras , (habiendo llamado a su método {{domxref("Animation.reverse", "reverse()")}}), establece el tiempo de la reproducción en 0.</p> +</div> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><em>Animation</em>.finish(); </pre> + +<h3 id="Parámetros">Parámetros</h3> + +<p>None.</p> + +<h3 id="Valor_devuelto">Valor devuelto</h3> + +<p>None.</p> + +<dl> +</dl> + +<h3 id="Excepciones">Excepciones</h3> + +<dl> + <dt><code>InvalidState</code></dt> + <dd>La velocidad de reproducción del reproductor es 0 o la velocidad de reproducción de la animación es mayor que 0 y el tiempo de finalización de la animación es infinito.</dd> +</dl> + +<h2 id="Ejemplos"><strong>Ejemplos</strong></h2> + +<p>El siguiente ejemplo muestra cómo usar el método <code>finish()</code> y captura un error <code>InvalidState</code>.</p> + +<pre class="brush: js">interfaceElement.addEventListener("mousedown", function() { + try { + player.finish(); + } catch(e if e instanceof InvalidState) { + console.log("finish() called on paused or finished animation."); + } catch(e); + logMyErrors(e); //pasa el objeto excepción al manejador de errores. + } +}); +</pre> + +<p>El siguiente ejemplo finaliza todas las animaciones en un solo elemento, independientemente de su dirección de reproducción.</p> + +<pre class="brush: js">elem.getAnimations().forEach( + function(animation){ + return animation.finish(); + } +); +</pre> + +<h2 id="Especificaciones">Especificaciones</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 Animations', '#dom-animation-finish', 'finish()')}}</td> + <td>{{Spec2("Web Animations")}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_del_navegador">Compatibilidad del navegador</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>{{CompatChrome(39.0)}}</td> + <td>{{CompatGeckoDesktop(48)}}<sup>[1]</sup></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>Android Webview</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(39.0)}}</td> + <td>{{CompatGeckoMobile(48)}}<sup>[1]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(39.0)}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] La Web Animations API solo está habilitada por defecto en Firefox Developer Edition y Nightly builds. Puedes habilitarlo en versiones Beta y de lanzamiento estableciendo la preferencia <code>dom.animations-api.core.enabled</code> en <code>true</code>, y puedes deshabilitarlo en cualquier versión de Firefox estableciendo esta propiedad en <code>false</code>.</p> + +<h2 id="Ver_también" style="line-height: 30px; font-size: 2.14285714285714rem;">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Web_Animations_API">Web Animations API</a></li> + <li>{{domxref("Animation")}} para otros métodos y propiedades que puede usar para controlar la animación de la página web.</li> + <li>{{domxref("Animation.play()")}} para reproducir una animación hacia adelante.</li> + <li>{{domxref("Animation.reverse()")}} para reproducir una animación hacia atrás.</li> +</ul> diff --git a/files/es/web/api/animation/id/index.html b/files/es/web/api/animation/id/index.html new file mode 100644 index 0000000000..e44c852e72 --- /dev/null +++ b/files/es/web/api/animation/id/index.html @@ -0,0 +1,110 @@ +--- +title: Animation.id +slug: Web/API/Animation/id +tags: + - API + - Animacion + - Animaciones Web + - Experimental + - Reference + - id +translation_of: Web/API/Animation/id +--- +<p>{{ SeeCompatTable() }}{{ APIRef("Web Animations") }}</p> + +<p>La propiedad <code><strong>Animation</strong></code><strong><code>.id</code></strong> de la <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API">Web Animations API</a> devuelve o establece una cadena(string) utilizado para identificar la animación.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var <em>animationsId</em> = <em>Animation</em>.id; + +<em>Animation</em>.id = <em>newIdString</em>; +</pre> + +<h3 id="Valor">Valor</h3> + +<p>Un {{domxref("DOMString")}} que se puede usar para identificar la animación, o <code>null</code> si la animación no tiene <code>id</code>.</p> + +<h2 id="Ejemplos">Ejemplos</h2> + +<p>En el ejemplo <a href="http://codepen.io/rachelnabors/pen/eJyWzm?editors=0010">Follow the White Rabbit </a>, puedes asignar a <code>rabbitDownAnimation</code> un <code>id</code> de esta manera:</p> + +<pre class="brush: js">rabbitDownAnimation.effect.<em>id</em> = "rabbitGo"; +</pre> + +<h2 id="Especificaciones">Especificaciones</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 Animations', '#dom-animation-id', 'Animation.id' )}}</td> + <td>{{Spec2('Web Animations')}}</td> + <td>Editor's draft.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_del_navegador">Compatibilidad del navegador</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>{{CompatChrome(39.0)}}</td> + <td>{{CompatGeckoDesktop(48)}}<sup>[1]</sup></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>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(48)}}<sup>[1]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] La Web Animations API solo está habilitada por defecto en Firefox Developer Edition y Nightly builds. Puedes habilitarlo en versiones Beta y de lanzamiento estableciendo la preferencia <code>dom.animations-api.core.enabled</code> en <code>true</code>, y puedes deshabilitarlo en cualquier versión de Firefox estableciendo esta propiedad en <code>false</code>.</p> + +<h2 id="Ver_también" style="line-height: 30px; font-size: 2.14285714285714rem;">Ver también</h2> + +<ul> + <li>{{domxref("KeyframeEffect")}}</li> + <li><a href="/en-US/docs/Web/API/Web_Animations_API">Web Animations API</a></li> + <li>{{domxref("Animation")}}</li> +</ul> diff --git a/files/es/web/api/animation/index.html b/files/es/web/api/animation/index.html new file mode 100644 index 0000000000..ac1f5f46fb --- /dev/null +++ b/files/es/web/api/animation/index.html @@ -0,0 +1,147 @@ +--- +title: Animation +slug: Web/API/Animation +tags: + - API + - Animacion + - Experimental + - Interfaz + - Reeferencia + - Web Animations + - waapi + - web animation api +translation_of: Web/API/Animation +--- +<div>{{ APIRef("Web Animations") }}{{SeeCompatTable}}</div> + +<p>La interfaz <strong><code>Animation</code></strong> de la <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API">Web Animations API</a> representa un reproductor de animación y proporciona controles de reproducción y una línea de tiempo para un nodo o una fuente de animación.</p> + +<h2 id="Constructor">Constructor</h2> + +<dl> + <dt>{{domxref("Animation.Animation()", "Animation()")}}</dt> + <dd>Crea una nueva instancia de objeto <code>Animation</code>.</dd> +</dl> + +<h2 id="Propiedades">Propiedades</h2> + +<dl> + <dt>{{domxref("Animation.currentTime")}}</dt> + <dd>El valor del tiempo de la animación actual en milisegundos , ya sea en ejecución o en pausa. Si la animación carece de {{domxref("AnimationTimeline", "timeline")}}, está inactivo, o no se ha reproducido todavía, su valor es <code>null</code>.</dd> +</dl> + +<dl> + <dt>{{domxref("Animation.effect")}}</dt> + <dd>Obtiene y establece el {{domxref("AnimationEffectReadOnly")}} asociado con esta animación. Normalmente, este será un objeto {{domxref("KeyframeEffect")}}.</dd> + <dt>{{domxref("Animation.finished")}} {{readOnlyInline}}</dt> + <dd>Devuelve la Promesa actual terminada para esta animación.</dd> +</dl> + +<dl> + <dt>{{domxref("Animation.id")}}</dt> + <dd>Obtiene y establece la <code>String</code> usada para identificar la animación.</dd> + <dt>{{domxref("Animation.playState")}} {{readOnlyInline}}</dt> + <dd>Devuelve un valor enumerado que describe el estado de la reproducción de una animación.</dd> +</dl> + +<dl> + <dt>{{domxref("Animation.playbackRate")}}</dt> + <dd>Obtiene o establece la velocidad de reproducción de la animación.</dd> +</dl> + +<dl> + <dt>{{domxref("Animation.ready")}} {{readOnlyInline}}</dt> + <dd>Devuelve la Promesa actual lista para esta animación.</dd> +</dl> + +<dl> + <dt>{{domxref("Animation.startTime")}}</dt> + <dd>Obiene o establece la hora programada en la que debe comenzar la reproducción de la animación.</dd> +</dl> + +<dl> + <dt>{{domxref("Animation.timeline")}}</dt> + <dd>Obtiene o establece el {{domxref("AnimationTimeline", "timeline")}} asociado con esta animación.</dd> +</dl> + +<h3 id="Manejadores_de_eventos">Manejadores de eventos</h3> + +<dl> + <dt>{{domxref("Animation.oncancel")}}</dt> + <dd>Obtiene y establece en manejador de eventos para el evento <code>cancel</code>.</dd> + <dt>{{domxref("Animation.onfinish")}}</dt> + <dd>Obtiene y establece en manejador de eventos para el evento <code>finish</code> .</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<dl> + <dt>{{domxref("Animation.cancel()")}}</dt> + <dd>Borra todos los {{domxref("KeyframeEffect", "keyframeEffects")}} causados por la animación y aborta su reproducción.</dd> +</dl> + +<dl> + <dt>{{domxref("Animation.finish()")}}</dt> + <dd>Busca cualquier final de una animación, dependiendo de si la animación se está reproduciendo o invirtiendo.</dd> +</dl> + +<dl> + <dt>{{domxref("Animation.pause()")}}</dt> + <dd>Pone la reproducción en pausa.</dd> +</dl> + +<dl> + <dt>{{domxref("Animation.play()")}}</dt> + <dd><span id="result_box" lang="es"><span>Busca el final de una animación, dependiendo de si la animación se está reproduciendo o si se está invirtiendo.</span></span></dd> +</dl> + +<dl> + <dt>{{domxref("Animation.reverse()")}}</dt> + <dd><span id="result_box" lang="es"><span>Invierte la dirección de reproducción, deteniéndose al comienzo de la animación</span></span>. Si la animación finaliza o no se activa, volverá a reproducirse desde el final al principio.</dd> +</dl> + +<dl> + <dt>{{domxref("Animation.updatePlaybackRate()")}}</dt> + <dd>Establece la velocidad de la animación después de sincronizar por primera vez su posición de reproducción.</dd> +</dl> + +<h2 id="Problemas_de_accesibilidad">Problemas de accesibilidad</h2> + +<p>Las animaciones titilantes e intermitentes pueden causar dificultades a las personas con discapacidades cognitivas como Trastorno por Déficit de Atención con Hiperactividad (ADHD) además de causar ataques a personas con cinestosis, epilepsia, migranias o <span class="short_text" id="result_box" lang="es"><span>síndrome de sensibilidad escotópica</span></span>.</p> + +<p>Considera ofrecer un mecanismo para pausar o deshabilitar las animaciones, así como utilizar <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-motion">Reduced Motion Media Query</a> para crear una experiencia complementaria para los usuarios que han expresado su preferencia por experiencias no animadas.</p> + +<ul> + <li><a href="https://alistapart.com/article/designing-safer-web-animation-for-motion-sensitivity">Designing Safer Web Animation For Motion Sensitivity · An A List Apart Article </a></li> + <li><a href="https://css-tricks.com/introduction-reduced-motion-media-query/">An Introduction to the Reduced Motion Media Query | CSS-Tricks</a></li> + <li><a href="https://webkit.org/blog/7551/responsive-design-for-motion/">Responsive Design for Motion | WebKit</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/Accessibility/Understanding_WCAG/Operable#Guideline_2.2_%E2%80%94_Enough_Time_Provide_users_enough_time_to_read_and_use_content">MDN Understanding WCAG, Guideline 2.2 explanations</a></li> + <li><a href="https://www.w3.org/TR/UNDERSTANDING-WCAG20/time-limits-pause.html">Understanding Success Criterion 2.2.2 | W3C Understanding WCAG 2.0</a></li> +</ul> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName("Web Animations", "#the-animation-interface", "Animation")}}</td> + <td>{{Spec2("Web Animations")}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<p>{{Compat("api.Animation")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API">API de Animaciones Web</a></li> +</ul> diff --git a/files/es/web/api/animation/oncancel/index.html b/files/es/web/api/animation/oncancel/index.html new file mode 100644 index 0000000000..1f09835210 --- /dev/null +++ b/files/es/web/api/animation/oncancel/index.html @@ -0,0 +1,115 @@ +--- +title: Animation.oncancel +slug: Web/API/Animation/oncancel +tags: + - API + - Animacion + - Animaciones Web + - Experimental + - Reference + - oncancel +translation_of: Web/API/Animation/oncancel +--- +<p>{{ SeeCompatTable() }}{{ APIRef("Web Animations") }}</p> + +<p>La propiedad <code><strong>oncancel</strong></code> de la interfaz {{domxref("Animation")}} de la <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API">Web Animations API</a> es el manejador de eventos para el evento {{event("cancel")}} .</p> + +<p>El evento <code>cancel</code> puede ser activado manualmente con {{domxref("Animation.cancel()")}} cuando la animación entra en estado de reproducción <code>"idle"(inactivo)</code> desde otro estado, como cuando una animación se elimina de un elemento antes de que termine de reproducirse.</p> + +<div class="note"> +<p>La creación de una nueva animación, inicialmente inactiva, no activa el evento {{event("cancel")}} en la nueva animación.</p> +</div> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var <em>cancelHandler</em> = <em>Animation</em>.oncancel; + +<em>Animation</em>.oncancel = <em>cancelHandler</em>;</pre> + +<h3 id="Valor">Valor</h3> + +<p>Una función que será ejecutada cuando la animación sea cancelada, o <code>null</code> si no hay un manejador de eventos {{event("cancel")}}.</p> + +<h2 id="Ejemplos">Ejemplos</h2> + +<p>Si esta animación es cancelada, elimina su elemento.</p> + +<pre class="brush: js">animation.oncancel = animation.effect.target.remove(); +</pre> + +<h2 id="Especificaciones">Especificaciones</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 Animations', '#dom-animation-oncancel', 'Animation.oncancel' )}}</td> + <td>{{Spec2('Web Animations')}}</td> + <td>Editor's draft.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_del_navegador">Compatibilidad del navegador</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>{{CompatChrome(39.0)}}</td> + <td>{{CompatGeckoDesktop(48)}}<sup>[1]</sup></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>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile(48)}}<sup>[1]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] La Web Animations API solo está habilitada por defecto en Firefox Developer Edition y Nightly builds. Puedes habilitarlo en versiones Beta y de lanzamiento estableciendo la preferencia <code>dom.animations-api.core.enabled</code> en <code>true</code>, y puedes deshabilitarlo en cualquier versión de Firefox estableciendo esta propiedad en <code>false</code>.</p> + +<h2 id="Ver_también" style="line-height: 30px; font-size: 2.14285714285714rem;">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Web_Animations_API">Web Animations API</a></li> + <li>{{domxref("Animation")}}</li> + <li>The {{event("cancel")}} event</li> +</ul> diff --git a/files/es/web/api/animation/onfinish/index.html b/files/es/web/api/animation/onfinish/index.html new file mode 100644 index 0000000000..592014f698 --- /dev/null +++ b/files/es/web/api/animation/onfinish/index.html @@ -0,0 +1,131 @@ +--- +title: Animation.onfinish +slug: Web/API/Animation/onfinish +tags: + - API + - Animacion + - Animaciones Web + - Experimental + - Reference + - onfinish + - waapi +translation_of: Web/API/Animation/onfinish +--- +<p>{{ SeeCompatTable() }}{{ APIRef("Web Animations") }}</p> + +<p>La propiedad <code><strong>onfinish</strong></code> de la interfaz {{domxref("Animation")}} (de la <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API">Web Animations API</a>) es el manejador de eventos para el evento {{event("finish")}}. <span id="result_box" lang="es"><span>Este evento se envía cuando la animación termina de reproducirse</span></span>.</p> + +<p>El evento <code>finish</code> ocurre cuando la reproducción se completa de forma natural, así como cuando se llama al método {{domxref("Animation.finish()")}} para que la animación termine inmediatamente.</p> + +<div class="note"> +<p>El estado de reproducción <code>"paused"</code> reemplaza al estado <code>"finished"</code> ; Si la animación está pausada y finalizada, el estado<code>"paused"</code> será el único reportado. Puedes forzar el estado de la animación a <code>"finished"</code> configurando su {{domxref("Animation.startTime", "startTime")}} a <code>document.timeline.currentTime - (<em>Animation</em>.currentTime * <em>Animation</em>.playbackRate)</code>.</p> +</div> + +<h2 id="Sintaxis"><span class="highlight-span">Sintaxis</span></h2> + +<pre class="syntaxbox">var <em>finishHandler</em> = <em>Animation</em>.onfinish; + +<em>Animation</em>.onfinish = <em>finishHandler</em>;</pre> + +<h3 id="Valor">Valor</h3> + +<p>Una función que debe ser llamada para manejar el evento {{event("finish")}} , o <code>null</code> si no se establece ningún manejador para el evento <code>finish</code>.</p> + +<h2 id="Ejemplos">Ejemplos</h2> + +<p><code>Animation.onfinish</code> es utilizado en varias ocasiones en el juego de Alice in Web Animations API Land <a href="http://codepen.io/rachelnabors/pen/PNYGZQ?editors=0010">Growing/Shrinking Alice Game</a>. Aquí hay una instancia en la que agregamos eventos de puntero a un elemento después de que su animación de opacidad se haya desvanecido:</p> + +<pre class="brush: js">// <span id="result_box" lang="es"><span>Agrega una animación a los créditos finales del juego.</span></span> +var endingUI = document.getElementById("ending-ui"); +var bringUI = endingUI.animate(keysFade, timingFade); + +// Pone en Pausa dichos créditos. +bringUI.pause(); + +// <span id="result_box" lang="es"><span>Esta función elimina los eventos de puntero en los créditos.</span></span> +hide(endingUI); + +// Cuando los créditos se hayan desvanecido, +// volvemos a agregar los eventos de puntero cuando terminen. +bringUI.onfinish = function() { + endingUI.style.pointerEvents = 'auto'; +}; + +</pre> + +<h2 id="Especificaciones">Especificaciones</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 Animations', '#dom-animation-onfinish', 'Animation.onfinish' )}}</td> + <td>{{Spec2('Web Animations')}}</td> + <td>Editor's draft.</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>{{CompatChrome(39.0)}}</td> + <td>{{CompatGeckoDesktop(48)}}<sup>[1]</sup></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>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile(48)}}<sup>[1]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] La Web Animations API solo está habilitada por defecto en Firefox Developer Edition y Nightly builds. Puedes habilitarlo en versiones Beta y de lanzamiento estableciendo la preferencia <code>dom.animations-api.core.enabled</code> en <code>true</code>, y puedes deshabilitarlo en cualquier versión de Firefox estableciendo esta propiedad en <code>false</code>.</p> + +<h2 id="Ver_también" style="line-height: 30px; font-size: 2.14285714285714rem;">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Web_Animations_API">Web Animations API</a></li> + <li>{{domxref("Animation")}}</li> + <li>{{domxref("Animation.finish()")}}</li> +</ul> diff --git a/files/es/web/api/animation/pause/index.html b/files/es/web/api/animation/pause/index.html new file mode 100644 index 0000000000..0c0329dda7 --- /dev/null +++ b/files/es/web/api/animation/pause/index.html @@ -0,0 +1,106 @@ +--- +title: Animation.pause() +slug: Web/API/Animation/pause +tags: + - API + - Animacion + - Animaciones Web + - Experimental + - Referencia + - pausar + - pause + - waapi +translation_of: Web/API/Animation/pause +--- +<p>{{ SeeCompatTable() }}{{ APIRef("Web Animations") }}</p> + +<p>El método <code><strong>pause()</strong></code> de la interfaz {{domxref("Animation")}} de la <a href="/en-US/docs/Web/API/Web_Animations_API">Web Animations API</a>, suspende la reproducción de la animación.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">animation.pause(); +</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<p>None.</p> + +<h3 id="Valor_devuelto">Valor devuelto</h3> + +<p>None.</p> + +<h3 id="Excepciones">Excepciones</h3> + +<dl> + <dt>InvalidStateError</dt> + <dd>La animación {{domxref ("Animation.currentTime", "currentTime")}} no está resuelta <code>unresolved</code> (por ejemplo, si nunca se ha reproducido o no se está reproduciendo actualmente) y el tiempo de finalización de la animación es infinito positivo.</dd> +</dl> + +<p>Lanza un <code>InvalidStateError</code> si el {{domxref("Animation.currentTime", "currentTime")}} de la animación no está resuelto <code>unresolved</code> (tal vez no se haya iniciado la reproducción) y el fin de la animación es infinito positivo.</p> + +<h2 id="Ejemplos">Ejemplos</h2> + +<p><code>Animation.pause()</code> es utilizado en varias ocasiones en el juego Alice in Web Animations API Land <a href="http://codepen.io/rachelnabors/pen/PNYGZQ?editors=0010">Growing/Shrinking Alice Game</a>, porque las animaciones creadas con el método {{domxref("Element.animate()")}} se inician de inmediato y deben ser detenidas manualmente para evitar esto:</p> + +<pre class="brush: js">// animación de la magdalena que lentamente se está comiendo +var nommingCake = document.getElementById('eat-me_sprite').animate( +[ + { transform: 'translateY(0)' }, + { transform: 'translateY(-80%)' } +], { + fill: 'forwards', + easing: 'steps(4, end)', + duration: aliceChange.effect.timing.duration / 2 +}); + +// realmente solo debe funcionar al hacer click, así que se pausa inicialmente: +nommingCake.pause(); +</pre> + +<p>Adicionalmente, al restablecer:</p> + +<pre class="brush: js">// Una función multiusos para pausar las animaciones de Alicia, el pastelito y la botella que dice "drink me." +var stopPlayingAlice = function() { + aliceChange.pause(); + nommingCake.pause(); + drinking.pause(); +}; + +// Cuando el usuario suelte el cupcake o la botella, pause las animaciones. +cake.addEventListener("mouseup", stopPlayingAlice, false); +bottle.addEventListener("mouseup", stopPlayingAlice, false); +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th>Especificación</th> + <th>Estado</th> + <th>Comentario</th> + </tr> + <tr> + <td>{{SpecName('Web Animations', '#dom-animation-pause', 'play()')}}</td> + <td>{{Spec2("Web Animations")}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_navegadores">Compatibilidad en navegadores</h2> + +<div> +<p>{{Compat("api.Animation.pause")}}</p> +</div> + +<h2 id="Ver_también" style="line-height: 30px; font-size: 2.14285714285714rem;">Ver también</h2> + +<ul> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API">Web Animations API</a></li> + <li>{{domxref("Animation")}} para otros métodos y propiedades que puedes usar para el control de animaciones en páginas web.</li> + <li>{{domxref("Animation.pause()")}} para pausar una animación.</li> + <li>{{domxref("Animation.reverse()")}} para reproducir una animación al revés.</li> + <li>{{domxref("Animation.finish()")}} para finalizar una animación.</li> + <li>{{domxref("Animation.cancel()")}} para cancelar una animación.</li> +</ul> diff --git a/files/es/web/api/animation/play/index.html b/files/es/web/api/animation/play/index.html new file mode 100644 index 0000000000..9ccb5d68a6 --- /dev/null +++ b/files/es/web/api/animation/play/index.html @@ -0,0 +1,149 @@ +--- +title: Animation.play() +slug: Web/API/Animation/play +tags: + - API + - Animacion + - Animaciones Web + - Experimental + - Interface + - Reference + - metodo + - play + - waapi +translation_of: Web/API/Animation/play +--- +<div>{{ APIRef("Web Animations") }}{{SeeCompatTable}}</div> + +<p>El método <strong><code>play()</code></strong> de la interfaz {{ domxref("Animation") }} de la <a href="/en-US/docs/Web/API/Web_Animations_API">Web Animations API</a> inicia o reanuda la reproducción de una animación. Si la animación ha finalizado, llamando a <code>play()</code> reinicia la animación y la reproduce desde el principio.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">animation.play(); +</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<p>None.</p> + +<h3 id="Valor_devuelto">Valor devuelto</h3> + +<p>{{jsxref("undefined")}}</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>En el ejemplo <a href="http://codepen.io/rachelnabors/pen/PNYGZQ?editors=0010">Growing/Shrinking Alice Game</a> , hacer click o tocar el pastel hace que la animación de crecimiento de Alicia (<code>aliceChange</code>) sea reproducida hacia adelante, causando que Alicia se haga más grande, ademas de desencadenar la animación del pastel. Dos <code>Animation.play()</code> y un <code>EventListener</code>:</p> + +<pre class="brush: js">// El pastel tiene su propia animación: +var nommingCake = document.getElementById('eat-me_sprite').animate( +[ + { transform: 'translateY(0)' }, + { transform: 'translateY(-80%)' } +], { + fill: 'forwards', + easing: 'steps(4, end)', + duration: aliceChange.effect.timing.duration / 2 +}); + +// Pausa la animación del pastel para que no se reproduzca inmediatamente. +nommingCake.pause(); + +// Esta función se reproducirá cuando el usuario haga click o toque +var growAlice = function() { + + // Reproduce la animación de Alicia. + aliceChange.play(); + + // Reproduce la animación del pastel. + nommingCake.play(); + +} + +// Cuando el usuario hace click o toca, llama a growAlice, para reproducir todas las animaciones. +cake.addEventListener("mousedown", growAlice, false); +cake.addEventListener("touchstart", growAlice, false); +</pre> + +<h2 id="Especificaciones">Especificaciones</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 Animations', '#dom-animation-play', 'play()')}}</td> + <td>{{Spec2("Web Animations")}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_del_navegador">Compatibilidad del navegador</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>{{CompatChrome(39.0)}}</td> + <td>{{CompatGeckoDesktop(48)}}<sup>[1]</sup></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>Android Webview</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(39.0)}}</td> + <td>{{CompatGeckoMobile(48)}}<sup>[1]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(39.0)}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] La Web Animations API solo está habilitada por defecto en Firefox Developer Edition y Nightly builds. Puedes habilitarlo en versiones Beta y de lanzamiento estableciendo la preferencia <code>dom.animations-api.core.enabled</code> en <code>true</code>, y puedes deshabilitarlo en cualquier versión de Firefox estableciendo esta propiedad en <code>false</code>.</p> + +<h2 id="Ver_también" style="line-height: 30px; font-size: 2.14285714285714rem;">Ver también</h2> + +<ul> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API">Web Animations API</a></li> + <li>{{domxref("Animation")}} para otros métodos y propiedades que puedes usar para el control de animaciones en páginas web.</li> + <li>{{domxref("Animation.pause()")}} para pausar una animación.</li> + <li>{{domxref("Animation.reverse()")}} para reproducir una animación al revés.</li> + <li>{{domxref("Animation.finish()")}} para finalizar una animación.</li> + <li>{{domxref("Animation.cancel()")}} para cancelar una animación.</li> +</ul> diff --git a/files/es/web/api/animation/playbackrate/index.html b/files/es/web/api/animation/playbackrate/index.html new file mode 100644 index 0000000000..0961c0bd6c --- /dev/null +++ b/files/es/web/api/animation/playbackrate/index.html @@ -0,0 +1,162 @@ +--- +title: Animation.playbackRate +slug: Web/API/Animation/playbackRate +tags: + - API + - Animacion + - Animaciones Web + - Experimental + - Interface + - Reference + - playbackRate +translation_of: Web/API/Animation/playbackRate +--- +<p>{{APIRef("Web Animations")}}{{SeeCompatTable}}</p> + +<p>La propiedad <code><strong>Animation</strong></code><strong><code>.playbackRate</code></strong> de la <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API">Web Animations API</a> devuelve o establece la velocidad de reproducción de la animación.</p> + +<p>Las animaciones tienen un <strong>playback rate</strong> que proporciona un factor de escala para el cambio de velocidad de la animación {{domxref("DocumentTimeline", "timeline")}} valores del estado actual de la linea de tiempo de la animación. La velocidad de reproducción inicial es <code>1</code>.</p> + +<h2 id="Sintaxis" style="line-height: 30px; font-size: 2.14285714285714rem;">Sintaxis</h2> + +<pre class="syntaxbox" style="font-size: 14px;">var <em>currentPlaybackRate</em> = <em>Animation</em>.playbackRate; + +<em>Animation</em>.playbackRate = <em>newRate</em>; +</pre> + +<h3 id="Valor">Valor</h3> + +<p><span id="result_box" lang="es"><span>Toma un número que puede ser 0, negativo o positivo.</span> <span>Los valores negativos invierten la animación.</span> <span>El valor es un factor de escala, por lo que, por ejemplo, un valor de 2 duplicaría la velocidad de reproducción.</span></span></p> + +<div class="note"> +<p>si establecemos el <code>playbackRate</code> a <code>0</code> pausa la animación de manera efectiva (sin embargo, su {{domxref("Animation.playstate", "playstate")}} no se convierte necesariamente en <code>paused</code>).</p> +</div> + +<h2 id="Ejemplos">Ejemplos</h2> + +<p>En el ejemplo <a href="http://codepen.io/rachelnabors/pen/PNYGZQ?editors=0010">Growing/Shrinking Alice Game</a> , hacer click o tocar la botella, hace que la animación de crecimiento de Alicia (<code>aliceChange</code>) se invierta para reducirse:</p> + +<pre class="brush: js">var shrinkAlice = function() { + aliceChange.playbackRate = -1; + aliceChange.play(); +} + +// Con un toque o un click, Alicia se encogerá. +bottle.addEventListener("mousedown", shrinkAlice, false); +bottle.addEventListener("touchstart", shrinkAlice, false); +</pre> + +<p>Por el contrario, hacer click en el pastel hace que "crezca" reproduciendo <code>aliceChange</code> hacia adelante otra vez:</p> + +<pre class="brush: js">var growAlice = function() { + aliceChange.playbackRate = 1; + aliceChange.play(); +} + +// Con un toque o un click, Alicia crecerá. +cake.addEventListener("mousedown", growAlice, false); +cake.addEventListener("touchstart", growAlice, false); +</pre> + +<p>En otro ejemplo, <a href="http://codepen.io/rachelnabors/pen/PNGGaV?editors=0010">Red Queen's Race Game</a>, Alicia y La Reina Roja están ralentizandose constantemente:</p> + +<pre class="brush: js">setInterval( function() { + + // <span id="result_box" lang="es"><span>Asegúrate de que la velocidad de reproducción nunca descienda por debajo de .4</span></span> + + if (redQueen_alice.playbackRate > .4) { + redQueen_alice.playbackRate *= .9; + } + +}, 3000); +</pre> + +<p><span id="result_box" lang="es"><span>Pero hacer click o hacer tapping(pasar el puntero) sobre ellos hace que aceleren multiplicando su</span></span> <code>playbackRate</code>(velocidad de reproducción):</p> + +<pre class="brush: js">var goFaster = function() { + redQueen_alice.playbackRate *= 1.1; +} + +document.addEventListener("click", goFaster); +document.addEventListener("touchstart", goFaster); +</pre> + +<h2 id="Especificaciones"><span class="highlight-span">Especificaciones</span></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 Animations', '#dom-animation-playbackrate', 'Animation.playbackRate')}}</td> + <td>{{Spec2("Web Animations")}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_del_navegador"><span class="highlight-span">Compatibilidad del navegador</span></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>{{CompatChrome(39.0)}}</td> + <td>{{CompatGeckoDesktop(48)}}<sup>[1]</sup></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>Android Webview</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(39.0)}}</td> + <td>{{CompatGeckoMobile(48)}}<sup>[1]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(39.0)}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] La Web Animations API solo está habilitada por defecto en Firefox Developer Edition y Nightly builds. Puedes habilitarlo en versiones Beta y de lanzamiento estableciendo la preferencia <code>dom.animations-api.core.enabled</code> en <code>true</code>, y puedes deshabilitarlo en cualquier versión de Firefox estableciendo esta propiedad en <code>false</code>.</p> + +<h2 id="Ver_también" style="line-height: 30px; font-size: 2.14285714285714rem;">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Web_Animations_API">Web Animations API</a></li> + <li>{{domxref("Animation")}}</li> +</ul> diff --git a/files/es/web/api/animation/playstate/index.html b/files/es/web/api/animation/playstate/index.html new file mode 100644 index 0000000000..35d104739b --- /dev/null +++ b/files/es/web/api/animation/playstate/index.html @@ -0,0 +1,158 @@ +--- +title: Animation.playState +slug: Web/API/Animation/playState +tags: + - API + - Animacion + - Animaciones Web + - Experimental + - Reference + - playState +translation_of: Web/API/Animation/playState +--- +<p>{{APIRef("Web Animations")}}{{SeeCompatTable}}</p> + +<p>La propiedad <code><strong>Animation</strong></code><strong><code>.playState</code></strong> de la <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API">Web Animations API</a> devuelve y establece un valor enumerado que describe el estado de reproducción de una animación.</p> + +<div class="note"> +<p>Esta propiedad es de solo lectura para las Animaciones y Transiciones en CSS.</p> +</div> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var<em> currentPlayState</em> = <em>Animation</em>.playState; + +<em>Animation</em>.playState = <em>newState</em>; +</pre> + +<h3 id="Valor">Valor</h3> + +<dl> + <dt><code>idle(inactivo)</code></dt> + <dd><span id="result_box" lang="es"><span>El tiempo actual de la animación no está resuelto y no hay tareas pendientes.</span></span></dd> + <dt><code>pending(pendiente)</code></dt> + <dd><span id="result_box" lang="es"><span>La animación está esperando que se complete una tarea pendiente.</span></span></dd> + <dt><code>running(funcionando)</code></dt> + <dd><span class="short_text" id="result_box" lang="es"><span>La animación se está ejecutando.</span></span></dd> + <dt><code>paused(pausado)</code></dt> + <dd><span id="result_box" lang="es"><span>La animación se ha suspendido y la propiedad {{domxref ("Animation.currentTime")}} no se está actualizando.</span></span></dd> + <dt><code>finished(finalizado)</code></dt> + <dd><span id="result_box" lang="es"><span>La animación ha alcanzado uno de sus límites y la propiedad {{domxref ("Animation.currentTime")}} no se está actualizando.</span></span></dd> +</dl> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>En el ejemplo <a href="http://codepen.io/rachelnabors/pen/PNYGZQ?editors=0010">Growing/Shrinking Alice Game</a> , los jugadores pueden tener un final con (Alicia llorando en un mar de lágrimas) <a href="http://codepen.io/rachelnabors/pen/EPJdJx?editors=0010">Alice crying into a pool of tears</a>. En el juego, por razones de rendimiento, las lágrimas solo se deben animar cuando son visibles. <span id="result_box" lang="es"><span>Por lo tanto, deben detenerse tan pronto como estén animadas, de esta manera:</span></span></p> + +<pre class="brush: js">// <span class="short_text" id="result_box" lang="es"><span>Configurando las animaciones de lágrimas</span></span> + +tears.forEach(function(el) { + el.animate( + tearsFalling, + { + delay: getRandomMsRange(-1000, 1000), // cada lágrima aleatoria + duration: getRandomMsRange(2000, 6000), // cada lágrima aleatoria + iterations: Infinity, + easing: "cubic-bezier(0.6, 0.04, 0.98, 0.335)" + }); + el.playState = 'paused'; +}); + + +// Reproduce las lágrimas cayendo cuando el final necesita mostrarlas. + +tears.forEach(function(el) { + el.playState = 'playing'; +}); + + +// Reinicia la animación de las lágrimas y la detiene. + +tears.forEach(function(el) { + el.playState = "paused"; + el.currentTime = 0; +}); +</pre> + +<h2 id="Especificaciones"><span class="highlight-span">Especificaciones</span></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 Animations', '#play-state', 'playState')}}</td> + <td>{{Spec2("Web Animations")}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_del_navegador"><span class="highlight-span">Compatibilidad del navegador</span></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>{{CompatChrome(39.0)}} [1]</td> + <td>{{CompatGeckoDesktop(48)}}<sup>[2]</sup></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>Android Webview</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>{{CompatChrome(39.0)}} [1]</td> + <td>{{CompatChrome(39.0)}} [1]</td> + <td>{{CompatGeckoMobile(48)}}<sup>[2]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Antes de Chrome 50, este atributo mostraba <code>idle</code> para una animación que aún no había comenzado. A partir de Chrome 50, muestra <code>paused</code>.</p> + +<p>[2] La Web Animations API solo está habilitada por defecto en Firefox Developer Edition y Nightly builds. Puedes habilitarlo en versiones Beta y de lanzamiento estableciendo la preferencia <code>dom.animations-api.core.enabled</code> en <code>true</code>, y puedes deshabilitarlo en cualquier versión de Firefox estableciendo esta propiedad en <code>false</code>.</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Web_Animations_API">Web Animations API</a></li> + <li>{{domxref("Animation")}} <span id="result_box" lang="es"><span>para otros métodos y propiedades que puede usar para controlar la animación de la página web.</span></span></li> + <li>Los métodos {{domxref("Animation.play()")}}, {{domxref("Animation.pause()")}}, {{domxref("Animation.finish()")}} pueden establecer el <code>playState</code> de un <code>Animation</code> .</li> +</ul> diff --git a/files/es/web/api/animation/ready/index.html b/files/es/web/api/animation/ready/index.html new file mode 100644 index 0000000000..35dfb68954 --- /dev/null +++ b/files/es/web/api/animation/ready/index.html @@ -0,0 +1,122 @@ +--- +title: Animation.ready +slug: Web/API/Animation/ready +tags: + - API + - Animacion + - Animaciones Web + - Experimental + - Ready Promise + - Reference +translation_of: Web/API/Animation/ready +--- +<p>{{ SeeCompatTable() }}{{ APIRef("Web Animations") }}</p> + +<p>La propiedad de solo-lectura <strong><code>Animation.ready</code></strong> de la <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API">Web Animations API</a> devuelve un {{jsxref("Promise")}} que se resuelve cuando la animación está lista para reproducirse. Una nueva 'promesa' es creada cada vez que la animación entra en <a href="/en-US/docs/Web/API/Animation/playState">play state(estado de reproducción)</a> <code>"pending"(pendiente)</code> así como si la reproducción es cancelada, ya que en ambos escenarios, la animación estará lista para ser reiniciada.</p> + +<div class="note"> +<p>Dado que la misma {{jsxref("Promise")}} es usada para las solicitudes pendientes de <code>play</code> y<code>pause</code> , <span id="result_box" lang="es"><span>se recomienda a los autores que comprueben el estado de la animación cuando se resuelva la promesa</span></span>.</p> +</div> + +<h2 id="Sintaxis"><span class="highlight-span">Sintaxis</span></h2> + +<pre class="syntaxbox">var <em>readyPromise</em> = <em>Animation</em>.ready; +</pre> + +<h3 id="Valor">Valor</h3> + +<p>Un {{jsxref("Promise")}} que se resuelve cuando la animación esta lista para reproducirse. Por lo general, se usará una construcción similar a esta usando una promise lista:</p> + +<pre class="brush: js">animation.ready.then(function() { + // Hace lo que sea necesario cuando + // la animación está lista para reproducirse +});</pre> + +<h2 id="Ejemplo"><span class="highlight-span">Ejemplo</span></h2> + +<p>En el siguiente ejemplo, el estado de la animación será <code>running(reproduciendo)</code> cuando la<strong> Promise actual</strong> se resuelva ya que la animación no deja el estado de reproducción <code>pending</code> entre las llamadas <code>pause</code> and <code>play</code> ,por lo tanto, la <strong>Promise actual</strong> no cambia.</p> + +<pre class="brush: js">animation.pause(); +animation.ready.then(function() { + // Displays 'running' + alert(animation.playState); +}); +animation.play(); +</pre> + +<h2 id="Especificaciones"><span class="highlight-span"><span class="highlight-span">Especificaciones</span></span></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 Animations', '#dom-animation-ready', 'Animation.ready' )}}</td> + <td>{{Spec2('Web Animations')}}</td> + <td>Editor's draft.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_del_navegador"><span class="highlight-span"><span class="highlight-span">Compatibilidad del navegador</span></span></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>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop(48)}}<sup>[1]</sup></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>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>{{CompatGeckoMobile(48)}}<sup>[1]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] La Web Animations API solo está habilitada por defecto en Firefox Developer Edition y Nightly builds. Puedes habilitarlo en versiones Beta y de lanzamiento estableciendo la preferencia <code>dom.animations-api.core.enabled</code> en <code>true</code>, y puedes deshabilitarlo en cualquier versión de Firefox estableciendo esta propiedad en <code>false</code>.</p> + +<h2 id="Ver_también" style="line-height: 30px; font-size: 2.14285714285714rem;"><span class="highlight-span">Ver también</span></h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Web_Animations_API">Web Animations API</a></li> + <li>{{domxref("Animation")}}</li> + <li>{{domxref("Animation.playState")}}</li> +</ul> diff --git a/files/es/web/api/animation/reverse/index.html b/files/es/web/api/animation/reverse/index.html new file mode 100644 index 0000000000..9f2dbf790e --- /dev/null +++ b/files/es/web/api/animation/reverse/index.html @@ -0,0 +1,136 @@ +--- +title: Animation.reverse() +slug: Web/API/Animation/reverse +tags: + - API + - Animacion + - Animaciones Web + - Experimental + - Interface + - Reference + - metodo + - reverse + - waapi +translation_of: Web/API/Animation/reverse +--- +<div>{{APIRef("Web Animations")}}{{SeeCompatTable}}</div> + +<p>El método <strong><code>Animation.reverse()</code></strong> de la interfaz {{ domxref("Animation") }} Interface invierte la dirección de reproducción, lo que significa que la animación termina al principio. Si se llama en una animación sin reproducir, toda la animación se reproduce al revés. Si se llama en una animación pausada, continúa a la inversa.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">animation.reverse(); +</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<p>None.</p> + +<h3 id="Valor_devuelto">Valor devuelto</h3> + +<p>{{jsxref("undefined")}}</p> + +<h2 id="Ejemplos">Ejemplos</h2> + +<p>En el ejemplo <a href="http://codepen.io/rachelnabors/pen/PNYGZQ?editors=0010">Growing/Shrinking Alice Game</a> , hacer click o tocar la botella, hace que la animación de crecimiento de Alicia(<code>aliceChange</code>) sea reproducida al revés, lo que la hace más pequeña. Esto se hace estableciendo el {{ domxref("Animation.playbackRate") }} de <code>aliceChange</code> en <code>-1</code> de esta forma:</p> + +<pre class="brush: js">var shrinkAlice = function() { + // reproduce la animación de Alicia al revés. + aliceChange.playbackRate = -1; + aliceChange.play(); + + // reproduce la animación de la botella. + drinking.play() +}</pre> + +<p>Pero también se podría haber hecho lamando a <code>reverse()</code> en <code>aliceChange</code> así:</p> + +<pre class="brush: js">var shrinkAlice = function() { + // reproduce la animación de Alicia al revés. + aliceChange.reverse(); + + // reproduce la animación de la botella. + drinking.play() +}</pre> + +<h2 id="Especificaciones">Especificaciones</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 Animations', '#dom-animation-reverse', 'reverse()')}}</td> + <td>{{Spec2("Web Animations")}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_del_navegador">Compatibilidad del navegador</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>{{CompatChrome(39.0)}}</td> + <td>{{CompatGeckoDesktop(48)}}<sup>[1]</sup></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>Android Webview</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(39.0)}}</td> + <td>{{CompatGeckoMobile(48)}}<sup>[1]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(39.0)}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] La Web Animations API solo está habilitada por defecto en Firefox Developer Edition y Nightly builds. Puedes habilitarlo en versiones Beta y de lanzamiento estableciendo la preferencia <code>dom.animations-api.core.enabled</code> en <code>true</code>, y puedes deshabilitarlo en cualquier versión de Firefox estableciendo esta propiedad en <code>false</code>.</p> + +<h2 id="Ver_también" style="line-height: 30px; font-size: 2.14285714285714rem;">Ver también</h2> + +<ul> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API">Web Animations API</a></li> + <li>{{domxref("Animation")}} para otros métodos y propiedades que puedes usar para el control de animaciones en páginas web.</li> + <li>{{domxref("Animation.pause()")}} para pausar una animación.</li> + <li>{{domxref("Animation.play()")}} para reproducir una animación hacia adelante.</li> +</ul> diff --git a/files/es/web/api/animation/starttime/index.html b/files/es/web/api/animation/starttime/index.html new file mode 100644 index 0000000000..8ad69e8ffa --- /dev/null +++ b/files/es/web/api/animation/starttime/index.html @@ -0,0 +1,138 @@ +--- +title: Animation.startTime +slug: Web/API/Animation/startTime +tags: + - API + - Animacion + - Animaciones Web + - Experimental + - Interface + - Reference + - startTime +translation_of: Web/API/Animation/startTime +--- +<p>{{ SeeCompatTable() }}{{ APIRef("Web Animations") }}</p> + +<p><span id="result_box" lang="es"><span>La propiedad <strong><code>Animation.startTime</code></strong> de la interfaz {{domxref ("Animación")}} es un valor de punto flotante de doble precisión que indica el tiempo programado en el que debe comenzar la reproducción de una animación.</span></span></p> + +<p>El <strong>start time</strong> <strong>(tiempo de inicio)</strong> es el valor de tiempo de su {{domxref("timeline", "DocumentTimeline")}}cuando su objetivo {{domxref("KeyframeEffect")}} está programado para comenzar la reproducción. <span id="result_box" lang="es"><span>El </span></span><strong>start time</strong> <strong>(tiempo de inicio)</strong><span lang="es"><span> de una animación inicialmente no está resuelto (lo que significa que es <code>null</code> porque no tiene valor).</span></span></p> + +<h2 id="Sintaxis"><span class="highlight-span">Sintaxis</span></h2> + +<pre class="syntaxbox">var <em>animationStartedWhen</em> = <em>Animation</em>.startTime; + +<em>Animation</em>.startTime = <em>newStartTime</em>;</pre> + +<h3 id="Valor">Valor</h3> + +<p>Un número de punto flotante que representa el tiempo actual en milisegundos, o nulo si no se establece ningún valor de tiempo. Puede leer este valor para determinar en qué momento está establecido el punto de inicio, y puede modificarlo para que la animación comience en un momento diferente.</p> + +<h2 id="Ejemplos">Ejemplos</h2> + +<p>En el ejemplo <a href="http://codepen.io/rachelnabors/pen/zxYexJ?editors=0010">Running on Web Animations API example</a>, podemos sincronizar todos los nuevos gatos animados dándoles el mismo tiempo de inicio <code>startTime</code> que el gato original:</p> + +<pre class="brush: js">var catRunning = document.getElementById ("withWAAPI").animate(keyframes, timing); + +/* Una función que crea nuevos gatos. */ +function addCat(){ + var newCat = document.createElement("div"); + newCat.classList.add("cat"); + return newCat; +} + +/* Esta es la función que agrega un gato a la columna WAAPI */ +function animateNewCatWithWAAPI() { + // crea unnuevo gato + var newCat = addCat(); + + // Animar a dicho gato con la función "animate" de WAAPI + var newAnimationPlayer = newCat.animate(keyframes, timing); + + // Establece que el punto de inicio de la animación sea el mismo que el original<code class="language-js"><span class="comment token"> .cat#withWAAPI</span></code> + newAnimationPlayer.startTime = catRunning.startTime;<em><strong> +</strong></em> + // Agrega el gato a la pila. + WAAPICats.appendChild(newCat); +} +</pre> + +<h2 id="Especificaciones"><span class="highlight-span"><span class="highlight-span">Especificaciones</span></span></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 Animations', '#dom-animation-starttime', 'Animation.startTime' )}}</td> + <td>{{Spec2('Web Animations')}}</td> + <td>Editor's draft.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_del_navegador"><span class="highlight-span"><span class="highlight-span">Compatibilidad del navegador</span></span></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>{{CompatChrome(39.0)}}</td> + <td>{{CompatGeckoDesktop(48)}}<sup>[1]</sup></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>Android Webview</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(39.0)}}</td> + <td>{{CompatGeckoMobile(48)}}<sup>[1]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(39.0)}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] La Web Animations API solo está habilitada por defecto en Firefox Developer Edition y Nightly builds. Puedes habilitarlo en versiones Beta y de lanzamiento estableciendo la preferencia <code>dom.animations-api.core.enabled</code> en <code>true</code>, y puedes deshabilitarlo en cualquier versión de Firefox estableciendo esta propiedad en <code>false</code>.</p> + +<h2 id="Ver_también" style="line-height: 30px; font-size: 2.14285714285714rem;"><span class="highlight-span">Ver también</span></h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Web_Animations_API">Web Animations API</a></li> + <li>{{domxref("Animation")}}</li> + <li>{{domxref("Animation.currentTime")}} para el tiempo actual de la animación.</li> +</ul> diff --git a/files/es/web/api/animation/terminado/index.html b/files/es/web/api/animation/terminado/index.html new file mode 100644 index 0000000000..5d321ba012 --- /dev/null +++ b/files/es/web/api/animation/terminado/index.html @@ -0,0 +1,120 @@ +--- +title: Animation.finished +slug: Web/API/Animation/terminado +tags: + - API + - Animacion + - Animaciones Web + - Experimental + - Reference +translation_of: Web/API/Animation/finished +--- +<p>{{ SeeCompatTable() }}{{ APIRef("Web Animations") }}</p> + +<p>La propiedad de solo-lectura de <code><strong>Animation</strong></code><strong><code>.finished</code></strong> de la <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API">Web Animations API</a> devuelve un {{jsxref("Promise")}} que se resuelve una vez que la animación a terminado de reproducirse.</p> + +<div class="note"> +<p>Una vez que la reproducción de la animación abandona el estado <code>finished</code> ( es decir, la reproducción se está ejecutando otra vez ), Un nuevo <code>Promise</code> es creado para esta propiedad. El nuevo <code>Promise</code> será resuelto cuando se haya completado la actual secuencia de la animación.</p> +</div> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var <em>animationsPromise</em> = <em>Animation.</em>finished; +</pre> + +<h3 id="Valor">Valor</h3> + +<p>Un objeto {{jsxref("Promise")}} que se resuelve cuando haya finalizado la reproducción de la animación.</p> + +<h2 id="Ejemplos">Ejemplos</h2> + +<p>El siguiente código espera a que todas las animaciones que se ejecutan en el elemento <code>elem</code> hayan terminado, después elimina el elemento del arbol del DOM:</p> + +<pre class="brush: js">Promise.all( + elem.getAnimations().map( + function(animation) { + return animation.finished + } + ) +).then( + function() { + return elem.remove(); + } +);</pre> + +<h2 id="Especificaciones">Especificaciones</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 Animations', '#dom-animation-finished', 'Animation.finished' )}}</td> + <td>{{Spec2('Web Animations')}}</td> + <td>Editor's draft.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_del_navegador">Compatibilidad del navegador</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>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop(48)}}<sup>[1]</sup></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>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>{{CompatGeckoDesktop(48)}}<sup>[1]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] La Web Animations API solo está habilitada por defecto en Firefox Developer Edition y Nightly builds. Puedes habilitarlo en versiones Beta y de lanzamiento estableciendo la preferencia <code>dom.animations-api.core.enabled</code> en <code>true</code>, y puedes deshabilitarlo en cualquier versión de Firefox estableciendo esta propiedad en <code>false</code>.</p> + +<h2 id="Ver_también" style="line-height: 30px; font-size: 2.14285714285714rem;">Ver también</h2> + +<ul> + <li>{{domxref("KeyframeEffect")}}</li> + <li><a href="/en-US/docs/Web/API/Web_Animations_API">Web Animations API</a></li> + <li>{{domxref("Animation")}}</li> +</ul> diff --git a/files/es/web/api/animation/tiempoactual/index.html b/files/es/web/api/animation/tiempoactual/index.html new file mode 100644 index 0000000000..acd56f9170 --- /dev/null +++ b/files/es/web/api/animation/tiempoactual/index.html @@ -0,0 +1,114 @@ +--- +title: Animation.currentTime +slug: Web/API/Animation/tiempoActual +tags: + - Animacion +translation_of: Web/API/Animation/currentTime +--- +<p>{{APIRef("Web Animations")}}{{SeeCompatTable}}</p> + +<p>La propiedad <code><strong>Animation</strong></code><strong><code>.currentTime</code></strong> de la <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API">Web Animations API</a> devuelve y establece el valor del tiempo de la animación en milisegundos, tanto si se está ejecutando como en pausa.</p> + +<p>Si la animación carece de un {{domxref("AnimationTimeline", "timeline")}}, está inactiva, o no ha sido reproducida todavía, el valor devuelto por <code>currentTime</code> es <code>null</code>.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var <em>currentTime</em> = <em>Animation</em>.currentTime; +<em>Animation</em>.currentTime =<em> newTime;</em></pre> + +<h3 id="Valor">Valor</h3> + +<p>Un número que representa el tiempo actual en milisegundos, o <code>null</code> para desactivar la animación.</p> + +<h2 id="Ejemplos">Ejemplos</h2> + +<p>En el juego <a href="http://codepen.io/rachelnabors/pen/PNYGZQ?editors=0010">Drink Me/Eat Me </a>, la altura de Alicia está animada, por lo que puede cambiar de pequeña a grande y de grande a pequeña. Al inicio del juego, su altura de fija estableciendo el <code>currentTime</code> (tiempoActual) a la mitad de la duración total del<a href="/en-US/docs/Web/API/Web_Animations_API/Animation_timing_options"><code>KeyframeEffect</code></a>:</p> + +<pre class="brush: js">aliceChange<strong>.</strong>currentTime = aliceChange.effect.timing.duration / 2;</pre> + +<p>Un modo más genérico para encontrar la marca del 50% en una animación sería :</p> + +<pre class="brush: js">animation.currentTime = + animation.effect.getComputedTiming().delay + + animation.effect.getComputedTiming().activeDuration / 2;</pre> + +<h2 id="Especificaciones">Especificaciones</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 Animations', '#dom-animation-currenttime', 'currentTime')}}</td> + <td>{{Spec2("Web Animations")}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_del_navegador">Compatibilidad del navegador</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>{{CompatChrome(39.0)}}</td> + <td>{{CompatGeckoDesktop(48)}}<sup>[1]</sup></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>Android Webview</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(39.0)}}</td> + <td>{{CompatGeckoMobile(48)}}<sup>[1]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(39.0)}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] La Web Animations API solo está habilitada por defecto en Firefox Developer Edition y Nightly builds. Puedes habilitarlo en versiones Beta estableciendo la preferencia <code>dom.animations-api.core.enabled</code> en <code>true</code>, y puede ser deshabilitado en cualquier versión de Firefox, estableciendo esta preferencia en <code>false</code>.</p> + +<h2 id="Ver_también" style="line-height: 30px; font-size: 2.14285714285714rem;">Ver también</h2> + +<ul> + <li>{{domxref("Animation")}} <span id="result_box" lang="es"><span>para otros métodos y propiedades que puede usar para controlar la animación de la página web</span></span>.</li> + <li>{{domxref("Animation.startTime")}} para programar el tiempo de inicio de una animación.</li> + <li><a href="/en-US/docs/Web/API/Web_Animations_API">Web Animations API</a></li> +</ul> diff --git a/files/es/web/api/animation/timeline/index.html b/files/es/web/api/animation/timeline/index.html new file mode 100644 index 0000000000..ba34392efd --- /dev/null +++ b/files/es/web/api/animation/timeline/index.html @@ -0,0 +1,111 @@ +--- +title: Animation.timeline +slug: Web/API/Animation/timeline +tags: + - API + - Animacion + - Animaciones Web + - Experimental + - Reference + - timeline +translation_of: Web/API/Animation/timeline +--- +<p>{{ SeeCompatTable() }}{{ APIRef("Web Animations") }}</p> + +<p>La propiedad <strong><code>Animation.timeline</code></strong> de la interfaz {{domxref ("Animation")}} devuelve o establece el {{domxref ("AnimationTimeline", "timeline")}} asociado a esta animación. Un 'timeline' es una fuente de valores de tiempo para propósitos de sincronización, y es un objeto basado en {{domxref ("AnimationTimeline")}}. Por defecto, la línea de tiempo de la animación y la línea de tiempo de {{domxref ("Document")}} son las mismas.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var <em>animationsTimeline</em> = <em>Animation</em>.timeline; + +<em>Animation</em>.timeline = <em>newTimeline</em>;</pre> + +<h3 id="Valor">Valor</h3> + +<p>Un {{domxref ("AnimationTimeline", "timeline object", "", 1)}} para usar como la fuente de sincronización para la animación, o <code>null</code> para usar el predeterminado, que es el 'timeline' del {{domxref ("Document")}}.</p> + +<h2 id="Ejemplos">Ejemplos</h2> + +<p>Aquí establecemos que la línea de tiempo <code>timeline</code> de la animación sea la misma que la del tiempo del documento (por cierto, esta es la <code>timeline</code> predeterminada para todas las animaciones):</p> + +<pre class="brush: js">animation.timeline = document.timeline; +</pre> + +<h2 id="Especificaciones">Especificaciones</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 Animations', '#dom-animation-timeline', 'Animation.timeline' )}}</td> + <td>{{Spec2('Web Animations')}}</td> + <td>Editor's draft.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_del_navegador">Compatibilidad del navegador</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>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop(48)}}<sup>[1]</sup></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>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>{{CompatGeckoMobile(48)}}<sup>[1]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] La Web Animations API solo está habilitada por defecto en Firefox Developer Edition y Nightly builds. Puedes habilitarlo en versiones Beta y de lanzamiento estableciendo la preferencia <code>dom.animations-api.core.enabled</code> en <code>true</code>, y puedes deshabilitarlo en cualquier versión de Firefox estableciendo esta propiedad en <code>false</code>.</p> + +<h2 id="Ver_también" style="line-height: 30px; font-size: 2.14285714285714rem;">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Web_Animations_API">Web Animations API</a></li> + <li>{{domxref("Animation")}}</li> + <li>{{domxref("AnimationTimeline")}} el objeto padre del que heredan todas las timeLine.</li> + <li>{{domxref("DocumentTimeline")}} el único objeto timeLine disponible en este momento.</li> + <li>{{domxref("Document.timeline")}} el timeLine predeterminado asignado a todas las animaciones.</li> +</ul> diff --git a/files/es/web/api/animationevent/animationname/index.html b/files/es/web/api/animationevent/animationname/index.html new file mode 100644 index 0000000000..ada4eb4a04 --- /dev/null +++ b/files/es/web/api/animationevent/animationname/index.html @@ -0,0 +1,101 @@ +--- +title: AnimationEvent.animationName +slug: Web/API/AnimationEvent/animationName +tags: + - API + - Animaciones Web + - AnimationEvent + - CSSOM + - Experimental + - Propiedad + - Referencia +translation_of: Web/API/AnimationEvent/animationName +--- +<p>{{SeeCompatTable}}{{ apiref("Web Animations API") }}</p> + +<p>La propiedad de solo-lectura <code><strong>AnimationEvent.animationName</strong></code> es un {{domxref("DOMString")}} conteniendo el valor de la propiedad de CSS {{cssxref("animation-name")}} asociada con la transición.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><em>name</em> = <em>AnimationEvent</em>.animationName</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estatus</th> + <th scope="col">Comentario</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('CSS3 Animations', '#AnimationEvent-animationName', 'AnimationEvent.animationName') }}</td> + <td>{{ Spec2('CSS3 Animations')}}</td> + <td>Definición Inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{ CompatGeckoDesktop("6.0") }}</td> + <td>10.0</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome para Android</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatChrome(43.0)}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="sect1"> </h2> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="https://developer.mozilla.org/en-US/docs/CSS/Using_CSS_animations">Usando animaciones CSS</a></li> + <li>Las propiedades CSS relacionadas con animacióny reglas: {{cssxref("animation")}}, {{cssxref("animation-delay")}}, {{cssxref("animation-direction")}}, {{cssxref("animation-duration")}}, {{cssxref("animation-fill-mode")}}, {{cssxref("animation-iteration-count")}}, {{cssxref("animation-name")}}, {{cssxref("animation-play-state")}}, {{cssxref("animation-timing-function")}}, {{cssxref("@keyframes")}}.</li> + <li>La interface {{domxref("AnimationEvent")}} a la cual pertenece.</li> +</ul> diff --git a/files/es/web/api/animationevent/index.html b/files/es/web/api/animationevent/index.html new file mode 100644 index 0000000000..c726ac42f9 --- /dev/null +++ b/files/es/web/api/animationevent/index.html @@ -0,0 +1,186 @@ +--- +title: AnimationEvent +slug: Web/API/AnimationEvent +tags: + - API + - Animaciones Web + - Experimental + - Interface + - Referencia +translation_of: Web/API/AnimationEvent +--- +<p>{{SeeCompatTable}}{{APIRef("Web Animations API")}}</p> + +<p>La interfaz <strong><code>AnimationEvent</code></strong> representa los eventos que proporciona información relacionada con las <a href="/en-US/docs/Web/Guide/CSS/Using_CSS_animations">animaciones</a>.</p> + +<p>{{InheritanceDiagram}}</p> + +<h2 id="Propiedades">Propiedades</h2> + +<p><em>También hereda las propiedades de su padre {{domxref("Event")}}</em>.</p> + +<dl> + <dt>{{domxref("AnimationEvent.animationName")}} {{readonlyInline}}</dt> + <dd>Es un {{domxref("DOMString")}} que contiene el valor de la propiedad CSS {{cssxref("animation-name")}} asociado con la transición.</dd> + <dt>{{domxref("AnimationEvent.elapsedTime")}} {{readonlyInline}}</dt> + <dd>Es un número flotante que da la cantidad de tiempo que ha estado corriendo la animación, en segundos, cuando este evento es disparado, excluyendo cualquier vez que la aimación fue pausada. Para un evento <code>"animationstart"</code>, <code>elapsedTime</code> es <code>0.0</code> a ménos que hubiera un valor negativo para {{cssxref("animation-delay")}}, en tal caso sería disparado el evento con <code>elapsedTime</code> conteniendo <code>(-1 * </code><em>retraso</em><code>)</code>.</dd> + <dt>{{domxref("AnimationEvent.pseudoElement")}} {{readonlyInline}}</dt> + <dd>Es un {{domxref("DOMString")}}, empezando con <code>'::'</code>, conteniendo el nombre del <a href="/en-US/docs/Web/CSS/Pseudo-elements" title="/en-US/docs/Web/CSS/Pseudo-elements">pseudo-element</a> en el cual corre la animación. Si la animación no corre sobre un pseudo-element sino en el elemento, un string vacío: ''. </dd> +</dl> + +<h2 id="Constructor">Constructor</h2> + +<dl> + <dt>{{domxref("AnimationEvent.AnimationEvent", "AnimationEvent()")}}</dt> + <dd>Crea un evento <code>AnimationEvent</code> con los parametros dados.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<p><em>También hereda los métodos de su padre {{domxref("Event")}}</em>.</p> + +<dl> + <dt>{{domxref("AnimationEvent.initAnimationEvent()")}} {{non-standard_inline}}{{deprecated_inline}}</dt> + <dd>Inicializa un evento <code>AnimationEvent</code> creado utilizando el método obsoleto {{domxref("Document.createEvent()", "Document.createEvent(\"AnimationEvent\")")}}</dd> +</dl> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estatus</th> + <th scope="col">Comentario</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('CSS3 Animations', '#AnimationEvent-interface', 'AnimationEvent') }}</td> + <td>{{ Spec2('CSS3 Animations') }}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_Navegadores">Compatibilidad de Navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td> + <p>1.0 {{ property_prefix("webkit") }}</p> + + <p>{{CompatChrome(43.0)}}</p> + </td> + <td>{{ CompatGeckoDesktop("6.0") }}</td> + <td>10.0</td> + <td>12 {{ property_prefix("o") }}<br> + 12.10<br> + 15.0 {{ property_prefix("webkit") }}</td> + <td>4.0 {{ property_prefix("webkit") }}</td> + </tr> + <tr> + <td>Constructor de<code> AnimationEvent()</code></td> + <td> + <p>{{CompatChrome(43.0)}}</p> + </td> + <td>{{ CompatGeckoDesktop("23.0") }}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>initAnimationEvent()</code> {{non-standard_inline}}{{deprecated_inline}}</td> + <td>1.0</td> + <td>{{ CompatGeckoDesktop("6.0") }}<br> + Removed in {{ CompatGeckoDesktop("23.0") }}</td> + <td>10.0</td> + <td>12</td> + <td>4.0</td> + </tr> + <tr> + <td><code>pseudoelement</code></td> + <td>{{CompatNo}}</td> + <td>{{ CompatGeckoDesktop("23.0") }}</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>Característica</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome para Android</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatVersionUnknown}}{{ property_prefix("webkit") }}</td> + <td>{{ CompatGeckoMobile("6.0") }}</td> + <td>10.0</td> + <td>12 {{ property_prefix("o") }}<br> + 12.10<br> + 15.0 {{ property_prefix("webkit") }}</td> + <td>{{CompatVersionUnknown}}{{ property_prefix("webkit") }}</td> + <td>{{CompatChrome(43.0)}}</td> + </tr> + <tr> + <td>Constructor de<code> AnimationEvent()</code></td> + <td>{{CompatNo}}</td> + <td>{{ CompatGeckoMobile("23.0") }}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(43.0)}}</td> + </tr> + <tr> + <td><code>initAnimationEvent()</code> {{non-standard_inline}}{{deprecated_inline}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{ CompatGeckoMobile("6.0") }}<br> + Removed in {{ CompatGeckoMobile("23.0") }}</td> + <td>10.0</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>pseudoelement</code></td> + <td>{{CompatNo}}</td> + <td>{{ CompatGeckoMobile("23.0") }}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/CSS/Using_CSS_animations">Usando animaciones CSS</a></li> + <li>Las propiedades CSS referentes a animación y reglas: {{cssxref("animation")}}, {{cssxref("animation-delay")}}, {{cssxref("animation-direction")}}, {{cssxref("animation-duration")}}, {{cssxref("animation-fill-mode")}}, {{cssxref("animation-iteration-count")}}, {{cssxref("animation-name")}}, {{cssxref("animation-play-state")}}, {{cssxref("animation-timing-function")}}, {{cssxref("@keyframes")}}.</li> +</ul> diff --git a/files/es/web/api/api_de_almacenamiento_web/index.html b/files/es/web/api/api_de_almacenamiento_web/index.html new file mode 100644 index 0000000000..26a858d254 --- /dev/null +++ b/files/es/web/api/api_de_almacenamiento_web/index.html @@ -0,0 +1,146 @@ +--- +title: API de almacenamiento web +slug: Web/API/API_de_almacenamiento_web +tags: + - API + - API de almacenamiento web + - Almacenamiento web + - Storage + - localStorage + - sessionStorage +translation_of: Web/API/Web_Storage_API +--- +<p>{{DefaultAPISidebar("Web Storage API")}}</p> + +<p>La <strong>API de almacenamiento web</strong> proporciona los mecanismos mediante los cuales el navegador puede almacenar información de tipo clave/valor, de una forma mucho más intuitiva que utilizando cookies.</p> + +<h2 id="Almacenamiento_web_conceptos_y_uso"><strong>Almacenamiento web, conceptos y uso</strong></h2> + +<p>Los dos mecanismos en el almacenamiento web son los siguientes:</p> + +<ul> + <li><strong><code>sessionStorage</code> </strong>mantiene un área de almacenamiento separada para cada origen que está disponible mientras dure la sesión de la página (mientras el navegador esté abierto, incluyendo recargas de página y restablecimientos).</li> + <li><strong><code>localStorage</code> </strong>hace lo mismo, pero persiste incluso cuando el navegador se cierre y se reabra.</li> +</ul> + +<p>Estos mecanismos están disponibles mediante las propiedades <a href="https://developer.mozilla.org/es/docs/Web/API/Window/sessionStorage" title="La propiedad sessionStorage permite acceder a un objeto Storage asociado a la sesión actual. La propiedad sessionStorage es similar a localStorage, la única diferencia es que la información almacenada en localStorage no posee tiempo de expiración, por el contrario la información almacenada en sessionStorage es eliminada al finalizar la sesion de la página. La sesión de la página perdura mientras el navegador se encuentra abierto, y se mantiene por sobre las recargas y reaperturas de la página. Abrir una página en una nueva pestaña o ventana iniciará una nueva sesión, lo que difiere en la forma en que trabajan las cookies de sesión."><code>Window.sessionStorage</code></a> y <a href="https://developer.mozilla.org/es/docs/Web/API/Window/localStorage" title="La propiedad localStorage te permite acceder al objeto local Storage. localStorage es similar a sessionStorage. La única diferencia es que, mientras los datos almacenados en localStorage no tienen fecha de expiración, los datos almacenados en sessionStorage son eliminados cuando finaliza la sesion de navegación - lo cual ocurre cuando se cierra el navegador."><code>Window.localStorage</code></a> (dicho con más precisión, en navegadores con soporte, el objeto <code>Window</code> implementa los objetos <code>WindowLocalStorage</code> y <code>WindowSessionStorage</code>, en los cuales se basan las propiedades <code>localStorage</code> y <code>sessionStorage</code>). Al invocar uno de éstos, se creará una instancia del objeto <a href="https://developer.mozilla.org/es/docs/Web/API/Storage" title="La interfaz Storage de la API de almacenamiento web provee acceso al almacenamiento de la sesión o al almacenamiento local para un dominio en particular, permitiéndote por ejemplo añadir, modificar o eliminar elementos de dato almacenados."><code>Storage</code></a>, a través del cual los datos pueden ser creados, recuperados y eliminados. sessionStorage y localStorage utilizan un objeto de almacenamiento diferente según su origen — funcionan y son controlados por separado.</p> + +<div class="note"> +<p><strong>Nota</strong>: Acceder al Almacenamiento web desde IFrames de terceros está prohibido si el usuario tiene <a href="https://support.mozilla.org/en-US/kb/disable-third-party-cookies">deshabilitadas las cookies de terceros</a> (Firefox implementa este comportamiento a partir de la <a href="/en-US/docs/Mozilla/Firefox/Releases/43">versión 43</a>).</p> +</div> + +<div class="note"> +<p><strong>Nota:</strong> El almacenamiento web no es lo mismo que <a href="/en-US/docs/Storage" title="Storage">mozStorage</a> (interfaces Mozilla's XPCOM para SQLite) o la <a href="/en-US/docs/Session_store_API" title="Session_store_API">Session store API</a> (una utilidad de almacenamiento <a href="/en-US/docs/XPCOM" title="XPCOM">XPCOM</a> usada por extensiones).</p> +</div> + +<h2 id="Interfaces_de_almacenamiento_web">Interfaces de almacenamiento web</h2> + +<dl> + <dt>{{domxref("Storage")}}</dt> + <dd>Permite crear, recuperar y eliminar datos de un dominio y tipo de almacenamiento (sesión o local) específicos.</dd> + <dt>{{domxref("Window")}}</dt> + <dd>La API de almacenamiento web extiende el objeto {{domxref("Window")}} con dos nuevas propiedades — {{domxref("Window.sessionStorage")}} y {{domxref("Window.localStorage")}} — que proveen acceso a la sesión actual del dominio y a objetos {{domxref("Storage")}} locales, respectivamente. También ofrece un manejador de evento {{domxref("Window.onstorage")}} que se dispara cuando un área de la memoria cambia (por ejemplo, cuando se almacena un nuevo elemento).</dd> + <dt>{{domxref("StorageEvent")}}</dt> + <dd>El evento <code>storage</code> se dispara en el objeto <code>Window</code> de un documento cuando un área de la memoria cambia.</dd> +</dl> + +<h2 id="Ejemplos">Ejemplos</h2> + +<p>Para ilustrar algunos usos típicos del almacenamiento web, hemos creado un ejemplo simple, llamado <a href="https://github.com/mdn/web-storage-demo">Demo de almacenamiento web</a>. La <a href="http://mdn.github.io/web-storage-demo/">página de inicio</a> proporciona controles que puedes utilizar para personalizar el color, la tipografía y la imagen decorativa. Cuando seleccionas una opción diferente, la página se actualiza instantáneamente; además, tus opciones se almacenan en <code>localStorage</code>, de forma que si abandonas la página y la vuelves a cargar, tus opciones son recordadas.</p> + +<p>También creamos una<a href="http://mdn.github.io/web-storage-demo/event.html"> página de salida del evento</a> — si cargas esta página en otra pestaña y luego haces cambios a tus opciones en la página de inicio, verás que se muestra la información almacenada actualizada puesto que se dispara un evento {{event("StorageEvent")}}.</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('Web Storage')}}</td> + <td>{{Spec2('Web Storage')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegadores"><strong>Compatibilidad </strong>de navegadores</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>localStorage</td> + <td>4</td> + <td>3.5</td> + <td>8</td> + <td>10.50</td> + <td>4</td> + </tr> + <tr> + <td>sessionStorage</td> + <td>5</td> + <td>2</td> + <td>8</td> + <td>10.50</td> + <td>4</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Caracteristica</th> + <th>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>2.1</td> + <td>{{ CompatUnknown }}</td> + <td>8</td> + <td>11</td> + <td>iOS 3.2</td> + </tr> + </tbody> +</table> +</div> + +<p>Todos los navegadores tienen distintos niveles de capacidad tanto para localStorage como para sessionStorage. Aquí está una <a class="external external-icon" href="http://dev-test.nemikor.com/web-storage/support-test/" rel="noopener" title="http://dev-test.nemikor.com/web-storage/support-test/">análisis detallado de todas las capacidades de almacenamiento de diferentes navegadores</a>.</p> + +<div class="note"> +<p><strong>Nota: </strong>Desde iOS 5.1, Safari Mobile almacena los datos de localStorage en la carpeta de caché, la cual está sujeta a limpiezas ocasionales, a petición del sistema operativo, típicamente cuando el espacio es reducido.</p> +</div> + +<h2 id="Navegación_privada_Modo_incógnito">Navegación privada / Modo incógnito</h2> + +<p>La mayoría de los navegadores de hoy en día soportan una opción de privacidad llamada 'Modo incógnito', 'Navegación privada', o algo similar, que básicamente se asegura de que la sesión de navegación no deje rastros después de que el navegador se cierra. Esto es fundamentalmente incompatible con el almacenamiento web por obvias razones. Por ello, muchos navegadores están experimentando con diferentes escenarios para lidiar con esta incompatibilidad.</p> + +<p>La mayoría de los navegadores han optado por una estrategia donde las API de almacenamiento siguen disponibles y aparentemente completamente funcionales, con la única gran diferencia de que todos los datos almacenados son eliminados después de cerrar el navegador. Para estos navegadores aún hay diferentes interpretaciones sobre qué debería hacerse con los datos almacenados existentes (de una sesión de navegación normal). ¿Deberían de estar disponibles para lectura cuando esté en modo privado? Entonces, hay algunos navegadores, sobre todo Safari, que han optado por una solución donde el almacenamiento está disponible, pero vacío, y tiene un cupo de 0 bytes asignado, por lo que se vuelve imposible usar esta memoria para escribir datos.</p> + +<p>Los desarrolladores deberían de estar conscientes de estas diferentes implementaciones y tenerlas en cuenta a la hora de desarrollar aplicaciones web que depende de la API de almacenamiento web. Para más información, échale un vistazo a<a href="https://blog.whatwg.org/tag/localstorage"> esta entrada de blog WHATWG</a> que trata específicamente con este tema.</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API">Usando la API de almacenamiento web</a></li> +</ul> diff --git a/files/es/web/api/api_de_almacenamiento_web/usando_la_api_de_almacenamiento_web/index.html b/files/es/web/api/api_de_almacenamiento_web/usando_la_api_de_almacenamiento_web/index.html new file mode 100644 index 0000000000..086af18610 --- /dev/null +++ b/files/es/web/api/api_de_almacenamiento_web/usando_la_api_de_almacenamiento_web/index.html @@ -0,0 +1,272 @@ +--- +title: Usando la API de almacenamiento web +slug: Web/API/API_de_almacenamiento_web/Usando_la_API_de_almacenamiento_web +tags: + - API + - API de almacenamiento web + - Guía + - localStorage + - sessionStorage +translation_of: Web/API/Web_Storage_API/Using_the_Web_Storage_API +--- +<div>{{DefaultAPISidebar("Web Storage API")}}</div> + +<div class="summary"> +<p>La API de almacenamiento web proporciona los mecanismos mediante los cuales el navegador puede almacenar información de tipo clave/valor, de una forma mucho más intuitiva que utilizando cookies.</p> + +<p>Este artículo proporciona una guía general de cómo usar esta tecnología.</p> +</div> + +<h2 id="Conceptos_básicos">Conceptos básicos</h2> + +<p>Los objetos de almacenamiento son simples almacenes de clave/valor, similares a objetos, pero que permanecen intactos cuando la página se recarga. Las claves y los valores siempre son cadenas de texto (fíjate que las claves con enteros se convierten automáticamente a cadenas, tal y como lo hacen los objetos). Puedes acceder a estos valores como un objeto, o con los métodos {{domxref("Storage.getItem()")}} y {{domxref("Storage.setItem()")}}. Estas tres líneas modifican el valor de colorSetting de la misma manera:</p> + +<pre class="brush: js notranslate" style="white-space: pre;">localStorage.colorSetting = '#a4509b'; +localStorage['colorSetting'] = '#a4509b'; +localStorage.setItem('colorSetting', '#a4509b');</pre> + +<div class="note"> +<p><strong>Nota</strong>: Se recomiendo usar la API de almacenamiento web (<code>setItem</code>, <code>getItem</code>, <code>removeItem</code>, <code>key</code>, <code>length</code>) para prevenir las dificultades asociadas al uso de simples objetos como almacenes de valores llave/valor.</p> +</div> + +<p>Los dos mecanismos en el almacenamiento web son los siguientes:</p> + +<ul> + <li><strong><code>sessionStorage</code> </strong>mantiene un área de almacenamiento separada para cada origen que está disponible mientras dure la sesión de la página (mientras el navegador esté abierto, incluyendo recargas de página y restablecimientos).</li> + <li><strong><code>localStorage</code> </strong>hace lo mismo, pero persiste incluso cuando el navegador se cierre y se reabra.</li> +</ul> + +<p>Estos mecanismos están disponibles mediante las propiedades <a href="https://developer.mozilla.org/es/docs/Web/API/Window/sessionStorage" title="La propiedad sessionStorage permite acceder a un objeto Storage asociado a la sesión actual. La propiedad sessionStorage es similar a localStorage, la única diferencia es que la información almacenada en localStorage no posee tiempo de expiración, por el contrario la información almacenada en sessionStorage es eliminada al finalizar la sesion de la página. La sesión de la página perdura mientras el navegador se encuentra abierto, y se mantiene por sobre las recargas y reaperturas de la página. Abrir una página en una nueva pestaña o ventana iniciará una nueva sesión, lo que difiere en la forma en que trabajan las cookies de sesión."><code>Window.sessionStorage</code></a> y <a href="https://developer.mozilla.org/es/docs/Web/API/Window/localStorage" title="La propiedad localStorage te permite acceder al objeto local Storage. localStorage es similar a sessionStorage. La única diferencia es que, mientras los datos almacenados en localStorage no tienen fecha de expiración, los datos almacenados en sessionStorage son eliminados cuando finaliza la sesion de navegación - lo cual ocurre cuando se cierra el navegador."><code>Window.localStorage</code></a> (dicho con más precisión, en navegadores con soporte, el objeto <code>Window</code> implementa los objetos <code>WindowLocalStorage</code> y <code>WindowSessionStorage</code>, en los cuales se basan las propiedades <code>localStorage</code> y <code>sessionStorage</code>). Al invocar uno de éstos, se creará una instancia del objeto <a href="https://developer.mozilla.org/es/docs/Web/API/Storage" title="La interfaz Storage de la API de almacenamiento web provee acceso al almacenamiento de la sesión o al almacenamiento local para un dominio en particular, permitiéndote por ejemplo añadir, modificar o eliminar elementos de dato almacenados."><code>Storage</code></a>, a través del cual los datos pueden ser creados, recuperados y eliminados. sessionStorage y localStorage utilizan un objeto de almacenamiento diferente según su origen — funcionan y son controlados por separado.</p> + +<p>Así que, por ejemplo, si en un inicio se llama a <code>localStorage</code> en un documento, esto devolverá un objeto {{domxref("Storage")}}; llamar a <code>sessionStorage</code> en un documento devolverá un objeto {{domxref("Storage")}} diferente. Ambos objetos se pueden manipular de la misma forma, pero separados.</p> + +<h2 id="Detectar_la_característica_localStorage">Detectar la característica localStorage</h2> + +<p>Para poder usar localStorage, debemos de verificar que tiene soporte y que está disponible en la sesión del buscador actual.</p> + +<h3 id="Probar_la_disponibilidad">Probar la disponibilidad</h3> + +<div class="blockIndicator note"> +<p>Nota: esta API está disponible en las versiones actuales de todos los navegadores principales. La prueba de disponibilidad es necesaria sólo si debes soportar navegadores muy antiguos, como Internet Explorer 6 o 7, o en las circunstancias limitadas descritas más abajo.</p> +</div> + +<p>Los buscadores que soportan localStorage tienen una propiedad en el objeto window que se llama localStorage. Sin embargo, por varias razones, el sólo asegurarse de que la propiedad existe puede arrojar excepciones. El que localStorage exista no es garantía suficiente de que en verdad esté disponible, puesto que varios buscadores ofrecen configuraciones que lo inhabilitan. Así que un buscador puede <em>soportar </em>localStorage, pero puede no hacerlo <em>disponible </em>para los scripts en la página. Un ejemplo de esto es Safari, que en el modo de búsqueda privada ofrece un objeto localStorage vacío con un cupo de 0, por lo que es inutilizable. Sin embargo, es posible que aún así obtengamos un QuotaExceededError legítimo, lo que significa que ya usamos todo el espacio de almacenamiento disponible, aunque el almacenamiento esté, de hecho, <em>disponible</em>. Nuestra detección de la característica debe de tomar en cuenta estos escenarios.</p> + +<p>Esta función detecta si localStorage tiene soporte y está disponible:</p> + +<pre class="brush: js notranslate">function storageAvailable(type) { + try { + var storage = window[type], + x = '__storage_test__'; + storage.setItem(x, x); + storage.removeItem(x); + return true; + } + catch(e) { + return e instanceof DOMException && ( + // everything except Firefox + e.code === 22 || + // Firefox + e.code === 1014 || + // test name field too, because code might not be present + // everything except Firefox + e.name === 'QuotaExceededError' || + // Firefox + e.name === 'NS_ERROR_DOM_QUOTA_REACHED') && + // acknowledge QuotaExceededError only if there's something already stored + storage.length !== 0; + } +}</pre> + +<p>Y aquí se muestra cómo usarla:</p> + +<pre class="brush: js notranslate">if (storageAvailable('localStorage')) { + // Yippee! We can use localStorage awesomeness +} +else { + // Too bad, no localStorage for us +}</pre> + +<p>También puedes probar sessionStorage invocando <code>storageAvailable('sessionStorage')</code>.</p> + +<p>Aquí puedes ver una <a href="https://gist.github.com/paulirish/5558557">breve historia de la detección de la característica localStorage</a>.</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>Para ilustrar un uso típico de almacenamiento web, creamos un ejemplo simple que llamamos <strong>Demo de almacenamiento web</strong>. La <a href="https://mdn.github.io/dom-examples/web-storage/">página de inicio</a> proporciona unos controles que se pueden usar para personalizar el color, la tipografía y la imagen decorativa:</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/9685/landing.png" style="display: block; height: 482px; margin: 0px auto; width: 700px;">Cuando seleccionas una opción diferente, la página se actualiza instantáneamente; además, tus opciones se almacenan en <code>localStorage</code>, de forma que si abandonas la página y la vuelves a cargar, tus opciones son recordadas.</p> + +<p>También creamos una <a href="https://mdn.github.io/dom-examples/web-storage/event.html">página de salida del evento</a> — si cargas esta página en otra pestaña y luego haces cambios a tus opciones en la página de inicio, verás que se muestra la información almacenada actualizada puesto que se dispara un {{domxref("StorageEvent")}}.</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/9687/event-output.png" style="display: block; height: 482px; margin: 0px auto; width: 700px;"></p> + +<div class="note"> +<p><strong>Nota</strong>: Puedes ver las páginas de ejemplo usando los links de arriba y también puedes <a href="https://github.com/mdn/dom-examples/tree/master/web-storage">ver el código fuente.</a></p> +</div> + +<h3 id="Probar_si_la_memoria_tiene_valores">Probar si la memoria tiene valores</h3> + +<p>En el inicio de <a href="https://github.com/mdn/dom-examples/blob/master/web-storage/main.js">main.js</a>, probamos si el objeto ya tiene valores (es decir, si la página ya fue visitada):</p> + +<pre class="brush: js notranslate">if(!localStorage.getItem('bgcolor')) { + populateStorage(); +} else { + setStyles(); +}</pre> + +<p>El método {{domxref("Storage.getItem()")}} se usa para obtener un dato de la memoria; en este caso, estamos probando si el dato <code>bgcolor</code> existe; si no, corremos <code>populateStorage()</code> para añadir los valores personalizados actuales a la memoria. Si ya hay valores guardados, corremos <code>setStyles()</code> para actualizar el estilo de la página con los valores almacenados.</p> + +<p><strong>Nota</strong>: También puedes usar {{domxref("Storage.length")}} para probar si el objeto de almacenamiento está vació o no.</p> + +<h3 id="Obtener_valores_de_la_memoria">Obtener valores de la memoria</h3> + +<p>Como dijimos arriba, los valores se pueden recuperar de la memoria usando {{domxref("Storage.getItem()")}}. Este método usa la llave del dato como argumento y devuelve el valor. Por ejemplo:</p> + +<pre class="brush: js notranslate">function setStyles() { + var currentColor = localStorage.getItem('bgcolor'); + var currentFont = localStorage.getItem('font'); + var currentImage = localStorage.getItem('image'); + + document.getElementById('bgcolor').value = currentColor; + document.getElementById('font').value = currentFont; + document.getElementById('image').value = currentImage; + + htmlElem.style.backgroundColor = '#' + currentColor; + pElem.style.fontFamily = currentFont; + imgElem.setAttribute('src', currentImage); +}</pre> + +<p>Aquí, en las primeras tres líneas tomamos los valores del almacenamiento local. Después, fijamos los valores mostrados en los elementos del formulario a esos valores, de forma que se mantengan sincronizados cuando recargues la página. Finalmente, actualizamos los estilos y la imagen decorativa en la página para que tus opciones personalizadas vuelvan a aparecer al recargar.</p> + +<h3 id="Guardar_valores_en_la_memoria">Guardar valores en la memoria</h3> + +<p>{{domxref("Storage.setItem()")}} se usa tanto para crear nuevos datos como para actualizar valores existentes (si el dato ya existía). Este método recibe dos argumentos: la llave del dato que se va a crear/modificar y el valor que se va a guardar.</p> + +<pre class="brush: js notranslate">function populateStorage() { + localStorage.setItem('bgcolor', document.getElementById('bgcolor').value); + localStorage.setItem('font', document.getElementById('font').value); + localStorage.setItem('image', document.getElementById('image').value); + + setStyles(); +}</pre> + +<p>La función <code>populateStorage()</code> define tres elementos en el almacenamiento local — el color de fondo, la tipografía y la ruta de almacenamiento de la imagen. Luego corre la función <code>setStyles()</code> para actualizar el estilo de la página, etc.</p> + +<p>También incluimos un manejador <code>onchange</code> para cada elemento del formulario, de manera que los datos y los estilos son actualizados cada vez que un valor del formulario cambia:</p> + +<pre class="brush: js notranslate">bgcolorForm.onchange = populateStorage; +fontForm.onchange = populateStorage; +imageForm.onchange = populateStorage;</pre> + +<h3 id="Responder_a_cambios_en_la_memoria_con_el_evento_StorageEvent">Responder a cambios en la memoria con el evento StorageEvent</h3> + +<p>El evento {{domxref("StorageEvent")}} se dispara siempre que se hace un cambio al objeto {{domxref("Storage")}} (nota que este evento no se dispara para cambios en sessionStorage). Este evento no va a trabajar en la misma página en la que se están haciendo los cambios, sino que es una manera para que las otras páginas del dominio que usan la memoria sincronicen los cambios que se están haciendo. Las páginas en otros dominios no pueden acceder a los mismos objetos de almacenamiento.</p> + +<p>En la página de eventos (ver <a href="https://github.com/mdn/dom-examples/blob/master/web-storage/event.js">events.js</a>) el único JavaScript es el siguiente:</p> + +<pre class="brush: js notranslate">window.addEventListener('storage', function(e) { + document.querySelector('.my-key').textContent = e.key; + document.querySelector('.my-old').textContent = e.oldValue; + document.querySelector('.my-new').textContent = e.newValue; + document.querySelector('.my-url').textContent = e.url; + document.querySelector('.my-storage').textContent = JSON.stringify(e.storageArea); +});</pre> + +<p>Aquí añadimos un detector de evento al objeto <code>window</code> que se dispara cuando el objeto {{domxref("Storage")}} asociado con el origen actual cambia. Como puedes ver arriba, el objeto asociado a este evento tiene varias propiedades que contienen información útil — la llave del dato que cambió, el valor anterior al cambio, el nuevo valor tras el cambio, la URL del documento que cambió la memoria y el objeto de almacenamiento mismo (que volvimos una cadena para que pudieras ver su contenido).</p> + +<h3 id="Borrar_registros">Borrar registros</h3> + +<p>El almacenamiento web también provee un par de métodos simples para remover datos. No los usamos en nuestro demo, pero se pueden añadir de manera muy simple a tu proyecto:</p> + +<ul> + <li>{{domxref("Storage.removeItem()")}} recibe un solo argumento — la llave del dato que quieres eliminar — y lo remueve del objeto de almacenamiento de ese dominio.</li> + <li>{{domxref("Storage.clear()")}} no recibe argumentos; vacía todo el objeto de almacenamiento de ese dominio.</li> +</ul> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', 'webstorage.html#webstorage')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>localStorage</td> + <td>4</td> + <td>3.5</td> + <td>8</td> + <td>10.50</td> + <td>4</td> + </tr> + <tr> + <td>sessionStorage</td> + <td>5</td> + <td>2</td> + <td>8</td> + <td>10.50</td> + <td>4</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>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>2.1</td> + <td>{{ CompatUnknown }}</td> + <td>8</td> + <td>11</td> + <td>iOS 3.2</td> + </tr> + </tbody> +</table> +</div> + +<p>Todos los navegadores tienen distintos niveles de capacidad tanto para localStorage como para sessionStorage. Aquí está una <a class="external external-icon" href="http://dev-test.nemikor.com/web-storage/support-test/" rel="noopener" title="http://dev-test.nemikor.com/web-storage/support-test/">análisis detallado de todas las capacidades de almacenamiento de diferentes navegadores</a>.</p> + +<div class="note"> +<p><strong>Nota: </strong>Desde iOS 5.1, Safari Mobile almacena los datos de localStorage en la carpeta de caché, la cual está sujeta a limpiezas ocasionales, a petición del sistema operativo, típicamente cuando el espacio es reducido.</p> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Web_Storage_API">Página de inicio de la API de almacenamiento web</a></li> +</ul> diff --git a/files/es/web/api/api_del_portapapeles/index.html b/files/es/web/api/api_del_portapapeles/index.html new file mode 100644 index 0000000000..53e43f6bd5 --- /dev/null +++ b/files/es/web/api/api_del_portapapeles/index.html @@ -0,0 +1,76 @@ +--- +title: API del portapapeles +slug: Web/API/API_del_portapapeles +translation_of: Web/API/Clipboard_API +--- +<div>{{DefaultAPISidebar("Clipboard API")}}</div> + +<p>La <strong>API del portapapeles </strong>permite acceder los comandos del portapapeles (cortar, copiar y pegar), así como leer y escribir de manera asíncrona el portapapeles del sistema. Acceder al contenido del portapapeles está sujeta a la <a href="/es/docs/Web/API/Permissions_API">API de permisos</a>: El permiso <code>clipboard-write</code> es concedido automáticamente a las páginas cuando están en la pestaña activa. El permiso <code>clipboard-read</code> debe ser solicitado, lo que se puede hacer intentando leer directamente el portapapeles.</p> + +<p>Esta API está diseñada para reemplazar el acceso al portapapeles usando {{domxref("document.execCommand()")}}.</p> + +<h2 id="Accediendo_al_portapapeles">Accediendo al portapapeles</h2> + +<p>En vez de instanciar un objeto <code>Clipboard</code>, se puede acceder al portapapeles del sistema a través de la variable global {{domxref("Navigator.clipboard")}}:</p> + +<pre class="brush: js notranslate">navigator.clipboard.readText().then( + clipText => document.querySelector(".editor").innerText += clipText);</pre> + +<p>Esta pieza de código lee el texto que hay en el portapapeles y lo añade al primer elemento que tenga la clase <code>editor</code>. Desde que {{domxref("Clipboard.readText", "readText()")}} (y también {{domxref("Clipboard.read", "read()")}}, de hecho) devuelve una cadena de texto vacía si el contenido del portapapeles no es texto, este código es seguro.</p> + +<h2 id="Interfaces">Interfaces</h2> + +<dl> + <dt>{{domxref("Clipboard")}} {{securecontext_inline}}</dt> + <dd>Proporciona una interfaz para leer y escribir texto y datos. La especificación se refiere a esto como 'Async Clipboard API.'</dd> + <dt>{{domxref("ClipboardEvent")}} {{securecontext_inline}}</dt> + <dd>Representa la información del evento que se ha disparado. Los eventos que se pueden disparar son: {{domxref("Element/cut_event", "cortar")}}, {{domxref("Element/copy_event", "copiar")}}, y {{domxref("Element/paste_event", "pegar")}}. La especificación se refiere a esto como 'Clipboard Event API'.</dd> + <dt>{{domxref("ClipboardItem")}} {{securecontext_inline}}</dt> + <dd>Representa uno de los objetos del portapapeles, usado en la lectura y escritura de datos.</dd> +</dl> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Observaciones</th> + </tr> + <tr> + <td>{{SpecName('Clipboard API')}}</td> + <td>{{Spec2('Clipboard API')}}</td> + <td>Definición primitiva.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<h3 id="Clipboard">Clipboard</h3> + +<div> + + +<p>{{Compat("api.Clipboard")}}</p> + +<h3 id="ClipboardEvent">ClipboardEvent</h3> + +<div class="hidden">The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</div> + +<p>{{Compat("api.ClipboardEvent")}}</p> + +<h3 id="ClipboardItem">ClipboardItem</h3> + + + +<p>{{Compat("api.ClipboardItem")}}</p> + +<h2 id="Véase_también">Véase también</h2> + +<ul> + <li><a href="/es/docs/Web/API/Permissions">Permissions API</a></li> + <li><a href="/es/docs/Web/API/Permissions_API/Using_the_Permissions_API">Using the Permissions API</a></li> +</ul> +</div> diff --git a/files/es/web/api/attr/index.html b/files/es/web/api/attr/index.html new file mode 100644 index 0000000000..2e73f60c55 --- /dev/null +++ b/files/es/web/api/attr/index.html @@ -0,0 +1,194 @@ +--- +title: Attr +slug: Web/API/Attr +translation_of: Web/API/Attr +--- +<div>{{APIRef("DOM")}}</div> + +<p>Este tipo representa un atributo de un elemento DOM como un objeto. En muchos métodos DOM, probablemente vas a obtener el atributo como una cadena (e.g., {{domxref("Element.getAttribute()")}}, pero algunas funciones (e.g., {{domxref("Element.getAttributeNode()")}}) or means of iterating give <code>Attr</code> types.</p> + +<p>{{InheritanceDiagram}}</p> + +<div class="warning"><strong>Advertencia:En el DOM Core 1, 2 y 3</strong>, <code>Attr</code> se hereda del {{domxref("Node")}}. Este ya no es el caso en <a class="external" href="https://www.w3.org/TR/dom/">DOM4</a>.Para llevar la implementación de Attr a la especifiación, se esta trabajando para cambiarlo y dejar de heredar de{{domxref("Node")}}. No debe de utilizar ninguna propiedad o método de nodo en los objetos <code>Attr</code>. <span class="tlid-translation translation" lang="es"><span title="">A partir de Gecko 7.0 (Firefox 7.0 / Thunderbird 7.0 / SeaMonkey 2.4), los que se eliminarán enviarán mensajes de advertencia a la consola</span></span>. <span class="tlid-translation translation" lang="es"><span title="">Debe revisar su código en consecuencia.</span> <span title="">Consulte Propiedades y métodos en desuso para obtener una lista completa.</span></span></div> + +<h2 id="Propiedades">Propiedades</h2> + +<dl> + <dt>{{domxref("Attr.name", "name")}} {{readOnlyInline}}</dt> + <dd>El nombre del atributo.</dd> + <dt>{{domxref("Attr.namespaceURI", "namespaceURI")}} {{readOnlyInline}}</dt> + <dd>Un {{domxref("DOMString")}} representing the namespace URI of the attribute, or <code>null</code> if there is no namespace.</dd> + <dt>{{domxref("Attr.localName", "localName")}} {{readOnlyInline}}</dt> + <dd>A {{domxref("DOMString")}} representing the local part of the qualified name of the attribute.</dd> + <dt>{{domxref("Attr.prefix", "prefix")}} {{readOnlyInline}}</dt> + <dd>A {{domxref("DOMString")}} representing the namespace prefix of the attribute, or <code>null</code> if no prefix is specified.</dd> + <dt>{{domxref("Attr.specified", "specified")}} {{readOnlyInline}}</dt> + <dd>This property always returns <code>true</code>. Originally, it returned <code>true </code>if the attribute was explicitly specified in the source code or by a script, and <code>false</code> if its value came from the default one defined in the document's <acronym title="Document Type Definition">DTD</acronym>.</dd> + <dt>{{domxref("Attr.value", "value")}}</dt> + <dd>El valor del atributo.</dd> +</dl> + +<div class="note"> +<p><strong>Note:</strong> DOM Level 3 defined <code>namespaceURI</code>, <code>localName</code> and <code>prefix</code> on the {{domxref("Node")}} interface. In DOM4 they were moved to <code>Attr</code>.</p> + +<p>This change is implemented in Chrome since version 46.0 and Firefox since version 48.0.</p> +</div> + +<h2 id="Propiedades_y_métodos_obsoletos">Propiedades y métodos obsoletos</h2> + +<p>Las siguientes propiedades son obsoletos. Where available, the appropriate replacement is provided.</p> + +<dl> + <dt><code>attributes</code></dt> + <dd>Este propiedad ahora siempre devuelve <code>NULL</code>.</dd> + <dt><code>childNodes</code></dt> + <dd>Este propiedad ahora siempre devuelve <code>NULL</code>.</dd> + <dt><code>firstChild</code></dt> + <dd>Este propiedad ahora siempre devuelve <code>NULL</code>.</dd> + <dt><code>isId</code> {{readOnlyInline}}</dt> + <dd>Indicates whether the attribute is an "ID attribute". An "ID attribute" being an attribute which value is expected to be unique across a DOM Document. In HTML DOM, "id" is the only ID attribute, but XML documents could define others. Whether or not an attribute is unique is often determined by a {{Glossary("DTD")}} or other schema description.</dd> + <dt><code>lastChild</code></dt> + <dd>Este propiedad ahora siempre devuelve <code>NULL</code>.</dd> + <dt><code>nextSibling</code></dt> + <dd>Este propiedad ahora siempre devuelve <code>NULL</code>.</dd> + <dt><code>nodeName</code></dt> + <dd>Utilizar {{domxref("Attr.name")}} en su lugar.</dd> + <dt><code>nodeType</code></dt> + <dd>Esta propiedad ahora siempre devuelve 2 (<code>ATTRIBUTE_NODE</code>).</dd> + <dt><code>nodeValue</code></dt> + <dd>Utilizar {{domxref("Attr.value")}} en su lugar.</dd> + <dt><code>ownerDocument</code></dt> + <dd>Seguramente nunca usaste esta propiedad asi que no deberias preocuparte si esque ya no está disponible.</dd> + <dt><code>ownerElement</code> {{deprecated_inline("7.0")}} {{obsolete_inline("29.0")}} {{readOnlyInline}}</dt> + <dd>Since you get an <code>Attr</code> object from an {{domxref("Element")}}, you should already know the associated element.</dd> + <dd>Contrary to above claim, {{domxref("Document.evaluate")}} can return <code>Attr</code> objects from an XPath, in which case you would not easily know the owner.</dd> + <dt><code>parentNode</code></dt> + <dd>Estra propiedad ahora siempre devuelve <code>NULL</code>.</dd> + <dt><code>previousSibling</code></dt> + <dd>Estra propiedad ahora siempre devuelve <code>NULL</code>.</dd> + <dt><code>schemaTypeInfo</code> {{obsolete_inline}} {{readOnlyInline}}</dt> + <dd>The type information associated with this attribute. While the type information contained in this attribute is guaranteed to be correct after loading the document or invoking {{domxref("Document.normalizeDocument")}}, this property may not be reliable if the node was moved.</dd> + <dt><code>specified</code></dt> + <dd>Estra propiedad ahora siempre devuelve <code>true</code>.</dd> + <dt><code>textContent</code></dt> + <dd>Utilizar {{domxref("Attr.value")}} en su lugar.</dd> +</dl> + +<p>Los siguientes metodos ahora son obsoletos.</p> + +<dl> + <dt><code>appendChild()</code></dt> + <dd>Modify the value of {{domxref("Attr.value")}} instead.</dd> + <dt><code>cloneNode()</code></dt> + <dd>Seguramente nunca usaste esta propiedad asi que no deberias preocuparte si esque ya no está disponible.</dd> + <dt><code>createAttribute()</code></dt> + <dd>Use {{domxref("Element.setAttribute()")}} instead.</dd> + <dt><code>createAttributeNS()</code></dt> + <dd>Use {{domxref("Element.setAttributeNS()")}} instead.</dd> + <dt><code>getAttributeNode()</code></dt> + <dd>Use {{domxref("Element.getAttribute()")}} instead.</dd> + <dt><code>getAttributeNodeNS()</code></dt> + <dd>Use {{domxref("Element.getAttributeNS()")}} instead.</dd> + <dt><code>hasAttributes() </code>{{obsolete_inline("21.0")}}</dt> + <dd>Estra propiedad ahora retorna false.</dd> + <dt><code>hasChildNodes()</code></dt> + <dd>Estra propiedad ahora devuelve <code>false</code>.</dd> + <dt><code>insertBefore()</code></dt> + <dd>Modify the value of {{domxref("Attr.value")}} instead.</dd> + <dt><code>isSupported()</code></dt> + <dd>Seguramente nunca usaste esta propiedad asi que no deberias preocuparte si esque ya no está disponible.</dd> + <dt><code>isEqualNode()</code></dt> + <dd>Seguramente nunca usaste esta propiedad asi que no deberias preocuparte si esque ya no está disponible.</dd> + <dt><code>normalize()</code></dt> + <dd>Seguramente nunca usaste esta propiedad asi que no deberias preocuparte si esque ya no está disponible.</dd> + <dt><code>removeAttributeNode()</code></dt> + <dd>Use {{domxref("Element.removeAttribute()")}} instead.</dd> + <dt><code>removeChild()</code></dt> + <dd>Modify the value of {{domxref("Attr.value")}} instead.</dd> + <dt><code>replaceChild()</code></dt> + <dd>Modify the value of {{domxref("Attr.value")}} instead.</dd> + <dt><code>setAttributeNode()</code></dt> + <dd>Use {{domxref("Element.setAttribute()")}} instead.</dd> + <dt><code>setAttributeNodeNS()</code></dt> + <dd>Use {{domxref("Element.setAttributeNS()")}} instead.</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("DOM4", "#interface-attr", "Attr")}}</td> + <td>{{Spec2("DOM4")}}</td> + <td>Moved <code>namespaceURI</code>, <code>prefix</code> and <code>localName</code> from {{domxref("Node")}} to this API and removed <code>ownerElement</code>, <code>schemaTypeInfo</code> and <code>isId</code>.</td> + </tr> + <tr> + <td>{{SpecName("DOM3 Core", "core.html#ID-637646024", "Attr")}}</td> + <td>{{Spec2("DOM3 Core")}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</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>{{CompatVersionUnknown}}<sup>[1]</sup></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</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>Android Webview</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}} [1]</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}<sup>[1]</sup></td> + </tr> + </tbody> +</table> +</div> + +<p>[1] As of Chrome 45, this property no longer inherits from Node.</p> diff --git a/files/es/web/api/audiobuffer/index.html b/files/es/web/api/audiobuffer/index.html new file mode 100644 index 0000000000..1909323a6d --- /dev/null +++ b/files/es/web/api/audiobuffer/index.html @@ -0,0 +1,108 @@ +--- +title: AudioBuffer +slug: Web/API/AudioBuffer +translation_of: Web/API/AudioBuffer +--- +<p>{{APIRef("Web Audio API")}}</p> + +<p>La interfaz <strong><code>AudioBuffer</code></strong> representa un pequeño recurso de audio que se almacena en memoria, creado a partir de un archivo de audio usando el método {{ domxref("AudioContext.decodeAudioData()") }}, o de datos en bruto con el método {{ domxref("AudioContext.createBuffer()") }}. Una véz cargado en AudioBuffer, el audio puede ser reproducido pasandolo en el método {{ domxref("AudioBufferSourceNode") }}.</p> + +<p>Objetos de este tipo son diseñados para almacenar pequeños trozos de audio, normalmente menos de 45 segundos. Para audios más extensos, los objectos implementan {{domxref("MediaElementAudioSourceNode")}} que es más adecuado. El buffer contiene data en el siguiente formado: non-interleaved IEEE754 32-bit linear PCM with a nominal range between <code>-1</code> and <code>+1</code>, that is, 32bits floating point buffer, with each samples between -1.0 and 1.0. If the {{domxref("AudioBuffer")}} has multiple channels, they are stored in separate buffer.</p> + +<h2 id="Constructor">Constructor</h2> + +<dl> + <dt>{{domxref("AudioBuffer.AudioBuffer", "AudioBuffer()")}}</dt> + <dd>Crea y retorna una nueva instancia de <code>AudioBuffer</code> </dd> +</dl> + +<h2 id="Propiedades">Propiedades</h2> + +<dl> + <dt>{{domxref("AudioBuffer.sampleRate")}} {{readonlyInline}}</dt> + <dd>Returns a float representing the sample rate, in samples per second, of the PCM data stored in the buffer.</dd> + <dt>{{domxref("AudioBuffer.length")}} {{readonlyInline}}</dt> + <dd>Returns an integer representing the length, in sample-frames, of the PCM data stored in the buffer.</dd> + <dt>{{domxref("AudioBuffer.duration")}} {{readonlyInline}}</dt> + <dd>Returns a double representing the duration, in seconds, of the PCM data stored in the buffer.</dd> + <dt>{{domxref("AudioBuffer.numberOfChannels")}} {{readonlyInline}}</dt> + <dd>Returns an integer representing the number of discrete audio channels described by the PCM data stored in the buffer.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<dl> + <dt>{{domxref("AudioBuffer.getChannelData()")}}</dt> + <dd>Returns a {{jsxref("Float32Array")}} containing the PCM data associated with the channel, defined by the <code>channel</code> parameter (with <code>0</code> representing the first channel).</dd> + <dt>{{domxref("AudioBuffer.copyFromChannel()")}}</dt> + <dd>Copies the samples from the specified channel of the <span class="idlType"><code>AudioBuffer</code></span> to the <code>destination</code> array.</dd> + <dt>{{domxref("AudioBuffer.copyToChannel()")}}</dt> + <dd>Copies the samples to the specified channel of the <span class="idlType"><code>AudioBuffer</code></span>, from the <code>source</code> array.</dd> +</dl> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>El siguiente ejemplo muestra como se crea un <code>AudioBuffer</code> y rellena con un sonido blanco aleatorio. Puedes encontrar el código completo en nuestro repositorio: <a href="https://github.com/mdn/webaudio-examples">webaudio-examples</a>; y una versión disponible: <a href="https://mdn.github.io/webaudio-examples/audio-buffer/">running live</a></p> + +<pre class="brush: js">var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); + +// Create an empty three-second stereo buffer at the sample rate of the AudioContext +var myArrayBuffer = audioCtx.createBuffer(2, audioCtx.sampleRate * 3, audioCtx.sampleRate); + +// Fill the buffer with white noise; +// just random values between -1.0 and 1.0 +for (var channel = 0; channel < myArrayBuffer.numberOfChannels; channel++) { + // This gives us the actual array that contains the data + var nowBuffering = myArrayBuffer.getChannelData(channel); + for (var i = 0; i < myArrayBuffer.length; i++) { + // Math.random() is in [0; 1.0] + // audio needs to be in [-1.0; 1.0] + nowBuffering[i] = Math.random() * 2 - 1; + } +} + +// Get an AudioBufferSourceNode. +// This is the AudioNode to use when we want to play an AudioBuffer +var source = audioCtx.createBufferSource(); + +// set the buffer in the AudioBufferSourceNode +source.buffer = myArrayBuffer; + +// connect the AudioBufferSourceNode to the +// destination so we can hear the sound +source.connect(audioCtx.destination); + +// start the source playing +source.start(); +</pre> + +<h2 id="Especificaciones">Especificaciones</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-audiobuffer-interface', 'AudioBuffer')}}</td> + <td>{{Spec2('Web Audio API')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2> + +<div> +<div class="hidden">La tabla de compatibilidades en esta página está generada por una data estructurada. Si te gustaria contribuir incluyendo data, por favor reviza <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> y envianos un pull request.</div> + +<p>{{Compat("api.AudioBuffer")}}</p> +</div> + +<h2 id="Mira_también">Mira también</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/audionode/index.html b/files/es/web/api/audionode/index.html new file mode 100644 index 0000000000..ea6ff34406 --- /dev/null +++ b/files/es/web/api/audionode/index.html @@ -0,0 +1,154 @@ +--- +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/baseaudiocontext/createbiquadfilter/index.html b/files/es/web/api/baseaudiocontext/createbiquadfilter/index.html new file mode 100644 index 0000000000..b94165b364 --- /dev/null +++ b/files/es/web/api/baseaudiocontext/createbiquadfilter/index.html @@ -0,0 +1,130 @@ +--- +title: BaseAudioContext.createBiquadFilter() +slug: Web/API/BaseAudioContext/createBiquadFilter +translation_of: Web/API/BaseAudioContext/createBiquadFilter +--- +<p>{{ APIRef("Web Audio API") }}</p> + +<div> +<p>El metodo <code>createBiquadFilter()</code> de la interfaz {{ domxref("BaseAudioContext") }} crea un {{ domxref("BiquadFilterNode") }}, el cual representa un filtro de segundo orden configurable, asi como varios tipos de filtros comunes diferentes.</p> +</div> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="brush: js">var audioCtx = new AudioContext(); +var biquadFilter = audioCtx.createBiquadFilter();</pre> + +<h3 id="Description" name="Description">Retorna</h3> + +<p>Un {{domxref("BiquadFilterNode")}}.</p> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<p>El siguiente ejemplo muestra el uso básico de un AudioContext para crear un nodo de filtro Biquad. Para ver el ejemplo trabanjando completamente, mire nuestra demostración <a href="http://mdn.github.io/voice-change-o-matic/">voice-change-o-matic</a> (mirar tambien <a href="https://github.com/mdn/voice-change-o-matic">source code</a>).</p> + +<pre class="brush: js">var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); + +// Configurar los diferentes nodos de audio que usaremos para la aplicación. +var analyser = audioCtx.createAnalyser(); +var distortion = audioCtx.createWaveShaper(); +var gainNode = audioCtx.createGain(); +var biquadFilter = audioCtx.createBiquadFilter(); +var convolver = audioCtx.createConvolver(); + +// conectar los nodos juntos + +source = audioCtx.createMediaStreamSource(stream); +source.connect(analyser); +analyser.connect(distortion); +distortion.connect(biquadFilter); +biquadFilter.connect(convolver); +convolver.connect(gainNode); +gainNode.connect(audioCtx.destination); + +// Manipule el filtro Biquad + +biquadFilter.type = "lowshelf"; +biquadFilter.frequency.value = 1000; +biquadFilter.gain.value = 25;</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificaciones</th> + <th scope="col">Estados</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('Web Audio API', '#dom-baseaudiocontext-createbiquadfilter', 'createBiquadFilter()')}}</td> + <td>{{Spec2('Web Audio API')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_el_navegador">Compatibilidad con el navegador</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatChrome(10.0)}}{{property_prefix("webkit")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(25.0)}} </td> + <td>{{CompatNo}}</td> + <td>15.0 {{property_prefix("webkit")}}<br> + 22</td> + <td>6.0{{property_prefix("webkit")}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>26.0</td> + <td>1.2</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>33.0</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_tambien">Ver tambien</h2> + +<ul> + <li><a href="/en-US/docs/Web_Audio_API/Using_Web_Audio_API">Using the Web Audio API</a></li> +</ul> diff --git a/files/es/web/api/baseaudiocontext/index.html b/files/es/web/api/baseaudiocontext/index.html new file mode 100644 index 0000000000..593f535ef0 --- /dev/null +++ b/files/es/web/api/baseaudiocontext/index.html @@ -0,0 +1,293 @@ +--- +title: BaseAudioContext +slug: Web/API/BaseAudioContext +tags: + - API + - Audio + - BaseAudioContext + - Interface + - NeedsTranslation + - Reference + - TopicStub + - Web Audio API +translation_of: Web/API/BaseAudioContext +--- +<p>{APIRef("Web Audio API")}}</p> + + +<p>The <code>BaseAudioContext</code> interface acts as a base definition for online and offline audio-processing graphs, as represented by {{domxref("AudioContext")}} and {{domxref("OfflineAudioContext")}} resepectively. You wouldn't use <code>BaseAudioContext</code> directly — you'd use its features via one of these two inheriting interfaces.</p> + +<p>A <code>BaseAudioContext</code> can be a target of events, therefore it implements the {{domxref("EventTarget")}} interface.</p> + +<p>{{InheritanceDiagram}}</p> + +<h2 id="Properties">Properties</h2> + +<dl> + <dt>{{domxref("BaseAudioContext.baseLatency")}} {{readonlyinline}}</dt> + <dd>Returns a double epresents the number of seconds of processing latency incurred by the AudioContext passing the audio from the AudioDestinationNode to the audio subsystem. </dd> + <dt>{{domxref("BaseAudioContext.currentTime")}} {{readonlyInline}}</dt> + <dd>Returns a double representing an ever-increasing hardware time in seconds used for scheduling. It starts at <code>0</code>.</dd> + <dt>{{domxref("BaseAudioContext.destination")}} {{readonlyInline}}</dt> + <dd>Returns an {{domxref("AudioDestinationNode")}} representing the final destination of all audio in the context. It can be thought of as the audio-rendering device.</dd> + <dt>{{domxref("BaseAudioContext.listener")}} {{readonlyInline}}</dt> + <dd>Returns the {{domxref("AudioListener")}} object, used for 3D spatialization.</dd> + <dt>{{domxref("BaseAudioContext.sampleRate")}} {{readonlyInline}}</dt> + <dd>Returns a float representing the sample rate (in samples per second) used by all nodes in this context. The sample-rate of an {{domxref("AudioContext")}} cannot be changed.</dd> + <dt>{{domxref("BaseAudioContext.state")}} {{readonlyInline}}</dt> + <dd>Returns the current state of the <code>AudioContext</code>.</dd> +</dl> + +<h3 id="Event_handlers">Event handlers</h3> + +<dl> + <dt>{{domxref("BaseAudioContext.onstatechange")}}</dt> + <dd>An event handler that runs when an event of type {{event("statechange")}} has fired. This occurs when the <code>AudioContext</code>'s state changes, due to the calling of one of the state change methods ({{domxref("AudioContext.suspend")}}, {{domxref("AudioContext.resume")}}, or {{domxref("AudioContext.close")}}).</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<p><em>Also implements methods from the interface </em>{{domxref("EventTarget")}}.</p> + +<dl> + <dt>{{domxref("BaseAudioContext.createBuffer()")}}</dt> + <dd>Creates a new, empty {{ domxref("AudioBuffer") }} object, which can then be populated by data and played via an {{ domxref("AudioBufferSourceNode") }}.</dd> + <dt>{{domxref("BaseAudioContext.createConstantSource()")}}</dt> + <dd>Creates a {{domxref("ConstantSourceNode")}} object, which is an audio source that continuously outputs a monaural (one-channel) sound signal whose samples all have the same value.</dd> + <dt>{{domxref("BaseAudioContext.createBufferSource()")}}</dt> + <dd>Creates an {{domxref("AudioBufferSourceNode")}}, which can be used to play and manipulate audio data contained within an {{ domxref("AudioBuffer") }} object. {{ domxref("AudioBuffer") }}s are created using {{domxref("AudioContext.createBuffer")}} or returned by {{domxref("AudioContext.decodeAudioData")}} when it successfully decodes an audio track.</dd> + <dt>{{domxref("BaseAudioContext.createScriptProcessor()")}}</dt> + <dd>Creates a {{domxref("ScriptProcessorNode")}}, which can be used for direct audio processing via JavaScript.</dd> + <dt>{{domxref("BaseAudioContext.createStereoPanner()")}}</dt> + <dd>Creates a {{domxref("StereoPannerNode")}}, which can be used to apply stereo panning to an audio source.</dd> + <dt>{{domxref("BaseAudioContext.createAnalyser()")}}</dt> + <dd>Creates an {{domxref("AnalyserNode")}}, which can be used to expose audio time and frequency data and for example to create data visualisations.</dd> + <dt>{{domxref("BaseAudioContext.createBiquadFilter()")}}</dt> + <dd>Creates a {{domxref("BiquadFilterNode")}}, which represents a second order filter configurable as several different common filter types: high-pass, low-pass, band-pass, etc.</dd> + <dt>{{domxref("BaseAudioContext.createChannelMerger()")}}</dt> + <dd>Creates a {{domxref("ChannelMergerNode")}}, which is used to combine channels from multiple audio streams into a single audio stream.</dd> + <dt>{{domxref("BaseAudioContext.createChannelSplitter()")}}</dt> + <dd>Creates a {{domxref("ChannelSplitterNode")}}, which is used to access the individual channels of an audio stream and process them separately.</dd> + <dt>{{domxref("BaseAudioContext.createConvolver()")}}</dt> + <dd>Creates a {{domxref("ConvolverNode")}}, which can be used to apply convolution effects to your audio graph, for example a reverberation effect.</dd> + <dt>{{domxref("BaseAudioContext.createDelay()")}}</dt> + <dd>Creates a {{domxref("DelayNode")}}, which is used to delay the incoming audio signal by a certain amount. This node is also useful to create feedback loops in a Web Audio API graph.</dd> + <dt>{{domxref("BaseAudioContext.createDynamicsCompressor()")}}</dt> + <dd>Creates a {{domxref("DynamicsCompressorNode")}}, which can be used to apply acoustic compression to an audio signal.</dd> + <dt>{{domxref("BaseAudioContext.createGain()")}}</dt> + <dd>Creates a {{domxref("GainNode")}}, which can be used to control the overall volume of the audio graph.</dd> + <dt>{{domxref("BaseAudioContext.createIIRFilter()")}}</dt> + <dd>Creates an {{domxref("IIRFilterNode")}}, which represents a second order filter configurable as several different common filter types.</dd> + <dt>{{domxref("BaseAudioContext.createOscillator()")}}</dt> + <dd>Creates an {{domxref("OscillatorNode")}}, a source representing a periodic waveform. It basically generates a tone.</dd> + <dt>{{domxref("BaseAudioContext.createPanner()")}}</dt> + <dd>Creates a {{domxref("PannerNode")}}, which is used to spatialise an incoming audio stream in 3D space.</dd> + <dt>{{domxref("BaseAudioContext.createPeriodicWave()")}}</dt> + <dd>Creates a {{domxref("PeriodicWave")}}, used to define a periodic waveform that can be used to determine the output of an {{ domxref("OscillatorNode") }}.</dd> + <dt>{{domxref("BaseAudioContext.createWaveShaper()")}}</dt> + <dd>Creates a {{domxref("WaveShaperNode")}}, which is used to implement non-linear distortion effects.</dd> + <dt>{{domxref("BaseAudioContext.decodeAudioData()")}}</dt> + <dd>Asynchronously decodes audio file data contained in an {{domxref("ArrayBuffer")}}. In this case, the ArrayBuffer is usually loaded from an {{domxref("XMLHttpRequest")}}'s <code>response</code> attribute after setting the <code>responseType</code> to <code>arraybuffer</code>. This method only works on complete files, not fragments of audio files.</dd> + <dt>{{domxref("BaseAudioContext.resume()")}}</dt> + <dd>Resumes the progression of time in an audio context that has previously been suspended/paused.</dd> +</dl> + +<h2 id="Examples">Examples</h2> + +<p>Basic audio context declaration:</p> + +<pre class="brush: js">var audioCtx = new AudioContext();</pre> + +<p>Cross browser variant:</p> + +<pre class="brush: js">var AudioContext = window.AudioContext || window.webkitAudioContext; +var audioCtx = new AudioContext(); + +var oscillatorNode = audioCtx.createOscillator(); +var gainNode = audioCtx.createGain(); +var finish = audioCtx.destination; +// etc.</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', '#BaseAudioContext', 'BaseAudioContext')}}</td> + <td>{{Spec2('Web Audio API')}}</td> + <td> </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>Edge</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>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>15.0{{property_prefix("webkit")}}<br> + 22</td> + <td>6.0{{property_prefix("webkit")}}</td> + </tr> + <tr> + <td><code>baseLatency</code></td> + <td>{{CompatChrome(60)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>createConstantSource()</code></td> + <td>{{CompatChrome(56)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop(52)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatOpera(43)}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>createStereoPanner()</code></td> + <td>{{CompatChrome(42)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(37.0)}} </td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>onstatechange</code>, <code>state</code>, <code>suspend()</code>, <code>resume()</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(40.0)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatSafari(8.0)}}</td> + </tr> + <tr> + <td>Unprefixed</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td> </td> + <td> </td> + <td> </td> + <td> </td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android Webview</th> + <th>Chrome for Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Mobile</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>{{CompatVersionUnknown}}</td> + <td>2.2</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>baseLatency</code></td> + <td>{{CompatChrome(60)}}</td> + <td>{{CompatChrome(60)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>createConstantSource()</code></td> + <td>{{CompatChrome(56)}}</td> + <td>{{CompatChrome(56)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoMobile(52)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>createStereoPanner()</code></td> + <td>{{CompatChrome(42)}}</td> + <td>{{CompatChrome(42)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>onstatechange</code>, <code>state</code>, <code>suspend()</code>, <code>resume()</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>Unprefixed</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatOperaMobile(43)}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web_Audio_API/Using_Web_Audio_API">Using the Web Audio API</a></li> + <li>{{domxref("AudioContext")}}</li> + <li>{{domxref("OfflineAudioContext")}}</li> +</ul> diff --git a/files/es/web/api/batterymanager/charging/index.html b/files/es/web/api/batterymanager/charging/index.html new file mode 100644 index 0000000000..8295785a2c --- /dev/null +++ b/files/es/web/api/batterymanager/charging/index.html @@ -0,0 +1,28 @@ +--- +title: BatteryManager.charging +slug: Web/API/BatteryManager/charging +tags: + - Apps + - Batería + - Battery + - Firefox OS + - Mobile + - Móvil + - WebAPI +translation_of: Web/API/BatteryManager/charging +--- +<p>{{ ApiRef() }}</p> +<h2 id="Summary" name="Summary">Resumen</h2> +<p>Un valor boleano indicando si o no esta cargando la batería del dispositivo (está conectado el cargador).</p> +<h2 id="Syntax" name="Syntax">Sintaxis</h2> +<pre class="syntaxbox">var <em>charging</em> = navigator.battery.charging</pre> +<p>Valor de retorno, <code>charging</code> indica si o no la batería esta siendo cargada; si la batería se está cargando (o si no hay batería), este valor es <code>true</code>. De lo contrario el valor es <code>false</code>.</p> +<h2 id="Specifications">Specifications</h2> +<p>{{page("/en-US/docs/Web/API/BatteryManager","Specifications")}}</p> +<h2 id="Browser_compatibility">Browser compatibility</h2> +<p>{{page("/en-US/docs/Web/API/BatteryManager","Browser_compatibility")}}</p> +<h2 id="See_also">See also</h2> +<ul> + <li>{{domxref("BatteryManager")}}</li> + <li>{{domxref("window.navigator.battery","navigator.battery")}}</li> +</ul> diff --git a/files/es/web/api/batterymanager/chargingtime/index.html b/files/es/web/api/batterymanager/chargingtime/index.html new file mode 100644 index 0000000000..6876834636 --- /dev/null +++ b/files/es/web/api/batterymanager/chargingtime/index.html @@ -0,0 +1,26 @@ +--- +title: BatteryManager.chargingTime +slug: Web/API/BatteryManager/chargingTime +tags: + - API + - Battery + - Battery API + - Mobile + - Property +translation_of: Web/API/BatteryManager/chargingTime +--- +<p>{{ APIRef("BatteryManager") }}</p> +<h2 id="Summary" name="Summary">Resumen</h2> +<p>Indica la cantidad de tiempo, en segundos, que faltan para que la batería esté completamente cargada.</p> +<h2 id="Syntax" name="Syntax">Sintaxis</h2> +<pre class="syntaxbox">var <em>time</em> = navigator.battery.chargingTime</pre> +<p>Cuando devuelve, <code>time</code> es el tiempo restante en segundos para que la batería esté completamente cargada o 0 (cero) si la batería ya está completamente cargada. Si la batería está descargándose —o si el sistema no puede determinar el restante de carga— el valor es <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Infinity" title="/en-US/docs/JavaScript/Reference/Global_Objects/Infinity">Infinity</a></code>.</p> +<h2 id="Especificaciones">Especificaciones</h2> +<p>{{page("/en-US/docs/Web/API/BatteryManager","Specifications")}}</p> +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> +<p>{{page("/en-US/docs/Web/API/BatteryManager","Browser_compatibility")}}</p> +<h2 id="See_also">See also</h2> +<ul> + <li>{{domxref("BatteryManager")}}</li> + <li>{{domxref("window.navigator.battery","navigator.battery")}}</li> +</ul> diff --git a/files/es/web/api/batterymanager/dischargingtime/index.html b/files/es/web/api/batterymanager/dischargingtime/index.html new file mode 100644 index 0000000000..4cc79f0b9d --- /dev/null +++ b/files/es/web/api/batterymanager/dischargingtime/index.html @@ -0,0 +1,29 @@ +--- +title: BatteryManager.dischargingTime +slug: Web/API/BatteryManager/dischargingTime +tags: + - API + - Apps + - Batería + - Battery + - Firefox OS + - Gecko DOM Reference + - WebAPI + - aplicaciones +translation_of: Web/API/BatteryManager/dischargingTime +--- +<p>{{ ApiRef() }}</p> +<h2 id="Summary" name="Summary">Resumen</h2> +<p>Indíca la cantidad de tiempo, en segundos, que restan antes de que la batería se descargue completamente.</p> +<h2 id="Syntax" name="Syntax">Sintaxis</h2> +<pre class="syntaxbox">var <em>time</em> = navigator.battery.dischargingTime</pre> +<p>Valor de retorno, <code>time</code> es el tiempo restante en segundos antes que la batería esté completamente descargada y el sistema se suspenda. Este valor es <span style="line-height: inherit;"><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Infinity" title="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Infinity">Infinity</a> si la batería se está cargando en vez de descargando, o si el sistema es incapaz de calcular el tiempo de descarga (o si no hay batería)</span></p> +<h2 id="Specifications">Specifications</h2> +<p>{{page("/en-US/docs/Web/API/BatteryManager","Specifications")}}</p> +<h2 id="Browser_compatibility">Browser compatibility</h2> +<p>{{page("/en-US/docs/Web/API/BatteryManager","Browser_compatibility")}}</p> +<h2 id="See_also">See also</h2> +<ul> + <li>{{domxref("BatteryManager")}}</li> + <li>{{domxref("window.navigator.battery","navigator.battery")}}</li> +</ul> diff --git a/files/es/web/api/batterymanager/index.html b/files/es/web/api/batterymanager/index.html new file mode 100644 index 0000000000..5d2aee0710 --- /dev/null +++ b/files/es/web/api/batterymanager/index.html @@ -0,0 +1,127 @@ +--- +title: BatteryManager +slug: Web/API/BatteryManager +translation_of: Web/API/BatteryManager +--- +<p>{{APIRef()}}</p> +<h2 id="Sumario">Sumario</h2> +<p>La interfaz <code>BatteryManager</code> proporciona la información del nivel de carga de la bateria del sistema.</p> +<p>La propiedad {{domxref("window.navigator.battery","navigator.battery")}} devuelve una petición de la interfaz <code>BatteryManager</code> que se utiliza para interactuar con la API Battery Status.</p> +<h2 id="Propiedades">Propiedades</h2> +<dl> + <dt> + {{domxref("BatteryManager.charging")}} {{ReadOnlyInline}}</dt> + <dd> + Valor booleano que indica si la bateria se está o no cargando.</dd> + <dt> + {{domxref("BatteryManager.chargingTime")}} {{ReadOnlyInline}}</dt> + <dd> + Número que indica el tiempo que queda en segundos hasta que la batería esté completamente cargada, o 0 si la batería está completamente cargada.</dd> + <dt> + {{domxref("BatteryManager.dischargingTime")}} {{ReadOnlyInline}}</dt> + <dd> + Número que indica el tiempo restante en segundos hasta que la batería esté completamente descargada y el sistema entra en suspensión.</dd> + <dt> + {{domxref("BatteryManager.level")}} {{ReadOnlyInline}}</dt> + <dd> + Número que indica el nivel de carga de la batería del sistema, los valores están escalados entre 0.0 y 1.0.</dd> +</dl> +<h3 id="Eventos_del_controlador">Eventos del controlador</h3> +<dl> + <dt> + {{domxref("BatteryManager.onchargingchange")}}</dt> + <dd> + Controlador para el evento {{event("chargingchange")}} ; Este evento se envía cuando se actualiza el estado de carga de la batería.</dd> + <dt> + {{domxref("BatteryManager.onchargingtimechange")}}</dt> + <dd> + Controlador para el evento {{event("chargingtimechange")}}; Este evento se envía cuando se actualiza el tiempo de carga de la batería.</dd> + <dt> + {{domxref("BatteryManager.ondischargingtimechange")}}</dt> + <dd> + Controlador para el evento{{event("dischargingtimechange")}}; Este evento se envía cuando se actualiza el tiempo de descarga de la batería.</dd> + <dt> + {{domxref("BatteryManager.onlevelchange")}}</dt> + <dd> + Controlador para el evento {{event("levelchange")}}; Este evento se envía cuando se actualizael nivel de la batería.</dd> +</dl> +<h2 id="Métodos">Métodos</h2> +<p>Heredado de{{domxref("EventTarget")}}:</p> +<p>{{page("/en-US/docs/Web/API/EventTarget","Methods")}}</p> +<h2 id="Especificaciones">Especificaciones</h2> +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificaciones</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('Battery API')}}</td> + <td>{{Spec2('Battery API')}}</td> + <td>Especificaciones iniciales.</td> + </tr> + </tbody> +</table> +<h2 id="Compatibilidad">Compatibilidad</h2> +<p>{{ CompatibilityTable() }}</p> +<div id="compat-desktop"> + <table class="compat-table"> + <tbody> + <tr> + <th>Característica</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() }}<br> + Chrome on Android: <a href="http://crbug.com/135863">crbug.com/135863</a><br> + Chrome OS: <a href="http://crbug.com/122593">crbug.com/122593</a></td> + <td>{{CompatGeckoDesktop("10")}} {{ property_prefix("moz") }} [1]<br> + {{CompatGeckoDesktop("16")}} (without prefix) [2]</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>{{ CompatUnknown() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{CompatGeckoMobile("10")}} {{ property_prefix("moz") }} [1]<br> + {{CompatGeckoMobile("16")}} (without prefix) [2]</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + </tr> + </tbody> + </table> +</div> +<h3 id="Notas_Gecko">Notas Gecko</h3> +<p>[1] Descativado por defecto en Firefox 10.0, pero se puede habilitar estableciendo las preferencias en <code>dom.battery.enabled</code> a <code>true</code>. A partir de Firefox 11.0, <code>mozBattery</code> está activado por defecto.</p> +<p class="note">[2] La Battery API actualmente es soportada por Android, Windows, y Linux con UPower instalado. Está soportado para MacOS con Gecko 18.0 {{geckoRelease("18.0")}}.</p> +<h2 id="Ver_también">Ver también</h2> +<ul> + <li>{{ domxref("window.navigator.battery","navigator.battery") }}</li> + <li>La <a href="/en-US/docs/WebAPI/Battery_Status" title="/en-US/docs/WebAPI/Battery_Status">Battery Status API</a></li> +</ul> diff --git a/files/es/web/api/batterymanager/level/index.html b/files/es/web/api/batterymanager/level/index.html new file mode 100644 index 0000000000..d88c8ffbe3 --- /dev/null +++ b/files/es/web/api/batterymanager/level/index.html @@ -0,0 +1,22 @@ +--- +title: BatteryManager.level +slug: Web/API/BatteryManager/level +tags: + - API +translation_of: Web/API/BatteryManager/level +--- +<p>{{ APIRef("BatteryManager") }}</p> +<h2 id="Summary" name="Summary">Resumen</h2> +<p>Indica el valor actual del nivel de carga, estos valores están entre 0.0 a 1.0.</p> +<h2 id="Syntax" name="Syntax">Sintaxis</h2> +<pre class="syntaxbox">var level = navigator.battery.level</pre> +<p>Es un número que representa el nivel de carga de la batería del sistema en una escala entre los valores 0.0 y 1.0. Un valor de 0 significa que la batería está vacía y el sistema esta apunto de entrar en suspensión. Un valor de 1.0 significa que la batería está cargada al máximo. Este valor también nos indica que el sistema no puede determinar el nivel de carga de la batería o si no está alimentado por batería.</p> +<h2 id="Especificaciones">Especificaciones</h2> +<p>{{page("/es/docs/Web/API/BatteryManager","Especificaciones")}}</p> +<h2 id="Compatibilidad_del_navegador">Compatibilidad del navegador</h2> +<p>{{page("/es/docs/Web/API/BatteryManager","Compatibilidad")}}</p> +<h2 id="Vea_también">Vea también</h2> +<ul> + <li>{{domxref("BatteryManager")}}</li> + <li>{{domxref("window.navigator.battery","navigator.battery")}}</li> +</ul> diff --git a/files/es/web/api/batterymanager/onchargingchange/index.html b/files/es/web/api/batterymanager/onchargingchange/index.html new file mode 100644 index 0000000000..2688bfc3aa --- /dev/null +++ b/files/es/web/api/batterymanager/onchargingchange/index.html @@ -0,0 +1,20 @@ +--- +title: BatteryManager.onchargingchange +slug: Web/API/BatteryManager/onchargingchange +translation_of: Web/API/BatteryManager/onchargingchange +--- +<p>{{ APIRef("BatteryManager") }}</p> +<h2 id="Summary" name="Summary">Resumen</h2> +<p>Especifica un evento oyente para recibir eventos {{event("chargingchange")}}. Estos eventos se producen cuando se actualiza el estado de la batería {{domxref("BatteryManager.charging", "charging")}}.</p> +<h2 id="Syntax" name="Syntax">Sintaxis</h2> +<pre class="syntaxbox">navigator.battery.onchargingchange = funcRef</pre> +<p>Donde <code><em>funcRef</em></code> es una función para llamar cuando se produce el evento {{event("chargingchange")}}.</p> +<h2 id="Especificaciones">Especificaciones</h2> +<p>{{page("/en-US/docs/Web/API/BatteryManager","Specifications")}}</p> +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> +<p>{{page("/en-US/docs/Web/API/BatteryManager","Browser_compatibility")}}</p> +<h2 id="Ver_también">Ver también</h2> +<ul> + <li>{{domxref("BatteryManager")}}</li> + <li>{{domxref("window.navigator.battery","navigator.battery")}}</li> +</ul> diff --git a/files/es/web/api/batterymanager/onlevelchange/index.html b/files/es/web/api/batterymanager/onlevelchange/index.html new file mode 100644 index 0000000000..2b2e957619 --- /dev/null +++ b/files/es/web/api/batterymanager/onlevelchange/index.html @@ -0,0 +1,20 @@ +--- +title: BatteryManager.onlevelchange +slug: Web/API/BatteryManager/onlevelchange +translation_of: Web/API/BatteryManager/onlevelchange +--- +<p>{{ APIRef("BatteryManager") }}</p> +<h2 id="Summary" name="Summary">Resumen</h2> +<p>Especifica un detector de eventos para recibir eventos de {{event("levelchange")}} (<em>"cambio de nivel</em>"). Estos eventos ocurren cuando el {{domxref("BatteryManager.level")}} de batería se actualiza.</p> +<h2 id="Syntax" name="Syntax">Sintaxis</h2> +<pre class="syntaxbox">navigator.battery.onlevelchange = funcRef</pre> +<p>Donde <code><em>funcRef</em></code> es una función que se convoca cuando el evento de {{event("levelchange")}} sucede.</p> +<h2 id="Especificaciones">Especificaciones</h2> +<p>{{page("/en-US/docs/Web/API/BatteryManager","Specifications")}}</p> +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2> +<p>{{page("/en-US/docs/Web/API/BatteryManager","Browser_compatibility")}}</p> +<h2 id="Véase_también">Véase también</h2> +<ul> + <li>{{domxref("BatteryManager")}}</li> + <li>{{domxref("window.navigator.battery","navigator.battery")}}</li> +</ul> diff --git a/files/es/web/api/beforeunloadevent/index.html b/files/es/web/api/beforeunloadevent/index.html new file mode 100644 index 0000000000..5bd5e2204f --- /dev/null +++ b/files/es/web/api/beforeunloadevent/index.html @@ -0,0 +1,70 @@ +--- +title: BeforeUnloadEvent +slug: Web/API/BeforeUnloadEvent +translation_of: Web/API/BeforeUnloadEvent +--- +<p>{{APIRef}}</p> + +<p>El evento <strong><code>beforeunload</code></strong> se diapara cuando la ventana, el documento y sus recursos están a punto de ser cerrados.</p> + +<p>Cuando una cadena no vacía es asignada a la propiedad <code>returnValue</code> del Evento, un cuadro de diálogo aparece, pidiendo a los usuarios la confirmación para la página (ver ejemplo a continuación). Cuando no es asignado un valor, el evento se procesa en silencio. Algunas implementaciones muestran solamente el cuadro de diálogo si el marco o cualquier marco embebido recibe un gesto o interacción del usuario. Ver {{anch("Compatibilidad del navegador")}} para más información.</p> + +<table class="properties"> + <tbody> + <tr> + <td>Burbujas</td> + <td>No</td> + </tr> + <tr> + <td>Cancelable</td> + <td>Sí</td> + </tr> + <tr> + <td>Objetos de destino</td> + <td>defaultView</td> + </tr> + <tr> + <td>Interface</td> + <td>{{domxref("Event")}}</td> + </tr> + </tbody> +</table> + +<h2 id="Ejemplos">Ejemplos</h2> + +<pre class="brush:js;">window.addEventListener("beforeunload", function( event ) { + event.returnValue = "\o/"; +}); + +//is equivalent to +window.addEventListener("beforeunload", function( event ) { + event.preventDefault(); +});</pre> + +<p>Los navegadores basado en Webkit no se basan en las especificaciones del cuadro de diálogo. Un ejemplo compatible con la mayoria de los navegadores seria algo parecido al siguiente ejemplo.</p> + +<pre class="brush: js">window.addEventListener("beforeunload", function (e) { + var confirmationMessage = "\o/"; + + (e || window.event).returnValue = confirmationMessage; //Gecko + IE + return confirmationMessage; //Webkit, Safari, Chrome etc. +});</pre> + +<h2 id="Compatibilidad_del_navegador">Compatibilidad del navegador</h2> + +<div> +<div class="hidden">La table de compatibilidad en esta página se genera a partir de los datos estructurados. Si le gustaría contrubuir con los datos, por favor revise <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> y envíenos un un pull request.</div> + +<p>{{Compat("api.BeforeUnloadEvent")}}</p> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{Event("DOMContentLoaded")}}</li> + <li>{{Event("readystatechange")}}</li> + <li>{{Event("load")}}</li> + <li>{{Event("beforeunload")}}</li> + <li>{{Event("unload")}}</li> + <li><a href="http://www.whatwg.org/specs/web-apps/current-work/#prompt-to-unload-a-document" title="http://www.whatwg.org/specs/web-apps/current-work/#prompt-to-unload-a-document">Descargas de documentos — Solicitud para descargar un documento</a></li> +</ul> diff --git a/files/es/web/api/blob/blob/index.html b/files/es/web/api/blob/blob/index.html new file mode 100644 index 0000000000..5aa6b895d6 --- /dev/null +++ b/files/es/web/api/blob/blob/index.html @@ -0,0 +1,75 @@ +--- +title: Blob() +slug: Web/API/Blob/Blob +tags: + - API + - Archivo + - Blob + - File API + - Referencia +translation_of: Web/API/Blob/Blob +--- +<p>{{APIRef("File API")}}</p> + +<p>El constructor <code><strong>Blob()</strong></code> retorna un nuevo objeto {{domxref("Blob")}} . El contenido del blob consiste en la concatenación de los valores obtenidos en el parrametro <em>array</em>.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var aBlob = new Blob(<em> array</em>, <em>options</em> ); +</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code><var>array</var></code></dt> + <dd>Es un {{jsxref("Array")}} de {{jsxref("ArrayBuffer")}}, {{domxref("ArrayBufferView")}}, {{domxref("Blob")}}, objetos {{domxref("USVString")}}, o una mezcla de cualquiera de éstos objetos, que será puesto dentro de {{domxref("Blob")}}. Los objetos <code>USVString</code> estan codificados como UTF-8.</dd> + <dt><code><var>options</var></code> {{optional_inline}}</dt> + <dd> + <p>Un objeto opcional de tipo {{domxref("BlobPropertyBag")}} que puede especificar las siguientes propiedades:</p> + + <dl> + <dt><code>type</code> {{optional_inline}}</dt> + <dd>El {{Glossary("MIME type")}} de la información que será almacenada en el blob. El valor por defecto es una cadena vacía, (<code>""</code>).</dd> + <dt><code>endings</code> {{optional_inline}} {{non-standard_inline}}</dt> + <dd>Cómo interpretar los carácteres de nueva línea (<code>\n</code>) en el contenido, si la información es texto. El valor por defecto, <code>transparent</code>, copia los caracteres de nueva línea en el blob sin cambiarlos. Para convertir las nuevas líneas a la convención nativa del sistema, se especifica <code>endings</code>.</dd> + </dl> + </dd> +</dl> + +<h3 id="Valor_de_retorno">Valor de retorno</h3> + +<p>Un nuevo objeto {{domxref("Blob")}} conteniendo la información especificada.</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush: js language-js">var unaParteDeArchivo = ['<a id="a"><b id="b">hey!</b></a>']; // un array de un solo DOMString +var oMiBlob = new Blob(unaParteDeArchivo, {type : 'text/html'}); // el blob</pre> + +<h2 id="Specification" name="Specification">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('File API', '#constructorBlob', 'Blob()')}}</td> + <td>{{Spec2('File API')}}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_los_navegadores">Compatibilidad de los navegadores</h2> + + + +<p>{{Compat("api.Blob.Blob")}}</p> + +<h2 id="Vea_también">Vea también</h2> + +<ul> + <li>La interfaz deprecada {{domxref("BlobBuilder")}}, la cual es reemplazada por este constructor.</li> +</ul> diff --git a/files/es/web/api/blob/index.html b/files/es/web/api/blob/index.html new file mode 100644 index 0000000000..2ee7811292 --- /dev/null +++ b/files/es/web/api/blob/index.html @@ -0,0 +1,194 @@ +--- +title: Blob +slug: Web/API/Blob +translation_of: Web/API/Blob +--- +<p>{{ APIRef("File API") }}</p> + +<h2 id="Resumen">Resumen</h2> + +<p>Un objeto <code>Blob</code> representa un objeto tipo fichero de datos planos inmutables. Los Blobs representan datos que no necesariamente se encuentran en un formato nativo de JavaScript. La interfaz {{ domxref("File") }} se encuentra basada en un <code>Blob</code>, heredando y expendiendo la funcionalidad de un <code>Blob</code> para soportar archivos en el sistema del usuario.</p> + +<p>Una forma fácil de construir un <code>Blob</code> es invocando el constructor {{domxref("Blob.Blob", "Blob()")}}. Otra manera es utilizando el método <code>slice()</code> para crear un blob que contiene un subconjunto de los datos de otro <code>Blob</code>.</p> + +<h2 id="Constructor">Constructor</h2> + +<dl> + <dt>{{domxref("Blob.Blob", "Blob()")}}</dt> + <dd>Regresa un nuevo objeto <code>Blob</code> creado cuyo contenido consiste en la concatenación de un arreglo de valores establecidos en el parámetro de la función.</dd> +</dl> + +<h2 id="Propiedades">Propiedades</h2> + +<dl> + <dt>{{domxref("Blob.size")}} {{readonlyinline}}</dt> + <dd>El tamaño, en bytes, de los datos contenidos en el objeto <code>Blob</code></dd> + <dt>{{domxref("Blob.type")}} {{readonlyinline}}</dt> + <dd>Una cadena (String) indicando el tipo MIME de los datos contenidos en el <code>Blob</code>. Si el tipo es desconocido, esta cadena será vacía.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<dl> + <dt>{{domxref("Blob.slice()")}}</dt> + <dd><code><font face="Open Sans, sans-serif">Regresa un nuevo objeto </font>Blob</code> conteniendo los datos de un rango específico de bytes del origen del <code>Blob</code>.</dd> +</dl> + +<div class="note"><strong>Nota:</strong> Esté consciente que el método <code>slice()</code> posee prefijos propios del fabricante en algunos exploradores y versiones: <code>blob.mozSlice()</code> para Firefox 12 e inferior y <code>blob.webkitSlice()</code> en Safari. Una versión anterior del método <code>slice()</code>, sin prefijos del fabricante, tenía diferente semántica, y se encuentra obsoleto. El soporte para <code>blob.mozSlice()</code> ha sido eliminado a partir de Firefox 30.</div> + +<h2 id="Ejemplos">Ejemplos</h2> + +<h3 id="Ejemplo_de_uso_de_un_constructor_de_Blob">Ejemplo de uso de un constructor de Blob</h3> + +<p>El siguiente código:</p> + +<pre class="brush: js">var aFileParts = ['<a id="a"><b id="b">hey!</b></a>']; +var oMyBlob = new Blob(aFileParts, {type : 'text/html'}); // the blob +</pre> + +<p>es equivalente a:</p> + +<pre class="brush: js">var oBuilder = new BlobBuilder(); +var aFileParts = ['<a id="a"><b id="b">hey!</b></a>']; +oBuilder.append(aFileParts[0]); +var oMyBlob = oBuilder.getBlob('text/xml'); // the blob +</pre> + +<div class="warning"> +<p>La interfaz {{ domxref("BlobBuilder") }} ofrece otra manera de crear <code>Blob</code>, pero se encuentra ahora obsoleta y no debería volverse a utilizar.</p> +</div> + +<h3 id="Ejemplo_para_crear_una_URL_en_un_arreglo_tipado_utilizando_un_blob">Ejemplo para crear una URL en un arreglo tipado utilizando un blob</h3> + +<p>El siguiente código:</p> + +<pre class="brush: js">var typedArray = GetTheTypedArraySomehow(); +var blob = new Blob([typedArray], {type: 'application/octet-binary'}); // pass a useful mime type here +var url = URL.createObjectURL(blob); +// url will be something like: blob:d3958f5c-0777-0845-9dcf-2cb28783acaf +// now you can use the url in any context that regular URLs can be used in, for example img.src, etc. +</pre> + +<h3 id="Ejemplo_para_extraer_datos_de_un_Blob">Ejemplo para extraer datos de un Blob</h3> + +<p>La única manera de leer contenido de un Blob es utilizando un {{domxref("FileReader")}}. El siguiente código lee el contenido de un Blob como un arreglo tipado.</p> + +<pre class="brush: js">var reader = new FileReader(); +reader.addEventListener("loadend", function() { + // reader.result contains the contents of blob as a typed array +}); +reader.readAsArrayBuffer(blob);</pre> + +<p>Al utilizar otros métodos de {{domxref("FileReader")}}, es posible leer los contenidos del Blob como una cadena o una URL de datos.</p> + +<h2 id="Browser_Compatibility" name="Browser_Compatibility">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('File API','#blob','Blob')}}</td> + <td>{{Spec2('File API')}}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">Compatibilidad de navegadores</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>5</td> + <td>4</td> + <td>10</td> + <td>11.10</td> + <td>5.1</td> + </tr> + <tr> + <td><code>slice()</code></td> + <td>10 {{property_prefix("webkit")}}‡<br> + 21</td> + <td>5 {{ property_prefix("moz") }}‡<br> + 13</td> + <td>10</td> + <td>12</td> + <td>5.1 (<a class="external" href="http://trac.webkit.org/changeset/83873">534.29</a>) {{ property_prefix("webkit") }}</td> + </tr> + <tr> + <td><code>Blob()</code> constructor</td> + <td>20</td> + <td>{{ CompatGeckoDesktop("13.0") }}</td> + <td>10</td> + <td>12.10</td> + <td>6 (<a class="external" href="http://trac.webkit.org/changeset/115582">536.10</a>)</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>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>{{ CompatUnknown() }}</td> + <td>{{ CompatGeckoMobile("13.0") }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<h3 id="Notas_en_implementaciones_del_método_slice()">Notas en implementaciones del método slice()</h3> + +<p>El método <code>slice()</code> ha tomado inicialmente <code>length</code> como el segundo argumento para indicar el número de bytes para copiar en el nuevo <code>Blob</code>. Si usted especificó valores como <code>start + length</code> excediento el tamaño del <code>Blob </code>de origen, el <code>Blob</code> retornado contendrá los datos a partir del índice de inicio hasta el final del <code>Blob</code> de origen.</p> + +<p>Esa versión del método <code>slice()</code> fué implementada en <a class="link-https" href="https://hg.mozilla.org/mozilla-central/rev/1b3947ed93c6">Firefox 4</a>, <a class="external" href="http://trac.webkit.org/changeset/55670">WebKit</a>, y <a class="external" href="http://www.opera.com/docs/specs/presto28/file/#blob">Opera 11.10</a>. Sin embargo, desde que la sintaxis ha diferido desde <a href="/en/JavaScript/Reference/Global_Objects/Array/slice" title="en/JavaScript/Reference/Global Objects/Array/slice"><code>Array.slice()</code></a> y <a href="/en/JavaScript/Reference/Global_Objects/String/slice" title="en/JavaScript/Reference/Global Objects/String/slice"><code>String.slice()</code></a>, Gecko y WebKit removieron este soporte y agregaron soporte para la nueva sintaxis como {{ manch("mozSlice") }}/<a class="external" href="http://trac.webkit.org/changeset/83873"><code>Blob.webkitSlice</code></a>.</p> + +<p>Comenzando en Gecko 13.0 {{ geckoRelease("13.0") }} y Chrome 21, {{ manch("slice") }} no se encuentra más prefijado. El soporte para <code>mozSlice()</code> ha sido eliminado en Gecko 30.0 {{ geckoRelease("30.0") }}.‡</p> + +<h3 id="Notas_de_Gecko">Notas de Gecko</h3> + +<p>Antes de Gecko 12.0 {{ geckoRelease("12.0") }}, existía un error que afectaba el comportamiento de {{ manch("slice") }}; No funcionaba para las posiciones <code>start</code> and <code>end</code> por fuera del rango de valores de 64 bits con signo; Ha sido ahora arreglado para soportar valores de 64 bits sin signo.</p> + +<h2 id="Disponilidad_del_alcance_del_código_en_Chrome">Disponilidad del alcance del código en Chrome</h2> + +<p>El alcance JSM del <code>Blob </code>se encuentra disponible sin la necesidad de hacer nada en especial.</p> + +<p>En el alcance de arranque, este debe importarse de igual modo:</p> + +<pre class="brush: js">const {Blob, Services} = Cu.import('resource://gre/modules/Services.jsm', {});</pre> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{ domxref("BlobBuilder") }}</li> + <li>{{ domxref("File") }}</li> +</ul> diff --git a/files/es/web/api/blob/type/index.html b/files/es/web/api/blob/type/index.html new file mode 100644 index 0000000000..73dc045027 --- /dev/null +++ b/files/es/web/api/blob/type/index.html @@ -0,0 +1,121 @@ +--- +title: Blob.type +slug: Web/API/Blob/type +tags: + - API + - Archivo + - Archivos + - DOM + - Propiedad + - Referencia +translation_of: Web/API/Blob/type +--- +<div>{{APIRef("File API")}}</div> + +<p>La propiedad <strong><code>type</code></strong> de un objeto <code><a href="/en-US/docs/Web/API/Blob">Blob</a></code> proporciona el tipo MIME del archivo. Retorna una cadena vacía si el tipo no puede ser determinado.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var tipo = <var>instanceOfFile</var>.type</pre> + +<h2 id="Valor">Valor</h2> + +<p>Una cadena</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush:js">var i, fileInput, files, allowedFileTypes; + +// fileInput es un HTMLInputElement: <input type="file" multiple id="myfileinput"> +fileInput = document.getElementById("myfileinput"); + +// files es un objeto FileList (similar a NodeList) +files = fileInput.files; + +// nuestra aplicacion solo acepta imagenes *.png, *.jpeg y *.gif +allowedFileTypes = ["image/png", "image/jpeg", "image/gif"]; + +for (i = 0; i < files.length; i++) { + // Prueba si file.type es un tipo de archivo permitido. + if (allowedFileTypes.indexOf(<strong>files[i].type</strong>) > -1) { + // El tipo de archivo es uno de los permitidos. Hacer algo aquí. + } +}); +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Espeficicaciones</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('File API', '#dfn-type', 'type')}}</td> + <td>{{Spec2('File API')}}</td> + <td>Definicion inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_browsers">Compatibilidad con browsers</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>File.type</td> + <td>5</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("2")}}</td> + <td>10.0</td> + <td>11.10</td> + <td>5.1</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>File.type</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("Blob")}}</li> +</ul> diff --git a/files/es/web/api/blobbuilder/index.html b/files/es/web/api/blobbuilder/index.html new file mode 100644 index 0000000000..e07f1217cf --- /dev/null +++ b/files/es/web/api/blobbuilder/index.html @@ -0,0 +1,193 @@ +--- +title: BlobBuilder +slug: Web/API/BlobBuilder +tags: + - API + - Archivo + - DOM + - File API + - NeedsBrowserCompatibility + - Obsoleto + - Referencia +translation_of: Web/API/BlobBuilder +--- +<p>{{APIRef("File API")}}{{ obsolete_header}}</p> + +<p>La interfaz BlobBuilder provee una manera fácil de construir objetos {{domxref("Blob")}} . Solo crea un BlobBuilder y anexa trozos de datos invocando el método {{manch("append")}} . Cuando termines de construir tu objeto, llama al método {{manch("getBlob")}} para obtener un objeto {{domxref("Blob")}} que contiene los datos que le enviaste al blob builder.</p> + +<div class="note"><strong>Nota:</strong> La interfaz <code>BlobBuilder</code> ha sido descontinuada en favor de introducir el constructor mas reciente {{domxref('Blob')}}.</div> + +<h2 id="Información_general_de_los_metodos">Información general de los metodos</h2> + +<table class="standard-table"> + <tbody> + <tr> + <td><code>void <a href="/en-US/docs/Web/API/BlobBuilder#append()">append</a>(in ArrayBuffer data);</code></td> + </tr> + <tr> + <td><code>void <a href="/en-US/docs/Web/API/BlobBuilder#append()">append</a>(in Blob data);</code></td> + </tr> + <tr> + <td><code>void <a href="/en-US/docs/Web/API/BlobBuilder#append()">append</a>(in String data, [optional] in String endings);</code></td> + </tr> + <tr> + <td><code>Blob <a href="/en-US/docs/Web/API/BlobBuilder#getBlob()">getBlob</a>([optional] in DOMString contentType);</code></td> + </tr> + <tr> + <td><code>File <a href="/en-US/docs/Web/API/BlobBuilder#getFile()">getFile</a>(in DOMString name, [optional] in DOMString contentType);</code></td> + </tr> + </tbody> +</table> + +<h2 id="Metodos">Metodos</h2> + +<h3 id="append()">append()</h3> + +<p>Anexa el contenido del objeto javascript especificado al {{domxref("Blob")}} que esta siendo construido. Si el valor especificado no es un {{domxref("Blob")}}, <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer">ArrayBuffer</a></code>, o <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String"><code>String</code></a>, el valor es convertido a String antes de ser anexado al blob.</p> + +<pre class="syntaxbox">void append( + in ArrayBuffer data +); + +void append( + in Blob data +); + + +void append( + in String data, + [optional] in String endings +); +</pre> + +<h3 id="Parametros">Parametros</h3> + +<dl> + <dt><code>data</code></dt> + <dd>Los datos a anexar al objeto {{domxref("Blob")}} que esta siendo construido.</dd> + <dt><code>endings</code></dt> + <dd>Establece como serán escritas las cadenas que contienen <code>\n</code>. Puede ser <code>"transparent"</code> (los finales no cambian) o <code>"native"</code> (los finales cambian para coincidir a conveniencia del sistema operativo anfitrión). El valor predeterminado es <code>"transparent"</code>.</dd> +</dl> + +<h3 id="getBlob()">getBlob()</h3> + +<p>Regresa el objeto {{domxref("Blob")}} que ha sido construido usando los datos pasados atraves del método {{manch("append")}}.</p> + +<pre class="syntaxbox">Blob getBlob( + in DOMString contentType {{optional_inline}} +); +</pre> + +<h3 id="Parametros_2">Parametros</h3> + +<dl> + <dt>contentType {{optional_inline}}</dt> + <dd>El tipo MIME de los datos que seran regresados en el objeto {{domxref("Blob")}}. Esto será la propiedad tipo (Type) de los objetos <code>Blob</code>.</dd> +</dl> + +<h3 id="Valor_de_Retorno">Valor de Retorno</h3> + +<p>Un objeto {{domxref("Blob")}} conteniendo todos los datos pasados por cualquier llamada hecha al método {{manch("append")}} desde que el <code>BlobBuilder</code> fue creado. Esto tambien reinicializa el <code>BlobBuilder</code> sí que la siguiente llamada al metodo {{manch("append")}} es empezar de nuevo , un blob vacio.</p> + +<h3 id="getFile()_non-standard_inline">getFile() {{non-standard_inline}}</h3> + +<p>Retorna un objeto {{domxref("File")}}.</p> + +<pre class="syntaxbox">File getFile( + in DOMString name, + [optional] in DOMString contentType +); +</pre> + +<h3 id="Parametros_3">Parametros</h3> + +<dl> + <dt>name</dt> + <dd>El nombre del archivo.</dd> + <dt>contentType {{optional_inline}}</dt> + <dd>El tipo MIME de dats regresados en el objeto {{domxref("File")}}. Este será el valor de la propiedad tipo (type) del objeto <code>File</code>.</dd> +</dl> + +<h3 id="Valor_de_Retorno_2">Valor de Retorno</h3> + +<p>Un Objeto {{domxref("File")}}.</p> + +<h2 id="Compatibilidad_con_Nevegadores">Compatibilidad con Nevegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support (soporte básico)</td> + <td>8[1]</td> + <td>{{CompatNo}}[2]</td> + <td>10[3]</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}[1]</td> + </tr> + <tr> + <td><code>getfile()</code> {{non-standard_inline}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</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>Característica</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 (soporte básico)</td> + <td>3[1]</td> + <td>{{CompatNo}}[2]</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}[1]</td> + </tr> + <tr> + <td><code>getfile()</code> {{non-standard_inline}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] WebKit implementa el API como <code>WebKitBlobBuilder</code>, aunque es obsoleta ahora y ha hecho su soporte configurable. Actualmente Safari deshabilita esta caracteristica en Nightly, asi que probablemente no venga en la version final. Por otra parte, Chrome, que lo ha soportado desde Chrome 8, mantiene disponible esta caracteristica. Asi que Chrome podrá continuar soportando esta caracteristica. (Visita <a href="http://trac.webkit.org/changeset/115666">WebKit changeset</a> para mas detalles).</p> + +<p>[2] Gecko implementa el API como <code>MozBlobBuilder</code>. Empezando con Firefox 14, usando <code>MozBlobBuilder mostrará un mensaje de advertencia en la consola de que usar </code><code>MozBlobBuilder</code> es obsoleto y se sugiere usar el constructor {{domxref("Blob")}} en su lugar. En Gecko 18.0 esta caracteristica fue removida..</p> + +<p>[3] Trident implementa el API como <code>MSBlobBuilder</code>.</p> + +<h2 id="Vea_también">Vea también</h2> + +<ul> + <li>{{spec("http://dev.w3.org/2009/dap/file-system/file-writer.html#idl-def-BlobBuilder", "File API Specification: BlobBuilder", "ED")}}</li> + <li>{{domxref("Blob")}}</li> + <li>{{domxref("File")}}</li> +</ul> diff --git a/files/es/web/api/body/formdata/index.html b/files/es/web/api/body/formdata/index.html new file mode 100644 index 0000000000..6915954d6e --- /dev/null +++ b/files/es/web/api/body/formdata/index.html @@ -0,0 +1,72 @@ +--- +title: Body.formData() +slug: Web/API/Body/formData +tags: + - API + - BODY + - Experimental + - Fetch + - Fetch API + - FormData + - Method + - NeedsExample + - Reference +translation_of: Web/API/Body/formData +--- +<div>{{APIRef("Fetch")}}</div> + +<p>El método <strong><code>formData()</code></strong> de {{domxref("Body")}} mixin toma una cadena {{domxref("Response")}} y la lee completamente. Esto devuelve una promesa que resuelve con un objeto {{domxref("FormData")}}.</p> + +<div class="note"> +<p><strong>Nota</strong>: Esto es principalmente relevante en <a href="/en-US/docs/Web/API/ServiceWorker_API">service workers</a>. Si un usuario envia un formulario y un service worker intercepta el request, tu por ejemplo podrás llamar a <code>formData()</code> para obtener un mapeo del tipo llave-valor, modificar algunos campos, luego enviar el formulario al servidor (o utilizarlo localmente).</p> +</div> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">response.formData() +.then(function(formdata) { + // hacer algo con tu formdata +});</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<p>Ninguno.</p> + +<h3 id="Valor_de_retorno">Valor de retorno</h3> + +<p>Una {{domxref("Promise")}} que resuelve con un objeto {{domxref("FormData")}}.</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>TBD.</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('Fetch','#dom-body-formdata','formData()')}}</td> + <td>{{Spec2('Fetch')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_navegadores">Compatibilidad en navegadores</h2> + +<div class="hidden">La tabla de compatibilidad en esta página es generada por datos estructurados. Si te gustaría contribuir con los datos, por favor revisar <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> y envíanos un pull request.</div> + +<p>{{Compat("api.Body.formData")}}</p> + +<h2 id="Ver_también">Ver también</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> diff --git a/files/es/web/api/body/index.html b/files/es/web/api/body/index.html new file mode 100644 index 0000000000..3693a73653 --- /dev/null +++ b/files/es/web/api/body/index.html @@ -0,0 +1,99 @@ +--- +title: Body +slug: Web/API/Body +tags: + - API + - BODY + - Experimental + - Fetch + - Fetch API + - Interface + - NeedsTranslation + - Reference + - TopicStub + - request +translation_of: Web/API/Body +--- +<div>{{ APIRef("Fetch") }}</div> + +<p><span class="seoSummary">The <strong><code>Body</code></strong> {{glossary("mixin")}} of the <a href="/en-US/docs/Web/API/Fetch_API">Fetch API</a> represents the body of the response/request, allowing you to declare what its content type is and how it should be handled.</span></p> + +<p><code>Body</code> is implemented by both {{domxref("Request")}} and {{domxref("Response")}}. This provides these objects with an associated <dfn>body</dfn> (a <a href="/en-US/docs/Web/API/Streams_API">stream</a>), a <dfn>used flag</dfn> (initially unset), and a <dfn>MIME type</dfn> (initially the empty byte sequence).</p> + +<h2 id="Properties">Properties</h2> + +<dl> + <dt>{{domxref("Body.body")}} {{readonlyInline}}</dt> + <dd>A simple getter used to expose a {{domxref("ReadableStream")}} of the body contents.</dd> + <dt>{{domxref("Body.bodyUsed")}} {{readonlyInline}}</dt> + <dd>A {{domxref("Boolean")}} that indicates whether the body has been read.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<dl> + <dt>{{domxref("Body.arrayBuffer()")}}</dt> + <dd>Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with an {{domxref("ArrayBuffer")}}.</dd> + <dt>{{domxref("Body.blob()")}}</dt> + <dd>Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("Blob")}}.</dd> + <dt>{{domxref("Body.formData()")}}</dt> + <dd>Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("FormData")}} object.</dd> + <dt>{{domxref("Body.json()")}}</dt> + <dd>Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as {{jsxref("JSON")}}.</dd> + <dt>{{domxref("Body.text()")}}</dt> + <dd>Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("USVString")}} (text). The response is <em>always</em> decoded using UTF-8.</dd> +</dl> + +<h2 id="Examples">Examples</h2> + +<p>The example below uses a simple fetch call to grab an image and display it in an {{htmlelement("img")}} tag. You'll notice that since we are requesting an image, we need to run {{domxref("Body.blob","Body.blob()")}} ({{domxref("Response")}} implements body) to give the response its correct MIME type.</p> + +<h3 id="HTML_Content">HTML Content</h3> + +<pre class="brush: html"><img class="my-image" src="https://wikipedia.org/static/images/project-logos/frwiki-1.5x.png"> +</pre> + +<h3 id="JS_Content">JS Content</h3> + +<pre class="brush: js">const myImage = document.querySelector('.my-image'); +fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/Delete_key1.jpg') + .then(res => res.blob()) + .then(res => { + const objectURL = URL.createObjectURL(res); + myImage.src = objectURL; +});</pre> + +<p>{{ EmbedLiveSample('Examples', '100%', '250px') }}</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('Fetch','#body-mixin','Body')}}</td> + <td>{{Spec2('Fetch')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("api.Body")}}</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/body/json/index.html b/files/es/web/api/body/json/index.html new file mode 100644 index 0000000000..54c8d75d12 --- /dev/null +++ b/files/es/web/api/body/json/index.html @@ -0,0 +1,82 @@ +--- +title: Body.json() +slug: Web/API/Body/json +translation_of: Web/API/Body/json +--- +<div>{{APIRef("Fetch API")}}</div> + +<p>El método <strong><code>json()</code></strong> de {{DOMxRef("Body")}} recibe un flujo de datos {{DOMxRef("Response")}} y lo lee a término. Devuelve una promesa con el cuerpo del texto transformado a {{JSxRef("JSON")}}.</p> + +<h2 id="Sintáxis">Sintáxis</h2> + +<pre class="syntaxbox"><em>response</em>.json().then(<em>data</em> => { + // do something with your data +});</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<p>No.</p> + +<h3 id="Valor_devuelto">Valor devuelto</h3> + +<p>Una {{jsxref("Promise")}} que se resuelve a un objeto JavaScript. Este objeto puede ser cualquier cosa que pueda ser representada por JSON (un objeto, un array, una cadena de caracteres, un número...).</p> + +<h2 id="Example">Example</h2> + +<p>In our <a href="https://github.com/mdn/fetch-examples/tree/master/fetch-json">fetch json example</a> (run <a href="http://mdn.github.io/fetch-examples/fetch-json/">fetch json live</a>), we create a new request using the {{DOMxRef("Request.Request", "Request()")}} constructor, then use it to fetch a <code>.json</code> file. When the fetch is successful, we read and parse the data using <code>json()</code>, then read values out of the resulting objects as you'd expect and insert them into list items to display our product data.</p> + +<pre class="brush: js highlight[5]">const myList = document.querySelector('ul'); +const myRequest = new Request('products.json'); + +fetch(myRequest) + .then(response => response.json()) + .then(data => { + for (const product of data.products) { + let listItem = document.createElement('li'); + listItem.appendChild( + document.createElement('strong') + ).textContent = product.Name; + listItem.append( + ` can be found in ${ + product.Location + }. Cost: ` + ); + listItem.appendChild( + document.createElement('strong') + ).textContent = `£${product.Price}`; + myList.appendChild(listItem); + } + });</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("Fetch", "#dom-body-json", "Body.json()")}}</td> + <td>{{Spec2("Fetch")}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("api.Body.json")}}</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/CORS">Cross-Origin Resource Sharing (CORS)</a></li> + <li><a href="/en-US/docs/Web/HTTP">HTTP</a></li> +</ul> diff --git a/files/es/web/api/cachestorage/index.html b/files/es/web/api/cachestorage/index.html new file mode 100644 index 0000000000..fdcfe56217 --- /dev/null +++ b/files/es/web/api/cachestorage/index.html @@ -0,0 +1,198 @@ +--- +title: CacheStorage +slug: Web/API/CacheStorage +tags: + - API + - CacheStorage + - Experimental + - Interface + - NeedsTranslation + - Reference + - Service Workers + - ServiceWorker + - TopicStub +translation_of: Web/API/CacheStorage +--- +<p>{{APIRef("Service Workers API")}}</p> + +<p>The <strong><code>CacheStorage</code></strong> interface represents the storage for {{domxref("Cache")}} objects.</p> + +<p>The interface:</p> + +<ul> + <li>Provides a master directory of all the named caches that can be accessed by a {{domxref("ServiceWorker")}} or other type of worker or {{domxref("window")}} scope (you’re not limited to only using it with service workers, even though the {{SpecName('Service Workers')}} spec defines it). + <div class="note"><strong>Note</strong>: <a href="https://bugs.chromium.org/p/chromium/issues/detail?id=1026063">Chrome and Safari only expose `CacheStorage` to the windowed context over HTTPS</a>. {{domxref("window.caches")}} will be undefined unless an SSL certificate is configured.</div> + </li> + <li>Maintains a mapping of string names to corresponding {{domxref("Cache")}} objects.</li> +</ul> + +<p>Use {{domxref("CacheStorage.open()")}} to obtain a {{domxref("Cache")}} instance.</p> + +<p>Use {{domxref("CacheStorage.match()")}} to check if a given {{domxref("Request")}} is a key in any of the {{domxref("Cache")}} objects that the <code>CacheStorage</code> object tracks.</p> + +<p>You can access <code>CacheStorage</code> through the global {{domxref("WindowOrWorkerGlobalScope.caches", "caches")}} property.</p> + +<div class="note"><strong>Note</strong>: CacheStorage always rejects with a <code>SecurityError</code> on untrusted origins (i.e. those that aren't using HTTPS, although this definition will likely become more complex in the future.) When testing, you can get around this by checking the "Enable Service Workers over HTTP (when toolbox is open)" option in the Firefox Devtools options/gear menu.</div> + +<div class="note"><strong>Note</strong>: {{domxref("CacheStorage.match()")}} is a convenience method. Equivalent functionality to match a cache entry can be implemented by returning an array of cache names from {{domxref("CacheStorage.keys()")}}, opening each cache with {{domxref("CacheStorage.open()")}}, and matching the one you want with {{domxref("Cache.match()")}}.</div> + +<h2 id="Methods">Methods</h2> + +<dl> + <dt>{{domxref("CacheStorage.match()")}}</dt> + <dd>Checks if a given {{domxref("Request")}} is a key in any of the {{domxref("Cache")}} objects that the {{domxref("CacheStorage")}} object tracks, and returns a {{jsxref("Promise")}} that resolves to that match.</dd> + <dt>{{domxref("CacheStorage.has()")}}</dt> + <dd>Returns a {{jsxref("Promise")}} that resolves to <code>true</code> if a {{domxref("Cache")}} object matching the <code>cacheName</code> exists.</dd> + <dt>{{domxref("CacheStorage.open()")}}</dt> + <dd>Returns a {{jsxref("Promise")}} that resolves to the {{domxref("Cache")}} object matching the <code>cacheName</code> (a new cache is created if it doesn't already exist.)</dd> + <dt>{{domxref("CacheStorage.delete()")}}</dt> + <dd>Finds the {{domxref("Cache")}} object matching the <code>cacheName</code>, and if found, deletes the {{domxref("Cache")}} object and returns a {{jsxref("Promise")}} that resolves to <code>true</code>. If no {{domxref("Cache")}} object is found, it resolves to <code>false</code>.</dd> + <dt>{{domxref("CacheStorage.keys()")}}</dt> + <dd>Returns a {{jsxref("Promise")}} that will resolve with an array containing strings corresponding to all of the named {{domxref("Cache")}} objects tracked by the {{domxref("CacheStorage")}}. Use this method to iterate over a list of all the {{domxref("Cache")}} objects.</dd> +</dl> + +<h2 id="Examples">Examples</h2> + +<p>This code snippet is from the MDN <a href="https://github.com/mdn/sw-test/">sw-test example</a> (see <a href="https://mdn.github.io/sw-test/">sw-test running live</a>.) This service worker script waits for an {{domxref("InstallEvent")}} to fire, then runs {{domxref("ExtendableEvent.waitUntil","waitUntil")}} to handle the install process for the app. This consists of calling {{domxref("CacheStorage.open")}} to create a new cache, then using {{domxref("Cache.addAll")}} to add a series of assets to it.</p> + +<p>In the second code block, we wait for a {{domxref("FetchEvent")}} to fire. We construct a custom response like so:</p> + +<ol> + <li>Check whether a match for the request is found in the CacheStorage. If so, serve that.</li> + <li>If not, fetch the request from the network, then also open the cache created in the first block and add a clone of the request to it using {{domxref("Cache.put")}} (<code>cache.put(event.request, response.clone())</code>.)</li> + <li>If this fails (e.g. because the network is down), return a fallback response.</li> +</ol> + +<p>Finally, return whatever the custom response ended up being equal to, using {{domxref("FetchEvent.respondWith")}}.</p> + +<pre class="brush: js notranslate">self.addEventListener('install', function(event) { + event.waitUntil( + caches.open('v1').then(function(cache) { + return cache.addAll([ + '/sw-test/', + '/sw-test/index.html', + '/sw-test/style.css', + '/sw-test/app.js', + '/sw-test/image-list.js', + '/sw-test/star-wars-logo.jpg', + '/sw-test/gallery/bountyHunters.jpg', + '/sw-test/gallery/myLittleVader.jpg', + '/sw-test/gallery/snowTroopers.jpg' + ]); + }) + ); +}); + +self.addEventListener('fetch', function(event) { + event.respondWith(caches.match(event.request).then(function(response) { + // caches.match() always resolves + // but in case of success response will have value + if (response !== undefined) { + return response; + } else { + return fetch(event.request).then(function (response) { + // response may be used only once + // we need to save clone to put one copy in cache + // and serve second one + let responseClone = response.clone(); + + caches.open('v1').then(function (cache) { + cache.put(event.request, responseClone); + }); + return response; + }).catch(function () { + return caches.match('/sw-test/gallery/myLittleVader.jpg'); + }); + } + })); +}); +</pre> + +<p>This snippet shows how the API can be used outside of a service worker context, and uses the <code>await</code> operator for much more readable code.</p> + +<pre class="brush: js notranslate">// Try to get data from the cache, but fall back to fetching it live. +async function getData() { + const cacheVersion = 1; + const cacheName = `myapp-${ cacheVersion }`; + const url = 'https://jsonplaceholder.typicode.com/todos/1'; + let cachedData = await getCachedData( cacheName, url ); + + if ( cachedData ) { + console.log( 'Retrieved cached data' ); + return cachedData; + } + + console.log( 'Fetching fresh data' ); + + const cacheStorage = await caches.open( cacheName ); + await cacheStorage.add( url ); + cachedData = await getCachedData( cacheName, url ); + await deleteOldCaches( cacheName ); + + return cachedData; +} + +// Get data from the cache. +async function getCachedData( cacheName, url ) { + const cacheStorage = await caches.open( cacheName ); + const cachedResponse = await cacheStorage.match( url ); + + if ( ! cachedResponse || ! cachedResponse.ok ) { + return false; + } + + return await cachedResponse.json(); +} + +// Delete any old caches to respect user's disk space. +async function deleteOldCaches( currentCache ) { + const keys = await caches.keys(); + + for ( const key of keys ) { + const isOurCache = 'myapp-' === key.substr( 0, 6 ); + + if ( currentCache === key || ! isOurCache ) { + continue; + } + + caches.delete( key ); + } +} + +try { + const data = await getData(); + console.log( { data } ); +} catch ( error ) { + console.error( { error } ); +}</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('Service Workers', '#cachestorage', 'CacheStorage')}}</td> + <td>{{Spec2('Service Workers')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("api.CacheStorage")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker_API/Using_Service_Workers">Using Service Workers</a></li> + <li>{{domxref("Cache")}}</li> + <li>{{domxref("WindowOrWorkerGlobalScope.caches")}}</li> +</ul> diff --git a/files/es/web/api/cachestorage/keys/index.html b/files/es/web/api/cachestorage/keys/index.html new file mode 100644 index 0000000000..eee8e0e443 --- /dev/null +++ b/files/es/web/api/cachestorage/keys/index.html @@ -0,0 +1,74 @@ +--- +title: CacheStorage.keys() +slug: Web/API/CacheStorage/keys +translation_of: Web/API/CacheStorage/keys +--- +<p><font><font>{{APIRef ("API de Service Workers")}}</font></font></p> + +<p><span class="seoSummary"><font><font>El </font></font><code><strong>keys</strong></code><strong><code>()</code></strong><font><font>método de la interfaz {{domxref ("CacheStorage")}} devuelve un {{jsxref ("Promise")}} que se resolverá con una matriz que contiene las cadenas correspondientes a todos los {{domxref ("Cache")}} objetos rastreados por el objeto {{domxref ("CacheStorage")}} en el orden en que fueron creados. </font><font>Use este método para iterar sobre una lista de todos los objetos {{domxref ("Cache")}}.</font></font></span></p> + +<p><font><font>Puede acceder a </font></font><code>CacheStorage</code><font><font>través de la propiedad global {{domxref ("WindowOrWorkerGlobalScope.caches", "caches")}}.</font></font></p> + +<h2 id="Sintaxis"><font><font>Sintaxis</font></font></h2> + +<pre class="syntaxbox notranslate"><font><font>caches.keys().then(function(</font></font><em><font><font>keyList</font></font></em><font><font>) {</font></font><font><font> + // haz algo con tu keyList</font></font><font><font> +});</font></font> +</pre> + +<h3 id="Parámetros"><font><font>Parámetros</font></font></h3> + +<p><font><font>Ninguna.</font></font></p> + +<h3 id="Valor_de_retorno"><font><font>Valor de retorno</font></font></h3> + +<p>a {{jsxref("Promise")}} that resolves with an array of the {{domxref("Cache")}} names inside the {{domxref("CacheStorage")}} object.</p> + +<h2 id="Examples" style="line-height: 30px; font-size: 2.14285714285714rem;">Examples</h2> + +<p>In this code snippet we wait for an {{domxref("ServiceWorkerGlobalScope.onactivate", "activate")}} event, and then run a {{domxref("ExtendableEvent.waitUntil","waitUntil()")}} block that clears up any old, unused caches before a new service worker is activated. Here we have a whitelist containing the names of the caches we want to keep (<code>cacheWhitelist</code>). We return the keys of the caches in the {{domxref("CacheStorage")}} object using <code>keys()</code>, then check each key to see if it is in the whitelist. If not, we delete it using {{domxref("CacheStorage.delete()")}}.</p> + +<pre class="brush: js notranslate"><font><font><font><font>then.addEventListener('activar', función (evento) { </font></font></font></font><font><font><font><font> + var cacheWhitelist = ['v2']; </font></font></font></font> +<font><font><font><font> + event.waitUntil( </font></font></font></font><font><font><font><font> + caches.keys().then(function(keyList) { </font></font></font></font><font><font><font><font> + return Promise.all(keyList.map(function(key) {</font></font></font></font><font><font> + if (cacheWhitelist.indexOf(key) === -1) { + return caches.delete(<font><font>key</font></font>); + } + }); + })</font></font><font><font> + );</font></font><font><font> +});</font></font></pre> + +<h2 id="Especificaciones"><font><font>Especificaciones</font></font></h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col"><font><font>Especificación</font></font></th> + <th scope="col"><font><font>Estado</font></font></th> + <th scope="col"><font><font>Comentario</font></font></th> + </tr> + <tr> + <td><font><font>{{SpecName('Service Workers', '# dom-cachestorage-keys', 'CacheStorage: keys')}}</font></font></td> + <td><font><font>{{Spec2 ('Trabajadores de servicio')}}</font></font></td> + <td><font><font>Definición inicial</font></font></td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_del_navegador"><font><font>Compatibilidad del navegador</font></font></h2> + + + +<p><font><font>{{Compat("api.CacheStorage.keys")}}</font></font></p> + +<h2 id="Ver_también"><font><font>Ver también</font></font></h2> + +<ul> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker_API/Using_Service_Workers"><font><font>Uso de trabajadores del servicio</font></font></a></li> + <li><font><font>{{domxref("Cache")}}</font></font></li> + <li><font><font><font><font>{{domxref("WindowOrWorkerGlobalScope.caches")}}</font></font></font></font></li> +</ul> diff --git a/files/es/web/api/cameracapabilities/effects/index.html b/files/es/web/api/cameracapabilities/effects/index.html new file mode 100644 index 0000000000..1204fb0c34 --- /dev/null +++ b/files/es/web/api/cameracapabilities/effects/index.html @@ -0,0 +1,37 @@ +--- +title: CameraCapabilities.effects +slug: Web/API/CameraCapabilities/effects +translation_of: Archive/B2G_OS/API/CameraCapabilities/effects +--- +<p>{{ ApiRef() }}</p> +<p>{{ non-standard_header() }}</p> +<p>{{ B2GOnlyHeader2('certified') }}</p> +<h2 id="Resumen">Resumen</h2> +<p>El valor de la propiedad <code>effects</code> en un <code><a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array" title="/en-US/docs/JavaScript/Reference/Global_Objects/Array">Array</a></code> que identifica los efectos (tales como <code>normal</code>, <code>sepia</code>, <code>mono</code>, etc.) que soporta la camara.</p> +<h2 id="Sintaxis">Sintaxis</h2> +<pre>var effects = instanceOfCameraControl.capabilities.effects</pre> +<h2 id="Valor">Valor</h2> +<p>Devuelve un <code><a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array" title="/en-US/docs/JavaScript/Reference/Global_Objects/Array">Array</a></code> de cadenas.</p> +<h2 id="Ejemplo">Ejemplo</h2> +<pre class="brush: js">var options = { + camera: navigator.mozCameras.getListOfCameras()[0] +}; + +function onSuccess(camera) { + var effects = camera.capabilities.effects; + + effects.forEach(function (value) { + console.log(value) + }); +}; + +navigator.mozCameras.getCamera(options, onSuccess) +</pre> +<h2 id="Specification" name="Specification">Especifiacion</h2> +<p>No forma parte de ninguna especifiacion; en cualquier caso, esta API deberia ser eliminada cuando la <a class="external" href="http://dev.w3.org/2011/webrtc/editor/getusermedia.html" rel="external" title="http://dev.w3.org/2011/webrtc/editor/getusermedia.html">WebRTC Capture and Stream API</a> haya sido implementada.</p> +<h2 id="Ver_tambien">Ver tambien</h2> +<ul> + <li>{{domxref("CameraCapabilities")}}</li> + <li>{{domxref("CameraControl")}}</li> + <li>{{domxref("CameraManager")}}</li> +</ul> diff --git a/files/es/web/api/cameracapabilities/fileformats/index.html b/files/es/web/api/cameracapabilities/fileformats/index.html new file mode 100644 index 0000000000..5193200866 --- /dev/null +++ b/files/es/web/api/cameracapabilities/fileformats/index.html @@ -0,0 +1,37 @@ +--- +title: CameraCapabilities.fileFormats +slug: Web/API/CameraCapabilities/fileFormats +translation_of: Archive/B2G_OS/API/CameraCapabilities/fileFormats +--- +<p>{{ ApiRef() }}</p> +<p>{{ non-standard_header() }}</p> +<p>{{ B2GOnlyHeader2('certified') }}</p> +<h2 id="Summary">Summary</h2> +<p>La propiedad <code>fileFormats</code> es un <code><a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array" title="/en-US/docs/JavaScript/Reference/Global_Objects/Array">Array</a></code> que identifica los formatos de archivo que soporta la camara, tales como <code>jpeg</code>, <code>rgb565</code>, etc.</p> +<h2 id="Sintaxis">Sintaxis</h2> +<pre>var formats = instanceOfCameraControl.capabilities.fileFormats</pre> +<h2 id="Valor">Valor</h2> +<p>Devuelve un <code><a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array" title="/en-US/docs/JavaScript/Reference/Global_Objects/Array">Array</a></code> de cadenas.</p> +<h2 id="Ejemplo">Ejemplo</h2> +<pre class="brush: js">var options = { + camera: navigator.mozCameras.getListOfCameras()[0] +}; + +function onSuccess(camera) { + var formats = camera.capabilities.fileFormats; + + formats.forEach(function (value) { + console.log(value) + }); +}; + +navigator.mozCameras.getCamera(options, onSuccess) +</pre> +<h2 id="Specification" name="Specification">Especificacion</h2> +<p>No es parte de ninguna especificacion; en cualquier caso, esta API deberia ser eliminada cuando la <a class="external" href="http://dev.w3.org/2011/webrtc/editor/getusermedia.html" rel="external" title="http://dev.w3.org/2011/webrtc/editor/getusermedia.html">WebRTC Capture and Stream API</a> haya sido implementada.</p> +<h2 id="Ver_tambien">Ver tambien</h2> +<ul> + <li>{{domxref("CameraCapabilities")}}</li> + <li>{{domxref("CameraControl")}}</li> + <li>{{domxref("CameraManager")}}</li> +</ul> diff --git a/files/es/web/api/cameracapabilities/flashmodes/index.html b/files/es/web/api/cameracapabilities/flashmodes/index.html new file mode 100644 index 0000000000..be89eac3ac --- /dev/null +++ b/files/es/web/api/cameracapabilities/flashmodes/index.html @@ -0,0 +1,37 @@ +--- +title: CameraCapabilities.flashModes +slug: Web/API/CameraCapabilities/flashModes +translation_of: Archive/B2G_OS/API/CameraCapabilities/flashModes +--- +<p>{{ ApiRef() }}</p> +<p>{{ non-standard_header() }}</p> +<p>{{ B2GOnlyHeader2('certified') }}</p> +<h2 id="Resumen">Resumen</h2> +<p>La propiedad <code>flashModes</code> es un <code><a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array" title="/en-US/docs/JavaScript/Reference/Global_Objects/Array">Array</a></code> de cadenas que identifican cada modo de flash soportado por la camara. Los posibles valores son <code>auto</code>, <code>off</code>, <code>on</code> o <code>torch</code>.</p> +<h2 id="Sintaxis">Sintaxis</h2> +<pre>var flash = instanceOfCameraControl.capabilities.flashModes</pre> +<h2 id="Valor">Valor</h2> +<p>Devuelve un <code><a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array" title="/en-US/docs/JavaScript/Reference/Global_Objects/Array">Array</a></code> de cadenas.</p> +<h2 id="Ejemplo">Ejemplo</h2> +<pre class="brush: js">var options = { + camera: navigator.mozCameras.getListOfCameras()[0] +}; + +function onSuccess(camera) { + var flash = camera.capabilities.flashModes; + + flash.forEach(function (value) { + console.log(value) + }); +}; + +navigator.mozCameras.getCamera(options, onSuccess) +</pre> +<h2 id="Specification" name="Specification">Especifiacion</h2> +<p>No es parte de ninguna especificacion; en cualquier caso, esta API deberia ser eliminada cuando la <a class="external" href="http://dev.w3.org/2011/webrtc/editor/getusermedia.html" rel="external" title="http://dev.w3.org/2011/webrtc/editor/getusermedia.html">WebRTC Capture and Stream API</a> haya sido implementada.</p> +<h2 id="Ver_tambien">Ver tambien</h2> +<ul> + <li>{{domxref("CameraCapabilities")}}</li> + <li>{{domxref("CameraControl")}}</li> + <li>{{domxref("CameraManager")}}</li> +</ul> diff --git a/files/es/web/api/cameracapabilities/index.html b/files/es/web/api/cameracapabilities/index.html new file mode 100644 index 0000000000..a534b51ab5 --- /dev/null +++ b/files/es/web/api/cameracapabilities/index.html @@ -0,0 +1,86 @@ +--- +title: CameraCapabilities +slug: Web/API/CameraCapabilities +translation_of: Archive/B2G_OS/API/CameraCapabilities +--- +<p>{{ Apiref() }}</p> +<p>{{ non-standard_header() }}</p> +<p>{{ B2GOnlyHeader2('certified') }}</p> +<p>The {{domxref("CameraControl.capabilities")}} property returns a <code>CameraCapabilities</code> object, which describes all the camera's capabilities.</p> +<h2 id="Properties">Properties</h2> +<dl> + <dt> + {{domxref("CameraCapabilities.effects")}} {{readonlyinline}}</dt> + <dd> + An <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array" title="/en-US/docs/JavaScript/Reference/Global_Objects/Array">Array</a></code> of strings identifying the effects (such as <code>normal</code>, <code>sepia</code>, <code>mono</code>, etc.) that the camera supports.</dd> + <dt> + {{domxref("CameraCapabilities.fileFormats")}} {{readonlyinline}}</dt> + <dd> + An <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array" title="/en-US/docs/JavaScript/Reference/Global_Objects/Array">Array</a></code> of strings identifying the file formats supported by the camera, such as <code>jpeg</code>, <code>rgb565</code>, etc.</dd> + <dt> + {{domxref("CameraCapabilities.flashModes")}} {{readonlyinline}}</dt> + <dd> + An <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array" title="/en-US/docs/JavaScript/Reference/Global_Objects/Array">Array</a></code> of strings identifying each of the flash modes supported by the camera. Possible values are <code>auto</code>, <code>off</code>, <code>on</code> or <code>torch</code>.</dd> + <dt> + {{domxref("CameraCapabilities.focusModes")}} {{readonlyinline}}</dt> + <dd> + An <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array" title="/en-US/docs/JavaScript/Reference/Global_Objects/Array">Array</a></code> of strings identifying each of the focus modes supported by the camera such as auto, fixed, macro, etc.</dd> + <dt> + {{domxref("CameraCapabilities.maxExposureCompensation")}} {{readonlyinline}}</dt> + <dd> + A number that defines the maximum supported exposure compensation value.</dd> + <dt> + {{domxref("CameraCapabilities.maxFocusAreas")}} {{readonlyinline}}</dt> + <dd> + A number that defines the maximum number of focus areas supported by the camera.</dd> + <dt> + {{domxref("CameraCapabilities.maxMeteringAreas")}} {{readonlyinline}}</dt> + <dd> + A number that defines the maximum number of metering areas supported by the camera.</dd> + <dt> + {{domxref("CameraCapabilities.minExposureCompensation")}} {{readonlyinline}}</dt> + <dd> + A number that defines the minimum supported exposure compensation value.</dd> + <dt> + {{domxref("CameraCapabilities.pictureSizes")}} {{readonlyinline}}</dt> + <dd> + An <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array" title="/en-US/docs/JavaScript/Reference/Global_Objects/Array">Array</a></code> of objects containing the <code>height</code> and <code>width</code> properties supported for picture taking.</dd> + <dt> + {{domxref("CameraCapabilities.previewSizes")}} {{readonlyinline}}</dt> + <dd> + An <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array" title="/en-US/docs/JavaScript/Reference/Global_Objects/Array">Array</a></code> of objects containing the <code>height</code> and <code>width</code> properties supported for the video preview stream.</dd> + <dt> + {{domxref("CameraCapabilities.recorderProfiles")}} {{readonlyinline}}</dt> + <dd> + An object with attributes for each of the supported recorder profiles.</dd> + <dt> + {{domxref("CameraCapabilities.sceneModes")}} {{readonlyinline}}</dt> + <dd> + An <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array" title="/en-US/docs/JavaScript/Reference/Global_Objects/Array">Array</a></code> of strings identifying each of the scene modes supported by the camera such as <code>auto</code>, <code>night</code>, <code>beach</code>, etc.</dd> + <dt> + {{domxref("CameraCapabilities.stepExposureCompensation")}} {{readonlyinline}}</dt> + <dd> + A number that defines the exposure compensation minimum step-size.</dd> + <dt> + {{domxref("CameraCapabilities.videoSizes")}} {{readonlyinline}}</dt> + <dd> + An <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array" title="/en-US/docs/JavaScript/Reference/Global_Objects/Array">Array</a></code> of objects containing the <code>height</code> and <code>width</code> properties supported for video recording.</dd> + <dt> + {{domxref("CameraCapabilities.whiteBalanceModes")}} {{readonlyinline}}</dt> + <dd> + An <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array" title="/en-US/docs/JavaScript/Reference/Global_Objects/Array">Array</a></code> of strings identifiers for each white balance modes supported by the camera such as <code>auto</code>, <code>fluorecent</code>, etc.</dd> + <dt> + {{domxref("CameraCapabilities.zoomRatios")}} {{readonlyinline}}</dt> + <dd> + An <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array" title="/en-US/docs/JavaScript/Reference/Global_Objects/Array">Array</a></code> of numbers representing all the supported zoom ratios. If the camera has no zoom capabilities, the value is <code>null</code>.</dd> +</dl> +<h2 id="Methods">Methods</h2> +<p>None.</p> +<h2 id="Specification">Specification</h2> +<p>Not part of any specification; however, this API should be removed when the <a class="external" href="http://dev.w3.org/2011/webrtc/editor/getusermedia.html" rel="external" title="http://dev.w3.org/2011/webrtc/editor/getusermedia.html">WebRTC Capture and Stream API</a> has been implemented.</p> +<h2 id="See_also">See also</h2> +<ul> + <li>{{ domxref("CameraControl") }}</li> + <li>{{ domxref("CameraManager") }}</li> + <li>{{ domxref("window.navigator.mozCameras","navigator.mozCameras") }}</li> +</ul> diff --git a/files/es/web/api/cameracapabilities/maxexposurecompensation/index.html b/files/es/web/api/cameracapabilities/maxexposurecompensation/index.html new file mode 100644 index 0000000000..2baf025df3 --- /dev/null +++ b/files/es/web/api/cameracapabilities/maxexposurecompensation/index.html @@ -0,0 +1,33 @@ +--- +title: CameraCapabilities.maxExposureCompensation +slug: Web/API/CameraCapabilities/maxExposureCompensation +translation_of: Archive/B2G_OS/API/CameraCapabilities/maxExposureCompensation +--- +<p>{{ ApiRef() }}</p> +<p>{{ non-standard_header() }}</p> +<p>{{ B2GOnlyHeader2('certified') }}</p> +<h2 id="Resumen">Resumen</h2> +<p>La propiedad <code>maxExposureCompensation</code> es un número que define el valor máximo de compensación de exposición soportado.</p> +<h2 id="Sintaxis">Sintaxis</h2> +<pre>var max = instanceOfCameraControl.capabilities.maxExposureCompensation</pre> +<h2 id="Valor">Valor</h2> +<p>Devuelve un número.</p> +<h2 id="Ejemplo">Ejemplo</h2> +<pre class="brush: js">var options = { + camera: navigator.mozCameras.getListOfCameras()[0] +}; + +function onSuccess(camera) { + console.log(camera.capabilities.maxExposureCompensation); +}; + +navigator.mozCameras.getCamera(options, onSuccess) +</pre> +<h2 id="Specification" name="Specification">Especificación</h2> +<p>No forma parte de ninguna especificación; No obstante, esta API debería ser eliminada cuando la <a class="external" href="http://dev.w3.org/2011/webrtc/editor/getusermedia.html" rel="external" title="http://dev.w3.org/2011/webrtc/editor/getusermedia.html">WebRTC Capture and Stream API</a> haya sido implementada.</p> +<h2 id="Ver_también">Ver también</h2> +<ul> + <li>{{domxref("CameraCapabilities")}}</li> + <li>{{domxref("CameraControl")}}</li> + <li>{{domxref("CameraManager")}}</li> +</ul> diff --git a/files/es/web/api/cameracapabilities/maxfocusareas/index.html b/files/es/web/api/cameracapabilities/maxfocusareas/index.html new file mode 100644 index 0000000000..6d0024bebb --- /dev/null +++ b/files/es/web/api/cameracapabilities/maxfocusareas/index.html @@ -0,0 +1,33 @@ +--- +title: CameraCapabilities.maxFocusAreas +slug: Web/API/CameraCapabilities/maxFocusAreas +translation_of: Archive/B2G_OS/API/CameraCapabilities/maxFocusAreas +--- +<p>{{ Apiref() }}</p> +<p>{{ non-standard_header() }}</p> +<p>{{ B2GOnlyHeader2('certified') }}</p> +<h2 id="Resumen">Resumen</h2> +<p>La propiedad <code>maxFocusAreas</code> es un numero que define el numero maximo de areas de foco que permite la camara.</p> +<h2 id="Sintaxis">Sintaxis</h2> +<pre>var max = instanceOfCameraControl.capabilities.maxFocusAreas</pre> +<h2 id="Valor">Valor</h2> +<p>Devuelve un numero.</p> +<h2 id="Ejemplo">Ejemplo</h2> +<pre class="brush: js">var options = { + camera: navigator.mozCameras.getListOfCameras()[0] +}; + +function onSuccess(camera) { + console.log(camera.capabilities.maxFocusAreas); +}; + +navigator.mozCameras.getCamera(options, onSuccess) +</pre> +<h2 id="Specification" name="Specification">Especificacion</h2> +<p>No es parte de ninguna especificacion; en cualquier caso, esta API deberia ser eliminada cuando la <a class="external" href="http://dev.w3.org/2011/webrtc/editor/getusermedia.html" rel="external" title="http://dev.w3.org/2011/webrtc/editor/getusermedia.html">WebRTC Capture and Stream API</a> haya sido implementada.</p> +<h2 id="Ver_tambien">Ver tambien</h2> +<ul> + <li>{{domxref("CameraCapabilities")}}</li> + <li>{{domxref("CameraControl")}}</li> + <li>{{domxref("CameraManager")}}</li> +</ul> diff --git a/files/es/web/api/canvas_api/tutorial/compositing/ejemplo/index.html b/files/es/web/api/canvas_api/tutorial/compositing/ejemplo/index.html new file mode 100644 index 0000000000..b85b83238c --- /dev/null +++ b/files/es/web/api/canvas_api/tutorial/compositing/ejemplo/index.html @@ -0,0 +1,295 @@ +--- +title: Ejemplo de composición +slug: Web/API/Canvas_API/Tutorial/Compositing/Ejemplo +tags: + - Canvas + - Ejemplo + - HTML + - HTML5 + - Tutorial + - graficos +translation_of: Web/API/Canvas_API/Tutorial/Compositing/Example +--- +<div>{{CanvasSidebar}}</div> + +<p>Este programa de ejemplo muestra una cantidad de <a href="/es/docs/Web/API/CanvasRenderingContext2D.globalCompositeOperation">operaciones de composición</a>. La salida se ve así:</p> + +<p>{{EmbedLiveSample("Ejemplo_de_composición", "100%", 7250)}}</p> + +<h2 id="Ejemplo_de_composición">Ejemplo de composición</h2> + +<p>Este código establece los valores globales utilizados por el resto del programa.</p> + +<pre class="brush: js">var canvas1 = document.createElement("canvas"); +var canvas2 = document.createElement("canvas"); +var gco = [ 'source-over','source-in','source-out','source-atop', + 'destination-over','destination-in','destination-out','destination-atop', + 'lighter', 'copy','xor', 'multiply', 'screen', 'overlay', 'darken', + 'lighten', 'color-dodge', 'color-burn', 'hard-light', 'soft-light', + 'difference', 'exclusion', 'hue', 'saturation', 'color', 'luminosity' + ].reverse(); +var gcoText = [ +'Esta es la configuración predeterminada y dibuja nuevas formas sobre el contenido del canvas existente.', +'La nueva forma se dibuja solo donde la nueva forma y el canvas de destino se superponen. Todo lo demás se hace transparente.', +'La nueva forma se dibuja donde no se superpone al contenido del canvas existente.', +'La nueva forma solo se dibuja donde se solapa con el contenido del canvas existente.', +'Se dibujan nuevas formas detrás del contenido del canvas existente', +'El contenido del canvas existente se conserva donde la nueva forma y el contenido del canvas existente se superponen. Todo lo demás se hace transparente.', +'El contenido existente se mantiene donde no se superpone a la nueva forma.', +'El canvas existente solo se conserva donde se solapa con la nueva forma. La nueva forma se dibuja detrás del contenido del canvas.', +'Donde ambas formas se superponen, el color se determina agregando valores de color.', +'Solo se muestra la nueva forma.', +'Las formas se hacen transparentes donde ambas se superponen y se dibujan de manera normal en cualquier otro lugar.', +'Los píxeles de la capa superior se multiplican con el píxel correspondiente de la capa inferior. El resultado es una imagen más oscura. ', +'Los píxeles están invertidos, multiplicados e invertidos nuevamente. Una imagen más clara es el resultado (opuesto a multiplicar).', +'Una combinación de multiplicar y pantalla. Las partes oscuras en la capa base se oscurecen y las partes claras se vuelven más claras.', +'Conserva los píxeles más oscuros de ambas capas.', +'Conserva los píxeles más claros de ambas capas.', +'Divide la capa inferior por la capa superior invertida.', +'Divide la capa inferior invertida por la capa superior, y luego invierte el resultado.', +'Una combinación de multiplicar y pantalla como superposición, pero con la parte superior y la capa inferior intercambiado.', +'Una versión más suave de la luz dura. Negro puro o blanco no da como resultado negro o blanco puro.', +'Resta la capa inferior de la capa superior o viceversa para obtener siempre un valor positivo.', +'Al igual que la diferencia, pero con menor contraste.', +'Conserva la luma y el croma de la capa inferior, mientras adopta el tono de la capa superior.', +'Conserva la luma y el tono de la capa inferior, mientras adopta el croma de la capa superior.', +'Conserva la luma de la capa inferior, mientras adopta el matiz y el croma de la capa superior.', +'Conserva el tono y el croma de la capa inferior, mientras adopta la luma de la capa superior.' + ].reverse(); +var width = 320; +var height = 340; +</pre> + +<h3 id="Programa_principal">Programa principal</h3> + +<p>Cuando se carga la página, este código se ejecuta para configurar y ejecutar el ejemplo:</p> + +<pre class="brush: js">window.onload = function() { + // lum en sRGB + var lum = { + r: 0.33, + g: 0.33, + b: 0.33 + }; + // redimensionar canvas + canvas1.width = width; + canvas1.height = height; + canvas2.width = width; + canvas2.height = height; + lightMix() + colorSphere(); + runComposite(); + return; +}; +</pre> + +<p>Y este código, <code>runComposite()</code>, maneja la mayor parte del trabajo, dependiendo de una serie de funciones de utilidad para hacer las partes difíciles.</p> + +<pre class="brush: js">function createCanvas() { + var canvas = document.createElement("canvas"); + canvas.style.background = "url("+op_8x8.data+")"; + canvas.style.border = "1px solid #000"; + canvas.style.margin = "5px"; + canvas.width = width/2; + canvas.height = height/2; + return canvas; +} + +function runComposite() { + var dl = document.createElement("dl"); + document.body.appendChild(dl); + while(gco.length) { + var pop = gco.pop(); + var dt = document.createElement("dt"); + dt.textContent = pop; + dl.appendChild(dt); + var dd = document.createElement("dd"); + var p = document.createElement("p"); + p.textContent = gcoText.pop(); + dd.appendChild(p); + + var canvasToDrawOn = createCanvas(); + var canvasToDrawFrom = createCanvas(); + var canvasToDrawResult = createCanvas(); + + var ctx = canvasToDrawResult.getContext('2d'); + ctx.clearRect(0, 0, width, height) + ctx.save(); + ctx.drawImage(canvas1, 0, 0, width/2, height/2); + ctx.globalCompositeOperation = pop; + ctx.drawImage(canvas2, 0, 0, width/2, height/2); + ctx.globalCompositeOperation = "source-over"; + ctx.fillStyle = "rgba(0,0,0,0.8)"; + ctx.fillRect(0, height/2 - 20, width/2, 20); + ctx.fillStyle = "#FFF"; + ctx.font = "14px arial"; + ctx.fillText(pop, 5, height/2 - 5); + ctx.restore(); + + var ctx = canvasToDrawOn.getContext('2d'); + ctx.clearRect(0, 0, width, height) + ctx.save(); + ctx.drawImage(canvas1, 0, 0, width/2, height/2); + ctx.fillStyle = "rgba(0,0,0,0.8)"; + ctx.fillRect(0, height/2 - 20, width/2, 20); + ctx.fillStyle = "#FFF"; + ctx.font = "14px arial"; + ctx.fillText('existing content', 5, height/2 - 5); + ctx.restore(); + + var ctx = canvasToDrawFrom.getContext('2d'); + ctx.clearRect(0, 0, width, height) + ctx.save(); + ctx.drawImage(canvas2, 0, 0, width/2, height/2); + ctx.fillStyle = "rgba(0,0,0,0.8)"; + ctx.fillRect(0, height/2 - 20, width/2, 20); + ctx.fillStyle = "#FFF"; + ctx.font = "14px arial"; + ctx.fillText('new content', 5, height/2 - 5); + ctx.restore(); + + dd.appendChild(canvasToDrawOn); + dd.appendChild(canvasToDrawFrom); + dd.appendChild(canvasToDrawResult); + + dl.appendChild(dd); + } +}; +</pre> + +<h3 id="Funciones_de_utilidad">Funciones de utilidad</h3> + +<p>El programa se basa en una serie de funciones de utilidad.</p> + +<pre class="brush: js">var lightMix = function() { + var ctx = canvas2.getContext("2d"); + ctx.save(); + ctx.globalCompositeOperation = "lighter"; + ctx.beginPath(); + ctx.fillStyle = "rgba(255,0,0,1)"; + ctx.arc(100, 200, 100, Math.PI*2, 0, false); + ctx.fill() + ctx.beginPath(); + ctx.fillStyle = "rgba(0,0,255,1)"; + ctx.arc(220, 200, 100, Math.PI*2, 0, false); + ctx.fill() + ctx.beginPath(); + ctx.fillStyle = "rgba(0,255,0,1)"; + ctx.arc(160, 100, 100, Math.PI*2, 0, false); + ctx.fill(); + ctx.restore(); + ctx.beginPath(); + ctx.fillStyle = "#f00"; + ctx.fillRect(0,0,30,30) + ctx.fill(); +}; +</pre> + +<pre class="brush: js">var colorSphere = function(element) { + var ctx = canvas1.getContext("2d"); + var width = 360; + var halfWidth = width / 2; + var rotate = (1 / 360) * Math.PI * 2; // por grado + var offset = 0; // scrollbar offset + var oleft = -20; + var otop = -20; + for (var n = 0; n <= 359; n ++) { + var gradient = ctx.createLinearGradient(oleft + halfWidth, otop, oleft + halfWidth, otop + halfWidth); + var color = Color.HSV_RGB({ H: (n + 300) % 360, S: 100, V: 100 }); + gradient.addColorStop(0, "rgba(0,0,0,0)"); + gradient.addColorStop(0.7, "rgba("+color.R+","+color.G+","+color.B+",1)"); + gradient.addColorStop(1, "rgba(255,255,255,1)"); + ctx.beginPath(); + ctx.moveTo(oleft + halfWidth, otop); + ctx.lineTo(oleft + halfWidth, otop + halfWidth); + ctx.lineTo(oleft + halfWidth + 6, otop); + ctx.fillStyle = gradient; + ctx.fill(); + ctx.translate(oleft + halfWidth, otop + halfWidth); + ctx.rotate(rotate); + ctx.translate(-(oleft + halfWidth), -(otop + halfWidth)); + } + ctx.beginPath(); + ctx.fillStyle = "#00f"; + ctx.fillRect(15,15,30,30) + ctx.fill(); + return ctx.canvas; +}; +</pre> + +<pre class="brush: js">// HSV (1978) = H: Hue / S: Saturation / V: Value +Color = {}; +Color.HSV_RGB = function (o) { + var H = o.H / 360, + S = o.S / 100, + V = o.V / 100, + R, G, B; + var A, B, C, D; + if (S == 0) { + R = G = B = Math.round(V * 255); + } else { + if (H >= 1) H = 0; + H = 6 * H; + D = H - Math.floor(H); + A = Math.round(255 * V * (1 - S)); + B = Math.round(255 * V * (1 - (S * D))); + C = Math.round(255 * V * (1 - (S * (1 - D)))); + V = Math.round(255 * V); + switch (Math.floor(H)) { + case 0: + R = V; + G = C; + B = A; + break; + case 1: + R = B; + G = V; + B = A; + break; + case 2: + R = A; + G = V; + B = C; + break; + case 3: + R = A; + G = B; + B = V; + break; + case 4: + R = C; + G = A; + B = V; + break; + case 5: + R = V; + G = A; + B = B; + break; + } + } + return { + R: R, + G: G, + B: B + }; +}; + +var createInterlace = function (size, color1, color2) { + var proto = document.createElement("canvas").getContext("2d"); + proto.canvas.width = size * 2; + proto.canvas.height = size * 2; + proto.fillStyle = color1; // top-left + proto.fillRect(0, 0, size, size); + proto.fillStyle = color2; // top-right + proto.fillRect(size, 0, size, size); + proto.fillStyle = color2; // bottom-left + proto.fillRect(0, size, size, size); + proto.fillStyle = color1; // bottom-right + proto.fillRect(size, size, size, size); + var pattern = proto.createPattern(proto.canvas, "repeat"); + pattern.data = proto.canvas.toDataURL(); + return pattern; +}; + +var op_8x8 = createInterlace(8, "#FFF", "#eee");</pre> diff --git a/files/es/web/api/canvas_api/tutorial/compositing/index.html b/files/es/web/api/canvas_api/tutorial/compositing/index.html new file mode 100644 index 0000000000..1d45712fd4 --- /dev/null +++ b/files/es/web/api/canvas_api/tutorial/compositing/index.html @@ -0,0 +1,117 @@ +--- +title: Compositing and clipping +slug: Web/API/Canvas_API/Tutorial/Compositing +tags: + - Canvas + - Graphics + - HTML + - HTML5 + - Intermediate + - Lienzo + - NeedsTranslation + - Recorte + - TopicStub + - Tutorial +translation_of: Web/API/Canvas_API/Tutorial/Compositing +--- +<div>{{CanvasSidebar}} {{PreviousNext("Web/API/Canvas_API/Tutorial/Transformations", "Web/API/Canvas_API/Tutorial/Basic_animations")}}</div> + +<div class="summary"> +<p>En todos nuestros <a href="/en-US/docs/Web/API/Canvas_API/Tutorial/Transformations">ejemplos a</a>nteriores, las formas siempre fueron dibujadas una encima de la anterior. Estos es más que adecuado para la mayoría de las situaciones pero se limita al orden compuesto de las figuras. Podemos, sin embargo, cambiar este comportamiento estableciendo el valor de la propiedad <code>globalCompositeOperation</code>. Además, la proeidad <code>clip</code> nos permite ocultar partes de figuras que no queremos mostrar.</p> +</div> + +<h2 id="globalCompositeOperation" name="globalCompositeOperation"><code>globalCompositeOperation</code></h2> + +<p>No solo podemos dibujar formas nuevas detrás de las ya existentes sino que las podemos utilizar para enmascarar ciertas áreas, limpiar secciones del lienzo (canvas no se limita a utilizar rectángulos como en el método {{domxref("CanvasRenderingContext2D.clearRect", "clearRect()")}}) y algunas cosas más.</p> + +<dl> + <dt>{{domxref("CanvasRenderingContext2D.globalCompositeOperation", "globalCompositeOperation = type")}}</dt> + <dd>Esto establece el tipo de operación compuesta a aplicar cuando se dibujan nuevas figuras, en donde tipo (type) es una cadena de caracteres que identifica cual de las doce operaciones compuestas se utilizará.</dd> +</dl> + +<p>Vea <a href="/en-US/docs/Web/API/Canvas_API/Tutorial/Compositing/Example">ejemplos de composición</a> para el código de los siguientes ejemplos.</p> + +<p>{{EmbedLiveSample("Compositing_example", 750, 6750, "" ,"Web/API/Canvas_API/Tutorial/Compositing/Example")}}</p> + +<h2 id="Clipping_paths" name="Clipping_paths">Trazado de Recorte</h2> + +<p><img alt="" class="internal" src="https://mdn.mozillademos.org/files/209/Canvas_clipping_path.png" style="float: right;">Un trazado de recoirte es como una figura normal en el lienzo pero actúa como una máscara para ocultar las partes de la misma que no se quieren mostrar. Este efecto se muestra en la figura de la derecha. La estrella roja es nuestro trazado de recorte. Todo lo que cae fuera de este trazado no se dibujará en el lienzo.</p> + +<p>Si comparamos el trazado de recorte con la propiedad <code>globalCompositeOperation</code> que hemos visto antes, vemos dos modos compuestos que logran mas o menos los mismos efectos en <code>source-in</code> y <code>source-atop</code>. Las diferencias mas importantes entre éstos dos son que el trazado de recorte no dibujan nunca en el lienzo y que nunca se afecta por agregar nuevas figuras. Esto vuelve al trazado de recorte ideal para dibujar múltiples figuras en un área delimitada.</p> + +<p>En el capítulo acerca de <a href="/en-US/docs/Web/API/Canvas_API/Tutorial/Drawing_shapes" title="Web/Guide/HTML/Canvas_tutorial/Drawing_shapes#Drawing_paths">dibujo de figuras</a> solo menciono a los métodos <code>stroke()</code> y <code>fill()</code> pero existe un tercer método que se usa para trazados llamado <code>clip()</code>.</p> + +<dl> + <dt>{{domxref("CanvasRenderingContext2D.clip", "clip()")}}</dt> + <dd>Convierte al trazado en ejecución a un trazado de recorte.</dd> +</dl> + +<p>Se utiliza <code>clip()</code> en lugar de <code>closePath()</code> para cerrar el trazado y volverlo uno de recorte, en vez de marcar (stroke) o rellenar el trazado.</p> + +<p>Por edfecto el elemento {{HTMLElement("canvas")}} tiene un trazado de recorte que es de extacamente el mismo tamaño del propio lienzo. En otras palabras, la máscara de recorte (clipping) no se da.</p> + +<h3 id="A_clip_example" name="A_clip_example">Un ejemplo de <code>clip</code></h3> + +<p>En este ejemplo, utilizamos un trazado de recorte de forma circular para restringir el dibujo de un conjunto de estrellas aleatorias dentro de una región particular del lienzo.</p> + +<pre class="brush: js;highlight[9] notranslate">function dibuja() { + var ctx = document.getElementById('lienzo').getContext('2d'); + ctx.fillRect(0, 0, 150, 150); + ctx.translate(75, 75); + + // crear un trazado de corte de forma circular + ctx.beginPath(); + ctx.arc(0, 0, 60, 0, Math.PI * 2, true); + ctx.clip(); + + // pinta el fondo + var lingrad = ctx.createLinearGradient(0, -75, 0, 75); + lingrad.addColorStop(0, '#232256'); + lingrad.addColorStop(1, '#143778'); + + ctx.fillStyle = lingrad; + ctx.fillRect(-75, -75, 150, 150); + + // dibuja las estrellas + for (var j = 1; j < 50; j++) { + ctx.save(); + ctx.fillStyle = '#fff'; + ctx.translate(75 - Math.floor(Math.random() * 150), + 75 - Math.floor(Math.random() * 150)); + dibulaEstrella(ctx, Math.floor(Math.random() * 4) + 2); + ctx.restore(); + } + +} + +function dibujaEstrella(ctx, r) { + ctx.save(); + ctx.beginPath(); + ctx.moveTo(r, 0); + for (var i = 0; i < 9; i++) { + ctx.rotate(Math.PI / 5); + if (i % 2 === 0) { + ctx.lineTo((r / 0.525731) * 0.200811, 0); + } else { + ctx.lineTo(r, 0); + } + } + ctx.closePath(); + ctx.fill(); + ctx.restore(); +} +</pre> + +<div class="hidden"> +<pre class="brush: html notranslate"><canvas id="lienzo" width="150" height="150"></canvas></pre> + +<pre class="brush: js notranslate">dibuja();</pre> +</div> + +<p>En las primeras líneas de código, dibujamos un rectángulo negro del tamaño del lienzo como telón de fondo, luego trasladamos el origen del mismo al centro. A continuación, creamos un trazado de recorte de forma circular, a través de dibujar un arco y mediante la llamada a <code>clip()</code>. El recorte también es parte del estado guardado del lienzo. Si queremos mantener el recorte original, podríamos haber guardado el estado anterior del lienzo justo antes de que creamos el nuevo.</p> + +<p>Todo lo que se dibuja después de crear un recorte aparecerá dentro de su trazado. Se puede ver claramente esto en el dibujo de gradiente lineal que realizamos a continuación. Después se ubican estrellas en 50 posiciones alteatorias y escaladas utilizando la función <code>drawStar()</code>. Una vez más, las estrellas solo aparecen dentro del recorte trazado en el lienzo.</p> + +<p>{{EmbedLiveSample("A_clip_example", "180", "180", "https://mdn.mozillademos.org/files/208/Canvas_clip.png")}}</p> + +<p>{{PreviousNext("Web/API/Canvas_API/Tutorial/Transformations", "Web/API/Canvas_API/Tutorial/Basic_animations")}}</p> diff --git a/files/es/web/api/canvasimagesource/index.html b/files/es/web/api/canvasimagesource/index.html new file mode 100644 index 0000000000..bf143d9335 --- /dev/null +++ b/files/es/web/api/canvasimagesource/index.html @@ -0,0 +1,42 @@ +--- +title: CanvasImageSource +slug: Web/API/CanvasImageSource +tags: + - API + - Auxiliar + - Canvas + - Referencia +translation_of: Web/API/CanvasImageSource +--- +<p>{{APIRef("Canvas API")}}</p> + +<p>El tipo auxiliar <code><strong>CanvasImageSource</strong></code> representa cualquiera de los siguientes tipos:</p> + +<ul> + <li>{{domxref("CSSImageValue")}}</li> + <li>{{domxref("HTMLImageElement")}}</li> + <li>{{domxref("SVGImageElement")}}</li> + <li>{{domxref("HTMLVideoElement")}}</li> + <li>{{domxref("HTMLCanvasElement")}}</li> + <li>{{domxref("ImageBitmap")}}</li> + <li>{{domxref("OffscreenCanvas")}}</li> +</ul> + +<p>Este es un tipo auxiliar usado para simplificar la especificación, no es una interfáz y por ello no hay objetos implementandolo.</p> + +<h2 id="Especificaciones">Especificaciones</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#canvasimagesource", "CanvasImageSource")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> diff --git a/files/es/web/api/canvasrenderingcontext2d/arc/index.html b/files/es/web/api/canvasrenderingcontext2d/arc/index.html new file mode 100644 index 0000000000..db4803a7ab --- /dev/null +++ b/files/es/web/api/canvasrenderingcontext2d/arc/index.html @@ -0,0 +1,226 @@ +--- +title: CanvasRenderingContext2D.arc() +slug: Web/API/CanvasRenderingContext2D/arc +translation_of: Web/API/CanvasRenderingContext2D/arc +--- +<div>{{APIRef}}</div> + +<p><span class="notranslate">El método <code><strong>CanvasRenderingContext2D</strong></code> <strong><code>.arc()</code></strong> de la API de Canvas 2D añade un arco a la trayectoria centrada en la posición <em>(x, y)</em> con el radio <em>r</em> comenzando en <em>startAngle</em> y terminando en <em>endAngle que</em> va en la dirección dada en sentido <em>antihorario</em> (predeterminado en sentido horario) .</span></p> + +<h2 id="Sintaxis"><span class="highlight-span"><span class="notranslate">Sintaxis</span></span></h2> + +<pre class="syntaxbox"><span class="notranslate"><var>Void <em>ctx</em> .arc (x, y, radio, startAngle, endAngle, antihorario);</var></span></pre> + +<h3 id="Parámetros"><span class="notranslate">Parámetros</span></h3> + +<dl> + <dt><code>x</code></dt> + <dd><span class="notranslate">La coordenada x del centro del arco.</span></dd> + <dt><code>y</code></dt> + <dd><span class="notranslate">La coordenada y del centro del arco.</span></dd> + <dt><code>radius</code></dt> + <dd><span class="notranslate">El radio del arco.</span></dd> + <dt><code>startAngle</code></dt> + <dd><span class="notranslate">El ángulo en el que se inicia el arco, medido en sentido horario desde el eje x positivo y expresado en radianes.</span></dd> + <dt><code>endAngle</code></dt> + <dd><span class="notranslate">El ángulo en el que termina el arco, medido en sentido horario desde el eje x positivo y expresado en radianes.</span></dd> + <dt><span class="notranslate"><code>anticlockwise</code> <span class="inlineIndicator optional optionalInline">Opcional</span></span></dt> + <dd><span class="notranslate">Un <a href="https://translate.googleusercontent.com/translate_c?depth=1&hl=es&rurl=translate.google.com&sl=auto&sp=nmt4&tl=es&u=https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean&usg=ALkJrhiYmhdjPGE_uAW2GdnX2VQcrdMSOA" title="El objeto booleano es un contenedor de objetos para un valor booleano."><code>Boolean</code></a> opcional que, si es <code>true</code> , hace que el arco se dibuje en sentido contrario a las agujas del reloj entre los dos ángulos.</span> <span class="notranslate"> De forma predeterminada, se dibuja en el sentido de las agujas del reloj.</span></dd> +</dl> + +<h2 id="Ejemplos"><span class="highlight-span"><span class="notranslate">Ejemplos</span></span></h2> + +<h3 id="Using_the_arc_method" name="Using_the_arc_method"><span class="notranslate">Utilizando el método del <code>arc</code></span></h3> + +<p><span class="notranslate">Esto es sólo un simple fragmento de código dibujando un círculo.</span></p> + +<h4 id="HTML">HTML</h4> + +<pre class="brush: html"><canvas id="canvas"></canvas> +</pre> + +<h4 id="JavaScript">JavaScript</h4> + +<pre class="brush: js">var canvas = document.getElementById('canvas'); +var ctx = canvas.getContext('2d'); + +ctx.beginPath(); +ctx.arc(75, 75, 50, 0, 2 * Math.PI); +ctx.stroke(); +</pre> + +<p><span class="notranslate">Edite el código de abajo y vea su actualización de cambios en vivo en el lienzo:</span></p> + +<div style="display: none;"> +<h6 id="Playable_code" name="Playable_code">Playable code</h6> + +<pre class="brush: html"><canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas> +<div class="playable-buttons"> + <input id="edit" type="button" value="Edit" /> + <input id="reset" type="button" value="Reset" /> +</div> +<textarea id="code" class="playable-code"> +ctx.beginPath(); +ctx.arc(50, 50, 50, 0, 2 * Math.PI, false); +ctx.stroke();</textarea> +</pre> + +<pre class="brush: js">var canvas = document.getElementById("canvas"); +var ctx = canvas.getContext("2d"); +var textarea = document.getElementById("code"); +var reset = document.getElementById("reset"); +var edit = document.getElementById("edit"); +var code = textarea.value; + +function drawCanvas() { + ctx.clearRect(0, 0, canvas.width, canvas.height); + eval(textarea.value); +} + +reset.addEventListener("click", function() { + textarea.value = code; + drawCanvas(); +}); + +edit.addEventListener("click", function() { + textarea.focus(); +}) + +textarea.addEventListener("input", drawCanvas); +window.addEventListener("load", drawCanvas); +</pre> +</div> + +<p>{{ EmbedLiveSample('Playable_code', 700, 360) }}</p> + +<h3 id="Different_shapes_demonstrated" name="Different_shapes_demonstrated"><span class="notranslate">Diferentes formas demostradas</span></h3> + +<p><span class="notranslate">En este ejemplo se dibujan diferentes formas para mostrar lo que es posible al usar <code>arc()</code> .</span></p> + +<div style="display: none;"> +<h6 id="HTML_2">HTML</h6> + +<pre class="brush: html"><canvas id="canvas" width="150" height="200"></canvas> +</pre> + +<h6 id="JavaScript_2">JavaScript</h6> +</div> + +<pre class="brush: js">var canvas = document.getElementById('canvas'); +var ctx = canvas.getContext('2d'); + +// Draw shapes +for (var i = 0; i < 4; i++) { + for(var j = 0; j < 3; j++) { + ctx.beginPath(); + var x = 25 + j * 50; // x coordinate + var y = 25 + i * 50; // y coordinate + var radius = 20; // Arc radius + var startAngle = 0; // Starting point on circle + var endAngle = Math.PI + (Math.PI * j) /2; // End point on circle + var anticlockwise = i % 2 == 1; // Draw anticlockwise + + ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise); + + if (i > 1) { + ctx.fill(); + } else { + ctx.stroke(); + } + } +}</pre> + +<p>{{ EmbedLiveSample('Different_shapes_demonstrated', 160, 210, "https://mdn.mozillademos.org/files/204/Canvas_arc.png") }}</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col"><span class="notranslate">Especificación</span></th> + <th scope="col"><span class="notranslate">Estado</span></th> + <th scope="col"><span class="notranslate">Comentario</span></th> + <td><span class="notranslate"><a class="external external-icon" href="https://translate.googleusercontent.com/translate_c?depth=1&hl=es&rurl=translate.google.com&sl=auto&sp=nmt4&tl=es&u=https://html.spec.whatwg.org/multipage/scripting.html&usg=ALkJrhjTH2Ij7ayPxhvtaZrELWW-GupMRw#dom-context-2d-arc" hreflang="en" lang="en">WHATWG HTML Estándar de vida</a></span><br> + <span class="notranslate"><a class="external external-icon" href="https://translate.googleusercontent.com/translate_c?depth=1&hl=es&rurl=translate.google.com&sl=auto&sp=nmt4&tl=es&u=https://html.spec.whatwg.org/multipage/scripting.html&usg=ALkJrhjTH2Ij7ayPxhvtaZrELWW-GupMRw#dom-context-2d-arc" hreflang="en" lang="en"><small lang="en-US">La definición de 'CanvasRenderingContext2D.arc' en esa especificación.</small></a></span></td> + <td><span class="notranslate"><span class="spec-Living">Estándar de vida</span></span></td> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-arc", "CanvasRenderingContext2D.arc")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_del_navegador"><span class="highlight-span"><span class="notranslate">Compatibilidad del navegador</span></span></h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</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>Chrome for Android</th> + <th>Edge</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}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 class="highlight-spanned" id="Notas_específicas_de_Gecko"><span class="highlight-span"><span class="notranslate">Notas específicas de Gecko</span> </span></h2> + +<p><span class="notranslate">Comenzando con Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1):</span></p> + +<ul> + <li><span class="notranslate">El parámetro <code>anticlockwise</code> es opcional,</span></li> + <li><span class="notranslate">Especificar un radio negativo ahora arroja un error <a href="https://translate.googleusercontent.com/translate_c?depth=1&hl=es&rurl=translate.google.com&sl=auto&sp=nmt4&tl=es&u=https://developer.mozilla.org/en-US/docs/Web/API/DOMError&usg=ALkJrhjJXFH50zmUpD4NUbH_0bFfrCdTxg" title="La interfaz DOMError describe un objeto de error que contiene un nombre de error."><code>IndexSizeError</code></a> ("Índice o tamaño es negativo o mayor que la cantidad permitida").</span></li> +</ul> + +<h2 class="highlight-spanned" id="Ver_también"><span class="highlight-span"><span class="notranslate">Ver también</span> </span></h2> + +<ul> + <li><span class="notranslate">La interfaz que lo define, <a href="https://translate.googleusercontent.com/translate_c?depth=1&hl=es&rurl=translate.google.com&sl=auto&sp=nmt4&tl=es&u=https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D&usg=ALkJrhi38xECKVHgn-8Z40wUeE-veK4pog" title='Para obtener un objeto de esta interfaz, llame a getContext () en un elemento &lt;canvas>, proporcionando "2d" como argumento:'><code>CanvasRenderingContext2D</code></a></span></li> +</ul> diff --git a/files/es/web/api/canvasrenderingcontext2d/beginpath/index.html b/files/es/web/api/canvasrenderingcontext2d/beginpath/index.html new file mode 100644 index 0000000000..1c91e264f4 --- /dev/null +++ b/files/es/web/api/canvasrenderingcontext2d/beginpath/index.html @@ -0,0 +1,180 @@ +--- +title: CanvasRenderingContext2D.beginPath() +slug: Web/API/CanvasRenderingContext2D/beginPath +tags: + - API + - Canvas + - CanvasRenderingContext2D + - Referencia + - metodo +translation_of: Web/API/CanvasRenderingContext2D/beginPath +--- +<div>{{APIRef}}</div> + +<p>El método <code><strong>CanvasRenderingContext2D</strong></code><strong><code>.beginPath() </code></strong>del API Canvas 2D comienza una nueva ruta vaciando la lista de sub-rutas. Invoca este método cuando quieras crear una nueva ruta. </p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">void <var><em>ctx</em>.beginPath();</var> +</pre> + +<h2 id="Ejemplos">Ejemplos</h2> + +<h3 id="Usando_el_método_beginPath">Usando el método <code>beginPath</code></h3> + +<p>Este es solo un trozo de código el cual usa el método <code>beginPath</code>.</p> + +<h4 id="HTML">HTML</h4> + +<pre class="brush: html"><canvas id="canvas"></canvas> +</pre> + +<h4 id="JavaScript">JavaScript</h4> + +<pre class="brush: js; highlight:[5,12]">var canvas = document.getElementById("canvas"); +var ctx = canvas.getContext("2d"); + +// First path +ctx.beginPath(); +ctx.strokeStyle = 'blue'; +ctx.moveTo(20,20); +ctx.lineTo(200,20); +ctx.stroke(); + +// Second path +ctx.beginPath(); +ctx.strokeStyle = 'green'; +ctx.moveTo(20,20); +ctx.lineTo(120,120); +ctx.stroke(); +</pre> + +<p>Edita el código aquí debajo y mira tus cambios actualizarse en vivo en el canvas:</p> + +<div style="display: none;"> +<h6 id="Playable_code">Playable code</h6> + +<pre class="brush: html"><canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas> +<div class="playable-buttons"> + <input id="edit" type="button" value="Edit" /> + <input id="reset" type="button" value="Reset" /> +</div> +<textarea id="code" class="playable-code" style="height:200px"> +// First path +ctx.beginPath(); +ctx.strokeStyle = 'blue'; +ctx.moveTo(20,20); +ctx.lineTo(200,20); +ctx.stroke(); + +// Second path +ctx.beginPath(); +ctx.strokeStyle = 'green'; +ctx.moveTo(20,20); +ctx.lineTo(120, 120); +ctx.stroke();</textarea> +</pre> + +<pre class="brush: js">var canvas = document.getElementById("canvas"); +var ctx = canvas.getContext("2d"); +var textarea = document.getElementById("code"); +var reset = document.getElementById("reset"); +var edit = document.getElementById("edit"); +var code = textarea.value; + +function drawCanvas() { + ctx.clearRect(0, 0, canvas.width, canvas.height); + eval(textarea.value); +} + +reset.addEventListener("click", function() { + textarea.value = code; + drawCanvas(); +}); + +edit.addEventListener("click", function() { + textarea.focus(); +}) + +textarea.addEventListener("input", drawCanvas); +window.addEventListener("load", drawCanvas); +</pre> +</div> + +<p>{{ EmbedLiveSample('Playable_code', 700, 460) }}</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estatus</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-beginpath", "CanvasRenderingContext2D.beginPath")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_los_navegadores">Compatibilidad de los navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Chrome para 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}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>The interface defining it, {{domxref("CanvasRenderingContext2D")}}</li> + <li>{{domxref("CanvasRenderingContext2D.closePath()")}}</li> +</ul> diff --git a/files/es/web/api/canvasrenderingcontext2d/clearrect/index.html b/files/es/web/api/canvasrenderingcontext2d/clearrect/index.html new file mode 100644 index 0000000000..64aa1a3908 --- /dev/null +++ b/files/es/web/api/canvasrenderingcontext2d/clearrect/index.html @@ -0,0 +1,203 @@ +--- +title: CanvasRenderingContext2D.clearRect() +slug: Web/API/CanvasRenderingContext2D/clearRect +translation_of: Web/API/CanvasRenderingContext2D/clearRect +--- +<div>{{APIRef}}</div> + +<div>El método <code><strong>CanvasRenderingContext2D</strong></code><strong><code>.clearRect() </code></strong><code>del API Canvas 2D convierte todos los pixeles en el rectangulo definido por el punto de inicio<em> (x, y) </em>y tamaño </code><em>(width, height)</em> a negro transparente, borrando cualquier contenido dibujado anteriormente.</div> + +<div> </div> + +<h2 id="Syntaxis">Syntaxis</h2> + +<div> +<h3 id="HTML_Content">HTML Content</h3> + +<pre class="brush: html">void <var><em>ctx</em>.clearRect(x, y, width, height);</var></pre> + +<h3 id="Parametros">Parametros</h3> + +<dl> + <dt><strong>x</strong></dt> + <dd>El eje <strong>x </strong> de la coordenada para el punto de inicio del rectangulo.</dd> + <dt>y</dt> + <dd>El eje <strong>y </strong> de la coordenada para el punto de inicio del rectangulo.</dd> + <dt>width</dt> + <dd>El ancho del rectangulo.</dd> + <dt>heigth</dt> + <dd>el alto del rectangulo.</dd> +</dl> + +<h2 id="Notas_de_uso">Notas de uso</h2> + +<p>Un problema común con <strong><code>clearRect </code></strong>es que puede parecer que no funciona cuando no se usan las <a href="/en-US/docs/Web/API/Canvas_API/Tutorial/Drawing_shapes#Drawing_paths">trayectorias de dibujo</a> (<a href="/en-US/docs/Web/API/Canvas_API/Tutorial/Drawing_shapes#Drawing_paths">paths</a>) de forma adecuada. No olvide llamar {{domxref("CanvasRenderingContext2D.beginPath", "beginPath()")}} antes de comenzar a dibujar el nuevo cuadro después de llamar <strong><code>clearRect</code></strong><code>.</code></p> + +<h2 id="Ejemplos">Ejemplos</h2> + +<dl> + <dt> + <h3 id="Usando_el_método_clearRect">Usando el método <code>clearRect</code></h3> + </dt> +</dl> + +<p><span style="display: none;"> </span> Este es un simple fragmento (snippet) de código que usa el método <strong><code>clearRect</code></strong>.</p> + +<h4 id="HTML">HTML</h4> + +<pre class="brush: html"><canvas id="canvas"></canvas></pre> +</div> + +<h4 id="JavaScript">JavaScript</h4> + +<pre class="brush: js">var canvas = document.getElementById('canvas'); +var ctx = canvas.getContext('2d'); c + +tx.beginPath(); ctx.moveTo(20, 20); +ctx.lineTo(200, 20); +ctx.lineTo(120, 120); +ctx.closePath(); // draws last line of the triangle +ctx.stroke(); + +ctx.clearRect(10, 10, 100, 100); + +// clear the whole canvas +// ctx.clearRect(0, 0, canvas.width, canvas.height);</pre> + +<h2 id="sect1"><span style="display: none;"> </span> </h2> + +<p>Edite el código de abajo y vea sus cambios actualizados en vivo en el canvas:</p> + +<p>{{ EmbedLiveSample('Playable_code', 700, 400) }}</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-clearrect", "CanvasRenderingContext2D.clearRect")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<div style="display: none;"> +<h6 id="Playable_code">Playable code</h6> + +<pre class="brush: html"><canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas> +<div class="playable-buttons"> + <input id="edit" type="button" value="Edit" /> + <input id="reset" type="button" value="Reset" /> +</div> +<textarea id="code" class="playable-code" style="height:140px;"> +ctx.beginPath(); +ctx.moveTo(20,20); +ctx.lineTo(200,20); +ctx.lineTo(120,120); +ctx.closePath(); // draws last line of the triangle +ctx.stroke(); + +ctx.clearRect(10, 10, 100, 100);</textarea> +</pre> + +<pre class="brush: js">var canvas = document.getElementById("canvas"); +var ctx = canvas.getContext("2d"); +var textarea = document.getElementById("code"); +var reset = document.getElementById("reset"); +var edit = document.getElementById("edit"); +var code = textarea.value; + +function drawCanvas() { + ctx.clearRect(0, 0, canvas.width, canvas.height); + eval(textarea.value); +} + +reset.addEventListener("click", function() { + textarea.value = code; + drawCanvas(); +}); + +edit.addEventListener("click", function() { + textarea.focus(); +}) + +textarea.addEventListener("input", drawCanvas); +window.addEventListener("load", drawCanvas); + +</pre> +</div> + +<table class="standard-table"> + <tbody> + </tbody> +</table> + +<h2 id="Compatibilidad_con_exploradores">Compatibilidad con exploradores</h2> + +<p>{{CompatibilityTable}}</p> + +<div> +<table class="compat-table"> + <tbody> + <tr> + <th>Caracteristica</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div> +<table class="compat-table"> + <tbody> + <tr> + <th>Caracteristica</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte Basico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Vea_También">Vea También</h2> + +<ul> + <li>The interface defining it, {{domxref("CanvasRenderingContext2D")}}</li> + <li>{{domxref("CanvasRenderingContext2D.fillRect()")}}</li> + <li>{{domxref("CanvasRenderingContext2D.strokeRect()")}}</li> +</ul> diff --git a/files/es/web/api/canvasrenderingcontext2d/drawimage/index.html b/files/es/web/api/canvasrenderingcontext2d/drawimage/index.html new file mode 100644 index 0000000000..2d5330ec53 --- /dev/null +++ b/files/es/web/api/canvasrenderingcontext2d/drawimage/index.html @@ -0,0 +1,232 @@ +--- +title: CanvasRenderingContext2D.drawImage() +slug: Web/API/CanvasRenderingContext2D/drawImage +tags: + - API + - Canvas + - CanvasRenderingContect2D + - Métodos + - Referencia +translation_of: Web/API/CanvasRenderingContext2D/drawImage +--- +<div>{{APIRef}}</div> + +<p>El método <code><strong>CanvasRenderingContext2D</strong></code><strong><code>.drawImage()</code></strong> de la API Canvas 2D proporciona diferentes formas para dibujar una imagen dentro de canvas.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">void <var><em>ctx</em>.drawImage(image, dx, dy);</var> +void <var><em>ctx</em>.drawImage(image, dx, dy, dWidth, dHeight);</var> +void <var><em>ctx</em>.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);</var> +</pre> + +<p><img alt="drawImage" src="https://mdn.mozillademos.org/files/225/Canvas_drawimage.jpg" style="float: right;"></p> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code>image</code></dt> + <dd>Un elemento a dibujar dentro del context. La especificación permite cualquier fuente de imagen en canvas ({{domxref("CanvasImageSource")}}), tal como una {{domxref("HTMLImageElement")}}, un {{domxref("HTMLVideoElement")}}, un {{domxref("HTMLCanvasElement")}} o un{{domxref("ImageBitmap")}}.</dd> + <dt><code>dx</code></dt> + <dd>La coordenada X del canvas destino en la cual se coloca la esquina superior izquierda de la imagen origen.</dd> + <dt><code>dy</code></dt> + <dd>La coordenada Y del canvas destino en la cual se coloca la esquina superior izquierda de la imagen origen.</dd> + <dt><code>dWidth</code></dt> + <dd>El ancho para dibujar la imagen en el canvas destino.</dd> + <dt><code>dHeight</code></dt> + <dd>El alto para dibujar la imagen en el canvas destino. Esto permite escalar la imagen dibujada. Si no se especifica, el alto de la imagen no se escala al dibujar.</dd> + <dt><code>sx</code></dt> + <dd>La coordenada X de la esquina superior izquierda del sub-rectangulo de la imagen origen a dibujar en el contexto de destino.</dd> + <dt><code>sy</code></dt> + <dd>La coordenada Y de la esquina superior izquierda del sub-rectangulo de la imagen origen a dibujar en el contexto de destino.</dd> + <dt><code>sWidth</code></dt> + <dd>El ancho del sub-rectangulo de la imagen origen a dibujar en el contexto de destino. Si no se especifica, se utiliza todo el rectangulo entero desde las coordenadas especificadas por <code>sx</code> y <code>sy </code>hasta la esquina inferior derecha de la imagen.</dd> + <dt><code>sHeight</code></dt> + <dd>La altura del sub-rectangulo de la imagen origen a dibujar en el contexto de destino.</dd> +</dl> + +<h3 id="Excepciones_lanzadas">Excepciones lanzadas</h3> + +<dl> + <dt><code>INDEX_SIZE_ERR</code></dt> + <dd>Si el canvas o la fuente de anchura o altura del rectangulo es igual a cero.</dd> + <dt><code>INVALID_STATE_ERR</code></dt> + <dd>La imagen no tiene datos de imagen.</dd> + <dt><code>TYPE_MISMATCH_ERR</code></dt> + <dd>El elemento de origen especificado no es compatible.</dd> +</dl> + +<h2 id="Ejemplos">Ejemplos</h2> + +<h3 id="Usando_el_método_drawImage">Usando el método drawImage</h3> + +<p>Este es sólo un simple fragmento de código que utiliza el método drawImage.</p> + +<h4 id="HTML">HTML</h4> + +<pre class="brush: html"><canvas id="canvas"></canvas> +<div style="display:none;"> + <img id="source" src="https://mdn.mozillademos.org/files/5397/rhino.jpg" + width="300" height="227"> +</div> +</pre> + +<h4 id="JavaScript">JavaScript</h4> + +<pre class="brush: js; highlight:[5]">var canvas = document.getElementById("canvas"); +var ctx = canvas.getContext("2d"); +var image = document.getElementById('source'); + +ctx.drawImage(image, 33, 71, 104, 124, 21, 20, 87, 104); +</pre> + +<p>Edita el código debajo y observa los cambios actualizarse en vivo en el canvas:</p> + +<div style="display: none;"> +<h6 id="Playable_code">Playable code</h6> + +<pre class="brush: html"><canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas> +<div style="display:none;"> + <img id="source" src="https://mdn.mozillademos.org/files/5397/rhino.jpg" width="300" height="227"> +</div> +<div class="playable-buttons"> + <input id="edit" type="button" value="Edit" /> + <input id="reset" type="button" value="Reset" /> +</div> +<textarea id="code" class="playable-code"> +ctx.drawImage(image, 33, 71, 104, 124, 21, 20, 87, 104);</textarea> +</pre> + +<pre class="brush: js">var canvas = document.getElementById("canvas"); +var ctx = canvas.getContext("2d"); +var image = document.getElementById('source'); +var textarea = document.getElementById("code"); +var reset = document.getElementById("reset"); +var edit = document.getElementById("edit"); +var code = textarea.value; + +function drawCanvas() { + ctx.clearRect(0, 0, canvas.width, canvas.height); + eval(textarea.value); +} + +reset.addEventListener("click", function() { + textarea.value = code; + drawCanvas(); +}); + +edit.addEventListener("click", function() { + textarea.focus(); +}) + +textarea.addEventListener("input", drawCanvas); +window.addEventListener("load", drawCanvas); +</pre> +</div> + +<p>{{ EmbedLiveSample('Playable_code', 700, 360) }}</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-drawimage", "CanvasRenderingContext2D.drawImage")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>ImageBitmap</code> como fuente de imagen</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop(42)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</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>Soporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>ImageBitmap</code> como fuente de imagen</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile(42)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="sect1"> </h2> + +<h2 id="Notas_de_compatibilidad">Notas de compatibilidad</h2> + +<ul> + <li>Soporte para voltear imagen usando valores negativos para <code>sw</code> y <code>sh</code> fue añadido en Gecko 5.0 {{geckoRelease("5.0")}}.</li> + <li>Empezando con {{geckoRelease("5.0")}} <code>drawImage()</code> maneja argumentos negativos de acuerdo con la especificación, volteando el rectangulo alrededor del eje apopiado.</li> + <li>Especificación de una imagen <code>null</code> o <code>undefined</code> al llamar o <code>drawImage()</code> correctamente lanzando una excepción <code>TYPE_MISMATCH_ERR</code> empezando con {{geckoRelease("5.0")}}.</li> + <li>antes de Gecko 7.0 {{ geckoRelease("7.0") }}, Firefox lanzó una excepción si alguno de los valores de las coordenadas no eran finitos o cero. De acuerado a la especificación esto ya no ocurre.</li> + <li>Gecko 9.0 {{ geckoRelease("9.0") }} ahora soporta correctamente CORS para dibujar imágenes a través de dominios sin <a href="/en/CORS_Enabled_Image#What_is_a_.22tainted.22_canvas.3F" title="en/CORS_Enabled_Image#What_is_a_.22tainted.22_canvas.3F">manchar el canvas</a>.</li> + <li>Gecko 11.0 {{ geckoRelease("11.0") }} ahora permite SVG-como-una-imagen para ser dibujada en el canvas sin <a href="/en/CORS_Enabled_Image#What_is_a_.22tainted.22_canvas.3F" title="en/CORS_Enabled_Image#What_is_a_.22tainted.22_canvas.3F">manchar el canvas</a>.</li> +</ul> + +<h2 id="Mira_también">Mira también</h2> + +<ul> + <li>Definiendo la interfaz, {{domxref("CanvasRenderingContext2D")}}.</li> +</ul> diff --git a/files/es/web/api/canvasrenderingcontext2d/fillrect/index.html b/files/es/web/api/canvasrenderingcontext2d/fillrect/index.html new file mode 100644 index 0000000000..bc1a6ddf65 --- /dev/null +++ b/files/es/web/api/canvasrenderingcontext2d/fillrect/index.html @@ -0,0 +1,169 @@ +--- +title: CanvasRenderingContext2D.fillRect() +slug: Web/API/CanvasRenderingContext2D/fillRect +translation_of: Web/API/CanvasRenderingContext2D/fillRect +--- +<div>{{APIRef}}</div> + +<p>El método <code><strong>CanvasRenderingContext2D</strong></code><strong><code>.fillRect()</code></strong> de la API Canvas 2D dibuja un rectángulo relleno en la posición ( x, y ). El tamaño del rectángulo se determina por width (anchura) y height (altura). El estilo de relleno se determina por el atributo <code>fillStyle</code>.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">void <var><em>ctx</em>.fillRect(x, y, width, height);</var> +</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code>x</code></dt> + <dd>La componente x de la coordenada para el punto de comienzo del rectángulo.</dd> + <dt><code>y</code></dt> + <dd>La componente y de la coordenada para el punto de comienzo del rectángulo.</dd> + <dt><code>width</code></dt> + <dd>La anchura del rectángulo.</dd> + <dt><code>height</code></dt> + <dd>La altura del rectángulo.</dd> +</dl> + +<h2 id="Ejemplos">Ejemplos</h2> + +<h3 id="Usando_el_método_fillRect">Usando el método <code>fillRect</code></h3> + +<p>El siguiente fragmento de código usa el método <code>fillRect</code>.</p> + +<h4 id="HTML">HTML</h4> + +<pre class="brush: html"><canvas id="canvas"></canvas> +</pre> + +<h4 id="JavaScript">JavaScript</h4> + +<pre class="brush: js; highlight:[4]">var canvas = document.getElementById("canvas"); +var ctx = canvas.getContext("2d"); +ctx.fillStyle = "green"; +ctx.fillRect(10, 10, 100, 100); + +// Rellenar el canvas completo +// ctx.fillRect(0, 0, canvas.width, canvas.height); +</pre> + +<p>Edita el código que se encuentra a continuación y observa en vivo los cambios actualizados en el canvas:</p> + +<div style="display: none;"> +<h6 id="Playable_code">Playable code</h6> + +<pre class="brush: html"><canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas> +<div class="playable-buttons"> + <input id="edit" type="button" value="Edit" /> + <input id="reset" type="button" value="Reset" /> +</div> +<textarea id="code" class="playable-code"> +ctx.fillStyle = "green"; +ctx.fillRect(10, 10, 100, 100);</textarea> +</pre> + +<pre class="brush: js">var canvas = document.getElementById("canvas"); +var ctx = canvas.getContext("2d"); +var textarea = document.getElementById("code"); +var reset = document.getElementById("reset"); +var edit = document.getElementById("edit"); +var code = textarea.value; + +function drawCanvas() { + ctx.clearRect(0, 0, canvas.width, canvas.height); + eval(textarea.value); +} + +reset.addEventListener("click", function() { + textarea.value = code; + drawCanvas(); +}); + +edit.addEventListener("click", function() { + textarea.focus(); +}) + +textarea.addEventListener("input", drawCanvas); +window.addEventListener("load", drawCanvas); +</pre> +</div> + +<p>{{ EmbedLiveSample('Playable_code', 700, 360) }}</p> + +<h2 id="Especificaciones">Especificaciones</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-context-2d-fillrect", "CanvasRenderingContext2D.fillRect")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_del_navegador">Compatibilidad del navegador</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Chrome para Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Documentos_relacionados">Documentos relacionados</h2> + +<ul> + <li>The interface defining it, {{domxref("CanvasRenderingContext2D")}}</li> + <li>{{domxref("CanvasRenderingContext2D.fillStyle")}}</li> + <li>{{domxref("CanvasRenderingContext2D.clearRect()")}}</li> + <li>{{domxref("CanvasRenderingContext2D.strokeRect()")}}</li> +</ul> diff --git a/files/es/web/api/canvasrenderingcontext2d/getimagedata/index.html b/files/es/web/api/canvasrenderingcontext2d/getimagedata/index.html new file mode 100644 index 0000000000..4f0c72afd0 --- /dev/null +++ b/files/es/web/api/canvasrenderingcontext2d/getimagedata/index.html @@ -0,0 +1,103 @@ +--- +title: CanvasRenderingContext2D.getImageData() +slug: Web/API/CanvasRenderingContext2D/getImageData +tags: + - CanvasRenderingContext2D + - Context 2D + - Español + - Method + - Reference + - getImageData +translation_of: Web/API/CanvasRenderingContext2D/getImageData +--- +<div>{{APIRef}}</div> + +<p> </p> + +<p>El método CanvasRenderingContext2D.getImageData() de la API de Canvas 2D devuelve un objeto ImageData que representa los datos de píxeles subyacentes para el área del lienzo denotada por el rectángulo que comienza en (sx, sy) y tiene un ancho de sw y una altura de sh. Este método no se ve afectado por la matriz de transformación de la lona.</p> + +<p>Los píxeles fuera del área del lienzo están presentes como valores negros transparentes en los datos de imagen devueltos.</p> + +<p> </p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">ImageData <var><em>ctx</em>.getImageData(sx, sy, sw, sh);</var> +</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code>sx</code></dt> + <dd>La coordenada 'x' de la esquina superior izquierda del rectángulo del que se extraerán los datos de imagen.</dd> + <dt><code>sy</code></dt> + <dd>La coordenada 'y' de la esquina superior izquierda del rectángulo del que se extraerá el ImageData.</dd> + <dt><code>sw</code></dt> + <dd>El ancho del rectángulo del que se extraerán los datos de la imagen.</dd> + <dt><code>sh</code></dt> + <dd>La altura del rectángulo del que se extraerán los datos de la imagen.</dd> +</dl> + +<h3 id="Valor_de_retorno">Valor de retorno</h3> + +<p>An <a href="https://developer.mozilla.org/en-US/docs/Web/API/ImageData" title="The ImageData interface represents the underlying pixel data of an area of a <canvas> element. It is created using the ImageData() constructor or creator methods on the CanvasRenderingContext2D object associated with a canvas: createImageData() and getImageData(). It can also be used to set a part of the canvas by using putImageData()."><code>ImageData</code></a> object containing the image data for the given rectangle of the canvas.</p> + +<h3 id="Errores_cometidos">Errores cometidos</h3> + +<dl> + <dt>IndexSizeError</dt> + <dd>Lanzado si cualquiera de los argumentos de anchura o altura es cero.</dd> +</dl> + +<h2 id="Ejemplos">Ejemplos</h2> + +<h3 id="Usando_el_método_getImageData">Usando el método getImageData</h3> + +<p>Esto es sólo un simple fragmento de código que utiliza el método getImageData. Para obtener más información, consulte <a href="https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas">Manipulación de píxeles con Canvas</a> y el objeto ImageData.</p> + +<h4 id="HTML">HTML</h4> + +<pre class="brush: html"><canvas id="canvas"></canvas> +</pre> + +<h4 id="JavaScript">JavaScript</h4> + +<pre class="brush: js; highlight:[6]">var canvas = document.getElementById('canvas'); +var ctx = canvas.getContext('2d'); +ctx.rect(10, 10, 100, 100); +ctx.fill(); + +console.log(ctx.getImageData(50, 50, 100, 100)); +// ImageData { width: 100, height: 100, data: Uint8ClampedArray[40000] } +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-getimagedata", "CanvasRenderingContext2D.getImageData")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<div class="hidden">La tabla de compatibilidad de esta página se genera a partir de datos estructurados. Si desea contribuir con los datos, visite <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> y envíenos una solicitud de extracción.</div> + +<p>{{Compat("api.CanvasRenderingContext2D.getImageData")}}</p> + +<h2 id="Véase_también">Véase también</h2> + +<ul> + <li>La interfaz que lo define, {{domxref("CanvasRenderingContext2D")}}.</li> + <li>{{domxref("ImageData")}}</li> + <li><a href="/en-US/docs/Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas">Manipulación de píxeles con Canvas</a></li> +</ul> diff --git a/files/es/web/api/canvasrenderingcontext2d/index.html b/files/es/web/api/canvasrenderingcontext2d/index.html new file mode 100644 index 0000000000..77df4af190 --- /dev/null +++ b/files/es/web/api/canvasrenderingcontext2d/index.html @@ -0,0 +1,519 @@ +--- +title: CanvasRenderingContext2D +slug: Web/API/CanvasRenderingContext2D +translation_of: Web/API/CanvasRenderingContext2D +--- +<div>{{APIRef}}</div> + +<p>La interfaz <code><strong>CanvasRenderingContext2D</strong></code> proporciona el contexto de renderizado 2D para la superficie de dibujo de un elemento {{ HTMLElement("canvas") }}.</p> + +<p>Para obtener un objeto de esta interfaz, llama a {{domxref("HTMLCanvasElement.getContext()", "getContext()")}} en un <code><canvas></code>, proporcionando "2d" como argumento:</p> + +<pre class="brush: js">var canvas = document.getElementById('mycanvas'); +var ctx = canvas.getContext('2d'); +</pre> + +<p>Una vez que tengas el contexto de renderizado 2D para un canvas, podrás dibujar en ella. Por ejemplo:</p> + +<pre class="brush: js">ctx.fillStyle = "rgb(200,0,0)"; +ctx.fillRect(10, 10, 55, 50); +</pre> + +<p>Mira las propiedades y métodos en la barra lateral. El <a href="/en-US/docs/Web/API/Canvas_API/Tutorial">tutorial de canvas</a> tiene más información, ejemplos y recursos también.</p> + +<h2 id="Dibujando_rectángulos">Dibujando rectángulos</h2> + +<p>Hay 3 métodos que inmediatamente dibujan rectángulos en el bitmap.</p> + +<dl> + <dt>{{domxref("CanvasRenderingContext2D.clearRect()")}}</dt> + <dd>Establece todos los píxeles del rectangulo definido por los puntos <em>(x, y) </em>y tamaños <em>(ancho, alto)</em> a negro transparente, borrando cualquier contenido previo.</dd> + <dt>{{domxref("CanvasRenderingContext2D.fillRect()")}}</dt> + <dd>Dibuja un rectángulo relleno en la posición <em>(x, y)</em> cuyo tamaño está determinado por la anchura y la altura.</dd> + <dt>{{domxref("CanvasRenderingContext2D.strokeRect()")}}</dt> + <dd>Dibuja un rectángulo que tiene como posición inicial <em>(x, y)</em> con un ancho w y altura h sobre el canvas, utilizando el estilo de trazo actual.</dd> +</dl> + +<h2 id="Dibujando_texto">Dibujando texto</h2> + +<p>Los siguientes métodos se proporcionan para dibujar texto. Mira también el objeto {{domxref("TextMetrics")}} para propiedades de texto.</p> + +<dl> + <dt>{{domxref("CanvasRenderingContext2D.fillText()")}}</dt> + <dd>Dibuja (llena) un texto dado en una posición (x, y) dada.</dd> + <dt>{{domxref("CanvasRenderingContext2D.strokeText()")}}</dt> + <dd>Dibuja (trazas) un texto dado en una posición (x, y) dada.</dd> + <dt>{{domxref("CanvasRenderingContext2D.measureText()")}}</dt> + <dd>Devuelve el objeto {{domxref("TextMetrics")}}.</dd> +</dl> + +<h2 id="Los_estilos_de_línea">Los estilos de línea</h2> + +<p>Los siguientes métodos y propiedades controlan como las líneas son dibujadas.</p> + +<dl> + <dt>{{domxref("CanvasRenderingContext2D.lineWidth")}}</dt> + <dd>Ancho de líneas. Por defecto <code>1.0</code></dd> + <dt>{{domxref("CanvasRenderingContext2D.lineCap")}}</dt> + <dd>Tipo de terminaciones en el final de las líneas. Posibles valores: <code>butt</code> (defecto), <code>round</code>, <code>square</code>.</dd> + <dt>{{domxref("CanvasRenderingContext2D.lineJoin")}}</dt> + <dd>Define el tipo de esquinas donde dos líneas se encuentran. Pislbes valores: <code>round</code>, <code>bevel</code>, <code>miter</code> (defecto).</dd> + <dt>{{domxref("CanvasRenderingContext2D.miterLimit")}}</dt> + <dd>Relación límite angular. Defecto <code>10</code>.</dd> + <dt>{{domxref("CanvasRenderingContext2D.getLineDash()")}}</dt> + <dd>Devuelve la matriz patrón de trazos actual que contiene un número de par de números no negativos.</dd> + <dt>{{domxref("CanvasRenderingContext2D.setLineDash()")}}</dt> + <dd>Establece el patrón de trazos linea actual.</dd> + <dt>{{domxref("CanvasRenderingContext2D.lineDashOffset")}}</dt> + <dd>Especifica donde inicia una gama de instrumentos en una línea.</dd> +</dl> + +<h2 id="Estilos_de_texto">Estilos de texto</h2> + +<p>Las siguientes propiedades control como el texto es presentado.</p> + +<dl> + <dt>{{domxref("CanvasRenderingContext2D.font")}}</dt> + <dd>Ajuste de fuente. Valor por defecto <code>10px sans-serif</code>.</dd> + <dt>{{domxref("CanvasRenderingContext2D.textAlign")}}</dt> + <dd>Text alignment setting. Possible values: <code>start</code> (default), <code>end</code>, <code>left</code>, <code>right</code> or <code>center</code>.</dd> + <dt>{{domxref("CanvasRenderingContext2D.textBaseline")}}</dt> + <dd>Baseline alignment setting. Possible values: <code>top</code>, <code>hanging</code>, <code>middle</code>, <code>alphabetic</code> (default), <code>ideographic</code>, <code>bottom</code>.</dd> + <dt>{{domxref("CanvasRenderingContext2D.direction")}}</dt> + <dd>Directionality. Possible values: <code>ltr, rtl</code>, <code>inherit</code> (default).</dd> +</dl> + +<h2 id="Estilo_del_relleno_y_de_los_bordes">Estilo del relleno y de los bordes</h2> + +<p>Fill styling es utilizado para estilizar los colores del relleno y los bordes de las formas.</p> + +<dl> + <dt>{{domxref("CanvasRenderingContext2D.fillStyle")}}</dt> + <dd>Utilizado para dar color al relleno de las formas. Color por defecto <code>#000</code> (negro).</dd> + <dt>{{domxref("CanvasRenderingContext2D.strokeStyle")}}</dt> + <dd>Utilizado para dar color al borde de las formas. Color por defecto <code>#000</code> (negro)..</dd> +</dl> + +<h2 id="Degradados_y_patrones">Degradados y patrones</h2> + +<dl> + <dt>{{domxref("CanvasRenderingContext2D.createLinearGradient()")}}</dt> + <dd>Creates a linear gradient along the line given by the coordinates represented by the parameters.</dd> + <dt>{{domxref("CanvasRenderingContext2D.createRadialGradient()")}}</dt> + <dd>Creates a radial gradient along the line given by the coordinates represented by the parameters.</dd> + <dt>{{domxref("CanvasRenderingContext2D.createPattern()")}}</dt> + <dd>Creates a pattern using the specified image (a {{domxref("CanvasImageSource")}}). It repeats the source in the directions specified by the repetition argument. This method returns a {{domxref("CanvasPattern")}}.</dd> +</dl> + +<h2 id="Sombras">Sombras</h2> + +<dl> + <dt>{{domxref("CanvasRenderingContext2D.shadowBlur")}}</dt> + <dd>Especifica el efecto de desenfoque. Predeterminado <code>0</code></dd> + <dt>{{domxref("CanvasRenderingContext2D.shadowColor")}}</dt> + <dd>Color de la sombra. Predeterminado totalmente transparente negro.</dd> + <dt>{{domxref("CanvasRenderingContext2D.shadowOffsetX")}}</dt> + <dd>Distancia horizontal del desplazamiento de la sombra. Predeterminado 0.</dd> + <dt>{{domxref("CanvasRenderingContext2D.shadowOffsetY")}}</dt> + <dd>Distancia vertical del desplazamiento de la sombra. Predeterminado 0.</dd> +</dl> + +<h2 id="Paths">Paths</h2> + +<p>The following methods can be used to manipulate paths of objects.</p> + +<dl> + <dt>{{domxref("CanvasRenderingContext2D.beginPath()")}}</dt> + <dd>Starts a new path by emptying the list of sub-paths. Call this method when you want to create a new path.</dd> + <dt>{{domxref("CanvasRenderingContext2D.closePath()")}}</dt> + <dd>Causes the point of the pen to move back to the start of the current sub-path. It tries to draw a straight line from the current point to the start. If the shape has already been closed or has only one point, this function does nothing.</dd> + <dt>{{domxref("CanvasRenderingContext2D.moveTo()")}}</dt> + <dd>Moves the starting point of a new sub-path to the <strong>(x, y)</strong> coordinates.</dd> + <dt>{{domxref("CanvasRenderingContext2D.lineTo()")}}</dt> + <dd>Connects the last point in the subpath to the <code>x, y</code> coordinates with a straight line.</dd> + <dt>{{domxref("CanvasRenderingContext2D.bezierCurveTo()")}}</dt> + <dd>Adds a cubic Bézier curve to the path. It requires three points. The first two points are control points and the third one is the end point. The starting point is the last point in the current path, which can be changed using <code>moveTo()</code> before creating the Bézier curve.</dd> + <dt>{{domxref("CanvasRenderingContext2D.quadraticCurveTo()")}}</dt> + <dd>Adds a quadratic Bézier curve to the current path.</dd> + <dt>{{domxref("CanvasRenderingContext2D.arc()")}}</dt> + <dd>Adds an arc to the path which is centered at <em>(x, y)</em> position with radius<em> r</em> starting at <em>startAngle</em> and ending at <em>endAngle</em> going in the given direction by <em>anticlockwise</em> (defaulting to clockwise).</dd> + <dt>{{domxref("CanvasRenderingContext2D.arcTo()")}}</dt> + <dd>Adds an arc to the path with the given control points and radius, connected to the previous point by a straight line.</dd> + <dt>{{domxref("CanvasRenderingContext2D.ellipse()")}} {{experimental_inline}}</dt> + <dd>Adds an ellipse to the path which is centered at <em>(x, y)</em> position with the radii <em>radiusX</em> and <em>radiusY</em> starting at <em>startAngle</em> and ending at <em>endAngle</em> going in the given direction by <em>anticlockwise</em> (defaulting to clockwise).</dd> + <dt>{{domxref("CanvasRenderingContext2D.rect()")}}</dt> + <dd>Creates a path for a rectangle at<em> </em>position <em>(x, y)</em> with a size that is determined by <em>width</em> and <em>height</em>.</dd> +</dl> + +<h2 id="Drawing_paths">Drawing paths</h2> + +<dl> + <dt>{{domxref("CanvasRenderingContext2D.fill()")}}</dt> + <dd>Fills the subpaths with the current fill style.</dd> + <dt>{{domxref("CanvasRenderingContext2D.stroke()")}}</dt> + <dd>Strokes the subpaths with the current stroke style.</dd> + <dt>{{domxref("CanvasRenderingContext2D.drawFocusIfNeeded()")}}</dt> + <dd>If a given element is focused, this method draws a focus ring around the current path.</dd> + <dt>{{domxref("CanvasRenderingContext2D.scrollPathIntoView()")}}</dt> + <dd>Scrolls the current path or a given path into the view.</dd> + <dt>{{domxref("CanvasRenderingContext2D.clip()")}}</dt> + <dd>Creates a clipping path from the current sub-paths. Everything drawn after <code>clip()</code> is called appears inside the clipping path only. For an example, see <a href="/en-US/docs/Web/API/Canvas_API/Tutorial/Compositing" title="Clipping paths">Clipping paths</a> in the Canvas tutorial.</dd> + <dt>{{domxref("CanvasRenderingContext2D.isPointInPath()")}}</dt> + <dd>Reports whether or not the specified point is contained in the current path.</dd> + <dt>{{domxref("CanvasRenderingContext2D.isPointInStroke()")}}</dt> + <dd>Reports whether or not the specified point is inside the area contained by the stroking of a path.</dd> +</dl> + +<h2 id="Transformations">Transformations</h2> + +<p>Objects in the <code>CanvasRenderingContext2D</code> rendering context have a current transformation matrix and methods to manipulate it. The transformation matrix is applied when creating the current default path, painting text, shapes and {{domxref("Path2D")}} objects. The methods listed below remain for historical and compatibility reasons as {{domxref("SVGMatrix")}} objects are used in most parts of the API nowadays and will be used in the future instead.</p> + +<dl> + <dt>{{domxref("CanvasRenderingContext2D.currentTransform")}}</dt> + <dd>Current transformation matrix ({{domxref("SVGMatrix")}} object).</dd> + <dt>{{domxref("CanvasRenderingContext2D.rotate()")}}</dt> + <dd>Adds a rotation to the transformation matrix. The angle argument represents a clockwise rotation angle and is expressed in radians.</dd> + <dt>{{domxref("CanvasRenderingContext2D.scale()")}}</dt> + <dd>Adds a scaling transformation to the canvas units by x horizontally and by y vertically.</dd> + <dt>{{domxref("CanvasRenderingContext2D.translate()")}}</dt> + <dd>Adds a translation transformation by moving the canvas and its origin x horzontally and y vertically on the grid.</dd> + <dt>{{domxref("CanvasRenderingContext2D.transform()")}}</dt> + <dd>Multiplies the current transformation matrix with the matrix described by its arguments.</dd> + <dt>{{domxref("CanvasRenderingContext2D.setTransform()")}}</dt> + <dd>Resets the current transform to the identity matrix, and then invokes the <code>transform()</code> method with the same arguments.</dd> + <dt>{{domxref("CanvasRenderingContext2D.resetTransform()")}} {{experimental_inline}}</dt> + <dd>Resets the current transform by the identity matrix.</dd> +</dl> + +<h2 id="Compositing">Compositing</h2> + +<dl> + <dt>{{domxref("CanvasRenderingContext2D.globalAlpha")}}</dt> + <dd>Alpha value that is applied to shapes and images before they are composited onto the canvas. Default <code>1.0</code> (opaque).</dd> + <dt>{{domxref("CanvasRenderingContext2D.globalCompositeOperation")}}</dt> + <dd>With <code>globalAlpha</code> applied this sets how shapes and images are drawn onto the existing bitmap.</dd> +</dl> + +<h2 id="Drawing_images">Drawing images</h2> + +<dl> + <dt>{{domxref("CanvasRenderingContext2D.drawImage()")}}</dt> + <dd>Draws the specified image. This method is available in multiple formats, providing a great deal of flexibility in its use.</dd> +</dl> + +<h2 id="Pixel_manipulation">Pixel manipulation</h2> + +<p>See also the {{domxref("ImageData")}} object.</p> + +<dl> + <dt>{{domxref("CanvasRenderingContext2D.createImageData()")}}</dt> + <dd>Creates a new, blank {{domxref("ImageData")}} object with the specified dimensions. All of the pixels in the new object are transparent black.</dd> + <dt>{{domxref("CanvasRenderingContext2D.getImageData()")}}</dt> + <dd>Returns an {{domxref("ImageData")}} object representing the underlying pixel data for the area of the canvas denoted by the rectangle which starts at <em>(sx, sy)</em> and has an <em>sw</em> width and <em>sh</em> height.</dd> + <dt>{{domxref("CanvasRenderingContext2D.putImageData()")}}</dt> + <dd>Paints data from the given {{domxref("ImageData")}} object onto the bitmap. If a dirty rectangle is provided, only the pixels from that rectangle are painted.</dd> +</dl> + +<h2 id="Image_smoothing">Image smoothing</h2> + +<dl> + <dt>{{domxref("CanvasRenderingContext2D.imageSmoothingEnabled")}} {{experimental_inline}}</dt> + <dd>Image smoothing mode; if disabled, images will not be smoothed if scaled.</dd> +</dl> + +<h2 id="The_canvas_state">The canvas state</h2> + +<p>The <code>CanvasRenderingContext2D</code> rendering context contains a variety of drawing style states (attributes for line styles, fill styles, shadow styles, text styles). The following methods help you to work with that state:</p> + +<dl> + <dt>{{domxref("CanvasRenderingContext2D.save()")}}</dt> + <dd>Saves the current drawing style state using a stack so you can revert any change you make to it using <code>restore()</code>.</dd> + <dt>{{domxref("CanvasRenderingContext2D.restore()")}}</dt> + <dd>Restores the drawing style state to the last element on the 'state stack' saved by <code>save()</code>.</dd> + <dt>{{domxref("CanvasRenderingContext2D.canvas")}}</dt> + <dd>A read-only back-reference to the {{domxref("HTMLCanvasElement")}}. Might be {{jsxref("null")}} if it is not associated with a {{HTMLElement("canvas")}} element.</dd> +</dl> + +<h2 id="Hit_regions">Hit regions</h2> + +<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> + +<h2 id="Non-standard_APIs">Non-standard APIs</h2> + +<h3 id="Blink_and_WebKit">Blink and WebKit</h3> + +<p>Most of these APIs are <a href="https://code.google.com/p/chromium/issues/detail?id=363198">deprecated and will be removed in the future</a>.</p> + +<dl> + <dt>{{non-standard_inline}} <code>CanvasRenderingContext2D.clearShadow()</code></dt> + <dd>Removes all shadow settings like {{domxref("CanvasRenderingContext2D.shadowColor")}} and {{domxref("CanvasRenderingContext2D.shadowBlur")}}.</dd> + <dt>{{non-standard_inline}} <code>CanvasRenderingContext2D.drawImageFromRect()</code></dt> + <dd>This is redundant with an equivalent overload of <code>drawImage</code>.</dd> + <dt>{{non-standard_inline}} <code>CanvasRenderingContext2D.setAlpha()</code></dt> + <dd>Use {{domxref("CanvasRenderingContext2D.globalAlpha")}} instead.</dd> + <dt>{{non-standard_inline}} <code>CanvasRenderingContext2D.setCompositeOperation()</code></dt> + <dd>Use {{domxref("CanvasRenderingContext2D.globalCompositeOperation")}} instead.</dd> + <dt>{{non-standard_inline}} <code>CanvasRenderingContext2D.setLineWidth()</code></dt> + <dd>Use {{domxref("CanvasRenderingContext2D.lineWidth")}} instead.</dd> + <dt>{{non-standard_inline}} <code>CanvasRenderingContext2D.setLineJoin()</code></dt> + <dd>Use {{domxref("CanvasRenderingContext2D.lineJoin")}} instead.</dd> + <dt>{{non-standard_inline}} <code>CanvasRenderingContext2D.setLineCap()</code></dt> + <dd>Use {{domxref("CanvasRenderingContext2D.lineCap")}} instead.</dd> + <dt>{{non-standard_inline}} <code>CanvasRenderingContext2D.setMiterLimit()</code></dt> + <dd>Use {{domxref("CanvasRenderingContext2D.miterLimit")}} instead.</dd> + <dt>{{non-standard_inline}} <code>CanvasRenderingContext2D.setStrokeColor()</code></dt> + <dd>Use {{domxref("CanvasRenderingContext2D.strokeStyle")}} instead.</dd> + <dt>{{non-standard_inline}} <code>CanvasRenderingContext2D.setFillColor()</code></dt> + <dd>Use {{domxref("CanvasRenderingContext2D.fillStyle")}} instead.</dd> + <dt>{{non-standard_inline}} <code>CanvasRenderingContext2D.setShadow()</code></dt> + <dd>Use {{domxref("CanvasRenderingContext2D.shadowColor")}} and {{domxref("CanvasRenderingContext2D.shadowBlur")}} instead.</dd> + <dt>{{non-standard_inline}} <code>CanvasRenderingContext2D.webkitLineDash</code></dt> + <dd>Use {{domxref("CanvasRenderingContext2D.getLineDash()")}} and {{domxref("CanvasRenderingContext2D.setLineDash()")}} instead.</dd> + <dt>{{non-standard_inline}} <code>CanvasRenderingContext2D.webkitLineDashOffset</code></dt> + <dd>Use {{domxref("CanvasRenderingContext2D.lineDashOffset")}} instead.</dd> + <dt>{{non-standard_inline}} <code>CanvasRenderingContext2D.webkitImageSmoothingEnabled</code></dt> + <dd>Use {{domxref("CanvasRenderingContext2D.imageSmoothingEnabled")}} instead.</dd> +</dl> + +<h3 id="Blink_only">Blink only</h3> + +<dl> + <dt>{{non-standard_inline}} <code>CanvasRenderingContext2D.getContextAttributes()</code></dt> + <dd>Inspired by the same <code>WebGLRenderingContext</code> method it returns an <code>Canvas2DContextAttributes</code> object that contains the attributes "storage" to indicate which storage is used ("persistent" by default) and the attribute "alpha" (<code>true</code> by default) to indicate that transparency is used in the canvas.</dd> + <dt>{{non-standard_inline}} <code>CanvasRenderingContext2D.isContextLost()</code></dt> + <dd>Inspired by the same <code>WebGLRenderingContext</code> method it returns <code>true</code> if the Canvas context has been lost, or <code>false</code> if not.</dd> +</dl> + +<h3 id="WebKit_only">WebKit only</h3> + +<dl> + <dt>{{non-standard_inline}} <code>CanvasRenderingContext2D.webkitBackingStorePixelRatio</code></dt> + <dd>The backing store size in relation to the canvas element. See <a href="http://www.html5rocks.com/en/tutorials/canvas/hidpi/">High DPI Canvas</a>.</dd> + <dt>{{non-standard_inline}} <code>CanvasRenderingContext2D.webkitGetImageDataHD</code></dt> + <dd>Intended for HD backing stores, but removed from canvas specifications.</dd> + <dt>{{non-standard_inline}} <code>CanvasRenderingContext2D.webkitPutImageDataHD</code></dt> + <dd>Intended for HD backing stores, but removed from canvas specifications.</dd> +</dl> + +<dl> +</dl> + +<h3 id="Gecko_only">Gecko only</h3> + +<dl> + <dt>{{non-standard_inline}} {{domxref("CanvasRenderingContext2D.filter")}}</dt> + <dd><span id="summary_alias_container"><span id="short_desc_nonedit_display">CSS and SVG filters as Canvas APIs</span></span>. Likely to be standardized in a new version of the specification.</dd> +</dl> + +<h4 id="Prefixed_APIs">Prefixed APIs</h4> + +<dl> + <dt>{{non-standard_inline}} <code>CanvasRenderingContext2D.mozCurrentTransform</code></dt> + <dd>Sets or gets the current transformation matrix, see {{domxref("CanvasRenderingContext2D.currentTransform")}}. {{ gecko_minversion_inline("7.0") }}</dd> + <dt>{{non-standard_inline}} <code>CanvasRenderingContext2D.mozCurrentTransformInverse</code></dt> + <dd>Sets or gets the current inversed transformation matrix. {{ gecko_minversion_inline("7.0") }}</dd> + <dt>{{non-standard_inline}} <code>CanvasRenderingContext2D.mozFillRule</code></dt> + <dd>The <a class="external" href="http://cairographics.org/manual/cairo-cairo-t.html#cairo-fill-rule-t" title="http://cairographics.org/manual/cairo-cairo-t.html#cairo-fill-rule-t">fill rule</a> to use. This must be one of <code>evenodd</code> or <code>nonzero</code> (default).</dd> + <dt>{{non-standard_inline}} <code>CanvasRenderingContext2D.mozImageSmoothingEnabled</code></dt> + <dd>See {{domxref("CanvasRenderingContext2D.imageSmoothingEnabled")}}.</dd> + <dt>{{non-standard_inline}} {{deprecated_inline}} <code>CanvasRenderingContext2D.mozDash</code></dt> + <dd>An array which specifies the lengths of alternating dashes and gaps {{ gecko_minversion_inline("7.0") }}. Use {{domxref("CanvasRenderingContext2D.getLineDash()")}} and {{domxref("CanvasRenderingContext2D.setLineDash()")}} instead.</dd> + <dt>{{non-standard_inline}} {{deprecated_inline}} <code>CanvasRenderingContext2D.mozDashOffset</code></dt> + <dd>Specifies where to start a dash array on a line. {{ gecko_minversion_inline("7.0") }}. Use {{domxref("CanvasRenderingContext2D.lineDashOffset")}} instead.</dd> + <dt>{{non-standard_inline}} {{deprecated_inline}} <code>CanvasRenderingContext2D.mozTextStyle</code></dt> + <dd>Introduced in in Gecko 1.9, deprecated in favor of the {{domxref("CanvasRenderingContext2D.font")}} property.</dd> + <dt>{{non-standard_inline}} {{obsolete_inline}} <code>CanvasRenderingContext2D.mozDrawText()</code></dt> + <dd>This method was introduced in Gecko 1.9 and is removed starting with Gecko 7.0. Use {{domxref("CanvasRenderingContext2D.strokeText()")}} or {{domxref("CanvasRenderingContext2D.fillText()")}} instead.</dd> + <dt>{{non-standard_inline}} {{obsolete_inline}} <code>CanvasRenderingContext2D.mozMeasureText()</code></dt> + <dd>This method was introduced in Gecko 1.9 and is unimplemented starting with Gecko 7.0. Use {{domxref("CanvasRenderingContext2D.measureText()")}} instead.</dd> + <dt>{{non-standard_inline}} {{obsolete_inline}} <code>CanvasRenderingContext2D.mozPathText()</code></dt> + <dd>This method was introduced in Gecko 1.9 and is removed starting with Gecko 7.0.</dd> + <dt>{{non-standard_inline}} {{obsolete_inline}} <code>CanvasRenderingContext2D.mozTextAlongPath()</code></dt> + <dd>This method was introduced in Gecko 1.9 and is removed starting with Gecko 7.0.</dd> +</dl> + +<h4 id="Internal_APIs_(chrome-context_only)">Internal APIs (chrome-context only)</h4> + +<dl> + <dt>{{non-standard_inline}} {{domxref("CanvasRenderingContext2D.asyncDrawXULElement()")}}</dt> + <dd>Renders a region of a XUL element into the <code>canvas</code>.</dd> + <dt>{{non-standard_inline}} {{domxref("CanvasRenderingContext2D.drawWindow()")}}</dt> + <dd>Renders a region of a window into the <code>canvas</code>. The contents of the window's viewport are rendered, ignoring viewport clipping and scrolling.</dd> + <dt>{{non-standard_inline}} <code>CanvasRenderingContext2D.demote()</code></dt> + <dd>This causes a context that is currently using a hardware-accelerated backend to fallback to a software one. All state should be preserved.</dd> +</dl> + +<h3 id="Internet_Explorer">Internet Explorer</h3> + +<dl> + <dt>{{non-standard_inline}} <code>CanvasRenderingContext2D.msFillRule</code></dt> + <dd>The <a class="external" href="http://cairographics.org/manual/cairo-cairo-t.html#cairo-fill-rule-t" title="http://cairographics.org/manual/cairo-cairo-t.html#cairo-fill-rule-t">fill rule</a> to use. This must be one of <code>evenodd</code> or <code>nonzero</code> (default).</dd> +</dl> + +<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#2dcontext:canvasrenderingcontext2d", "CanvasRenderingContext2D")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </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</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome("1")}}</td> + <td>{{CompatGeckoDesktop("1.8")}}</td> + <td>{{CompatIE("9")}}</td> + <td>{{CompatOpera("9")}}</td> + <td>{{CompatSafari("2")}}</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>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h3 id="Compatibility_notes">Compatibility notes</h3> + +<ul> + <li>Starting with Gecko 5.0 {{geckoRelease("5.0")}}, specifying invalid values are now silently ignored for the following methods and properties: <code>translate()</code>, <code>transform()</code>, <code>rotate(), </code><code>scale(),</code> <code>rect()</code>, <code>clearRect()</code>, <code>fillRect()</code>, <code>strokeRect()</code>, <code>lineTo()</code>, <code>moveTo()</code>, <code>quadraticCurveTo()</code>, <code>arc()</code>, <code>shadowOffsetX</code>, <code>shadowOffsetY</code>, <code>shadowBlur</code>.</li> +</ul> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{domxref("HTMLCanvasElement")}}</li> +</ul> + +<div id="SLG_balloon_obj" style="display: block;"> +<div class="SLG_ImTranslatorLogo" id="SLG_button" style="display: none; opacity: 1;"> </div> + +<div id="SLG_shadow_translation_result2" style="display: none;"> </div> + +<div id="SLG_shadow_translator" style="display: none; box-shadow: rgb(186, 185, 181) 0px 0px 0px;"> +<div id="SLG_planshet"> +<div id="SLG_arrow_up" style=""> </div> + +<div id="SLG_Bproviders" style=""> +<div class="SLG_BL_LABLE_ON" id="SLG_P0" title="Google">G</div> + +<div class="SLG_BL_LABLE_ON" id="SLG_P1" title="Microsoft">M</div> + +<div class="SLG_BL_LABLE_ON" id="SLG_P2" title="Translator">T</div> +</div> + +<div id="SLG_alert_bbl" style="display: none;"> +<div id="SLHKclose" style=""> </div> + +<div id="SLG_alert_cont"> </div> +</div> + +<div id="SLG_TB"> +<table id="SLG_tables"> + <tbody><tr> + <td class="SLG_td"><input></td> + <td class="SLG_td"><select><option value="auto">Detectar idioma</option><option value="af">Afrikáans</option><option value="sq">Albanés</option><option value="de">Alemán</option><option value="am">Amhárico</option><option value="ar">Árabe</option><option value="hy">Armenio</option><option value="az">Azerí</option><option value="bn">Bengalí</option><option value="be">Bielorruso</option><option value="my">Birmano</option><option value="bs">Bosnio</option><option value="bg">Búlgaro</option><option value="km">Camboyano</option><option value="kn">Canarés</option><option value="ca">Catalán</option><option value="ceb">Cebuano</option><option value="cs">Checo</option><option value="ny">Chichewa</option><option value="zh-CN">Chino simp</option><option value="zh-TW">Chino trad</option><option value="si">Cincalés</option><option value="ko">Coreano</option><option value="co">Corso</option><option value="ht">Criollo haitiano</option><option value="hr">Croata</option><option value="da">Danés</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Español</option><option value="eo">Esperanto</option><option value="et">Estonio</option><option value="eu">Euskera</option><option value="fi">Finlandés</option><option value="fr">Francés</option><option value="fy">Frisio</option><option value="gd">Gaélico escocés</option><option value="cy">Galés</option><option value="gl">Gallego</option><option value="ka">Georgiano</option><option value="el">Griego</option><option value="gu">Gujarati</option><option value="ha">Hausa</option><option value="haw">Hawaiano</option><option value="iw">Hebreo</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandés</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonesio</option><option value="en">Inglés</option><option value="ga">Irlandés</option><option value="is">Islandés</option><option value="it">Italiano</option><option value="ja">Japonés</option><option value="jw">Javanés</option><option value="kk">Kazajo</option><option value="ky">Kirguís</option><option value="ku">Kurdo</option><option value="lo">Lao</option><option value="la">Latín</option><option value="lv">Letón</option><option value="lt">Lituano</option><option value="lb">Luxemburgués</option><option value="mk">Macedonio</option><option value="ml">Malayalam</option><option value="ms">Malayo</option><option value="mg">Malgache</option><option value="mt">Maltés</option><option value="mi">Maorí</option><option value="mr">Maratí</option><option value="mn">Mongol</option><option value="ne">Nepalí</option><option value="no">Noruego</option><option value="pa">Panyabí</option><option value="ps">Pastún</option><option value="fa">Persa</option><option value="pl">Polaco</option><option value="pt">Portugués</option><option value="ro">Rumano</option><option value="ru">Ruso</option><option value="sm">Samoano</option><option value="sr">Serbio</option><option value="st">Sesoto</option><option value="sn">Shona</option><option value="sd">Sindhi</option><option value="so">Somalí</option><option value="sw">Suajili</option><option value="sv">Sueco</option><option value="su">Sundanés</option><option value="tl">Tagalo</option><option value="th">Tailandés</option><option value="ta">Tamil</option><option value="tg">Tayiko</option><option value="te">Telugu</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeco</option><option value="vi">Vietnamita</option><option value="xh">Xhosa</option><option value="yi">Yidis</option><option value="yo">Yoruba</option><option value="zu">Zulú</option></select></td> + <td class="SLG_td"> + <div id="SLG_switch_b" style="" title="Cambiar idiomas"> </div> + </td> + <td class="SLG_td"><select><option value="af">Afrikáans</option><option value="sq">Albanés</option><option value="de">Alemán</option><option value="am">Amhárico</option><option value="ar">Árabe</option><option value="hy">Armenio</option><option value="az">Azerí</option><option value="bn">Bengalí</option><option value="be">Bielorruso</option><option value="my">Birmano</option><option value="bs">Bosnio</option><option value="bg">Búlgaro</option><option value="km">Camboyano</option><option value="kn">Canarés</option><option value="ca">Catalán</option><option value="ceb">Cebuano</option><option value="cs">Checo</option><option value="ny">Chichewa</option><option value="zh-CN">Chino simp</option><option value="zh-TW">Chino trad</option><option value="si">Cincalés</option><option value="ko">Coreano</option><option value="co">Corso</option><option value="ht">Criollo haitiano</option><option value="hr">Croata</option><option value="da">Danés</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option selected value="es">Español</option><option value="eo">Esperanto</option><option value="et">Estonio</option><option value="eu">Euskera</option><option value="fi">Finlandés</option><option value="fr">Francés</option><option value="fy">Frisio</option><option value="gd">Gaélico escocés</option><option value="cy">Galés</option><option value="gl">Gallego</option><option value="ka">Georgiano</option><option value="el">Griego</option><option value="gu">Gujarati</option><option value="ha">Hausa</option><option value="haw">Hawaiano</option><option value="iw">Hebreo</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandés</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonesio</option><option value="en">Inglés</option><option value="ga">Irlandés</option><option value="is">Islandés</option><option value="it">Italiano</option><option value="ja">Japonés</option><option value="jw">Javanés</option><option value="kk">Kazajo</option><option value="ky">Kirguís</option><option value="ku">Kurdo</option><option value="lo">Lao</option><option value="la">Latín</option><option value="lv">Letón</option><option value="lt">Lituano</option><option value="lb">Luxemburgués</option><option value="mk">Macedonio</option><option value="ml">Malayalam</option><option value="ms">Malayo</option><option value="mg">Malgache</option><option value="mt">Maltés</option><option value="mi">Maorí</option><option value="mr">Maratí</option><option value="mn">Mongol</option><option value="ne">Nepalí</option><option value="no">Noruego</option><option value="pa">Panyabí</option><option value="ps">Pastún</option><option value="fa">Persa</option><option value="pl">Polaco</option><option value="pt">Portugués</option><option value="ro">Rumano</option><option value="ru">Ruso</option><option value="sm">Samoano</option><option value="sr">Serbio</option><option value="st">Sesoto</option><option value="sn">Shona</option><option value="sd">Sindhi</option><option value="so">Somalí</option><option value="sw">Suajili</option><option value="sv">Sueco</option><option value="su">Sundanés</option><option value="tl">Tagalo</option><option value="th">Tailandés</option><option value="ta">Tamil</option><option value="tg">Tayiko</option><option value="te">Telugu</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeco</option><option value="vi">Vietnamita</option><option value="xh">Xhosa</option><option value="yi">Yidis</option><option value="yo">Yoruba</option><option value="zu">Zulú</option></select></td> + <td class="SLG_td"> </td> + <td class="SLG_td"> + <div id="SLG_TTS_voice" style="" title="Inglés"> </div> + </td> + <td class="SLG_td"> + <div class="SLG_copy" id="SLG_copy" style="" title="Copiar"> </div> + </td> + <td class="SLG_td"> + <div id="SLG_bbl_font_patch"> </div> + + <div class="SLG_bbl_font" id="SLG_bbl_font" style="" title="Тamaño de fuente"> </div> + </td> + <td class="SLG_td"> + <div id="SLG_bbl_help" style="" title="Ayuda"> </div> + </td> + <td class="SLG_td"> + <div class="SLG_pin_off" id="SLG_pin" style="" title="Fijar la ventana de traducción"> </div> + </td> + </tr> +</tbody></table> +</div> +</div> + +<div id="SLG_shadow_translation_result" style=""> </div> + +<div class="SLG_loading" id="SLG_loading" style=""> </div> + +<div id="SLG_player2"> </div> + +<div id="SLG_alert100">La función de sonido está limitada a 200 caracteres</div> + +<div id="SLG_Balloon_options" style="background: rgb(255, 255, 255);"> +<div id="SLG_arrow_down" style=""> </div> + +<table id="SLG_tbl_opt" style="width: 100%;"> + <tbody><tr> + <td><input></td> + <td> + <div id="SLG_BBL_IMG" style="" title="Mostrar el botón ImTranslator 3 segundos"> </div> + </td> + <td><a class="SLG_options" title="Mostrar opciones">Opciones</a> : <a class="SLG_options" title="Historial de traducciones">Historia</a> : <a class="SLG_options" title="ImTranslator Feedback">Feedback</a> : <a class="SLG_options" href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GD9D8CPW8HFA2" title="Hacer una contribución">Donate</a></td> + <td><span id="SLG_Balloon_Close" title="Cerrar">Cerrar</span></td> + </tr> +</tbody></table> +</div> +</div> +</div> diff --git a/files/es/web/api/canvasrenderingcontext2d/linecap/index.html b/files/es/web/api/canvasrenderingcontext2d/linecap/index.html new file mode 100644 index 0000000000..e61f3c1465 --- /dev/null +++ b/files/es/web/api/canvasrenderingcontext2d/linecap/index.html @@ -0,0 +1,131 @@ +--- +title: CanvasRenderingContext2D.lineCap +slug: Web/API/CanvasRenderingContext2D/lineCap +translation_of: Web/API/CanvasRenderingContext2D/lineCap +--- +<div>{{APIRef}}</div> + +<p>La propiedad <code><strong>CanvasRenderingContext2D</strong></code><strong><code>.lineCap</code></strong> del API Canvas 2D determina la forma usada para dibujar los puntos finales de las líneas.</p> + +<div class="blockIndicator note"> +<p><strong>Nota:</strong> La líneas se puede dibujar con los métodos {{domxref("CanvasRenderingContext2D.stroke()", "stroke()")}}, {{domxref("CanvasRenderingContext2D.strokeRect()", "strokeRect()")}}, y {{domxref("CanvasRenderingContext2D.strokeText()", "strokeText()")}}.</p> +</div> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><em>ctx</em>.lineCap = "butt" || "round" || "square"; +</pre> + +<h3 id="Opciones">Opciones</h3> + +<dl> + <dt><code>"butt"</code></dt> + <dd>Los finales de las líneas son recortados. Valor por defecto.</dd> + <dt><code>"round"</code></dt> + <dd>Los finales de las líneas son redondeados.</dd> + <dt><code>"square"</code></dt> + <dd>Los finales de líneas son recortados al agregar un cuadrado de ancho y altura igual que el grosor de línea.</dd> +</dl> + +<h2 id="Ejemplos">Ejemplos</h2> + +<h3 id="Cambiando_los_finales_de_línea">Cambiando los finales de línea</h3> + +<p>En este ejemplo se redondean los puntos finales de una línea recta.</p> + +<h4 id="HTML">HTML</h4> + +<pre class="brush: html"><canvas id="canvas"></canvas> +</pre> + +<h4 id="JavaScript">JavaScript</h4> + +<pre class="brush: js; highlight:[7]">const canvas = document.getElementById('canvas'); +const ctx = canvas.getContext('2d'); + +ctx.beginPath(); +ctx.moveTo(20, 20); +ctx.lineWidth = 15; +ctx.lineCap = 'round'; +ctx.lineTo(100, 100); +ctx.stroke(); +</pre> + +<h4 id="Result">Result</h4> + +<p>{{ EmbedLiveSample('Changing_the_shape_of_line_caps', 700, 180) }}</p> + +<h3 id="Comparando_los_finales_de_línea">Comparando los finales de línea</h3> + +<p>En este ejemplo se dibujan 3 líneas, cada una con un valor distinto de la propiedad <code>lineCap</code>. Se agregaron dos guías para resaltar las diferencias entre las tres líneas. Cada una de estas líneas empiezan y terminan en estas guías.</p> + +<p>La línea de la izquiera usa la opción por defecto <code>"butt"</code>. Esta es dibujada completamente al ras de las líneas de guía. La segunda esta configurada para usar la opción <code>"round</code>. Esta agrega un semicírculo al final que tiene un radio de la mitad del grosor de línea. La línea de la derecha use la opción <code>"square"</code>. Esta agrega un cuadrado con ancho y altura de la mitad del grosor de línea.</p> + +<div class="hidden"> +<pre class="brush: html"><canvas id="canvas" width="150" height="150"></canvas></pre> +</div> + +<pre class="brush: js">const canvas = document.getElementById('canvas'); +const ctx = canvas.getContext('2d'); +const lineCap = ['butt', 'round', 'square']; + +// Draw guides +ctx.strokeStyle = '#09f'; +ctx.beginPath(); +ctx.moveTo(10, 10); +ctx.lineTo(140, 10); +ctx.moveTo(10, 140); +ctx.lineTo(140, 140); +ctx.stroke(); + +// Draw lines +ctx.strokeStyle = 'black'; +for (let i = 0; i < lineCap.length; i++) { + ctx.lineWidth = 15; + ctx.lineCap = lineCap[i]; + ctx.beginPath(); + ctx.moveTo(25 + i * 50, 10); + ctx.lineTo(25 + i * 50, 140); + ctx.stroke(); +} +</pre> + +<p>{{EmbedLiveSample("Comparison_of_line_caps", "180", "180", "https://mdn.mozillademos.org/files/236/Canvas_linecap.png")}}</p> + +<h2 id="Especificaciones">Especificaciones</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-context-2d-linecap", "CanvasRenderingContext2D.lineCap")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegador.">Compatibilidad de navegador.</h2> + + + +<p>{{Compat("api.CanvasRenderingContext2D.lineCap")}}</p> + +<h3 id="WebKitBlink-specific_notes">WebKit/Blink-specific notes</h3> + +<ul> + <li>En WebKit- y navegadores basados en Blink, el método no estandard y obsoleto <code>ctx.setLineCap()</code> es implementado ademas de esta propiedad.</li> +</ul> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>La interfaz que define esta propiedad: {{domxref("CanvasRenderingContext2D")}}</li> + <li>{{domxref("CanvasRenderingContext2D.lineWidth")}}</li> + <li>{{domxref("CanvasRenderingContext2D.lineJoin")}}</li> + <li><a href="/en-US/docs/Web/API/Canvas_API/Tutorial/Applying_styles_and_colors">Aplicando estilos y color</a></li> +</ul> diff --git a/files/es/web/api/canvasrenderingcontext2d/rotate/index.html b/files/es/web/api/canvasrenderingcontext2d/rotate/index.html new file mode 100644 index 0000000000..009b280c4c --- /dev/null +++ b/files/es/web/api/canvasrenderingcontext2d/rotate/index.html @@ -0,0 +1,137 @@ +--- +title: CanvasRenderingContext2D.rotate() +slug: Web/API/CanvasRenderingContext2D/rotate +tags: + - metodo +translation_of: Web/API/CanvasRenderingContext2D/rotate +--- +<div>{{APIRef}}</div> + +<p>El método <code><strong>CanvasRenderingContext2D</strong></code><strong><code>.rotate()</code></strong> de la API Canvas 2D añade una rotación a la matriz de transformación.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">void <em>ctx</em>.rotate(<em>angulo</em>); +</pre> + +<p><img alt="" class="internal" src="https://mdn.mozillademos.org/files/233/Canvas_grid_rotate.png" style="float: right;"></p> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code>angulo</code></dt> + <dd>El ángulo de rotación en radianes, en sentido horario. Se puede usar <em><code>grado</code></em><code><code>*</code> Math.PI / 180</code> si se quiere calcular a partir de un valor de grado sexagesimal.</dd> +</dl> + +<p>El centro de rotación es siempre el orígen del canvas. Para cambiar el centro de rotación hay que mover el canvas mediante el método {{domxref("CanvasRenderingContext2D.translate", "translate()")}}.</p> + +<h2 id="Ejemplos">Ejemplos</h2> + +<h3 id="Rotando_una_figura">Rotando una figura</h3> + +<p>En este ejemplo se rota un rectangulo 45º. Nótese que el centro de rotación es la esquina superior izquierda del canvas y no un punto cualquiera relativo a alguna figura.</p> + +<h4 id="HTML">HTML</h4> + +<pre class="brush: html"><canvas id="canvas"></canvas> +</pre> + +<h4 id="JavaScript">JavaScript</h4> + +<pre class="brush: js; highlight:[14]">const canvas = document.getElementById('canvas'); +const ctx = canvas.getContext('2d'); + +// origen del punto de transformación +ctx.arc(0, 0, 5, 0, 2 * Math.PI); +ctx.fillStyle = 'blue'; +ctx.fill(); + +// rectángulo sin rotar +ctx.fillStyle = 'gray'; +ctx.fillRect(100, 0, 80, 20); + +// rectángulo rotado 45º +ctx.rotate(45 * Math.PI / 180); +ctx.fillStyle = 'red'; +ctx.fillRect(100, 0, 80, 20); + +// se reinicia la matriz de transformación a la matriz identidad +ctx.setTransform(1, 0, 0, 1, 0, 0); +</pre> + +<h4 id="Resultado">Resultado</h4> + +<p>El <span style="color: blue;">centro de rotación es azul</span>. El <span style="color: gray;">rectángulo no rotado es gris</span>, y el <span style="color: red;">rectángulo rotado es rojo</span>.</p> + +<p>{{ EmbedLiveSample('Rotating_a_shape', 700, 180) }}</p> + +<h3 id="Rotando_una_figura_por_su_centro">Rotando una figura por su centro</h3> + +<p>Este ejemplo rota una figura alrededor del punto central de ésta. Para realizarlo se aplican estos pasos a la matriz de transformación:</p> + +<ol> + <li>Primero, {{domxref("CanvasRenderingContext2D.translate()", "translate()")}} mueve el orígen de la matriz hacia el centro de la figura.</li> + <li><code>rotate()</code> rota la matriz la cantidad deseada.</li> + <li>Finalmente, <code>translate()</code> mueve el origen de la matriz de nuevo a su punto inicial. Esto se realiza utilizando los valores del centro de coordenadas de la figura en dirección negativa.</li> +</ol> + +<h4 id="HTML_2">HTML</h4> + +<pre class="brush: html"><canvas id="canvas"></canvas> +</pre> + +<h4 id="JavaScript_2">JavaScript</h4> + +<p>La figura es un rectángulo con su esquina en (80, 60), un ancho de 140 y un alto de 30. El centro de la coordenada horizontal está en (80 + 140 / 2) = 150. Su centro en la coordenada vertical será (60 + 30 / 2) = 75. Por tanto, el punto central está en (150, 75).</p> + +<pre class="brush: js">const canvas = document.getElementById('canvas'); +const ctx = canvas.getContext('2d'); + +// rectángulo sin rotar +ctx.fillStyle = 'gray'; +ctx.fillRect(80, 60, 140, 30); + +// Matriz de transformación +ctx.translate(150, 75); +ctx.rotate(Math.PI / 2); +ctx.translate(-150, -75); + +// rectángulo rotado +ctx.fillStyle = 'red'; +ctx.fillRect(80, 60, 140, 30); +</pre> + +<h4 id="Resultado_2">Resultado</h4> + +<p>El <span style="color: gray;">rectángulo no rotado es gris</span>, y el <span style="color: red;">rectángulo rotado es rojo</span>.</p> + +<p>{{ EmbedLiveSample('Rotating_a_shape_around_its_center', 700, 180) }}</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Status</th> + <th scope="col">Comentarios</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-rotate", "CanvasRenderingContext2D.rotate")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_exploradores">Compatibilidad con exploradores</h2> + +<div class="hidden">La tabla de compatibilidad de esta página se genera a partir de datos estructurados. Si desea contribuir a estos datos, vaya a <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> y haga un pull request.</div> + +<p>{{Compat("api.CanvasRenderingContext2D.rotate")}}</p> + +<h2 id="Véase_también">Véase también</h2> + +<ul> + <li>La interface donde se define este método: {{domxref("CanvasRenderingContext2D")}}</li> +</ul> diff --git a/files/es/web/api/canvasrenderingcontext2d/save/index.html b/files/es/web/api/canvasrenderingcontext2d/save/index.html new file mode 100644 index 0000000000..6351bb3ad1 --- /dev/null +++ b/files/es/web/api/canvasrenderingcontext2d/save/index.html @@ -0,0 +1,91 @@ +--- +title: CanvasRenderingContext2D.save() +slug: Web/API/CanvasRenderingContext2D/save +tags: + - API + - Canvas + - CanvasRenderingContext2D + - Referencia + - metodo +translation_of: Web/API/CanvasRenderingContext2D/save +--- +<div>{{APIRef}}</div> + +<p>El método <code><strong>CanvasRenderingContext2D</strong></code><strong><code>.save()</code></strong> del API Canvas 2D guarda el estado completo del canvas añadiendo el estado actual a una pila.</p> + +<h3 id="El_estado_del_dibujo">El estado del dibujo</h3> + +<p>El estado del dibujo que se almacena en una pila consiste en los siguientes elementos:</p> + +<ul> + <li>La matriz de transformación actual.</li> + <li>La región de recorte actual.</li> + <li>La lista de punteado actual.</li> + <li>Los valores actuales de los siguientes atributos: {{domxref("CanvasRenderingContext2D.strokeStyle", "strokeStyle")}}, {{domxref("CanvasRenderingContext2D.fillStyle", "fillStyle")}}, {{domxref("CanvasRenderingContext2D.globalAlpha", "globalAlpha")}}, {{domxref("CanvasRenderingContext2D.lineWidth", "lineWidth")}}, {{domxref("CanvasRenderingContext2D.lineCap", "lineCap")}}, {{domxref("CanvasRenderingContext2D.lineJoin", "lineJoin")}}, {{domxref("CanvasRenderingContext2D.miterLimit", "miterLimit")}}, {{domxref("CanvasRenderingContext2D.lineDashOffset", "lineDashOffset")}}, {{domxref("CanvasRenderingContext2D.shadowOffsetX", "shadowOffsetX")}}, {{domxref("CanvasRenderingContext2D.shadowOffsetY", "shadowOffsetY")}}, {{domxref("CanvasRenderingContext2D.shadowBlur", "shadowBlur")}}, {{domxref("CanvasRenderingContext2D.shadowColor", "shadowColor")}}, {{domxref("CanvasRenderingContext2D.globalCompositeOperation", "globalCompositeOperation")}}, {{domxref("CanvasRenderingContext2D.font", "font")}}, {{domxref("CanvasRenderingContext2D.textAlign", "textAlign")}}, {{domxref("CanvasRenderingContext2D.textBaseline", "textBaseline")}}, {{domxref("CanvasRenderingContext2D.direction", "direction")}}, {{domxref("CanvasRenderingContext2D.imageSmoothingEnabled", "imageSmoothingEnabled")}}.</li> +</ul> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">void <em>ctx</em>.save();</pre> + +<h2 id="Ejemplos">Ejemplos</h2> + +<h3 id="Guardando_el_estado_del_dibujo">Guardando el estado del dibujo</h3> + +<p>Este ejemplo usa el método <code>save()</code> para guardar el estado por defecto y el método <code>restore()</code> para restaurarlo luego, de tal manera que luego se puede dibujar el segundo rectángulo con el estado por defecto.</p> + +<h4 id="HTML">HTML</h4> + +<pre class="brush: html"><canvas id="canvas"></canvas> +</pre> + +<h4 id="JavaScript">JavaScript</h4> + +<pre class="brush: js; highlight:[5]">const canvas = document.getElementById('canvas'); +const ctx = canvas.getContext('2d'); + +// Guardar el estado por defecto +ctx.save(); + +ctx.fillStyle = 'green'; +ctx.fillRect(10, 10, 100, 100); + +// Restaurar el estado por defecto +ctx.restore(); + +ctx.fillRect(150, 40, 100, 100); +</pre> + +<h4 id="Resultado">Resultado</h4> + +<p>{{ EmbedLiveSample('Saving_the_drawing_state', 700, 180) }}</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentarios</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-save", "CanvasRenderingContext2D.save")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_exploradores">Compatibilidad con exploradores</h2> + + + +<p>{{Compat("api.CanvasRenderingContext2D.save")}}</p> + +<h2 id="Véase_también">Véase también</h2> + +<ul> + <li>La interfaz donde se define este método: {{domxref("CanvasRenderingContext2D")}}</li> + <li>{{domxref("CanvasRenderingContext2D.restore()")}}</li> +</ul> diff --git a/files/es/web/api/childnode/after/index.html b/files/es/web/api/childnode/after/index.html new file mode 100644 index 0000000000..b6512e73c0 --- /dev/null +++ b/files/es/web/api/childnode/after/index.html @@ -0,0 +1,181 @@ +--- +title: ChildNode.after() +slug: Web/API/ChildNode/after +tags: + - API + - DOM + - Experimental + - Nodo + - Referencia + - metodo +translation_of: Web/API/ChildNode/after +--- +<p>{{APIRef("DOM")}} {{SeeCompatTable}}<br> + <span lang="es"><span>El método <code><strong>ChildNode.after()</strong></code> inserta un conjunto de objetos {{domxref("Node")}} o {{domxref("DOMString")}} en la lista de hijos de este <code>ChildNode</code> del padre, justo después de este <code>ChildNode</code>.</span> <span>Los objetos {{domxref("DOMString")}} se insertan como nodos equivalentes {{domxref("Text")}}.</span></span></p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">[Throws, Unscopable] +void ChildNode.after((Node o DOMString)... nodes); +</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code>nodes</code></dt> + <dd><span id="result_box" lang="es"><span>Un conjunto de objetos </span></span><span lang="es"><span>{{domxref("Node")}} o </span></span>{{domxref("DOMString")}}<span lang="es"><span> para insertar.</span></span></dd> +</dl> + +<h3 id="Excepciones">Excepciones</h3> + +<ul> + <li>{{domxref("HierarchyRequestError")}}: No se puede insertar nodo en el punto especificado de la jerarquía.</li> +</ul> + +<h2 id="Ejemplos">Ejemplos</h2> + +<h3 id="Insertando_un_elemento">Insertando un elemento</h3> + +<pre class="brush: js">var parent = document.createElement("div"); +var child = document.createElement("p"); +parent.appendChild(child); +var span = document.createElement("span"); + +child.after(span); + +console.log(parent.outerHTML); +// "<div><p></p><span></span></div>" +</pre> + +<h3 id="Insertando_texto">Insertando texto</h3> + +<pre class="brush: js">var parent = document.createElement("div"); +var child = document.createElement("p"); +parent.appendChild(child); + +child.after("Text"); + +console.log(parent.outerHTML); +// "<div><p></p>Text</div>"</pre> + +<h3 id="Insertando_un_elemento_y_texto">Insertando un elemento y texto</h3> + +<pre class="brush: js">var parent = document.createElement("div"); +var child = document.createElement("p"); +parent.appendChild(child); +var span = document.createElement("span"); + +child.after(span, "Text"); + +console.log(parent.outerHTML); +// "<div><p></p><span></span>Text</div>"</pre> + +<h3 id="ChildNode.after_es_unscopable"><code>ChildNode.after()</code> es unscopable</h3> + +<p>El método <code>after()</code> no está incluido en la declaración <code>with</code>.Consulte {{jsxref("Symbol.unscopables")}} para obtener más información.</p> + +<pre class="brush: js">with(node) { + after("foo"); +} +// ReferenceError: after is not defined </pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>Puedes usar un polyfill del método <code>after()</code> en Internet Explorer 9 y superiores con el siguente código:</p> + +<pre class="brush: js">// from: https://github.com/jserz/js_piece/blob/master/DOM/ChildNode/after()/after().md +(function (arr) { + arr.forEach(function (item) { + if (item.hasOwnProperty('after')) { + return; + } + Object.defineProperty(item, 'after', { + configurable: true, + enumerable: true, + writable: true, + value: function after() { + var argArr = Array.prototype.slice.call(arguments), + docFrag = document.createDocumentFragment(); + + argArr.forEach(function (argItem) { + var isNode = argItem instanceof Node; + docFrag.appendChild(isNode ? argItem : document.createTextNode(String(argItem))); + }); + + this.parentNode.insertBefore(docFrag, this.nextSibling); + } + }); + }); +})([Element.prototype, CharacterData.prototype, DocumentType.prototype]);</pre> + +<h3 id="Otro_polyfill">Otro polyfill</h3> + +<pre class="brush: js">// from: https://github.com/FabioVergani/js-Polyfill_Element.prototype.after/blob/master/after.js + +(function(x){ + var o=x.prototype,p='after'; + if(!o[p]){ + o[p]=function(){ + var e, m=arguments, l=m.length, i=0, t=this, p=t.parentNode, n=Node, s=String, d=document; + if(p!==null){ + while(i<l){ + e=m[i]; + if(e instanceof n){ + t=t.nextSibling; + if(t!==null){ + p.insertBefore(e,t); + }else{ + p.appendChild(e); + }; + }else{ + p.appendChild(d.createTextNode(s(e))); + }; + ++i; + }; + }; + }; + }; +})(Element); + + + +/* +minified: + +(function(x){ + var o=x.prototype; + o.after||(o.after=function(){var e,m=arguments,l=m.length,i=0,t=this,p=t.parentNode,n=Node,s=String,d=document;if(p!==null){while(i<l){((e=m[i]) instanceof n)?(((t=t.nextSibling )!==null)?p.insertBefore(e,t):p.appendChild(e)):p.appendChild(d.createTextNode(s(e)));++i;}}}); +}(Element)); +*/ +</pre> + +<h2 id="Especificación">Especificación</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('DOM WHATWG', '#dom-childnode-after', 'ChildNode.after()')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Definición Inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<p>{{Compat("api.ChildNode.after")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("ChildNode")}} y {{domxref("ParentNode")}}</li> + <li>{{domxref("ChildNode.before()")}}</li> + <li>{{domxref("ParentNode.append()")}}</li> + <li>{{domxref("Node.appendChild()")}}</li> + <li>{{domxref("NodeList")}}</li> +</ul> diff --git a/files/es/web/api/childnode/before/index.html b/files/es/web/api/childnode/before/index.html new file mode 100644 index 0000000000..b7ac4e3835 --- /dev/null +++ b/files/es/web/api/childnode/before/index.html @@ -0,0 +1,175 @@ +--- +title: ChildNode.before() +slug: Web/API/ChildNode/before +tags: + - API + - DOM + - Experimental + - Nodo + - Referencia + - metodo +translation_of: Web/API/ChildNode/before +--- +<p><textarea></textarea></p> + +<div id="gt-input-tool"> +<div id="itamenu"> </div> +</div> + +<div class="g-unit" id="gt-src-c"> +<div id="gt-src-p"> </div> +</div> + +<div id="gt-res-content"> +<div dir="ltr" style="zoom: 1;"><span id="result_box" lang="es"><span>{{APIRef ( "DOM")}} {{SeeCompatTable}}</span><br> +<br> +<span>El método <strong>ChildNode.before</strong> inserta un conjunto de objetos {{domxref ( "Node")}} o {{domxref ( "DOMString")}} en la lista de hijos de este ChildNode del padre, justo antes de este ChildNode.</span> <span>Los objetos {{domxref ( "DOMString")}} se insertan como nodos equivalentes {{domxref ( "Text")}}.</span></span></div> +</div> + +<h2 id="Síntasix">Síntasix</h2> + +<pre class="syntaxbox">[Throws, Unscopable] +void ChildNode.before((Node or DOMString)... nodes); +</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code>nodos</code></dt> + <dd><span id="result_box" lang="es"><span>Un conjunto de objetos {{domxref ( "Node")}} o {{domxref ( "DOMString")}} para insertar.</span></span></dd> +</dl> + +<h3 id="Excepciones">Excepciones</h3> + +<ul> + <li>{{domxref("HierarchyRequestError")}}: Node cannot be inserted at the specified point in the hierarchy.</li> +</ul> + +<h2 id="Ejemplos">Ejemplos</h2> + +<h3 id="Insertando_un_elemento">Insertando un elemento</h3> + +<pre class="brush: js">var parent = document.createElement("div"); +var child = document.createElement("p"); +parent.appendChild(child); +var span = document.createElement("span"); + +child.before(span); + +console.log(parent.outerHTML); +// "<div><span></span><p></p></div>" +</pre> + +<h3 id="Insertando_texto">Insertando texto</h3> + +<pre class="brush: js">var parent = document.createElement("div"); +var child = document.createElement("p"); +parent.appendChild(child); + +child.before("Text"); + +console.log(parent.outerHTML); +// "<div>Text<p></p></div>"</pre> + +<h3 id="Insertando_un_elemento_y_texto">Insertando un elemento y texto</h3> + +<pre class="brush: js">var parent = document.createElement("div"); +var child = document.createElement("p"); +parent.appendChild(child); +var span = document.createElement("span"); + +child.before(span, "Text"); + +console.log(parent.outerHTML); +// "<div><span></span>Text<p></p></div>"</pre> + +<h3 id="ChildNode.before()_es_unscopable"><code>ChildNode.before()</code> es unscopable</h3> + +<p><span id="result_box" lang="es"><span>El método before () no está definido en la declaración <em>with</em>.</span> <span>Consulte {{jsxref ( "Symbol.unscopables")}} para obtener más información.</span></span></p> + +<pre class="brush: js">with(node) { + before("foo"); +} +// ReferenceError: before is not defined </pre> + +<h2 id="Especificación">Especificación</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('DOM WHATWG', '#dom-childnode-before', 'ChildNode.before()')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Definición Inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_los_Navegadores">Compatibilidad en los Navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Función</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>{{CompatChrome(54.0)}}</td> + <td>{{CompatGeckoDesktop(49)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatOpera(39)}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Función</th> + <th>Android</th> + <th>Android Webview</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(54.0)}}</td> + <td>{{CompatGeckoMobile(49)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatOpera(39)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatChrome(54.0)}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("ChildNode")}} and {{domxref("ParentNode")}}</li> + <li>{{domxref("ChildNode.after()")}}</li> + <li>{{domxref("ParentNode.append()")}}</li> + <li>{{domxref("Node.appendChild()")}}</li> + <li>{{domxref("Node.insertBefore()")}}</li> + <li>{{domxref("NodeList")}}</li> +</ul> diff --git a/files/es/web/api/childnode/index.html b/files/es/web/api/childnode/index.html new file mode 100644 index 0000000000..f354d73bd1 --- /dev/null +++ b/files/es/web/api/childnode/index.html @@ -0,0 +1,180 @@ +--- +title: ChildNode +slug: Web/API/ChildNode +tags: + - API + - DOM + - Experimental + - Interface + - NeedsTranslation + - Node + - TopicStub +translation_of: Web/API/ChildNode +--- +<div>{{APIRef("DOM")}}</div> + +<p>The <code><strong>ChildNode</strong></code> interface contains methods that are particular to {{domxref("Node")}} objects that can have a parent.</p> + +<p><code>ChildNode</code> is a raw interface and no object of this type can be created; it is implemented by {{domxref("Element")}}, {{domxref("DocumentType")}}, and {{domxref("CharacterData")}} objects.</p> + +<h2 id="Properties">Properties</h2> + +<p><em>There are neither inherited, nor specific properties.</em></p> + +<h2 id="Methods">Methods</h2> + +<p><em>There are no inherited methods.</em></p> + +<dl> + <dt>{{domxref("ChildNode.remove()")}} {{experimental_inline}}</dt> + <dd>Removes this <code>ChildNode</code> from the children list of its parent.</dd> + <dt>{{domxref("ChildNode.before()")}} {{experimental_inline}}</dt> + <dd>Inserts a set of {{domxref("Node")}} or {{domxref("DOMString")}} objects in the children list of this <code>ChildNode</code>'s parent, just before this <code>ChildNode</code>. {{domxref("DOMString")}} objects are inserted as equivalent {{domxref("Text")}} nodes.</dd> + <dt>{{domxref("ChildNode.after()")}} {{experimental_inline}}</dt> + <dd>Inserts a set of {{domxref("Node")}} or {{domxref("DOMString")}} objects in the children list of this <code>ChildNode</code>'s parent, just after this <code>ChildNode</code>. {{domxref("DOMString")}} objects are inserted as equivalent {{domxref("Text")}} nodes.</dd> + <dt>{{domxref("ChildNode.replaceWith()")}} {{experimental_inline}}</dt> + <dd>Replaces this <code>ChildNode</code> in the children list of its parent with a set of {{domxref("Node")}} or {{domxref("DOMString")}} objects. {{domxref("DOMString")}} objects are inserted as equivalent {{domxref("Text")}} nodes.</dd> +</dl> + +<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('DOM WHATWG', '#interface-childnode', 'ChildNode')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Split the <code>ElementTraversal</code> interface in {{domxref("ParentNode")}} and <code>ChildNode</code>. <code>previousElementSibling</code> and <code>nextElementSibling</code> are now defined on the latter. The {{domxref("CharacterData")}} and {{domxref("DocumentType")}} implemented the new interfaces. Added the <code>remove()</code>, <code>before()</code>, <code>after()</code> and <code>replaceWith()</code> methods.</td> + </tr> + <tr> + <td>{{SpecName('Element Traversal', '#interface-elementTraversal', 'ElementTraversal')}}</td> + <td>{{Spec2('Element Traversal')}}</td> + <td>Added the initial definition of its properties to the <code>ElementTraversal</code> pure interface and use it on {{domxref("Element")}}.</td> + </tr> + </tbody> +</table> + +<h2 id="Polyfill">Polyfill</h2> + +<p>External on github: <a href="https://github.com/seznam/JAK/blob/master/lib/polyfills/childNode.js">childNode.js</a></p> + +<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 (on {{domxref("Element")}})</td> + <td>{{CompatChrome(1.0)}}</td> + <td>{{CompatGeckoDesktop(23)}}</td> + <td>9.0</td> + <td>10.0</td> + <td>4.0</td> + </tr> + <tr> + <td>Support on {{domxref("DocumentType")}} and {{domxref("CharacterData")}} {{experimental_inline}}</td> + <td>{{CompatChrome(23.0)}}</td> + <td>{{CompatGeckoDesktop(23)}}</td> + <td>{{CompatNo}}</td> + <td>16.0</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>remove()</code>{{experimental_inline}}</td> + <td>{{CompatChrome(29.0)}}</td> + <td>{{CompatGeckoDesktop(23)}}</td> + <td>Edge</td> + <td>16.0</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>before()</code>, <code>after()</code>, and <code>replaceWith()</code> {{experimental_inline}}</td> + <td>{{CompatChrome(54.0)}}</td> + <td>{{CompatGeckoDesktop(49)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatOpera(39)}}</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>Android Webview</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support (on {{domxref("Element")}})</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile(23)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>10.0</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Support on {{domxref("DocumentType")}} and {{domxref("CharacterData")}} {{experimental_inline}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile(23)}}</td> + <td>{{CompatNo}}</td> + <td>16.0</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>remove()</code>{{experimental_inline}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile(23)}}</td> + <td>{{CompatNo}}</td> + <td>16.0</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>before()</code>, <code>after()</code>, and <code>replaceWith()</code> {{experimental_inline}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(54.0)}}</td> + <td>{{CompatGeckoMobile(49)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatOperaMobile(39)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(54.0)}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>The {{domxref("ParentNode")}} pure interface.</li> + <li> + <div class="syntaxbox">Object types implementing this pure interface: {{domxref("CharacterData")}}, {{domxref("Element")}}, and {{domxref("DocumentType")}}.</div> + </li> +</ul> diff --git a/files/es/web/api/childnode/remove/index.html b/files/es/web/api/childnode/remove/index.html new file mode 100644 index 0000000000..90aab3d869 --- /dev/null +++ b/files/es/web/api/childnode/remove/index.html @@ -0,0 +1,94 @@ +--- +title: ChildNode.remove() +slug: Web/API/ChildNode/remove +tags: + - API + - ChildNode + - DOM + - Experimental + - metodo +translation_of: Web/API/ChildNode/remove +--- +<p><span id="result_box" lang="es"><span>{{APIRef ( "DOM")}}</span><br> + <span>El método<strong> ChildNode.remove ( ) </strong>elimina el objeto del árbol al que pertenece.</span></span></p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><em>node</em>.remove(); +</pre> + +<h2 id="Ejemplo">Ejemplo</h2> + +<h3 id="Utilizando_remove">Utilizando <code>remove()</code></h3> + +<pre class="brush: html"><div id="div-01">Este es el div-01</div> +<div id="div-02">Este es el div-02</div> +<div id="div-03">Este es el div-03</div> +</pre> + +<pre class="brush: js">var el = document.getElementById('div-02'); +el.nextElementSibling.remove(); // Elimina el div con el id 'div-03' +</pre> + +<h3 id="ChildNode.remove_es_unscopable"><code>ChildNode.remove()</code> es unscopable</h3> + +<p><span id="result_box" lang="es"><span>El método <code>remove()</code> no está definido en el contexto de las declaración <code>with</code>.</span> <span>Consulte {{jsxref ("Symbol.unscopables")}} para obtener más información.</span></span></p> + +<pre class="brush: js">with(node) { + remove(); +} +// ReferenceError: remove is not defined </pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>El código a continuación es un polyfill del método <code>remove()</code> para Internet Explorer 9 y superiores:</p> + +<pre class="brush: js">// from:https://github.com/jserz/js_piece/blob/master/DOM/ChildNode/remove()/remove().md +(function (arr) { + arr.forEach(function (item) { + if (item.hasOwnProperty('remove')) { + return; + } + Object.defineProperty(item, 'remove', { + configurable: true, + enumerable: true, + writable: true, + value: function remove() { + if (this.parentNode !== null) + this.parentNode.removeChild(this); + } + }); + }); +})([Element.prototype, CharacterData.prototype, DocumentType.prototype]);</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('DOM WHATWG', '#dom-childnode-remove', 'ChildNode.remove')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_los_navegadores">Compatibilidad en los navegadores</h2> + +<div> +<p>{{Compat("api.ChildNode.remove")}}</p> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><span class="short_text" id="result_box" lang="es"><span>La interfaz pura {{domxref ( "ChildNode")}} .</span></span></li> + <li> + <div class="syntaxbox"><span id="result_box" lang="es"><span>Tipos de objetos que implementan esta interfaz pura: {{domxref ( "CharacterData")}}, {{domxref ( "Elemento")}} y {{domxref ( "DocumentType")}}.</span></span></div> + </li> +</ul> diff --git a/files/es/web/api/childnode/replacewith/index.html b/files/es/web/api/childnode/replacewith/index.html new file mode 100644 index 0000000000..32f78b7e4e --- /dev/null +++ b/files/es/web/api/childnode/replacewith/index.html @@ -0,0 +1,141 @@ +--- +title: ChildNode.replaceWith() +slug: Web/API/ChildNode/replaceWith +tags: + - API + - DOM + - Experimental + - Nodo + - Referencia + - metodo +translation_of: Web/API/ChildNode/replaceWith +--- +<p><span id="result_box" lang="es"><span>{{APIRef ( "DOM")}} {{SeeCompatTable}}</span><br> + <br> + <span>El método <strong>ChildNode.replaceWith () </strong>reemplaza este ChildNode en la lista de hijos de su padre con un conjunto de objetos {{domxref ( "Node")}} o {{domxref ( "DOMString")}}.</span> <span>Los objetos {{domxref ( "DOMString")}} se insertan como nodos equivalentes {{domxref ( "Text")}}.</span></span></p> + +<p> </p> + +<h2 id="Síntasix">Síntasix</h2> + +<p> </p> + +<pre class="syntaxbox">[Throws, Unscopable] +void ChildNode.replaceWith((Node or DOMString)... nodes); +</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code>nodos</code></dt> + <dd><span id="result_box" lang="es"><span>Un conjunto de objetos {{domxref ( "Node")}} o {{domxref ( "DOMString")}} para reemplazar.</span></span></dd> +</dl> + +<h3 id="Excepciones">Excepciones</h3> + +<ul> + <li><span id="result_box" lang="es"><span>{{Domxref ( "HierarchyRequestError")}}: No se puede insertar nodo en el punto especificado de la jerarquía.</span></span></li> +</ul> + +<h2 id="Ejemplos">Ejemplos</h2> + +<h3 id="Utilizando_replaceWith()">Utilizando <code>replaceWith()</code></h3> + +<pre class="brush: js">var parent = document.createElement("div"); +var child = document.createElement("p"); +parent.appendChild(child); +var span = document.createElement("span"); + +child.replaceWith(span); + +console.log(parent.outerHTML); +// "<div><span></span></div>" +</pre> + +<h3 id="ChildNode.replaceWith()_es_unscopable"><code>ChildNode.replaceWith()</code> es unscopable</h3> + +<p><span id="result_box" lang="es"><span>El método replaceWith () no está incluido en la declaracion <em><code>with</code>.</em></span> <span>Consulte {{jsxref ( "Symbol.unscopables")}} para obtener más información.</span></span></p> + +<pre class="brush: js">with(node) { + replaceWith("foo"); +} +// ReferenceError: replaceWith is not defined </pre> + +<h2 id="Especificación">Especificación</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('DOM WHATWG', '#dom-childnode-replacewith', 'ChildNode.replacewith()')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Definición Inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_los_Navegadores">Compatibilidad en los Navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Función</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>{{CompatChrome(54.0)}}</td> + <td>{{CompatGeckoDesktop(49)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatOpera(39)}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Función</th> + <th>Android</th> + <th>Android Webview</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Mobile</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(54.0)}}</td> + <td>{{CompatGeckoMobile(49)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatOperaMobile(39)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatChrome(54.0)}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_También">Ver También</h2> + +<ul> + <li>{{domxref("ChildNode")}} and {{domxref("ParentNode")}}</li> + <li>{{domxref("Node.replaceChild()")}}</li> + <li>{{domxref("NodeList")}}</li> +</ul> diff --git a/files/es/web/api/clipboardevent/clipboarddata/index.html b/files/es/web/api/clipboardevent/clipboarddata/index.html new file mode 100644 index 0000000000..547b2d1f9e --- /dev/null +++ b/files/es/web/api/clipboardevent/clipboarddata/index.html @@ -0,0 +1,58 @@ +--- +title: ClipboardEvent.clipboardData +slug: Web/API/ClipboardEvent/clipboardData +tags: + - API + - Clipboard API + - Experimental + - Portapapeles + - Solo lectura + - metodo +translation_of: Web/API/ClipboardEvent/clipboardData +--- +<p>{{ apiref("Clipboard API") }} {{SeeCompatTable}}</p> + +<p>La propiedad <code><strong>ClipboardEvent.clipboardData</strong></code>, del tipo {{domxref("DataTransfer")}}, puede ser usuada:</p> + +<ul> + <li>Para especificar qué datos mover al portapapeles cuando se produzcan los eventos {{event("cut")}} y {{event("copy")}}, normalmente a través de {{domxref("DataTransfer.setData", "setData(format, data)")}};</li> + <li>Para obtener la información del portapapeles a ser pegada cuando se produce el evento {{event("paste")}}, normalmente a través de {{domxref("DataTransfer.getData", "getData(format)")}}.</li> +</ul> + +<p>Para más información, mira la documentación de los eventos {{event("cut")}}, {{event("copy")}}, y {{event("paste")}}.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><em>data</em> = <em>ClipboardEvent</em>.clipboardData</pre> + +<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('Clipboard API', '#widl-ClipboardEvent-clipboardData', 'ClipboardEvent.clipboardData') }}</td> + <td>{{ Spec2('Clipboard API') }}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + + + +<p>{{Compat("api.ClipboardEvent.clipboardData")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>Otros eventos del portapapeles: {{event("copy")}}, {{event("cut")}}, {{event("paste")}}</li> + <li>La interfaz base: {{domxref("ClipboardEvent")}}.</li> +</ul> diff --git a/files/es/web/api/clipboardevent/index.html b/files/es/web/api/clipboardevent/index.html new file mode 100644 index 0000000000..332846c031 --- /dev/null +++ b/files/es/web/api/clipboardevent/index.html @@ -0,0 +1,67 @@ +--- +title: ClipboardEvent +slug: Web/API/ClipboardEvent +tags: + - API + - Clipboard API + - Event + - Experimental + - Interface + - NeedsTranslation + - TopicStub +translation_of: Web/API/ClipboardEvent +--- +<p>{{APIRef("Clipboard API")}} {{SeeCompatTable}}</p> + +<p>The <strong><code>ClipboardEvent</code></strong> interface represents events providing information related to modification of the clipboard, that is {{event("cut")}}, {{event("copy")}}, and {{event("paste")}} events.</p> + +<h2 id="Constructor">Constructor</h2> + +<dl> + <dt>{{domxref("ClipboardEvent.ClipboardEvent", "ClipboardEvent()")}}</dt> + <dd>Creates a <code>ClipboardEvent</code> event with the given parameters.</dd> +</dl> + +<h2 id="Properties">Properties</h2> + +<p><em>Also inherits properties from its parent {{domxref("Event")}}</em>.</p> + +<dl> + <dt>{{domxref("ClipboardEvent.clipboardData")}} {{readonlyInline}}</dt> + <dd>Is a {{domxref("DataTransfer")}} object containing the data affected by the user-initiated {{event("cut")}}, {{event("copy")}}, or {{event("paste")}} operation, along with its MIME type.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<p><em>No specific methods; inherits methods from its parent {{domxref("Event")}}</em>.</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('Clipboard API', '#clipboard-event-interfaces', 'ClipboardEvent') }}</td> + <td>{{ Spec2('Clipboard API') }}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("api.ClipboardEvent")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>Copy-related events: {{event("copy")}}, {{event("cut")}}, {{event("paste")}}</li> +</ul> diff --git a/files/es/web/api/closeevent/index.html b/files/es/web/api/closeevent/index.html new file mode 100644 index 0000000000..f92dd84d16 --- /dev/null +++ b/files/es/web/api/closeevent/index.html @@ -0,0 +1,237 @@ +--- +title: CloseEvent +slug: Web/API/CloseEvent +translation_of: Web/API/CloseEvent +--- +<p>{{APIRef("Websockets API")}}</p> + +<p>Un <code>CloseEvent</code> se envia a los clientes usando {{Glossary("WebSockets")}} cuando la conexión esta cerrada. Esto se entrega al que escucha indicado por el atributo <code>onclose</code> del objeto <code>WebSocket.</code></p> + +<h2 id="Constructor">Constructor</h2> + +<dl> + <dt>{{domxref("CloseEvent.CloseEvent", "CloseEvent()")}}</dt> + <dd>Crear un nuevo <code>CloseEvent</code>.</dd> +</dl> + +<h2 id="Propiedades">Propiedades</h2> + +<p><em>Esta interface tambien hereda propiedades de su padre, {{domxref("Event")}}.</em></p> + +<dl> + <dt>{{domxref("CloseEvent.code")}} {{readOnlyInline}}</dt> + <dd>Devuelve un <code>unsigned short</code> que contienen el código de cierre enviado por el servidor. Los siguientes valores son los codigos de estado permitidos. Las siguientes definiciones vienen del sitio web de IANA [<a href="https://www.iana.org/assignments/websocket/websocket.xml#close-code-number">Ref</a>]. + <table class="standard-table" id="Status_codes"> + <tbody> + <tr> + <td class="header">Status code</td> + <td class="header">Name</td> + <td class="header">Description</td> + </tr> + <tr> + <td><code>0</code>–<code>999</code></td> + <td></td> + <td><strong>Reserved and not used.</strong></td> + </tr> + <tr> + <td><code>1000</code></td> + <td>Cierre Normal</td> + <td>Cierre normal; La conexion se completo con exito cualquiera sea el proposito para el cual fue creado.</td> + </tr> + <tr> + <td><code>1001</code></td> + <td>Going Away</td> + <td>El punto final se fue(desaparecio), ya sea por una falla en el servidor o por que el navegador esta navegando fuera de la página que abrio la conexión.</td> + </tr> + <tr> + <td><code>1002</code></td> + <td>Error de Protocolo</td> + <td>El punto final esta terminando la conexion debido a un error en el protocolo. </td> + </tr> + <tr> + <td><code>1003</code></td> + <td>Datos no soportadors</td> + <td>La conexión esta siendo terminada por que el punto final recibio daros de un tipo que acepta o soportar (por ejemplo, está esperando un solo texto y el punto final recibio datos binarios).</td> + </tr> + <tr> + <td><code>1004</code></td> + <td></td> + <td><strong>Reservado.</strong> Un signinficado se podria definir en un futuro.</td> + </tr> + <tr> + <td><code>1005</code></td> + <td>Estado no recibido. </td> + <td><strong>Reservado.</strong> Indica que no se proporciono ningún código de estado aunque se esperaba uno.</td> + </tr> + <tr> + <td><code>1006</code></td> + <td>Cierre anormal</td> + <td><strong>Reservado.</strong> Se usa para indicar que una conexion fue cerrada de forma anormal (es decir, sin que se envie un frame cerrado with no close frame being sent) when a status code is expected.</td> + </tr> + <tr> + <td><code>1007</code></td> + <td>Invalid frame payload data</td> + <td>The endpoint is terminating the connection because a message was received that contained inconsistent data (e.g., non-UTF-8 data within a text message).</td> + </tr> + <tr> + <td><code>1008</code></td> + <td>Violación de politica</td> + <td>The endpoint is terminating the connection because it received a message that violates its policy. This is a generic status code, used when codes 1003 and 1009 are not suitable.</td> + </tr> + <tr> + <td><code>1009</code></td> + <td>Mensaje muy grande</td> + <td>The endpoint is terminating the connection because a data frame was received that is too large.</td> + </tr> + <tr> + <td><code>1010</code></td> + <td>Extensión faltante.</td> + <td>The client is terminating the connection because it expected the server to negotiate one or more extension, but the server didn't.</td> + </tr> + <tr> + <td><code>1011</code></td> + <td>Error interno</td> + <td>The server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request.</td> + </tr> + <tr> + <td><code>1012</code></td> + <td>Reinicio de servicio</td> + <td>El servidor esta terminado la conexion porque esta reiniciando. [<a href="https://www.ietf.org/mail-archive/web/hybi/current/msg09670.html">Ref</a>]</td> + </tr> + <tr> + <td><code>1013</code></td> + <td>Trate mas tarde nuevamente</td> + <td>The server is terminating the connection due to a temporary condition, e.g. it is overloaded and is casting off some of its clients. [<a href="https://www.ietf.org/mail-archive/web/hybi/current/msg09670.html">Ref</a>]</td> + </tr> + <tr> + <td><code>1014</code></td> + <td>Bad Gateway</td> + <td>The server was acting as a gateway or proxy and received an invalid response from the upstream server. This is similar to 502 HTTP Status Code.</td> + </tr> + <tr> + <td><code>1015</code></td> + <td>TLS Saludo</td> + <td><strong>Reserved.</strong> Indicates that the connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can't be verified).</td> + </tr> + <tr> + <td><code>1016</code>–<code>1999</code></td> + <td></td> + <td><strong>Reservado para futuro uso del estandar WebSocket.</strong></td> + </tr> + <tr> + <td><code>2000</code>–<code>2999</code></td> + <td></td> + <td><strong>Reservado para uso de extensiones WebSocket .</strong></td> + </tr> + <tr> + <td><code>3000</code>–<code>3999</code></td> + <td></td> + <td>Available for use by libraries and frameworks. <strong>May not</strong> be used by applications. Available for registration at the IANA via first-come, first-serve.</td> + </tr> + <tr> + <td><code>4000</code>–<code>4999</code></td> + <td></td> + <td>Disponible para uso de aplicaciones.</td> + </tr> + </tbody> + </table> + </dd> + <dt>{{domxref("CloseEvent.reason")}} {{readOnlyInline}}</dt> + <dd>Retorna un {{domxref("DOMString")}} indicando la razon por que el servidor cerro la conexión. Esto es especifico para el servidor y sub-protocolo en particular. </dd> + <dt>{{domxref("CloseEvent.wasClean")}} {{readOnlyInline}}</dt> + <dd>Retorna un {{jsxref("Boolean")}} que indica si o no la conexion fue cerrada limpiamente.</dd> +</dl> + +<h2 id="Metodos">Metodos</h2> + +<p><em>Esta interface tambien hereda metodos de su padre, {{domxref("Event")}}.</em></p> + +<dl> + <dt>{{domxref("CloseEvent.initCloseEvent()")}} {{Non-standard_inline}} {{Obsolete_inline}}</dt> + <dd>Inicializa el valor de un <code>CloseEvent</code> creado. Si el evento ya ha sido enviado, este método no funciona. No use más este método, use el {{domxref("CloseEvent.CloseEvent", "CloseEvent()")}} constructor en su lugar.</dd> +</dl> + +<h2 id="Compatibilidad_entre_Navegadores">Compatibilidad entre Navegadores </h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("8.0")}}<sup>[1]</sup><br> + {{CompatGeckoDesktop("12.0")}}<sup>[2]</sup></td> + <td>10</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>initCloseEvent</code><code>()</code> {{Non-standard_inline}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("8.0")}}<br> + {{CompatNo}} 41.0</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>Edge</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>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("8.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>initCloseEvent</code><code>()</code> {{Non-standard_inline}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("8.0")}}<br> + {{CompatNo}} 41.0</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Prior to Gecko 8.0 {{geckoRelease("8.0")}}, Gecko sent the WebSocket {{event("close")}} event to the listener as a simple event. Support for <code>CloseEvent</code> was implemented in Gecko 8.0.</p> + +<p>[2] Prior to Gecko 12.0 {{geckoRelease("12.0")}}, Gecko reported the close code <code>CLOSE_NORMAL</code> when the channel was closed due to an unexpected error, or if it was closed due to an error condition that the specification doesn't cover. Now <code>CLOSE_GOING_AWAY</code> is reported instead.</p> + +<h2 id="Ver_tambien">Ver tambien</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/WebSocket"><code>WebSocket</code></a></li> +</ul> diff --git a/files/es/web/api/comment/index.html b/files/es/web/api/comment/index.html new file mode 100644 index 0000000000..b1c6a89de9 --- /dev/null +++ b/files/es/web/api/comment/index.html @@ -0,0 +1,75 @@ +--- +title: Comment +slug: Web/API/Comment +tags: + - API + - DOM + - Referências + - comentários +translation_of: Web/API/Comment +--- +<div>{{ ApiRef("DOM") }}</div> + +<p><span class="seoSummary">La interfaz <code><strong>Comment</strong></code> representa las anotaciones y comentarios dentro del código fuente; aunque generalmente no se muestran visualmente en el navegador, dichos comentarios están disponibles para ser leídos en la<strong> <a href="/es/docs/Tools/View_source">vista de código</a></strong>.<br> + Los comentarios se representan en HTML y XML como contenido entre '<!--' y '-->'. En XML, la secuencia de caracteres '--' no se puede usar dentro de un comentario.</span></p> + +<p>{{InheritanceDiagram}}</p> + +<h2 id="Propiedades">Propiedades</h2> + +<p><em>Esta interfaz no tiene ninguna propiedad específica, pero hereda las de su padre,{{domxref("CharacterData")}}, e indirectamente los de {{domxref("Node")}}.</em></p> + +<h2 id="Constructor">Constructor</h2> + +<dl> + <dt>{{ domxref("Comment.Comment()", "Comment()") }} {{experimental_inline}}</dt> + <dd>Devuelve un objeto <code>Comment</code> con el contenido del comentario como parámetro.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<p><em>Esta interfaz no tiene ninguna propiedad específica, pero hereda las de su padre,{{domxref("CharacterData")}}, e indirectamente los de {{domxref("Node")}}.</em></p> + +<h2 id="Specification" name="Specification">Especificaciones</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('DOM WHATWG', '#comment', 'Comment')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Agregado el constructor.</td> + </tr> + <tr> + <td>{{SpecName('DOM3 Core', 'core.html#ID-1728279322', 'Comment')}}</td> + <td>{{Spec2('DOM3 Core')}}</td> + <td>Sin cambios de {{SpecName('DOM2 Core')}}</td> + </tr> + <tr> + <td>{{SpecName('DOM2 Core', 'core.html#ID-1728279322', 'Comment')}}</td> + <td>{{Spec2('DOM2 Core')}}</td> + <td>Sin cambios de {{SpecName('DOM1')}}</td> + </tr> + <tr> + <td>{{SpecName('DOM1', 'level-one-core.html#ID-1728279322', 'Comment')}}</td> + <td>{{Spec2('DOM1')}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_entre_navegadores">Compatibilidad entre navegadores</h2> + +<div class="hidden">La tabla de compatibilidad de esta página se genera a partir de datos estructurados. Si desea contribuir a los datos, consulte <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> y envíenos un pull request.</div> + +<p>{{Compat("api.Comment")}}</p> + +<h2 id="Lea_también">Lea también</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Document_Object_Model" title="/en-US/docs/DOM/DOM_Reference">Índice de interfaces DOM</a></li> +</ul> diff --git a/files/es/web/api/console/assert/index.html b/files/es/web/api/console/assert/index.html new file mode 100644 index 0000000000..b57d21a2aa --- /dev/null +++ b/files/es/web/api/console/assert/index.html @@ -0,0 +1,140 @@ +--- +title: Console.assert() +slug: Web/API/console/assert +tags: + - API + - Consola + - DOM + - Debug + - Debugging + - Gecko DOM Referencia + - Métodos + - afirmación + - consola web +translation_of: Web/API/console/assert +--- +<div>{{APIRef("Console API")}}{{Non-standard_header}}</div> + +<p>Aparece un mensaje de error en la consola si la afirmación es falsa. Si la afirmación es verdadera, no aparecerá nada.</p> + +<p>{{AvailableInWorkers}}</p> + +<div class="note"> +<p><strong>Nota: </strong>El método <code>console.assert()</code> se implementa de diferente manera en Node.js que el mismo método disponible en los navegadores.</p> + +<p>En los navegadores, llamando <code>console.assert()</code> con una falsa afirmación hará que el <code>message</code> se imprima por consola sin interrumpir la ejecución del código posterior. En Node.js, sin embargo, una falsa afirmación lanzará un <code>AssertionError</code>.</p> +</div> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">console.assert(<em>afirmación</em>, <em>obj1</em> [, <em>obj2</em>, ..., <em>objN</em>]); +console.assert(<em>afirmación</em>, <em>msg</em> [, <em>subst1</em>, ..., <em>substN</em>]); +</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code>afirmación</code></dt> + <dd>Cualquier expresión booleana.Si la afirmación es falsa, el mensaje aparecerá en consola.</dd> + <dt><code>obj1</code> ... <code>objN</code></dt> + <dd>Salida de una lista de objetos de JavaScript. Las representaciones de cadena de cada uno de estos objetos se añaden juntos en el orden y salida indicados.</dd> + <dt><code>msg</code></dt> + <dd>Una cadena de JavaScript que contiene cero o más cadenas de sustitución.</dd> + <dt><code>subst1</code> ... <code>substN</code></dt> + <dd>Objetos de JavaScript con el que reemplaza las cadenas dentro de <code>msg</code>. Esto te da más control sobre el formato de salida.</dd> +</dl> + +<p>Para más detalles ver <a href="/en-US/docs/Web/API/console#Outputting_text_to_the_console">Salida de texto a la consola</a> en la documentación de {{domxref("console")}}.</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificaciones</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("Console API", "#consoleassertexpression-object", "console.assert()")}}</td> + <td>{{Spec2("Console API")}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("28.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Disponible en workers</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("38.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Caracterìstica</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("28.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Disponible en workers</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("38.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="http://www.opera.com/dragonfly/documentation/console/">Opera Dragonfly documentación: Consola</a></li> + <li><a href="http://msdn.microsoft.com/library/gg589530">MSDN: Usando F12 Herramientas de Consola para ver Errores y Estados</a></li> + <li><a href="https://developer.chrome.com/devtools/docs/console#assertions">Herramientas de Desarrollo de Chrome: Usando la Consola</a></li> +</ul> diff --git a/files/es/web/api/console/count/index.html b/files/es/web/api/console/count/index.html new file mode 100644 index 0000000000..c641504034 --- /dev/null +++ b/files/es/web/api/console/count/index.html @@ -0,0 +1,168 @@ +--- +title: Console.count() +slug: Web/API/Console/count +translation_of: Web/API/Console/count +--- +<div>{{APIRef("Console API")}}</div> + +<p>Registra el número de veces que se llama a <code>count()</code>. Esta función toma como argumento opcional una <code>etiqueta</code>.</p> + +<p>{{AvailableInWorkers}}</p> + +<p>Si la <code>etiqueta</code> es colocada, esta funcion muestra el numeros de veces que <code>count()</code> ha sido utilizada con la misma etiqueta.</p> + +<p>Si la <code>etiqueta</code> es omitida, la funcion registra el numero de veces que <code>count()</code> fue llamada en esta línea en particular.</p> + +<p>Por ejemplo, en este código:</p> + +<pre class="brush: js">var user = ""; + +function greet() { + console.count(); + return "hi " + user; +} + +user = "bob"; +greet(); +user = "alice"; +greet(); +greet(); +console.count();</pre> + +<p>La salida de la consola va a mostrar algo como esto:</p> + +<pre class="eval">"<no label>: 1" +"<no label>: 2" +"<no label>: 3" +"<no label>: 1" +</pre> + +<p>Note que al final de la linea de la salida: La llamada separada <code>count()</code> en la linea 11 es tratada como un evento independiente.</p> + +<p>Si pasamos la variable <code>user</code> como <code>etiqueta</code> en la primera llamada a <code>count()</code> y la cadena "alice" en la segunda llamada:</p> + +<pre class="brush: js">var user = ""; + +function greet() { + console.count(user); + return "hi " + user; +} + +user = "bob"; +greet(); +user = "alice"; +greet(); +greet(); +console.count("alice");</pre> + +<p>Vamos a ver una salida como esta:</p> + +<pre class="eval">"bob: 1" +"alice: 1" +"alice: 2" +"alice: 3"</pre> + +<p>Ahora tenemos diferentes contadores según el valor de la <code>etiqueta</code>. Al coincidir la etiqueta "alice" en la línea 11 con el valor de <code>user</code> dos veces, no se considera un evento independiente.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">console.count([label]); +</pre> + +<h2 id="Parámetros">Parámetros</h2> + +<dl> + <dt><code>label</code></dt> + <dd>Una cadena. Si se proporciona, la salida de <code>count()</code> indica el número de veces que fue llamada con la etiqueta. Si se omite, la salida de <code>count()</code> indica el número de veces que fue llamada en esa misma línea.</dd> +</dl> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("Console API", "#count", "console.count()")}}</td> + <td>{{Spec2("Console API")}}</td> + <td><span id="result_box" lang="es"><span>Definición inicial</span></span></td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_los_navegadores">Compatibilidad en los navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte basico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("30.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Available in workers</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("38.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Caracteritica</th> + <th>Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte basico</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("30.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Available in workers</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("38.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> diff --git a/files/es/web/api/console/dir/index.html b/files/es/web/api/console/dir/index.html new file mode 100644 index 0000000000..6faa810f7d --- /dev/null +++ b/files/es/web/api/console/dir/index.html @@ -0,0 +1,119 @@ +--- +title: Console.dir() +slug: Web/API/Console/dir +translation_of: Web/API/Console/dir +--- +<p>{{APIRef("Console API")}}</p> + +<p><span class="seoSummary">El método <strong><code>dir()</code></strong> de {{domxref("Console")}} despliega una lista interactiva de las propiedades del objeto JavaScript especificado. El resultado es presentado como un listado jerárquico con triángulos de despliegue que te dejan ver los contenidos de los objetos hijos.</span></p> + +<p>Dicho de otra manera, <code>console.dir()</code> es la manera de ver todas las propiedades de un objeto JavaScript específicado por consola, mediante la cual el desarrollador puede facilmente obtener las propiedades del objeto.</p> + +<p>{{AvailableInWorkers}}</p> + +<p><img alt="console-dir.png" class="default internal" src="/@api/deki/files/6081/=console-dir.png"></p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox notranslate">console.dir(<em>objeto</em>); +</pre> + +<h2 id="Parámetros">Parámetros</h2> + +<dl> + <dt><code>objeto</code></dt> + <dd><code>Un objeto JavaScript cuyas propiedades deben ser mostradas como resultado.</code></dd> +</dl> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estatus</th> + <th scope="col">Comentario</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("Console API", "#consoledirobject", "console.dir()")}}</td> + <td>{{Spec2("Console API")}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_navegadores">Compatibilidad en navegadores</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>Soporte Básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("8.0")}}</td> + <td>9</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Available in workers</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("38.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</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>Soporte Básico</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("8.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Available in workers</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("38.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a class="external" href="http://www.opera.com/dragonfly/documentation/console/">Opera Dragonfly documentation: Console</a></li> + <li><a class="external" href="http://msdn.microsoft.com/library/gg589530">MSDN: Using the F12 Tools Console to View Errors and Status</a></li> + <li><a href="https://developers.google.com/chrome-developer-tools/docs/console-api#consoledirobject">Chrome Console API reference</a></li> +</ul> diff --git a/files/es/web/api/console/dirxml/index.html b/files/es/web/api/console/dirxml/index.html new file mode 100644 index 0000000000..c4d6b529f5 --- /dev/null +++ b/files/es/web/api/console/dirxml/index.html @@ -0,0 +1,103 @@ +--- +title: Console.dirxml() +slug: Web/API/Console/dirxml +tags: + - API + - DOM + - Depuración + - metodo +translation_of: Web/API/Console/dirxml +--- +<div>{{APIRef("Console API")}}{{Non-standard_header}}</div> + +<p>Muestra en consola un árbol interactivo de los elementos descendientes del elemento XML/HTML especificado. Si no es posible mostrarlo como un elemento, la vista de objeto se muestra en su lugar. La salida se presenta como una lista jerárquica de nodos expandibles que le permiten ver el contenido de los nodos hijos.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">console.dirxml(<em>objeto</em>); +</pre> + +<h2 id="Parámetros">Parámetros</h2> + +<dl> + <dt><code>objeto</code></dt> + <dd>Un objeto JavaScript cuyas propiedades deben ser mostradas.</dd> +</dl> + +<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>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Available in workers</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Edge</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>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Available in workers</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a class="external" href="http://www.opera.com/dragonfly/documentation/console/">Opera Dragonfly documentation: Console</a></li> +</ul> diff --git a/files/es/web/api/console/error/index.html b/files/es/web/api/console/error/index.html new file mode 100644 index 0000000000..41efb36598 --- /dev/null +++ b/files/es/web/api/console/error/index.html @@ -0,0 +1,179 @@ +--- +title: console.error() +slug: Web/API/Console/error +tags: + - API + - DOM + - Depurando + - Desarrollo web + - consola web + - metodo +translation_of: Web/API/Console/error +--- +<div>{{APIRef("Console API")}}</div> + +<p>Muestra un mensaje de error en la Consola Web.</p> + +<p>{{AvailableInWorkers}}</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">console.error(<em>obj1</em> [, <em>obj2</em>, ..., <em>objN</em>]); +console.error(<em>msg</em> [, <em>subst1</em>, ..., <em>substN</em>]); +console.exception(<em>obj1</em> [, <em>obj2</em>, ..., <em>objN</em>]); +console.exception(<em>msg</em> [, <em>subst1</em>, ..., <em>substN</em>]); +</pre> + +<div class="note"> +<p><strong>Nota:</strong> <code>console.exception()</code> es un alias de <code>console.error()</code>; son funcionalmente identicas.</p> +</div> + +<h3 id="Parametros">Parametros</h3> + +<dl> + <dt><code>obj1</code> ... <code>objN</code></dt> + <dd> + <p>Una lista de objetos JavaScript para mostrar. Las representaciones en texto de cada uno de los objetos se agregan y muestran juntas (al final una tras otra), en el orden listado.</p> + </dd> + <dt><code>msg</code></dt> + <dd>Un texto (mensaje) conteniendo cero o más sustituciones de cadenas (sustituciones de strings). </dd> + <dt><code>subst1</code> ... <code>substN</code></dt> + <dd>Objetos JavaScript con la sustitución a reemplazar dentro del texto (<strong><code>msg</code></strong>). Esto brinda control adicional en el formato de salida del texto. </dd> +</dl> + +<p>Vea "<a href="/es/docs/Web/API/console#Outputting_text_to_the_console">Mostrando texto en la consola</a>" en la documentacion de {{domxref("console")}} para mas detalles.</p> + +<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("Console API", "#error", "console.error()")}}</td> + <td>{{Spec2("Console API")}}</td> + <td>Definicion inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Caracteristica</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte basico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("2.0")}}</td> + <td>8</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Substitucion de cadenas</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("9.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>console.exception</code> alias</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("28.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>Disponible en workers</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("38.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Caracteristica</th> + <th>Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte basico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("2.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Substitucion de cadenas</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("9.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>console.exception</code> alias</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("28.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>Disponible en workers</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("38.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Vea_también">Vea también</h2> + +<ul> + <li><a href="http://www.opera.com/dragonfly/documentation/console/">Documentacion de Opera Dragonfly: Console</a></li> + <li><a href="http://msdn.microsoft.com/library/gg589530">MSDN: Using the F12 Tools Console to View Errors and Status</a></li> + <li><a href="https://developers.google.com/chrome-developer-tools/docs/console#errors_and_warnings">Herramientas de desarrolladores de Chrome: Usando la Consola</a></li> +</ul> diff --git a/files/es/web/api/console/index.html b/files/es/web/api/console/index.html new file mode 100644 index 0000000000..9c1dd3fcba --- /dev/null +++ b/files/es/web/api/console/index.html @@ -0,0 +1,254 @@ +--- +title: Console +slug: Web/API/Console +tags: + - API + - DOM + - Debugging + - Depuración + - NeedsCompatTable + - NeedsTranslation + - Reference + - TopicStub + - consola web + - web console +translation_of: Web/API/Console +--- +<div>{{APIRef("Console API")}}{{Non-standard_header}}</div> + +<p>El objeto <code><strong>Console</strong> </code>provee acceso a la consola de depuración de los navegadores (e.j., la <a href="/en-US/docs/Tools/Web_Console">Consola Web</a> en Firefox). Los detalles de como funciona varían de navegador en navegador, pero hay un conjunto de características que <em>de facto</em> son generalmente proporcionadas.</p> + +<p><code>Console </code>puede ser accedido desde cualquier método global, {{domxref("Window")}} en el ámbito de navegación, {{domxref("WorkerGlobalScope")}}, y sus variantes especificas de <code>worker</code>.</p> + +<p>Esta página documenta los {{anch("Métodos")}} disponibles en el objeto <code>console </code>y da algunos ejemplos de {{anch("uso")}}.</p> + +<p>{{AvailableInWorkers}}</p> + +<h2 id="Métodos">Métodos</h2> + +<dl> + <dt>{{domxref("Console.assert()")}}</dt> + <dd>Registra un mensaje y envía una traza de error a la consola si el primer argumento es <code>false</code>.</dd> + <dt>{{domxref("Console.count()")}}</dt> + <dd>Registra el numero de veces que esta línea ha sido llamada con etiqueta dada.</dd> + <dt>{{domxref("Console.debug()")}} </dt> + <dd>Registra un mensaje con el nivel de<code>"debug"</code>. + <div class="note"><strong>Note</strong>: A partir de Chromium 58 este método solo aparece en las consolas de navegadores Chromium cuando el nivel "Verbose" está seleccionado.</div> + </dd> + <dt>{{domxref("Console.dir()")}}</dt> + <dd>Muestra un listado interactivo de las propiedades de un objeto JavaScript específico. Esta lista le permite examinar el contenido de los objetos hijos.</dd> + <dt>{{domxref("Console.dirxml()")}}</dt> + <dd> + <p>Muestra una representación en forma de árbol de un elemento XML/HTML si es posible o la vista del objeto JavaScript si no es posible.</p> + </dd> + <dt>{{domxref("Console.error()")}}</dt> + <dd>Muestra un mensaje de error. Se pueden utilizar <a href="/en-US/docs/Web/API/console#Using_string_substitutions">sustituciones de cadena</a> y argumentos adicionales con este método.</dd> + <dt>{{domxref("Console._exception()")}}</dt> + <dd>Es un alias de <code>error()</code>.</dd> + <dt>{{domxref("Console.group()")}}</dt> + <dd>Crea un nuevo <a href="/en-US/docs/Web/API/console#Using_groups_in_the_console">grupo</a>, indentando todos los mensajes subsecuentes en un nuevo nivel. Para retroceder un nivel, se utiliza <code>groupEnd()</code>.</dd> + <dt>{{domxref("Console.groupCollapsed()")}}</dt> + <dd>Crea un nuevo <a href="/en-US/docs/Web/API/console#Using_groups_in_the_console">grupo</a>, indentando todos los mensajes subsecuentes en un nuevo nivel. A diferencia de <code>group()</code>, inicia con la línea de grupo colapsada, requiriendo el uso de un botón de apertura para expandir el grupo. Para retroceder un nivel, se utiliza <code>groupEnd()</code>.</dd> + <dt>{{domxref("Console.groupEnd()")}}</dt> + <dd>Finaliza el <a href="/en-US/docs/Web/API/console#Using_groups_in_the_console">grupo</a> actual.</dd> + <dt>{{domxref("Console.info()")}}</dt> + <dd>Muestra un mensaje de información en la <a href="/en-US/docs/Tools/Web_Console">Consola Web</a>. Se puede utilizar <a href="/en-US/docs/Web/API/console#Using_string_substitutions">sustitución de cadena</a> y argumentos adicionales con este método.</dd> + <dt>{{domxref("Console.log()")}}</dt> + <dd>Para mensajes generales de registro de información. Se puede utilizar <a href="/en-US/docs/Web/API/console#Using_string_substitutions">sustitución de cadena</a> y argumentos adicionales con este método.</dd> + <dt>{{domxref("Console.profile()")}}</dt> + <dd>Inicia el registro de un perfil de rendimiento (<a href="/en-US/docs/Tools/Performance">Firefox performance tool</a>). Se puede especificar un nombre opcional para el perfil.</dd> + <dt>{{domxref("Console.profileEnd()")}}</dt> + <dd>Detiene el perfil. Usted puede revisar el perfil resultante en la herramienta de desempeño del navegador (por ejemplo, la <a href="/en-US/docs/Tools/Performance">herramienta de rendimiento de Firefox</a>).</dd> + <dt>{{domxref("Console.table()")}}</dt> + <dd>Muestra datos tabulares en forma de una tabla.</dd> + <dt>{{domxref("Console.time()")}}</dt> + <dd>Inicia un <a href="/en-US/docs/Web/API/console#Timers">temporizador </a>con un nombre específico como parámetro. Hasta 10.000 temporizadores simultáneos pueden ejecutarse en una página determinada.</dd> + <dt>{{domxref("Console.timeEnd()")}}</dt> + <dd>Detiene el <a href="/en-US/docs/Web/API/console#Timers">temporizador</a> especificado y registra el tiempo transcurrido, en segundos, desde su inicio.</dd> + <dt>{{domxref("Console.timeStamp()")}}</dt> + <dd>Adiciona una marca a las herramientas <a href="https://developer.chrome.com/devtools/docs/timeline">Timeline</a> o <a href="/en-US/docs/Tools/Performance/Waterfall">Waterfall</a> del navegador.</dd> + <dt>{{domxref("Console.trace()")}}</dt> + <dd>Muestra una <a href="/en-US/docs/Web/API/console#Stack_traces">traza de error</a>.</dd> + <dt>{{domxref("Console.warn()")}}</dt> + <dd>Muestra un mensaje de advertencia. Se puede utilizar <a href="/en-US/docs/Web/API/console#Using_string_substitutions">sustitución de cadena</a> y argumentos adicionales con este método.</dd> +</dl> + +<h2 id="Usage" name="Usage">Uso</h2> + +<h3 id="Outputting_text_to_the_console" name="Outputting_text_to_the_console">Enviar texto a la consola</h3> + +<p>La característica mas utilizada de la consola es la de mostrar texto y otro datos. Existen cuatro categorías de salida que se pueden generar, utilizando los métodos {{domxref("console.log()")}}, {{domxref("console.info()")}}, {{domxref("console.warn()")}} y {{domxref("console.error()")}}. Cada uno de estos muestran resultados que se lucen diferentes en el registro y se pueden utilizar los controles de filtro proveidos por el navegador para ver únicamente los tipos de salida de interés.</p> + +<p>Hay dos maneras de usar cada uno de los métodos de salida; se puede ingresar una lisa de objetos de cadena (objectos strings) los cuales serán concatenados en una sola cadena, la cual se mostrará en la consola, o se puede ingresar una lista que contenga ninguna o mas sustituciones de cadena seguida por una lista de objetos con los cuales reemplazarlas.</p> + +<h4 id="Mostrando_un_solo_objeto">Mostrando un solo objeto</h4> + +<p>La manera mas simple de utilizar los métodos de registro es mostrar un solo objeto:</p> + +<pre class="brush: js">var someObject = { str: "Algún texto", id: 5 }; +console.log(someObject); +</pre> + +<p>La salida se vera parecido a esto:</p> + +<pre>[09:27:13.475] ({str:"Algún texto", id:5})</pre> + +<h4 id="Mostrando_múltiples_objetos">Mostrando múltiples objetos</h4> + +<p>También se pueden mostrar múltiples objetos listándolos y luego llamando el método de registro, de esta forma:</p> + +<pre class="brush: js">var car = "Dodge Charger"; +var someObject = {str:"Algún texto", id:5}; +console.info("Mi primer carro fue un ", car, ". El objeto es: ", someObject);</pre> + +<p>La salida se verá parecido a esto:</p> + +<pre>[09:28:22.711] Mi primer carro fue un Dodge Charger . El objeto es: ({str:"Algún texto", id:5}) +</pre> + +<h4 id="Utilizando_sustituciones_de_cadena">Utilizando sustituciones de cadena</h4> + +<p>Gecko 9.0 {{geckoRelease("9.0")}} introdujo soporte para sustituciones de cadena. Cuando se ingresa una caden a uno de los objetos de consola que acepta una cadena, es posible utilizar las siguientes sustituciones de cadena:</p> + +<table class="standard-table" style="width: auto;"> + <tbody> + <tr> + <td class="header">Sustitución de cadena</td> + <td class="header">Descripción</td> + </tr> + <tr> + <td>%o</td> + <td>Muestra un hiper vinculo a un objeto JavaScript. Dando click en el link se abre un inspector.</td> + </tr> + <tr> + <td>%d or %i</td> + <td>Muestra un entero. El formato de presentación aun no esta soportado.</td> + </tr> + <tr> + <td>%s</td> + <td>Muestra una cadena.</td> + </tr> + <tr> + <td>%f</td> + <td>Muestra un valor de punto flotante. El formato de presentación aun no esta soportado.</td> + </tr> + </tbody> +</table> + +<p>Cada uno de estos llama al siguiente argumento de un array declarado en los argumentos. Por ejemplo:</p> + +<pre>for (var i=0; i<5; i++) { + console.log("Hola, %s. Usted me ha llamado %d veces.", "Bob", i+1); +} +</pre> + +<p>La salida se verá parecido a esto:</p> + +<pre>[13:14:13.481] Hola, Bob. Usted me ha llamado me 1 veces. +[13:14:13.483] Hola, Bob. Usted me ha llamado 2 veces. +[13:14:13.485] Hola, Bob. Usted me ha llamado 3 veces. +[13:14:13.487] Hola, Bob. Usted me ha llamado 4 veces. +[13:14:13.488] Hola, Bob. Usted me ha llamado 5 veces. +</pre> + +<h4 id="Dando_estilo_a_la_salida_de_la_consola.">Dando estilo a la salida de la consola.</h4> + +<p>Puedes usar la directiva <code>"%c" para aplicar un estilo </code>CSS a la salida de la consola:</p> + +<pre class="brush: js">console.log("%cMy stylish message", "color: red; font-style: italic");</pre> + +<div><img alt="" src="https://mdn.mozillademos.org/files/7739/console-style.png" style="display: block; height: 52px; margin-left: auto; margin-right: auto; width: 293px;"></div> + +<div>{{h3_gecko_minversion("Usando grupos en la consola", "9.0")}}</div> + +<p>Puedes usar grupos anidades para ayudar a organizar la salida visualmente combinando material relacionado. Para crear un nuevo bloque anidado, se debe usar <code>console.group(). El método console.groupCollapsed() es similar, pero crea el nuevo bloque colapsado, requiriendo el uso de un "botón de mostrar" para abrirlo y leerlo.</code></p> + +<div class="note"><strong>Nota:</strong> Grupos colapsados no están soportados en Gecko todavía, el método <code>groupCollapsed() es el mismo que </code><code>group()</code> en este momento.</div> + +<p class="note">Para editar el grupo actual, simplemente usa <code>console.groupEnd()</code>.</p> + +<p class="note">Por ejemplo con el siguiente código:</p> + +<pre class="brush: js">console.log("This is the outer level"); +console.group(); +console.log("Level 2"); +console.group(); +console.log("Level 3"); +console.warn("More of level 3"); +console.groupEnd(); +console.log("Back to level 2"); +console.groupEnd(); +console.debug("Back to the outer level"); +</pre> + +<p>La salida se verá así:</p> + +<p><img alt="nesting.png" class="default internal" src="/@api/deki/files/6082/=nesting.png"></p> + +<div>{{h3_gecko_minversion("Timers", "10.0")}}</div> + +<p>En orden para calcular la duración de una operación específica, Geco 10 introdujo soporte de contadores (timers del inglés) en el objeto console. Para iniciar un contador, usa el método <code>console.time</code><code>()</code> , pasándole como parámetro un nombre. Para detener un contador, y obtener el tiempo transcurrido en milisegúndos, solo usa el método <code>console.timeEnd(), nuevamente pasándole el nombre del contador como parámetro. Se pueden ejecutar hasta 10000 (diez mil) contadores simultáneamente en una página.</code></p> + +<p>Por ejemplo, teniendo el siguiente código:</p> + +<pre class="brush: js">console.time("answer time"); +alert("Click to continue"); +console.timeEnd("answer time"); +</pre> + +<p>Registrará el tiempo necesitado por el usuario para descartar el cuadro de alerta (alert box del inglés):</p> + +<p><img alt="timerresult.png" class="default internal" src="/@api/deki/files/6084/=timerresult.png"></p> + +<p>Tener presente de que los nombres de los contadores son mostrados cuando el contador inicia y cuando es detenido (respectivamente).</p> + +<div class="note"><strong>Nota:</strong> Es importante saber que si estas usando esto para registrar el tiempo del trafico de red, el contador reportará el tiempo total para la transacción, mientras que el tiempo listado en el panel de conexiones o panel de red (network panel del inglés) es solo la cantidad de tiempo requerida para la cabecera (transaction header). Si en cambio tienes el registro de cuerpo hablitado (response body loggin del inglés), el tiempo listado para la respuesta de la cabecera y el cuerpo combinados debiera coincidir con lo que vez en la salida de la consola. </div> + +<h3 id="Rastro_de_pilas_(Stack_traces)">Rastro de pilas (Stack traces)</h3> + +<p>El objeto consola tambien soporta la salida de una traza de pila (stack trace del inglés); Esto te mostrará la ruta de llamadas tomadas hasta alcanzar el punto de tu llamada {{domxref("console.trace()")}}. Dado un código como el siguiente:</p> + +<pre>foo(); + +function foo() { + function bar() { + console.trace(); + } + bar(); +} +</pre> + +<p>La salida en la consola se verá como esto:</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/7167/api-trace2.png" style="display: block; margin-left: auto; margin-right: auto;"></p> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<p><a href="https://github.com/DeveloperToolsWG/console-object/blob/master/api.md">Objeto API Console</a></p> + +<h2 id="Notas">Notas</h2> + +<ul> + <li>Al menos en Firefox, si una página define un objeto console, este objeto sobreescribirá el construido en Firefox.</li> + <li>Anteriormente a {{Gecko("12.0")}}, los métodos del objeto console solo funcionaban cuando la consola estaba abierta. Desde e iniciando con {{Gecko("12.0")}}, la salida es almacenada (cacheada del inglés cached) hasta que la consola web es abierta, entonces se muestra en ese momento.</li> + <li>Vale la pena destacar que el objeto console construido por Firefox es compatible con el provisto por <a class="external" href="http://getfirebug.com/" title="http://getfirebug.com/">Firebug</a>.</li> +</ul> + +<h2 id="Ver_tambien">Ver tambien</h2> + +<ul> + <li><a href="/en-US/docs/Tools">Herramientas</a></li> + <li><a href="/en-US/docs/Tools/Web_Console">Consola Web</a> - como la consola web en Firefox maneja las llamadas a la API Console</li> + <li><a href="/en-US/docs/Tools/Remote_Debugging">Depuración remota</a> - como ver la salida de la consola cuando el objetivo a depurar es un dispositivo móvil</li> + <li><a href="/en-US/Firefox_OS/Using_the_App_Manager">Depuración de aplicaciones con Firefox OS</a> - usando el Gestor de Aplicaciones para depurar aplicaciones en ejecución en Firefox OS</li> + <li><a href="/en-US/docs/Mozilla/Firefox_OS/Debugging/On-device_console_logging">Registro de consola en el dispositivo (on-device)</a> - como registrar con la consola en dispositivos Firefox OS</li> +</ul> + +<h3 id="Otras_implementaciones">Otras implementaciones</h3> + +<ul> + <li><a href="https://developers.google.com/chrome-developer-tools/docs/console-api">Herramientas para desarrolladores de Google Chrome</a></li> + <li><a href="http://getfirebug.com/wiki/index.php/Console_API">Firebug</a></li> + <li><a href="http://msdn.microsoft.com/en-us/library/hh772173(v=vs.85).aspx">Internet Explorer</a></li> + <li><a href="https://developer.apple.com/library/safari/documentation/AppleApplications/Conceptual/Safari_Developer_Guide/Console/Console.html">Safari</a></li> +</ul> diff --git a/files/es/web/api/console/info/index.html b/files/es/web/api/console/info/index.html new file mode 100644 index 0000000000..75fb215b47 --- /dev/null +++ b/files/es/web/api/console/info/index.html @@ -0,0 +1,163 @@ +--- +title: Console.info() +slug: Web/API/Console/info +tags: + - API + - Depuración + - Desarrollo web + - NecesidadNavegadorCompatible + - consola web + - metodo +translation_of: Web/API/Console/info +--- +<div>{{APIRef("Console API")}}</div> + +<div>Emite un mensaje informativo a la Consola Web. En Firefox y Chrome, se muestra un pequeño ícono "i" junto a estos elementos en el registro de la Consola Web.</div> + +<p> </p> + +<p>{{AvailableInWorkers}}</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">console.info(<em>obj1</em> [, <em>obj2</em>, ..., <em>objN</em>]); +console.info(<em>msg</em> [, <em>subst1</em>, ..., <em>substN</em>]); +</pre> + +<h2 id="Parametros">Parametros</h2> + +<dl> + <dt><code>obj1</code> ... <code>objN</code></dt> + <dd>Una lista de objetos JavaScript a la salida. Las representaciones de cadena de cada uno de estos objetos se anexan en el orden y salida.</dd> + <dt><code>msg</code></dt> + <dd>Un String en JavaScript contiene cero o mas strings de sustitucion</dd> + <dt><code>subst1</code> ... <code>substN</code></dt> + <dd>Objetos en JavaScript con los que reemplazar cadenas de sustitución dentro del mensaje. Esto le da un control adicional sobre el formato de la salida.</dd> +</dl> + +<p>Ver <a href="/en-US/docs/Web/API/console#Outputting_text_to_the_console">Salida de texto en la consola</a> en la documentacion de {{domxref("console")}} para detalles.</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificacion </th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("Console API", "#info", "console.info()")}}</td> + <td>{{Spec2("Console API")}}</td> + <td>Definicion inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_del_navegador">Compatibilidad del navegador</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Caracteristica</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte basico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("2.0")}}</td> + <td>8</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Sustitucion de strings</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("9.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Icono de informacion</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>Trabajadores Disponibles</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("38.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Caracteristica</th> + <th>Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte basico</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("2.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Sustitucion de strings</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("9.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Trabajadores Disponibles</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("38.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Vea_tambien">Vea tambien</h2> + +<ul> + <li><a class="external" href="http://www.opera.com/dragonfly/documentation/console/">Opera Dragonfly documentation: Console</a></li> + <li><a class="external" href="http://msdn.microsoft.com/library/gg589530">MSDN: Using the F12 Tools Console to View Errors and Status</a></li> +</ul> diff --git a/files/es/web/api/console/log/index.html b/files/es/web/api/console/log/index.html new file mode 100644 index 0000000000..56e369f395 --- /dev/null +++ b/files/es/web/api/console/log/index.html @@ -0,0 +1,190 @@ +--- +title: Console.log() +slug: Web/API/Console/log +tags: + - API + - Compatibilidad necesaria con navegadores + - Consola + - DOM + - Desarrollo web + - Método(2) + - consola web + - console.dir() + - console.log() + - debuguear + - depurar + - diferencia + - Árbol HTML + - Árbol JSON +translation_of: Web/API/Console/log +--- +<div>{{APIRef("Console API")}}</div> + +<div>Muestra un mensaje en la consola web (o del intérprete JavaScript).</div> + +<div> </div> + +<p>{{AvailableInWorkers}}</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">console.log(<em>obj1</em> [, <em>obj2</em>, ..., <em>objN</em>]); +console.log(<em>msg</em> [, <em>subst1</em>, ..., <em>substN</em>]); +</pre> + +<h2 id="Parámetros">Parámetros</h2> + +<dl> + <dt><code>obj1</code> ... <code>objN</code></dt> + <dd>Una lista de objetos JavaScript para mostrar. Las representaciones en texto de cada uno de los objetos se agregan y muestran juntas (al final una tras otra), en el orden listado.</dd> + <dt><code>msg</code></dt> + <dd>Un texto (mensaje) conteniendo cero o más sustituciones de cadenas (sustituciones de strings). </dd> + <dt><code>subst1</code> ... <code>substN</code></dt> + <dd>Objetos JavaScript con la sustitución a reemplazar dentro del texto (<strong><code>msg</code></strong>). Esto brinda control adicional en el formato de salida del texto. </dd> +</dl> + +<p>Vea "<a href="/es/docs/DOM/console#Outputting_text_to_the_console">Mostrando texto en la consola</a>" en la documentación de {{domxref("console")}} para mas detalles.</p> + +<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("Console API", "#log", "console.log()")}}</td> + <td>{{Spec2("Console API")}}</td> + <td>Definicion inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td> + <p>Soporte Básico</p> + </td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("2.0")}}</td> + <td>8</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Substitución de texto</td> + <td>{{CompatVersionUnknown}}<br> + {{CompatChrome(28)}}<sup>[1]</sup></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("9.0")}}</td> + <td>10<sup>[2]</sup></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Disponible en trabajadores</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("38.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("2.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Substitución de texto</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("9.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Disponible en trabajadores</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("38.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Si se le pasa un valor negativo a <strong><code>%d</code></strong>, este será redondeado hacia abajo al entero negativo mas cercano, por ejemplo: -0.1 se convierte en -1.</p> + +<p>[2] <code>%c</code> no esta soportado, <code>%d</code> devolverá 0 cuando no sea un número.</p> + +<h2 id="Diferencia_con_console.dir()">Diferencia con console.dir()</h2> + +<p>Te preguntarás cual es la diferencia entre console.dir() y console.log().</p> + +<p>Una diferencia útil en Chrome es cuando envías elementos DOM a la consola.</p> + +<p><img src="http://i.imgur.com/DozDcYR.png"></p> + +<p>Importante:</p> + +<ul> + <li><code>console.log</code> muestra el elemento en un árbol HTML</li> + <li><code>console.dir</code> muestra el elemento en un árbol JSON</li> +</ul> + +<p>Específicamente, <code>console.log</code> brinda un tratamiento especial a los elementos del DOM, mientras que console.dir no. Esto es útil a menudo cuando intentas ver la representación completa del objeto JavaScript del DOM. </p> + +<p>Hay mas información en la <a href="https://developers.google.com/chrome-developer-tools/docs/console-api#consoledirobject">referencia de la API Console de Chrome</a> acerca de esto y otras funciones.</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="http://www.opera.com/dragonfly/documentation/console/">Documentación Opera Dragonfly: Consola</a>.</li> + <li><a href="http://msdn.microsoft.com/library/gg589530">MSDN: Usando las herramientas F12 de Consola para ver errores y estados</a>.</li> + <li><a href="http://getfirebug.com/wiki/index.php/Console_API">Firebug wiki: Console API</a> - Firebug soporta características adicionales en su propia implementación de console.log(), como <a href="http://www.softwareishard.com/blog/firebug/firebug-tip-styled-logging/">consola con estilos</a>.</li> + <li><a href="http://nodejs.org/docs/latest/api/console.html#console_console_log_data">NodeJS: API de consola</a>.</li> +</ul> diff --git a/files/es/web/api/console/tabla/index.html b/files/es/web/api/console/tabla/index.html new file mode 100644 index 0000000000..53f57f5636 --- /dev/null +++ b/files/es/web/api/console/tabla/index.html @@ -0,0 +1,212 @@ +--- +title: Console.table() +slug: Web/API/Console/tabla +tags: + - API + - Consola + - DOM + - Depuración +translation_of: Web/API/Console/table +--- +<div>{{APIRef("Console API")}}</div> + +<p><span class="seoSummary">Muestra datos tabulares como una tabla.</span></p> + +<p>Esta función toma un argumento obligatorio: <code>data</code>, que debe ser un array o un objeto, y un parámetro adicional: <code>columns</code>.</p> + +<p>Muestra <code>data</code> como una tabla en la consola. Cada elemento en el array (o propiedad enumerable si <code>data</code> es un objeto) será una fila en la tabla.</p> + +<p>La primera columna de la tabla se identificará como <code>(index)</code>. Si <code>data</code> es un array, sus valores serán los índices del array. Si <code>data</code> es un objeto, entonces sus valores serán los nombres de las propiedades. Tenga en cuenta que (en Firefox) <code>console.table</code> está limitado a mostrar 1000 filas (la primera columna es la llamada <code>index</code>).</p> + +<p>{{AvailableInWorkers}}</p> + +<h3 id="Colecciones_de_tipos_primitivos">Colecciones de tipos primitivos</h3> + +<p>El argumento <code>data</code> puede ser un array o un objeto.</p> + +<pre class="brush: js">// un array de strings + +console.table(["apples", "oranges", "bananas"]);</pre> + +<p><img alt="" src="https://mdn.mozillademos.org/files/8567/console-table-array.png"></p> + +<pre class="brush: js">// un objeto cuyas propiedades son strings + +function Person(firstName, lastName) { + this.firstName = firstName; + this.lastName = lastName; +} + +var me = new Person("John", "Smith"); + +console.table(me);</pre> + +<p><img alt="" src="https://mdn.mozillademos.org/files/8559/console-table-simple-object.png"></p> + +<h3 id="Colecciones_de_tipos_compuestos">Colecciones de tipos compuestos</h3> + +<p>Si los elementos en el array, o propiedades en el objeto, son también arrays u objetos, sus elementos o propiedades serán enumeradas en la fila, una por columna:</p> + +<pre class="brush: js">// un array de arrays + +var people = [["John", "Smith"], ["Jane", "Doe"], ["Emily", "Jones"]] +console.table(people);</pre> + +<p><img alt="Table displaying array of arrays" src="https://mdn.mozillademos.org/files/8561/console-table-array-of-array.png"></p> + +<pre class="brush: js">// un array de objetos + +function Person(firstName, lastName) { + this.firstName = firstName; + this.lastName = lastName; +} + +var john = new Person("John", "Smith"); +var jane = new Person("Jane", "Doe"); +var emily = new Person("Emily", "Jones"); + +console.table([john, jane, emily]);</pre> + +<p>Tenga en cuenta que si el array contiene objetos, las columnas se etiquetarán con el nombre de la propiedad.</p> + +<p><img alt="Table displaying array of objects" src="https://mdn.mozillademos.org/files/8563/console-table-array-of-objects.png"></p> + +<pre class="brush: js">// un objeto cuyas propiedades son objetos + +var family = {}; + +family.mother = new Person("Jane", "Smith"); +family.father = new Person("John", "Smith"); +family.daughter = new Person("Emily", "Smith"); + +console.table(family);</pre> + +<p><img alt="Table displaying object of objects" src="https://mdn.mozillademos.org/files/8565/console-table-object-of-objects.png"></p> + +<h3 id="Restringiendo_las_columnas_mostradas">Restringiendo las columnas mostradas</h3> + +<p>Por defecto, <code>console.table()</code> muestra todos los elementos de cada fila. Puedes emplear el parámetro opcional <code>columns</code> para seleccionar un subconjunto de columnas que mostrar:</p> + +<pre class="brush: js">// an array of objects, logging only firstName + +function Person(firstName, lastName) { + this.firstName = firstName; + this.lastName = lastName; +} + +var john = new Person("John", "Smith"); +var jane = new Person("Jane", "Doe"); +var emily = new Person("Emily", "Jones"); + +console.table([john, jane, emily], ["firstName"]);</pre> + +<p><img alt="Table displaying array of objects with filtered output" src="https://mdn.mozillademos.org/files/8569/console-table-array-of-objects-firstName-only.png"></p> + +<h3 id="Ordenando_columnas">Ordenando columnas</h3> + +<p>Se puede ordenar la tabla por una columna en particular pulsando en la etiqueta de dicha columna.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">console.table(data [, <em>columns</em>]); +</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code>data</code></dt> + <dd>La información a mostrar. Puede ser tanto un array como un objeto.</dd> + <dt><code>columns</code></dt> + <dd>Un array que contenga los nombres de las columnas a incluir.</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("Console API", "#table", "console.table()")}}</td> + <td>{{Spec2("Console API")}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("34.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Disponible en workers</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("38.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("34.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Disponible en workers</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("38.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> diff --git a/files/es/web/api/console/time/index.html b/files/es/web/api/console/time/index.html new file mode 100644 index 0000000000..b714b4d20c --- /dev/null +++ b/files/es/web/api/console/time/index.html @@ -0,0 +1,122 @@ +--- +title: Console.time() +slug: Web/API/Console/time +translation_of: Web/API/Console/time +--- +<div>{{APIRef("Console API")}} +<p>Inicia un temporizador que puede usar para realizar un seguimiento de la duración de una operación. Le da a cada temporizador un nombre único y puede tener hasta 10.000 temporizadores ejecutándose en una página determinada. Cuando llame a {{domxref ("console.timeEnd()")}} con el mismo nombre, el navegador generará el tiempo, en milisegundos, transcurrido desde que se inició el temporizador.</p> + +<p>Consulte <a href="/en-US/docs/Web/API/console#Timers">Timers</a> en la documentación de {{domxref("console")}} para obtener detalles y ejemplos.</p> +</div> + +<p>{{AvailableInWorkers}}</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">console.time(<em>label</em>); +</pre> + +<h2 id="Parametros">Parametros</h2> + +<dl> + <dt><code>label</code></dt> + <dd>El nombre para dar el nuevo temporizador. Esto identificará el temporizador; use el mismo nombre cuando llame a {{domxref ("console.timeEnd()")}} para detener el temporizador y obtener el tiempo de salida a la consola.</dd> +</dl> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificacion</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("Console API", "#time", "console.time()")}}</td> + <td>{{Spec2("Console API")}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_exploradores">Compatibilidad con exploradores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>2</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("10.0")}}</td> + <td>11</td> + <td>{{CompatVersionUnknown}}</td> + <td>4.0</td> + </tr> + <tr> + <td>Available in workers</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("38.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Edge</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>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("10.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Available in workers</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("38.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{domxref("Console.timeEnd()")}}</li> + <li><a class="external" href="http://www.opera.com/dragonfly/documentation/console/">Opera Dragonfly documentation: Console</a></li> +</ul> diff --git a/files/es/web/api/console/timeend/index.html b/files/es/web/api/console/timeend/index.html new file mode 100644 index 0000000000..ad452782ab --- /dev/null +++ b/files/es/web/api/console/timeend/index.html @@ -0,0 +1,57 @@ +--- +title: Console.timeEnd() +slug: Web/API/Console/timeEnd +translation_of: Web/API/Console/timeEnd +--- +<div>{{APIRef("Console API")}}</div> + +<p>Detiene un temporizador que haya sido establecido previamente con {{domxref("console.time()")}}.</p> + +<p>Consulte la documentación de <a href="/en-US/docs/Web/API/console#Timers">Timers</a> para más detalles y ejemplos.</p> + +<p>{{AvailableInWorkers}}</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">console.timeEnd(<em>etiqueta</em>); +</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">etiqueta</span></font></dt> + <dd>El nombre del temporizador a detener. Al detenerse, el tiempo transcurrido será mostrado automáticamente en la <a href="/en-US/docs/Tools/Web_Console">Consola del Navegador</a>.</dd> +</dl> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estatus</th> + <th scope="col">Comentario</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("Console API", "#timeend", "console.timeEnd()")}}</td> + <td>{{Spec2("Console API")}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_Navegadores">Compatibilidad con Navegadores</h2> + +<div> +<div class="hidden">La tabla de compatibilidad en esta página es generada automáticamente. Si deseas contribuir con información, por favor visita <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> y envianos un pull request.</div> + +<p>{{Compat("api.Console.timeEnd")}}</p> +</div> + +<h2 id="Relacionados">Relacionados</h2> + +<ul> + <li><a href="http://www.opera.com/dragonfly/documentation/console/">Opera Dragonfly documentation: Console</a></li> +</ul> diff --git a/files/es/web/api/console/trace/index.html b/files/es/web/api/console/trace/index.html new file mode 100644 index 0000000000..7d11170b1e --- /dev/null +++ b/files/es/web/api/console/trace/index.html @@ -0,0 +1,132 @@ +--- +title: Console.trace() +slug: Web/API/Console/trace +translation_of: Web/API/Console/trace +--- +<div>{{APIRef("Console API")}}{{Non-standard_header}}</div> + +<p>Outputs a stack trace to the <a href="/en-US/docs/Tools/Web_Console">Web Console</a>.</p> + +<p>{{AvailableInWorkers}}</p> + +<p>Ver <a href="/en-US/docs/Web/API/console#Stack_traces">Stack traces</a> en la documentación de {{domxref("console")}} para detalles y ejemplos.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">console.trace(); +</pre> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush: js">function foo() { + function bar() { + console.trace(); + } + bar(); +} + +foo(); +</pre> + +<p>La siguiente indicador será mostrado en la consola:</p> + +<pre>bar +foo +<anonymous></pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("Console API", "#consoletraceobject--object-", "console.trace()")}}</td> + <td>{{Spec2("Console API")}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_el_navegador">Compatibilidad con el navegador</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("10.0")}}</td> + <td>11</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Available in workers</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("38.0")}}</td> + <td>{{CompatVersionUnknown}}</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>Edge</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>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("10.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Available in workers</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("38.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_tambien">Ver tambien</h2> + +<ul> + <li><a class="external" href="http://www.opera.com/dragonfly/documentation/console/">Opera Dragonfly documentation: Console</a></li> +</ul> diff --git a/files/es/web/api/console/warn/index.html b/files/es/web/api/console/warn/index.html new file mode 100644 index 0000000000..d16491e7c0 --- /dev/null +++ b/files/es/web/api/console/warn/index.html @@ -0,0 +1,63 @@ +--- +title: Console.warn() +slug: Web/API/Console/warn +tags: + - Desarrollo web +translation_of: Web/API/Console/warn +--- +<div>{{APIRef("Console API")}}</div> + +<p>Imprime un mensaje de advertencia en la Consola Web.</p> + +<p>{{AvailableInWorkers}}</p> + +<p>{{Note("En Firefox, las advertencias tienen un pequeño icono de signo de exclamación junto a estas en el registro de la Consola Web.")}}</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">console.warn(<em>obj1</em> [, <em>obj2</em>, ..., <em>objN</em>]); +console.warn(<em>msg</em> [, <em>subst1</em>, ..., <em>substN</em>]); +</pre> + +<h2 id="Parámetros">Parámetros</h2> + +<dl> + <dt><code>obj1</code> ... <code>objN</code></dt> + <dd>Una lista de objetos JavaScript para ser emitidos en la Consola Web. Las representaciones como string de cada uno de estos objetos son anexados juntos en el orden listado e impresos.</dd> + <dt><code>msg</code></dt> + <dd>Un string JavaScript que contiene cero o más strings de sustitución.</dd> + <dt><code>subst1</code> ... <code>substN</code></dt> + <dd>Objetos JavaScript con los cuales se reemplaza los strings de sustitución dentro de <code>msg</code>. Esto le proporciona un control adicional sobre el formato de salida.</dd> +</dl> + +<p>Vea <a href="/en-US/docs/Web/API/console#Outputting_text_to_the_console">Outputting text to the console</a> en la documentación de {{domxref("console")}} para mas detalles.</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estatus</th> + <th scope="col">Comentario</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("Console API", "#warn", "console.warn()")}}</td> + <td>{{Spec2("Console API")}}</td> + <td>Definición Inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_del_Navegador">Compatibilidad del Navegador</h2> + +<p>{{Compat("api.Console.warn")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a class="external" href="http://www.opera.com/dragonfly/documentation/console/">Opera Dragonfly documentation: Console</a></li> + <li><a class="external" href="http://msdn.microsoft.com/library/gg589530">MSDN: Using the F12 Tools Console to View Errors and Status</a></li> +</ul> diff --git a/files/es/web/api/constraint_validation/index.html b/files/es/web/api/constraint_validation/index.html new file mode 100644 index 0000000000..81811b4891 --- /dev/null +++ b/files/es/web/api/constraint_validation/index.html @@ -0,0 +1,154 @@ +--- +title: Constraint validation API +slug: Web/API/Constraint_validation +tags: + - API + - Constraint validation + - Landing + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/Constraint_validation +--- +<div>{{apiref()}}</div> + +<p><span class="seoSummary">The Constraint Validation API enables checking values that users have entered into form controls, before submitting the values to the server.</span></p> + +<h2 id="Concepts_and_usage">Concepts and usage</h2> + +<p>Certain HTML form controls, such as {{HTMLElement("input")}}, {{HTMLElement("select")}} and {{HTMLElement("textarea")}}, can restrict the format of allowable values, using attributes like <code>required</code> and <code>pattern</code> to set basic constraints.</p> + +<p>However, you may want to impose more complex constraints, or to provide clearer reporting of validation failures than the defaults. This can be done using the Constraint Validation API.</p> + +<div class="note"> +<p><strong>Note:</strong> Client-side constraint validation doesn't remove the need for validation on the server side. Even though client-side validation can prevent many common kinds of invalid values, invalid ones can still be sent by older browsers or by attackers trying to trick your web application. Therefore, you need to also validate input values on the server side, in a way that is consistent with what is done on the client side. Client side validation is a tool for giving quick feedback to the user. You should not rely on it to completely sanitize data received by the server.</p> +</div> + +<p>Validation of constraints through the constraint validation API is done either on a single form element or at the form level, on the {{ HTMLElement("form") }} element itself.</p> + +<h2 id="Constraint_validation_interfaces">Constraint validation interfaces</h2> + +<dl> + <dt><a href="/en-US/docs/Web/API/ValidityState">ValidityState</a></dt> + <dd>The ValidityState interface represents the <em>validity states</em> that a form control element can have, with respect to its defined constraints. Together, they help explain whether and why an element's value fails to validate.</dd> + <dt><a href="/en-US/docs/Web/Events/invalid">invalid</a> event</dt> + <dd>This event type is fired at a form control element if the element does not satisfy its constraints.</dd> +</dl> + +<h3 id="Extensions_to_other_interfaces">Extensions to other interfaces</h3> + +<p>The constraint validation API extends the interfaces for the form-associated elements listed below with a number of new properties and methods (elements that can have a <code>form</code> attribute that indicates their form owner):</p> + +<ul> + <li><code><strong><a href="/en-US/docs/Web/API/HTMLButtonElement">HTMLButtonElement</a></strong></code></li> + <li><code><strong><a href="/en-US/docs/Web/API/HTMLFieldsetElement">HTMLFieldsetElement</a></strong></code></li> + <li><code><strong><a href="/en-US/docs/Web/API/HTMLInputElement">HTMLInputElement</a></strong></code></li> + <li><code><strong><a href="/en-US/docs/Web/API/HTMLObjectElement">HTMLObjectElement</a></strong></code></li> + <li><code><strong><a href="/en-US/docs/Web/API/HTMLOutputElement">HTMLOutputElement</a></strong></code></li> + <li><code><strong><a href="/en-US/docs/Web/API/HTMLSelectElement">HTMLSelectElement</a></strong></code></li> + <li><code><strong><a href="/en-US/docs/Web/API/HTMLTextAreaElement">HTMLTextAreaElement</a></strong></code></li> +</ul> + +<h4 id="Properties">Properties</h4> + +<dl> + <dt><code>validity</code></dt> + <dd>A read-only properity that returns a <code><a href="/en-US/docs/Web/API/ValidityState">ValidityState</a></code> object, whose properties represent validation errors for the value of that element.</dd> + <dt><code>validationMessage</code></dt> + <dd>A read-only property that returns an empty string if the element is not a candidate for constraint validation, or if the element's value is valid. If the element's value is not valid, it returns a localized validation message. This will be displayed in the UI if the element is the only form control with a validity problem; if a custom error message is set using <code>setCustomValidity()</code>, this will be shown.</dd> + <dt><code>willValidate</code></dt> + <dd>A read-only boolean property that returns <code>true</code> if the element is a candidate for constraint validation; and <code>false</code> otherwise. Elements with the <code>HTMLObjectElement</code> interface are <em>never</em> candidates for constraint validation. Others may be barred from constraint validation depending on specific conditions.</dd> +</dl> + +<h4 id="Methods">Methods</h4> + +<dl> + <dt><code>checkValidity()</code></dt> + <dd>Checks the element's value against its constraints. If the value is invalid, it fires an <a href="/en-US/docs/Web/Events/invalid">invalid</a> event at the element and returns <code>false</code>; otherwise it returns <code>true</code>.</dd> + <dt><code>reportValidity()</code></dt> + <dd>Checks the element's value against its constraints and also reports the validity status; if the value is invalid, it fires an <a href="/en-US/docs/Web/Events/invalid">invalid</a> event at the element, returns <code>false</code>, and then reports the validity status to the user in whatever way the user agent has available. Otherwise, it returns <code>true</code>.</dd> + <dt><code>setCustomValidity(<em>message</em>)</code></dt> + <dd>Sets a custom error message string to be shown to the user upon submitting the form, explaining why the value is not valid — when a message is set, the validity state is set to invalid. To clear this state, invoke the function with an empty string passed as its argument. In this case the custom error message is cleared, the element is considered valid, and no message is shown.</dd> +</dl> + +<h2 id="Examples">Examples</h2> + +<p>Take the following form:</p> + +<pre class="brush: html"><form> + <label for="name">Enter username (upper and lowercase letters): </label> + <input type="text" name="name" id="name" required pattern="[A-Za-z]+"> + <button>Submit</button> +</form></pre> + +<p>The basic HTML form validation features will cause this to produce a default error message if you try to submit the form with either no valid filled in, or a value that does not match the <code>pattern</code>.</p> + +<p>If you wanted to instead display custom error messages, you could use JavaScript like the following:</p> + +<pre class="brush: js">const nameInput = document.querySelector('input'); +const form = document.querySelector('form'); + +nameInput.addEventListener('input', () => { + nameInput.setCustomValidity(''); + nameInput.checkValidity(); +}); + +nameInput.addEventListener('invalid', () => { + if(nameInput.value === '') { + nameInput.setCustomValidity('Enter your username!'); + } else { + nameInput.setCustomValidity('Usernames can only contain upper and lowercase letters. Try again!'); + } +});</pre> + +<p>The example renders like so:</p> + +<p>{{EmbedLiveSample('Examples')}}</p> + +<p>In brief:</p> + +<ul> + <li>We check the valid state of the input element every time its value is changed by running the <code>checkValidity()</code> method via the <code>input</code> event handler.</li> + <li>If the value is invalid, an <code>invalid</code> event is raised, and the <code>invalid</code> event handler function is run. Inside this function we work out whether the value is invalid because it is empty, or because it doesn't match the pattern, using an <code>if()</code> block, and set a custom validity error message.</li> + <li>As a result, if the input value is invalid when the submit button is pressed, one of the custom error messages will be shown.</li> + <li>If it is valid, it will submit as you'd expect. For this to happen, the custom validity has to be cancelled, by invoking <code>setCustomValidity()</code> with an empty string value. We therefore do this every time the <code>input</code> event is raised. If you don't do this, and a custom validity was previously set, the input will register as invalid, even if it current contains a valid value on submission.</li> +</ul> + +<div class="blockIndicator note"> +<p><strong>Note</strong>: Firefox supported a proprietary error attribute — <code>x-moz-errormessage</code> — for many versions, which allowed you set custom error messages in a similar way. This has been removed as of version 66 (see <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1513890">bug 1513890</a>).</p> +</div> + +<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', 'forms.html#the-constraint-validation-api', 'constraint validation API') }}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </td> + </tr> + <tr> + <td>{{ SpecName('HTML5.1', 'sec-forms.html#the-constraint-validation-api', 'constraint validation API') }}</td> + <td>{{Spec2('HTML5.1')}}</td> + <td>No change from the previous snapshot {{SpecName('HTML5 W3C')}}.</td> + </tr> + <tr> + <td>{{ SpecName('HTML5 W3C', 'forms.html#the-constraint-validation-api', 'constraint validation API') }}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>First snapshot of {{SpecName('HTML WHATWG')}} containing this interface.</td> + </tr> + </tbody> +</table> + +<h2 id="See_also">See also</h2> + +<ul> + <li><code><a href="/en-US/docs/Web/HTML/Element/input"><input></a></code></li> + <li><code><a href="/en-US/docs/Web/HTML/Element/select"><select></a></code></li> + <li><code><a href="/en-US/docs/Web/HTML/Element/textarea"><textarea></a></code></li> +</ul> diff --git a/files/es/web/api/crypto/index.html b/files/es/web/api/crypto/index.html new file mode 100644 index 0000000000..3eb118b7b7 --- /dev/null +++ b/files/es/web/api/crypto/index.html @@ -0,0 +1,66 @@ +--- +title: Crypto +slug: Web/API/Crypto +tags: + - API + - Interfaz + - Referencia + - Web Crypto API +translation_of: Web/API/Crypto +--- +<p>{{APIRef("Web Crypto API")}}</p> + +<p>La interfaz <code><strong>Crypto</strong></code> representa las características básicas de criptografía disponibles en el contexto actual. Permite acceder a un generador de números aleatorios criptográficamente fuerte y a primitivos criptográficos.</p> + +<p>Un objeto con esta interfaz está disponible en el contexto de la Web a través de la propiedad {{domxref("Window.crypto")}}.</p> + +<h2 id="Propiedades">Propiedades</h2> + +<p><em>Esta interfaz implementa las propiedades definidas en {{domxref("RandomSource")}}.</em></p> + +<dl> + <dt>{{domxref("Crypto.subtle")}} {{readOnlyInline}}</dt> + <dd>Retorna un {{domxref("SubtleCrypto")}} objeto proporcionando acceso a primitivos criptográficos comunes, como el hashing, el firmado, cifrado o descifrado.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<p><em>Esta interfaz implementa las propiedades definidas en {{domxref("RandomSource")}}.</em></p> + +<dl> + <dt>{{domxref("Crypto.getRandomValues()")}}</dt> + <dd>Llena el pasado {{ jsxref("TypedArray") }} valores aleatorio sólidos criptográficamente.</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("Web Crypto API", "#crypto-interface", "Crypto")}}</td> + <td>{{Spec2("Web Crypto API")}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_del_navegador">Compatibilidad del navegador</h2> + +<div> +<div class="hidden">La tabla de compatibilidad de esta página se genera a partir de datos estructurados. Si desea contribuir a los datos, por favor, compruebe <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> y enviarnos un pull request.</div> + +<p>{{Compat("api.Crypto")}}</p> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/Components.utils.importGlobalProperties">Components.utils.importGlobalProperties</a></li> +</ul> diff --git a/files/es/web/api/crypto/subtle/index.html b/files/es/web/api/crypto/subtle/index.html new file mode 100644 index 0000000000..af1106f076 --- /dev/null +++ b/files/es/web/api/crypto/subtle/index.html @@ -0,0 +1,51 @@ +--- +title: Crypto.subtle +slug: Web/API/Crypto/subtle +tags: + - API + - Criptografía + - Propiedad + - Referencia + - Sólo-Lectura + - Web Crypto API +translation_of: Web/API/Crypto/subtle +--- +<p>{{APIRef("Web Crypto API")}}</p> + +<p>La propiedad de sólo lectura <strong><code>Crypto.subtle</code></strong> retorna un objeto {{domxref("SubtleCrypto")}} permitiendo realizar operaciones criptográficas.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre>var <em>crypto</em> = crypto.subtle;</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{ SpecName('Web Crypto API', '#dfn-Crypto', 'Crypto.subtle') }}</td> + <td>{{ Spec2('Web Crypto API') }}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_del_navegador">Compatibilidad del navegador</h2> + + + +<p>{{Compat("api.Crypto.subtle")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("Crypto")}}.</li> + <li>{{domxref("SubtleCrypto")}}.</li> + <li><a href="https://vibornoff.github.io/webcrypto-examples/index.html">Compatibility test page</a>.</li> + <li><a href="https://github.com/vibornoff/webcrypto-shim">Shim for IE11 and Safari</a>.</li> +</ul> diff --git a/files/es/web/api/css_object_model/index.html b/files/es/web/api/css_object_model/index.html new file mode 100644 index 0000000000..3665c750cd --- /dev/null +++ b/files/es/web/api/css_object_model/index.html @@ -0,0 +1,129 @@ +--- +title: CSS Object Model +slug: Web/API/CSS_Object_Model +tags: + - API + - CSSOM + - Referencia +translation_of: Web/API/CSS_Object_Model +--- +<p>{{DefaultAPISidebar('CSSOM')}}</p> + +<p>El Modelo de objetos CSS (<strong>CSS Object Model</strong>) es un conjunto de APIs que permite manipular CSS desde JavaScript. Así como el DOM (Document Object Model) es para HTML, el CSSOM (CSS Object Model) es para CSS. Permite leer y modificar el estilo de CSS de forma dinámica.</p> + +<h2 id="Referencia">Referencia</h2> + +<div class="index"> +<ul> + <li>{{domxref("AnimationEvent")}}</li> + <li>{{domxref("CaretPosition")}}</li> + <li>{{domxref("CSS")}}</li> + <li>{{domxref("CSSCharsetRule")}}</li> + <li>{{domxref("CSSConditionRule")}}</li> + <li>{{domxref("CSSCounterStyleRule")}}</li> + <li>{{domxref("CSSFontFaceRule")}}</li> + <li>{{domxref("CSSFontFeatureValuesMap")}}</li> + <li>{{domxref("CSSFontFeatureValuesRule")}}</li> + <li>{{domxref("CSSGroupingRule")}}</li> + <li>{{domxref("CSSImportRule")}}</li> + <li>{{domxref("CSSKeyframeRule")}}</li> + <li>{{domxref("CSSKeyframesRule")}}</li> + <li>{{domxref("CSSMarginRule")}}</li> + <li>{{domxref("CSSMediaRule")}}</li> + <li>{{domxref("CSSNamespaceRule")}}</li> + <li>{{domxref("CSSPageRule")}}</li> + <li>{{domxref("CSSRule")}}</li> + <li>{{domxref("CSSRuleList")}}</li> + <li>{{domxref("CSSStyleSheet")}}</li> + <li>{{domxref("CSSStyleDeclaration")}}</li> + <li>{{domxref("CSSSupportsRule")}}</li> + <li>{{domxref("CSSVariablesMap")}}</li> + <li>{{domxref("CSSViewportRule")}}</li> + <li>{{domxref("ElementCSSInlineStyle")}}</li> + <li>{{domxref("GeometryUtils")}}</li> + <li>{{domxref("GetStyleUtils")}}</li> + <li>{{domxref("LinkStyle")}}</li> + <li>{{domxref("MediaList")}}</li> + <li>{{domxref("MediaQueryList")}}</li> + <li>{{domxref("PseudoElement")}}</li> + <li>{{domxref("Screen")}}</li> + <li>{{domxref("StyleSheet")}}</li> + <li>{{domxref("StyleSheetList")}}</li> + <li>{{domxref("TransitionEvent")}}</li> +</ul> +</div> + +<p>Algunas otras interfaces también son complementadas por las especificaciones relacionadas con CSSOM: {{domxref("Document")}}, {{domxref("Window")}}, {{domxref("Element")}}, {{domxref("HTMLElement")}}, {{domxref("HTMLImageElement")}}, {{domxref("Range")}}, {{domxref("MouseEvent")}}, y {{domxref("SVGElement")}}.</p> + +<h2 id="Tutoriales">Tutoriales</h2> + +<ul> + <li><a href="/en-US/docs/Determining_the_dimensions_of_elements">Determinar las dimensiones de los elementos</a> (Necesita actualización porque se realizó con DHTML/Ajax).</li> + <li><a href="/en-US/docs/WebAPI/Managing_screen_orientation">Gestionando la orientación de la pantalla</a></li> +</ul> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Epecificacion</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName("CSSOM")}}</td> + <td>{{Spec2("CSSOM")}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName("CSSOM View")}}</td> + <td>{{Spec2("CSSOM View")}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName("Screen Orientation")}}</td> + <td>{{Spec2("Screen Orientation")}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName("CSS3 Fonts")}}</td> + <td>{{Spec2("CSS3 Fonts")}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName("CSS3 Animations")}}</td> + <td>{{Spec2("CSS3 Animations")}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName("CSS3 Transitions")}}</td> + <td>{{Spec2("CSS3 Transitions")}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName("CSS3 Variables")}}</td> + <td>{{Spec2("CSS3 Variables")}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName("CSS3 Conditional")}}</td> + <td>{{Spec2("CSS3 Conditional")}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName("CSS3 Device")}}</td> + <td>{{Spec2("CSS3 Device")}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName("CSS3 Counter Styles")}}</td> + <td>{{Spec2("CSS3 Counter Styles")}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Notas_de_compatibilidad_con_los_navegadores">Notas de compatibilidad con los navegadores</h2> + +<p>Todas estas funcionalidades han sido añadidas a los navegadores poco a poco durante los años: Es un complejo proceso que no puede ser resumido en una simple tabla. Por favor busca la disponibilidad en navegadores en las interfaces específicas.</p> diff --git a/files/es/web/api/cssrule/csstext/index.html b/files/es/web/api/cssrule/csstext/index.html new file mode 100644 index 0000000000..4dd97fff2c --- /dev/null +++ b/files/es/web/api/cssrule/csstext/index.html @@ -0,0 +1,22 @@ +--- +title: CssRule.cssText +slug: Web/API/CSSRule/cssText +translation_of: Web/API/CSSRule/cssText +--- +<div> + {{APIRef}}</div> +<div> + </div> +<p><span style="font-size: 1.71428571428571rem; letter-spacing: -0.5px; line-height: 24px;">Summary</span></p> +<p><strong><font><font>cssText</font></font></strong><font><font> returns the current text style rule.</font></font></p> +<h3 id="Syntax" name="Syntax"><font><font>Syntax</font></font></h3> +<pre class="eval"><em><font><font>string</font></font></em> = cssRule.cssText +</pre> +<h3 id="Example" name="Example"><font><font>Instance</font></font></h3> +<pre class="eval">if (myRule.cssText.indexOf ("background-color")! = -1) { + bgRule = MyRule; +} +... +</pre> +<h3 id="Specification" name="Specification"><font><font>Specification</font></font></h3> +<p><font><font>DOM Level 2 Style - cssRule</font></font></p> diff --git a/files/es/web/api/cssrule/index.html b/files/es/web/api/cssrule/index.html new file mode 100644 index 0000000000..bd8837d217 --- /dev/null +++ b/files/es/web/api/cssrule/index.html @@ -0,0 +1,95 @@ +--- +title: CssRule +slug: Web/API/CSSRule +translation_of: Web/API/CSSRule +--- +<p>{{ ApiRef("CSSOM") }}</p> + +<p>El objeto <code>CSSRule </code>representa una única regla de estilo CSS. Puede ser parte de una lista <a href="/Es/DOM/Stylesheet.cssRules" title="es/DOM/stylesheet.cssRules">cssRules</a> de hojas de estilo (<a href="/Es/DOM/Stylesheet" title="es/DOM/stylesheet">stylesheet</a>).</p> + +<p>Existen varias clases de reglas y todas ellas comparten unas cuantas propiedades comunes en el interface {{ Anch("CSSRule") }} y la mayor parte de ellas son propiedades específicas de un tipo particular de reglas.</p> + +<table class="fullwidth-table"> + <tbody> + <tr> + <th>Tipo</th> + <th>interface específico de la regla</th> + <th>Descripción</th> + </tr> + <tr> + <td><code>CSSRule.STYLE_RULE</code></td> + <td>{{ Anch("CSSStyleRule") }}</td> + <td> </td> + </tr> + <tr> + <td><code>CSSRule.MEDIA_RULE</code></td> + <td>{{ Anch("CSSMediaRule") }}</td> + <td> </td> + </tr> + <tr> + <td><code>CSSRule.FONT_FACE_RULE</code></td> + <td>{{ Anch("CSSFontFaceRule") }}</td> + <td> </td> + </tr> + <tr> + <td><code>CSSRule.PAGE_RULE</code></td> + <td>{{ Anch("CSSPageRule") }}</td> + <td> </td> + </tr> + <tr> + <td><code>CSSRule.IMPORT_RULE</code></td> + <td>{{ Anch("CSSImportRule") }}</td> + <td> </td> + </tr> + <tr> + <td><code>CSSRule.CHARSET_RULE</code></td> + <td>{{ Anch("CSSCharsetRule") }}</td> + <td> </td> + </tr> + <tr> + <td><code>CSSRule.UNKNOWN_RULE</code></td> + <td>{{ Anch("CSSUnknownRule") }}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h3 id="CSSRule" name="CSSRule">CSSRule</h3> + +<dl> + <dt><a href="/Es/DOM/CssRule.cssText" title="es/DOM/cssRule.cssText">cssText</a></dt> + <dd>Devuelve la representación en forma de texto, de la regla. Ejem.: "h1,h2 { font-size: 16pt }".</dd> + <dt><a href="/es/DOM/cssRule.parentRule" title="es/DOM/cssRule.parentRule">parentRule</a></dt> + <dd>Devuelve la regla contenedora, si existe. Ejem.: una regla de estilo dentro de un bloque @media.</dd> + <dt><a href="/Es/DOM/CssRule.parentStyleSheet" title="es/DOM/cssRule.parentStyleSheet">parentStyleSheet</a></dt> + <dd>Devuelve el objeto <a href="/Es/DOM/Stylesheet" title="es/DOM/stylesheet">stylesheet</a> del que esta regla es parte.</dd> + <dt><a href="/es/DOM/cssRule.type" title="es/DOM/cssRule.type">type</a></dt> + <dd>El tipo de regla. ejem.: <code>CSSRule.CHARSET_RULE</code> o <code>CSSRule.IMPORT_RULE</code>.</dd> +</dl> + +<h3 id="CSSStyleRule" name="CSSStyleRule">CSSStyleRule</h3> + +<dl> + <dt><a href="/Es/DOM/CssRule.selectorText" title="es/DOM/cssRule.selectorText">selectorText</a></dt> + <dd>Recoje/Establece la representación en forma de texto, del selector de la regle. Ejem.: "h1,h2".</dd> + <dt><a href="/Es/DOM/CssRule.style" title="es/DOM/cssRule.style">style</a></dt> + <dd>Devuelve el objeto <a class="external" href="http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration">CSSStyleDeclaration</a> para el bloque <a class="external" href="http://www.w3.org/TR/1998/REC-CSS2-19980512/syndata.html#block">declaration block</a> de la regla.</dd> +</dl> + +<h3 id="CSSStyleRule_2" name="CSSStyleRule_2">CSSStyleRule</h3> + +<h3 id="CSSMediaRule" name="CSSMediaRule">CSSMediaRule</h3> + +<h3 id="CSSFontFaceRule" name="CSSFontFaceRule">CSSFontFaceRule</h3> + +<h3 id="CSSPageRule" name="CSSPageRule">CSSPageRule</h3> + +<h3 id="CSSImportRule" name="CSSImportRule">CSSImportRule</h3> + +<h3 id="CSSCharsetRule" name="CSSCharsetRule">CSSCharsetRule</h3> + +<h3 id="CSSUnknownRule" name="CSSUnknownRule">CSSUnknownRule</h3> + +<h3 id="Specification" name="Specification">Specification</h3> + +<p><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSRule">DOM Level 2 CSS: CSSRule</a></p> diff --git a/files/es/web/api/cssrule/parentstylesheet/index.html b/files/es/web/api/cssrule/parentstylesheet/index.html new file mode 100644 index 0000000000..f66c603137 --- /dev/null +++ b/files/es/web/api/cssrule/parentstylesheet/index.html @@ -0,0 +1,27 @@ +--- +title: cssRule.parentStyleSheet +slug: Web/API/CSSRule/parentStyleSheet +translation_of: Web/API/CSSRule/parentStyleSheet +--- +<div> + {{APIRef}}</div> +<div> + </div> +<p><span style="font-size: 1.71428571428571rem; letter-spacing: -0.5px; line-height: 24px;">Summary</span></p> +<p><strong><font><font>parentStyleSheet</font></font></strong><font><font> returns the object type of style sheet, in which the rule is defined.</font></font></p> +<h3 id="Syntax" name="Syntax"><font><font>Syntax</font></font></h3> +<pre class="eval"><em><font><font>stylesheet</font></font></em> = cssRule.parentStyleSheet +</pre> +<h3 id="Parameters" name="Parameters"><font><font>Parameters</font></font></h3> +<ul> + <li><code><font><font>stylesheet</font></font></code><font><font> stylesheet is an object type.</font></font></li> +</ul> +<h3 id="Example" name="Example"><font><font>Instance</font></font></h3> +<pre class="eval">if (bgRule.parentStyleSheet! = MySheet) { + // Style alien rule! +} +</pre> +<h3 id="Notes" name="Notes"><font><font>Letters</font></font></h3> +<p><font><font>See </font></font><a href="/es/DOM/event#DOM_styleSheet_Object" title="en / DOM / event # DOM_styleSheet_Object"><font><font>Gecko DOM Reference: event # DOM_styleSheet_Object</font></font></a><font><font> for more information about the interface type objects stylesheet.</font></font></p> +<h3 id="Specification" name="Specification"><font><font>Specification</font></font></h3> +<p><font><font>DOM Level 2 Style - cssRule</font></font></p> diff --git a/files/es/web/api/cssstyledeclaration/index.html b/files/es/web/api/cssstyledeclaration/index.html new file mode 100644 index 0000000000..f63d7a2cfd --- /dev/null +++ b/files/es/web/api/cssstyledeclaration/index.html @@ -0,0 +1,73 @@ +--- +title: CSSStyleDeclaration +slug: Web/API/CSSStyleDeclaration +tags: + - Interfaz + - Referencia +translation_of: Web/API/CSSStyleDeclaration +--- +<p>{{ APIRef("CSSOM") }}</p> + +<h2 id="Summary" name="Summary">Resúmen</h2> + +<p><code>CSSStyleDeclaration</code> representa una colección CSS de pares propiedad-valor. Se utiliza en unas cuantas APIs:</p> + +<ul> + <li>{{domxref("HTMLElement.style")}} - para manipular el estilo de un solo elemento (<elem style="...">);</li> + <li>En otras palabras, es un interface para los <a class="external" href="http://www.w3.org/TR/1998/REC-CSS2-19980512/syndata.html#block">bloques de declaraciones</a> devueltos por la propiedad <code><a href="/en/DOM/cssRule.style" rel="internal" title="en/DOM/cssRule.style">style</a></code> de una <code><a href="/en/DOM/cssRule" rel="internal" title="en/DOM/cssRule">regla CSS</a></code> en una <a href="/en/DOM/stylesheet" rel="internal" title="en/DOM/stylesheet">hoja de estilos</a>, cuando la regla es una <a href="/en/DOM/cssRule#CSSStyleRule" title="en/DOM/cssRule#CSSStyleRule">CSSStyleRule</a>.</li> + <li><code>CSSStyleDeclaration</code> es también un interface de <strong>sólo-lectura</strong> para el resultado de <a href="/en/DOM/window.getComputedStyle" title="en/DOM/window.getComputedStyle">window.getComputedStyle</a>().</li> +</ul> + +<h2 id="Syntax" name="Syntax">Atributos</h2> + +<dl> + <dt>{{domxref("CSSStyleDeclaration.cssText")}}</dt> + <dd>Representación textual del bloque de declaración. Estableciendo este atributo cambia el estilo.</dd> + <dt>{{domxref("CSSStyleDeclaration.length")}}</dt> + <dd>El número de propiedades. Ver el método del <strong>elemento</strong> inferior.</dd> + <dt>{{domxref("CSSStyleDeclaration.parentRule")}}</dt> + <dd>El contenedor {{domxref("CssRule")}}.</dd> +</dl> + +<h2 id="Syntax" name="Syntax">Métodos</h2> + +<dl> + <dt>{{domxref("CSSStyleDeclaration.getPropertyPriority()")}}</dt> + <dd>Retorna la prioridad opcional, "important". Ejemplo: <em>priString</em>= <em>styleObj</em>.getPropertyPriority('color')</dd> + <dt>{{domxref("CSSStyleDeclaration.getPropertyValue()")}}</dt> + <dd>Retorna el valor de la propiedad. Ejemplo: <em>valString</em>= <em>styleObj</em>.getPropertyValue('color')</dd> + <dt>{{domxref("CSSStyleDeclaration.item()")}}</dt> + <dd>Retorna un nombre de propiedad. Ejemplo: <em>nameString</em>= <em>styleObj</em>.item(0) Alternative: <em>nameString</em>= <em>styleObj</em>[0]</dd> + <dt>{{domxref("CSSStyleDeclaration.removeProperty()")}}</dt> + <dd>Retorna el valor borrado. Ejemplo: <em>valString</em>= <em>styleObj</em>.removeProperty('color')</dd> + <dt>{{domxref("CSSStyleDeclaration.setProperty()")}}</dt> + <dd>Sin retorno. Ejemplo: <em>styleObj</em>.setProperty('color', 'red', 'important')</dd> + <dt>{{domxref("CSSStyleDeclaration.getPropertyCSSValue()")}}</dt> + <dd><span style="color: rgb(255, 0, 0);">Solo soportado a través de getComputedStyle.</span> Devuelve un {{ domxref("ROCSSPrimitiveValue") }} en Firefox ({{ domxref("CSSPrimitiveValue") }}, en otros, los cuales implementan <a class="external" href="http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSValue" title="http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSValue">CSSValue</a>), o nulo para <a href="/en/CSS/Shorthand_properties" title="en/Guide to Shorthand CSS">Propiedades taquigráficas</a>. Ejemplo: <em>cssString</em>= window.getComputedStyle(<em>elemento</em>, <code>null</code>).getPropertyCSSValue('color').cssText;<br> + Observación: Gecko 1.9 devuelve <strong>null </strong>a menos que se utilice <a href="/en/DOM/window.getComputedStyle" title="en/DOM/window.getComputedStyle">getComputedStyle()</a>.<br> + Observación: Este método puede estar <a class="external" href="http://lists.w3.org/Archives/Public/www-style/2003Oct/0347.html" title="http://lists.w3.org/Archives/Public/www-style/2003Oct/0347.html">desaconsejado por el W3C</a> , y no está presente en el último <a href="http://dev.w3.org/csswg/cssom/#cssstyledeclaration" title="http://dev.w3.org/csswg/cssom/#cssstyledeclaration">borrador CSSOM</a>. No está soportado por IE e incluso aunque la función existe en Opera, llamarla lanza una excepción {{ domxref("DOMException") }} NOT_SUPPORTED_ERR.</dd> +</dl> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre class="brush: js">var styleObj= document.styleSheets[0].cssRules[0].style; +alert(styleObj.cssText); +for (var i = styleObj.length-1; i >= 0; i--) { + var nameString = styleObj[i]; + styleObj.removeProperty(nameString); +} +alert(styleObj.cssText);</pre> + +<h2 id="Notes" name="Notes">Notas</h2> + +<p>El bloque de declaración es esa parte de la regla de estilo que aparece dentro de las llaves ({}) y que actualmente proporciona las definiciones de estilo (para el selector, la parte que precede a las llaves).</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/Web/CSS/CSS_Properties_Reference" title="/en-US/docs/Web/CSS/CSS_Properties_Reference">Propiedades DOM CSS</a></li> +</ul> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<p><a class="external" href="http://dev.w3.org/csswg/cssom/#the-cssstyledeclaration-interface">CSSOM: CSSStyleDeclaration</a></p> diff --git a/files/es/web/api/cssstylerule/index.html b/files/es/web/api/cssstylerule/index.html new file mode 100644 index 0000000000..1026c9af82 --- /dev/null +++ b/files/es/web/api/cssstylerule/index.html @@ -0,0 +1,105 @@ +--- +title: CSSStyleRule +slug: Web/API/CSSStyleRule +tags: + - API +translation_of: Web/API/CSSStyleRule +--- +<p>{{ APIRef("CSSOM") }}</p> + +<p><strong><code>CSSStyleRule</code></strong> representa una sola regla de estilos CSS. Implementa la interfaz {{domxref("CSSRule")}} with a type value of <code>1</code> (<code>CSSRule.STYLE_RULE</code>).</p> + +<h2 id="Properties" name="Properties">Sintaxis</h2> + +<p>La sintaxis es descrita usando el formato <a class="external" href="http://dev.w3.org/2006/webapi/WebIDL/" title="http://dev.w3.org/2006/webapi/WebIDL/">WebIDL</a>.</p> + +<pre>interface CSSStyleRule : CSSRule { + attribute DOMString selectorText; + readonly attribute CSSStyleDeclaration style; +};</pre> + +<h2 id="Propiedades">Propiedades</h2> + +<dl> + <dt id="selectorText">{{domxref("CSSStyleRule.selectorText")}}</dt> + <dd>Obtiene la representación textual del selector para esta regla, e.g. <code>"h1,h2"</code>.</dd> + <dt id="style">{{domxref("CSSStyleRule.style")}} {{readonlyinline}}</dt> + <dd>Retorna el objeto {{domxref("CSSStyleDeclaration")}} para la regla. <strong>Sólo lectura.</strong></dd> +</dl> + +<h2 id="Specification" name="Specification">Especificaciones</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estatus</th> + <th scope="col">Comentario</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('CSSOM', '#the-cssstylerule-interface', 'CSSStyleRule') }}</td> + <td>{{ Spec2('CSSOM') }}</td> + <td>Sin cambios</td> + </tr> + <tr> + <td>{{ SpecName('DOM2 Style', 'css.html#CSS-CSSStyleRule', 'CSSRule') }}</td> + <td>{{ Spec2('DOM2 Style') }}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_entre_Navegadores">Compatibilidad entre Navegadores</h2> + +<p>Para obtener informacion de compatibilidad en los distintos navegadores, por favor consulta la tabla de compatibilidad de la interfaz asociada.</p> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}<br> + </td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + </tbody> +</table> +</div> diff --git a/files/es/web/api/cssstylerule/selectortext/index.html b/files/es/web/api/cssstylerule/selectortext/index.html new file mode 100644 index 0000000000..56dec42a94 --- /dev/null +++ b/files/es/web/api/cssstylerule/selectortext/index.html @@ -0,0 +1,23 @@ +--- +title: CssRule.selectorText +slug: Web/API/CSSStyleRule/selectorText +translation_of: Web/API/CSSStyleRule/selectorText +--- +<p>{{ ApiRef() }}</p> +<h3 id="Summary" name="Summary">Resumen</h3> +<p><strong>selectorText</strong> recoge/establece la representación en forma de texto, del selector para el grupo de reglas.</p> +<h3 id="Syntax" name="Syntax">Sintaxis</h3> +<pre class="eval"><em>string</em> = cssRule.selectorText +cssRule.selectorText = <em>string</em> +</pre> +<h3 id="Example" name="Example">Ejemplo</h3> +<pre> // for cssrule: body { background-color: darkblue; } + cssrule = document.styleSheets[1] + !!TODO!! + selector = cssrule.selectorText; + // selector is now "body" +</pre> +<h3 id="Notes" name="Notes">Notas</h3> +<p>La implementación puede haber eliminado espacios en blanco no significativos, en el momento de comprobar el selector.</p> +<h3 id="Specification" name="Specification">Especificación</h3> +<p>DOM Level 2 Style - cssRule</p> diff --git a/files/es/web/api/cssstylesheet/deleterule/index.html b/files/es/web/api/cssstylesheet/deleterule/index.html new file mode 100644 index 0000000000..f11a905d98 --- /dev/null +++ b/files/es/web/api/cssstylesheet/deleterule/index.html @@ -0,0 +1,21 @@ +--- +title: Stylesheet.deleteRule +slug: Web/API/CSSStyleSheet/deleteRule +translation_of: Web/API/CSSStyleSheet/deleteRule +--- +<p>{{ ApiRef() }}</p> +<h3 id="Summary" name="Summary">Resumen</h3> +<p>El método <strong>deleteRule</strong> elimina una regla de la hoja de estilos actual.</p> +<h3 id="Syntax" name="Syntax">Sintaxis</h3> +<pre class="eval">stylesheet.deleteRule(<em>index</em>) +</pre> +<h3 id="Parameters" name="Parameters">Parámetros</h3> +<ul> + <li><code>index</code> es un numero de tipo long, que indica la posición de la regla.</li> +</ul> +<h3 id="Example" name="Example">Ejemplo</h3> +<pre> myStyles.deleteRule(0); +</pre> +<h3 id="Specification" name="Specification">Especificación</h3> +<p><a class="external" href="http://www.w3.org/TR/2000/REC-DOM-Level-2-Style-20001113/css.html#CSS-CSSStyleSheet-deleteRule">deleteRule </a></p> +<p>{{ languages( { "pl": "pl/DOM/stylesheet.deleteRule" } ) }}</p> diff --git a/files/es/web/api/cssstylesheet/index.html b/files/es/web/api/cssstylesheet/index.html new file mode 100644 index 0000000000..f9781136ae --- /dev/null +++ b/files/es/web/api/cssstylesheet/index.html @@ -0,0 +1,64 @@ +--- +title: CSSStyleSheet +slug: Web/API/CSSStyleSheet +translation_of: Web/API/CSSStyleSheet +--- +<p>{{ ApiRef() }}</p> +<p> </p> +<p>This section describes the <a class="external" href="http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleSheet">CSSStyleSheet</a> object, which represents a single CSS stylesheet.</p> +<p>A CSS stylesheet consists of CSS rules, each of them can be manipulated through its <a href="/en/DOM/cssRule" title="en/DOM/cssRule">CSSRule</a> object. The stylesheet object itself lets you examine and modify the stylesheet, including its list of rules.</p> +<p>You can get the list of stylesheets for a given document using the <a href="/en/DOM/document.styleSheets" title="en/DOM/document.styleSheets">document.styleSheets</a> property.</p> +<h3 id="Properties" name="Properties">Properties</h3> +<dl> + <dt> + <a href="/en/DOM/stylesheet.cssRules" title="en/DOM/stylesheet.cssRules">stylesheet.cssRules</a></dt> + <dd> + Returns all of the CSS rules in the stylesheet as an array.</dd> + <dt> + <a href="/en/DOM/stylesheet.disabled" title="en/DOM/stylesheet.disabled">stylesheet.disabled</a></dt> + <dd> + This property indicates whether the current stylesheet has been applied or not.</dd> + <dt> + <a href="/en/DOM/stylesheet.href" title="en/DOM/stylesheet.href">stylesheet.href</a></dt> + <dd> + Returns the location of the stylesheet.</dd> + <dt> + <a href="/en/DOM/stylesheet.media" title="en/DOM/stylesheet.media">stylesheet.media</a></dt> + <dd> + Specifies the intended destination medium for style information.</dd> + <dt> + <a href="/en/DOM/stylesheet.ownerNode" title="en/DOM/stylesheet.ownerNode">stylesheet.ownerNode</a></dt> + <dd> + Returns the node that associates this style sheet with the document.</dd> + <dt> + <a href="/en/DOM/stylesheet.ownerRule" title="en/DOM/stylesheet.ownerRule">stylesheet.ownerRule</a></dt> + <dd> + If this style sheet comes from an @import rule, the ownerRule property will contain the CSSImportRule.</dd> + <dt> + <a href="/en/DOM/stylesheet.parentStyleSheet" title="en/DOM/stylesheet.parentStyleSheet">stylesheet.parentStyleSheet</a></dt> + <dd> + Returns the stylesheet that is including this one, if any.</dd> + <dt> + <a href="/en/DOM/stylesheet.title" title="en/DOM/stylesheet.title">stylesheet.title</a></dt> + <dd> + Returns the advisory title of the current style sheet.</dd> + <dt> + <a href="/en/DOM/stylesheet.type" title="en/DOM/stylesheet.type">stylesheet.type</a></dt> + <dd> + Specifies the style sheet language for this style sheet.</dd> +</dl> +<h3 id="Methods" name="Methods">Methods</h3> +<dl> + <dt> + <a href="/en/DOM/stylesheet.deleteRule" title="en/DOM/stylesheet.deleteRule">stylesheet.deleteRule</a></dt> + <dd> + Deletes a rule from the stylesheet.</dd> + <dt> + <a href="/en/DOM/stylesheet.insertRule" title="en/DOM/stylesheet.insertRule">stylesheet.insertRule</a></dt> + <dd> + Inserts a new style rule into the current style sheet.</dd> +</dl> +<h3 id="Specification" name="Specification">Specification</h3> +<p><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Style/stylesheets.html#StyleSheets-StyleSheet">DOM Level 2 Style Sheets: StyleSheet</a></p> +<p><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleSheet">DOM Level 2 CSS: CSSStyleSheet</a></p> +<p>{{ languages( { "pl": "pl/DOM/stylesheet" } ) }}</p> diff --git a/files/es/web/api/cssstylesheet/insertrule/index.html b/files/es/web/api/cssstylesheet/insertrule/index.html new file mode 100644 index 0000000000..ef0f3e522d --- /dev/null +++ b/files/es/web/api/cssstylesheet/insertrule/index.html @@ -0,0 +1,119 @@ +--- +title: CSSStyleSheet.insertRule() +slug: Web/API/CSSStyleSheet/insertRule +tags: + - CSSStyleSheet +translation_of: Web/API/CSSStyleSheet/insertRule +--- +<div> + {{APIRef}}</div> +<p><span style="color: rgb(77, 78, 83);">El método </span><code style="font-size: 14px; color: rgb(77, 78, 83);"><strong>CSSStyleSheet.insertRule()</strong></code><span style="color: rgb(77, 78, 83);"> inserta una nueva regla de estilo en la actual hoja de estilos.</span></p> +<p><span style="color: rgb(77, 78, 83);">Para conjuntos de reglas ésta contiene tanto al selector como la declaración de estilo. Para reglas-arroba, ésta especifica tanto al identificador-arroba como como al contenido de la regla. Si se asignan varias reglas en el </span>{{domxref("DOMString")}}<span style="color: rgb(77, 78, 83);"> como parámetro se dispara una </span><span style="font-family: 'Courier New', 'Andale Mono', monospace; line-height: normal;"> </span><span style="line-height: 1.5;">{{domxref("DOMException")}}</span><span style="line-height: 1.5;"> con el código </span><span style="font-family: 'Courier New', 'Andale Mono', monospace; line-height: normal;">SYNTAX_ERR</span><span style="line-height: 1.5;">.</span></p> +<h2 id="Syntax" name="Syntax">Syntax</h2> +<pre class="syntaxbox"><var>stylesheet</var>.insertRule(<var>regla</var>, índice)</pre> +<h3 id="Parameters" name="Parameters">Parameters</h3> +<ul> + <li><code>regla</code> es un {{domxref("DOMString")}} que contiene la regla que se va a insertar (selector y declaración).</li> + <li><font face="Courier New, Andale Mono, monospace"><span style="line-height: normal;">índice</span></font> es un <code>unsigned int</code> que representa la posicion en la que se va a insertar.</li> +</ul> +<h2 id="Examples" name="Examples">Ejemplos</h2> +<h3 id="Example_1" name="Example_1">Ejemplo 1</h3> +<pre class="brush: js">// Insertar una nueva regla al principio de mi hoja de estilos +myStyle.insertRule("#blanc { color: white }", 0); +</pre> +<h3 id="Example_2" name="Example_2">Example 2</h3> +<pre class="brush: js">/** + * Agregar una regla de hoja de estilos al documento(sin embargo, una mejor práctica puede ser + * cambiar las clases dinamicamente, así se mantiene la información de estilo en + * hojas de estilo genuinas (evitando agregar elementos extras al DOM)) + * Note que se necesita una matriz para las declaraciones y reglas ya que ECMAScript + * no proporciona un orden de iteración predecible y como CSS + * depende del <span style="line-height: normal;">orden</span><span style="line-height: normal;">(i.e., es cascada); aquellos sin necesidad de</span> + * reglas en cascada podrían construir una API basada en objetos de acceso más amigable. + * @param {Matriz} reglas. Acepta una matriz de declaraciones JSON-encoded + * @example +addStylesheetRules([ + ['h2', // Acepta un segundo argumento como una matriz de matrices + ['color', 'red'], + ['background-color', 'green', true] // 'true' para reglas !important + ], + ['.myClass', ['background-color', 'yellow'] + ] +]); + */ +function addStylesheetRules (decls) { + var styleEl = document.createElement('style'); + document.head.appendChild(styleEl); + // Aparentemente ¿alguna versión de Safari necesita la siguiente linea? No lo sé. + styleEl.appendChild(document.createTextNode('')); + var s = styleEl.sheet; + for (var i=0, rl = rules.length; i < rl; i++) { + var j = 1, rule = rules[i], selector = decl[0], propStr = ''; + // Si el segundo argumento de una regla es una matriz de matrices, corrijamos nuestras variables. + if (Object.prototype.toString.call(rule[1][0]) === '[object Array]') { + rule = rule[1]; + j = 0; + } + for (var pl=rule.length; j < pl; j++) { + var prop = rule[j]; + propStr += prop[0] + ':' + prop[1] + (prop[2] ? ' !important' : '') + ';\n'; + } + s.insertRule(selector + '{' + propStr + '}', s.cssRules.length); + } +}</pre> +<h2 id="Specification" name="Specification">Specification</h2> +<ul> + <li><a href="http://www.w3.org/TR/2000/REC-DOM-Level-2-Style-20001113/css.html#CSS-CSSStyleSheet-insertRule">insertRule </a></li> +</ul> +<h2 id="Browser_compatibility" style="line-height: 30px;">Browser compatibility</h2> +<p>{{ CompatibilityTable() }}</p> +<div id="compat-desktop"> + <table class="compat-table"> + <tbody> + <tr> + <th style="line-height: 16px;">Feature</th> + <th style="line-height: 16px;">Chrome</th> + <th style="line-height: 16px;">Firefox (Gecko)</th> + <th style="line-height: 16px;">Internet Explorer</th> + <th style="line-height: 16px;">Opera</th> + <th style="line-height: 16px;">Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>8</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + </tbody> + </table> +</div> +<div id="compat-mobile"> + <table class="compat-table"> + <tbody> + <tr> + <th style="line-height: 16px;">Feature</th> + <th style="line-height: 16px;">Android</th> + <th style="line-height: 16px;">Chrome for Android</th> + <th style="line-height: 16px;">Firefox Mobile (Gecko)</th> + <th style="line-height: 16px;">IE Mobile</th> + <th style="line-height: 16px;">Opera Mobile</th> + <th style="line-height: 16px;">Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + </tbody> + </table> +</div> +<h2 id="See_also">See also</h2> +<ul> + <li><a href="/en-US/docs/Web/API/CSSStyleSheet/deleteRule"><code>deleteRule</code></a></li> +</ul> diff --git a/files/es/web/api/cssstylesheet/ownerrule/index.html b/files/es/web/api/cssstylesheet/ownerrule/index.html new file mode 100644 index 0000000000..cd8c302ce3 --- /dev/null +++ b/files/es/web/api/cssstylesheet/ownerrule/index.html @@ -0,0 +1,19 @@ +--- +title: Stylesheet.ownerRule +slug: Web/API/CSSStyleSheet/ownerRule +--- +<p>{{ ApiRef() }}</p> +<h3 id="Summary" name="Summary">Resumen</h3> +<p>Si esta hoja de estilos viene de una regla <code>@import</code>, la propiedad <strong>ownerRule </strong>contendrá la CSSImportRule.</p> +<h3 id="Syntax" name="Syntax">Sintaxis</h3> +<pre class="eval"><em>rule</em> = stylesheet.ownerRule +</pre> +<h3 id="Parameters" name="Parameters">Parámetros</h3> +<ul> + <li><code>rule</code> es una cadena que contiene la regla de importación en el documento HTML o XML.</li> +</ul> +<h3 id="Notes" name="Notes">Notas</h3> +<p>Ten en cuenta que si el valor de la propiedad ownerNode en el elemento <a href="/es/DOM/element.style" title="es/DOM/element.style">STYLE</a> actual es NULL, el valor <strong>ownerRule </strong>devolverá !!TODO!! y viceversa.</p> +<h3 id="Specification" name="Specification">Specification</h3> +<p><a class="external" href="http://www.w3.org/TR/2000/REC-DOM-Level-2-Style-20001113/css.html#CSS-CSSStyleSheet-ownerRule">ownerRule </a></p> +<p>{{ languages( { "pl": "pl/DOM/stylesheet.ownerRule" } ) }}</p> diff --git a/files/es/web/api/customelementregistry/define/index.html b/files/es/web/api/customelementregistry/define/index.html new file mode 100644 index 0000000000..5ab2ecb1b9 --- /dev/null +++ b/files/es/web/api/customelementregistry/define/index.html @@ -0,0 +1,239 @@ +--- +title: CustomElementRegistry.define() +slug: Web/API/CustomElementRegistry/define +translation_of: Web/API/CustomElementRegistry/define +--- +<p>{{APIRef("CustomElementRegistry")}}</p> + +<p>El método <code><strong>define()</strong></code> de la interfaz {{domxref("CustomElementRegistry")}} define un nuevo elemento personalizado.</p> + +<p>Se pueden crear dos tipos de elementos personalizados:</p> + +<ul> + <li><strong>Elementos personalizados autónomos</strong>: Elementos autónomos; estos heredan de HTMLElement (Elemento HTML genérico).</li> + <li><strong>Elementos personalizados preconstruidos</strong>: Estos elementos heredan - y extienden - elementos HTML ya existentes (p.ej HTMLParagraphElement que es el elemento HTML <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/p" title="The HTML <p> element represents a paragraph."><code><p></code></a>).</li> +</ul> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">customElements.define(<em>name</em>, <em>constructor</em>, <em>options</em>); +</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt>name</dt> + <dd>Nombre del nuevo elemento personalizado. Fíjate en que los nombres de elementos personalizados deben contener un guión.</dd> + <dt>constructor</dt> + <dd>Constructor para el nuevo elemento personalizado</dd> + <dt>options {{optional_inline}}</dt> + <dd>Objecto que controla cómo se define el elemento. Actualmente solo se permite una opción: + <ul> + <li><code>extends</code>: Cadena que especifica el nombre del elemento preconstruido del cual se va a extender. Se usa para crear <em>elementos personalizados preconstruidos</em>.</li> + </ul> + </dd> +</dl> + +<h3 id="Valor_de_retorno">Valor de retorno</h3> + +<p>Void.</p> + +<h3 id="Excepciones">Excepciones</h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Excepción</th> + <th scope="col">Descripción</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>NotSupportedError</code></td> + <td>El {{domxref("CustomElementRegistry")}} ya contiene una entrada con el mismo nombre o el mismo constructor (o se ha definido ya de alguna otra manera), o se ha especificado <code>extends</code> pero el elemento del que se está intentando extender es desconocido.</td> + </tr> + <tr> + <td><code>SyntaxError</code></td> + <td>El nombre proporcionado no es un <a href="https://html.spec.whatwg.org/multipage/custom-elements.html#valid-custom-element-name">nombre válido de elemento personalizado</a>.</td> + </tr> + <tr> + <td><code>TypeError</code></td> + <td>El constructor referenciado no es un constructor</td> + </tr> + </tbody> +</table> + +<div class="note"> +<p><strong>Nota</strong>: A menudo se obtienen excepciones <code>NotSupportedError</code>s cuando el método <code>define()</code> está fallando, pero realmente es un problema relacionado con {{domxref("Element.attachShadow()")}}.</p> +</div> + +<h2 id="Ejemplos">Ejemplos</h2> + +<h3 id="Elemento_personalizado_autónomo">Elemento personalizado autónomo</h3> + +<p>El siguiente código está tomado de nuestro ejemplo <a href="https://github.com/mdn/web-components-examples/tree/master/popup-info-box-web-component">popup-info-box-web-component</a> (<a href="https://mdn.github.io/web-components-examples/popup-info-box-web-component/">verlo en vivo</a>).</p> + +<pre class="brush: js">// Crear una clase para el elemento +class PopUpInfo extends HTMLElement { + constructor() { + // Siempre lo primero es llamar a super en el constructor + super(); + + // Crear una shadow root + var shadow = this.attachShadow({mode: 'open'}); + + // Crear tres elementos span + var wrapper = document.createElement('span'); + wrapper.setAttribute('class','wrapper'); + + var icon = document.createElement('span'); + icon.setAttribute('class','icon'); + icon.setAttribute('tabindex', 0); + + var info = document.createElement('span'); + info.setAttribute('class','info'); + + // Coger el contenido del atributo text y ponerlo en el span info + var text = this.getAttribute('text'); + info.textContent = text; + + // Coger el contenido del atributo img (si existe) y ponerlo en el span icon + var imgUrl; + if(this.hasAttribute('img')) { + imgUrl = this.getAttribute('img'); + } else { + imgUrl = 'img/default.png'; + } + + // El span no puede tener directamente una imagen, pero si contener un elemento img + var img = document.createElement('img'); + img.src = imgUrl; + icon.appendChild(img); + + // Crear los estilos CSS e incluirlos en el shadow DOM + var style = document.createElement('style'); + + style.textContent = '.wrapper {' + + 'position: relative;' + + '}' + + + '.info {' + + 'font-size: 0.8rem;' + + 'width: 200px;' + + 'display: inline-block;' + + 'border: 1px solid black;' + + 'padding: 10px;' + + 'background: white;' + + 'border-radius: 10px;' + + 'opacity: 0;' + + 'transition: 0.6s all;' + + 'position: absolute;' + + 'bottom: 20px;' + + 'left: 10px;' + + 'z-index: 3;' + + '}' + + + 'img {' + + 'width: 1.2rem' + + '}' + + + '.icon:hover + .info, .icon:focus + .info {' + + 'opacity: 1;' + + '}'; + + // adjuntar los elementos creados (spans y estilo) al shadow DOM + // notese que el span wrapper contiene los spans icon e info + + shadow.appendChild(style); + shadow.appendChild(wrapper); + wrapper.appendChild(icon); + wrapper.appendChild(info); + } +} + +// Definir el nuevo elemento +customElements.define('popup-info', PopUpInfo); +</pre> + +<pre class="brush: html"><popup-info img="img/alt.png" text="Su código de validación de tarjeta (CVC) es una característica + extra de seguridad — consiste en 3 o 4 + numeros en la parte posterior de su tarjeta."></pre> + +<div class="note"> +<p><strong>Nota</strong>: Los constructores de elementos personalizados autónomos deben extender {{domxref("HTMLElement")}}.</p> +</div> + +<h3 id="Elemento_personalizado_preconstruido">Elemento personalizado preconstruido</h3> + +<p>El siguiente código está tomado de nuestro ejemplo <a href="https://github.com/mdn/web-components-examples/tree/master/word-count-web-component">word-count-web-component</a> (<a href="https://mdn.github.io/web-components-examples/word-count-web-component/">verlo en vivo</a>).</p> + +<pre class="brush: js">// Crear una clase para el elemento +class WordCount extends HTMLParagraphElement { + constructor() { + // Siempre lo primero es llamar a super en el constructor + super(); + + // contar palabras del padre de este elemento + var wcParent = this.parentNode; + + // la función countWords cuenta palabras (aunque estén separadas por más de un espacio) + // que existe en el nodo pasado como parámetro. + // innerText está definido para objetos <code>HTMLElement</code>, mientras que textContent para todos los objetos Node + // el operador || hace que obtengamos al menos uno de los dos + + function countWords(node){ + var text = node.innerText || node.textContent + return text.split(/\s+/g).length; + } + + var count = 'Words: ' + countWords(wcParent); + + // // Crear una shadow root + var shadow = this.attachShadow({mode: 'open'}); + + // Crear un nodo span con el número de palabras + var text = document.createElement('span'); + text.textContent = count; + + // Añadirlo a la shadow root + shadow.appendChild(text); + + + // Actualizar el contador cuando el contenido del elemento cambie + setInterval(function() { + var count = 'Words: ' + countWords(wcParent); + text.textContent = count; + }, 200) + + } +} + +// Define the new element +customElements.define('word-count', WordCount, { extends: 'p' });</pre> + +<pre class="brush: html"><p is="word-count"></p></pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName("HTML WHATWG", "custom-elements.html#dom-customelementregistry-define", "customElements.define()")}}</td> + <td>{{Spec2("HTML WHATWG")}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_navegadores">Compatibilidad navegadores</h2> + +<div> + + +<p>{{Compat("api.CustomElementRegistry.define")}}</p> +</div> diff --git a/files/es/web/api/customelementregistry/index.html b/files/es/web/api/customelementregistry/index.html new file mode 100644 index 0000000000..624bc8f1fb --- /dev/null +++ b/files/es/web/api/customelementregistry/index.html @@ -0,0 +1,101 @@ +--- +title: CustomElementRegistry +slug: Web/API/CustomElementRegistry +tags: + - API + - CustomElementRegistry + - Experimental + - Interface + - NeedsTranslation + - Reference + - TopicStub + - Web Components + - custom elements +translation_of: Web/API/CustomElementRegistry +--- +<div>{{DefaultAPISidebar("Web Components")}}</div> + +<p><span class="seoSummary">The <strong><code>CustomElementRegistry</code></strong> interface provides methods for registering custom elements and querying registered elements. To get an instance of it, use the {{domxref("window.customElements")}} property.</span></p> + +<h2 id="Methods">Methods</h2> + +<dl> + <dt>{{domxref("CustomElementRegistry.define()")}}</dt> + <dd>Defines a new <a href="/en-US/docs/Web/Web_Components/Custom_Elements">custom element</a>.</dd> + <dt>{{domxref("CustomElementRegistry.get()")}}</dt> + <dd>Returns the constuctor for the named custom element, or {{jsxref("undefined")}} if the custom element is not defined.</dd> + <dt>{{domxref("CustomElementRegistry.upgrade()")}}</dt> + <dd>Upgrades a custom element directly, even before it is connected to its shadow root.</dd> + <dt>{{domxref("CustomElementRegistry.whenDefined()")}}</dt> + <dd>Returns an empty {{jsxref("Promise", "promise")}} that resolves when a custom element becomes defined with the given name. If such a custom element is already defined, the returned promise is immediately fulfilled.</dd> +</dl> + +<h2 id="Examples">Examples</h2> + +<p>The following code is taken from our <a href="https://github.com/mdn/web-components-examples/tree/master/word-count-web-component">word-count-web-component</a> example (<a href="https://mdn.github.io/web-components-examples/word-count-web-component/">see it live also</a>). Note how we use the {{domxref("CustomElementRegistry.define()")}} method to define the custom element after creating its class.</p> + +<pre class="brush: js">// Create a class for the element +class WordCount extends HTMLParagraphElement { + constructor() { + // Always call super first in constructor + super(); + + // count words in element's parent element + var wcParent = this.parentNode; + + function countWords(node){ + var text = node.innerText || node.textContent + return text.split(/\s+/g).length; + } + + var count = 'Words: ' + countWords(wcParent); + + // Create a shadow root + var shadow = this.attachShadow({mode: 'open'}); + + // Create text node and add word count to it + var text = document.createElement('span'); + text.textContent = count; + + // Append it to the shadow root + shadow.appendChild(text); + + + // Update count when element content changes + setInterval(function() { + var count = 'Words: ' + countWords(wcParent); + text.textContent = count; + }, 200) + + } +} + +// Define the new element +customElements.define('word-count', WordCount, { extends: 'p' });</pre> + +<div class="note"> +<p><strong>Note:</strong> The <code>CustomElementRegistry</code> is available through the {{domxref("Window.customElements")}} property.</p> +</div> + +<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", "custom-elements.html#customelementregistry", "CustomElementRegistry")}}</td> + <td>{{Spec2("HTML WHATWG")}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("api.CustomElementRegistry")}}</p> diff --git a/files/es/web/api/customevent/index.html b/files/es/web/api/customevent/index.html new file mode 100644 index 0000000000..b189c77f66 --- /dev/null +++ b/files/es/web/api/customevent/index.html @@ -0,0 +1,94 @@ +--- +title: CustomEvent +slug: Web/API/CustomEvent +tags: + - API + - DOM + - Interfaz + - Referencia +translation_of: Web/API/CustomEvent +--- +<p>{{APIRef("DOM")}}La interfaz <strong><code>CustomEvent</code></strong> representa eventos inicializados por una aplicación para cualquier propósito.</p> + +<p>{{AvailableInWorkers}}</p> + +<h2 id="Constructor">Constructor</h2> + +<dl> + <dt>{{domxref("CustomEvent.CustomEvent", "CustomEvent()")}}</dt> + <dd> + <p>Crea un <code>CustomEvent</code>.</p> + </dd> +</dl> + +<h2 id="Propiedades">Propiedades</h2> + +<dl> + <dt>{{domxref("CustomEvent.detail")}} {{readonlyinline}}</dt> + <dd>Cualquier dato transmitido al inicializar el evento.</dd> +</dl> + +<p><em>Esta interfaz hereda las propiedades de su padre, </em>{{domxref("Event")}}:</p> + +<p>{{Page("/es/docs/Web/API/Event", "Propiedades")}}</p> + +<h2 id="Métodos">Métodos</h2> + +<dl> + <dt>{{domxref("CustomEvent.initCustomEvent()")}} {{deprecated_inline}}</dt> + <dd> + <p>Inicializar un objeto <code>CustomEvent</code>. Si el evento ya ha sido enviado, este método no hace nada.</p> + </dd> +</dl> + +<p><em>Esta interfaz hereda los métodos de su padre, </em>{{domxref("Event")}}:</p> + +<p>{{Page("/es/docs/Web/API/Event", "Métodos")}}</p> + +<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('DOM WHATWG','#interface-customevent','CustomEvent')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + + + +<p>{{Compat("api.CustomEvent")}}</p> + +<h2 id="Disparar_desde_código_privilegiado_a_código_no-privilegiado">Disparar desde código privilegiado a código no-privilegiado</h2> + +<p>Al disparar un CustomEvent desde código privilegiado (una extensión) a un código no-privilegiado (una página web), deben considerarse algunos problemas de seguridad. Firefox y otras aplicaciones Gecko restringen al objeto creado desde un contexto siendo directamente utilizado por otro, el cual automáticamente evitará los agujeros de seguridad, pero estas restricciones también pueden impedir que su código se ejecute como esperaba.</p> + +<p>Al crear un objeto CustomEvent, debes crear el objeto desde la misma <a href="/en-US/docs/XUL/window">ventana</a>. El atributo <code>detail</code> de tu CustomEvent estará sujeto a las mismas restricciones. Los valores de String y Array serán legibles sin restricciones por el content, pero los objetos personalizados no lo harán. Al utilizar un objeto personalizado, necesitaras definir que atributos de ese objeto se pueden leer desde la secuencia de comandos de contenido usando <a href="/en-US/docs/">Components.utils.cloneInto()</a>.</p> + +<pre class="brush: js">// doc es una referencia al contenido del documento +function dispatchCustomEvent(doc) { + var eventDetail = Components.utils.cloneInto({foo: 'bar'}, doc.defaultView); + var myEvent = doc.defaultView.CustomEvent("mytype", eventDetail); + doc.dispatchEvent(myEvent); +}</pre> + +<p>Pero hay que tener en cuenta que exponer una función permitirá que el script content lo ejecute con privilegios de chrome, lo que puede abrir una vulnerabilidad de seguridad.</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/Code_snippets/Interaction_between_privileged_and_non-privileged_pages" title="/en-US/docs/Code_snippets/Interaction_between_privileged_and_non-privileged_pages">Interacción entre páginas privilegiadas y no privilegiadas</a></li> + <li><a href="/en-US/docs/Web/API/window.postMessage" title="/en-US/docs/Web/API/window.postMessage">Window.postMessage</a></li> + <li><a href="/es/docs/Web/Guide/DOM/Events/Creacion_y_Activación_Eventos">Creación y activación de eventos</a></li> +</ul> diff --git a/files/es/web/api/datatransfer/index.html b/files/es/web/api/datatransfer/index.html new file mode 100644 index 0000000000..8d8a6a5b1d --- /dev/null +++ b/files/es/web/api/datatransfer/index.html @@ -0,0 +1,378 @@ +--- +title: DataTransfer +slug: Web/API/DataTransfer +translation_of: Web/API/DataTransfer +--- +<div>{{APIRef("HTML DOM")}}</div> + +<p>{{ gecko_minversion_header("1.9") }} El objeto <code>DataTransfer</code> es usado como contenedor de datos que estan siendo manipulados durante la operación de drag and drop. Este puede contener uno o varios objetos, de uno o varios tipos de datos. Para más información en cuanto a drag and drop, ver <a class="internal" href="/En/DragDrop/Drag_and_Drop" title="En/DragDrop/Drag and Drop">Drag and Drop</a>.</p> + +<p>Este objeto esta disponible desde la propiedad <code>dataTransfer</code> de todos los eventos de drag . No pueden ser creados por separado.</p> + +<h2 id="Properties" name="Properties">Lista de propiedades</h2> + +<table class="standard-table"> + <tbody> + <tr> + <td class="header">Properties</td> + <td class="header">Type</td> + </tr> + <tr> + <td><code><a href="#dropEffect.28.29" title="En/DragDrop/DataTransfer#dropEffect">dropEffect</a></code></td> + <td><code><a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String" title="en/String">String</a></code></td> + </tr> + <tr> + <td><code><a href="#effectAllowed.28.29" title="En/DragDrop/DataTransfer#effectAllowed">effectAllowed</a></code></td> + <td><code><a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String" title="en/String">String</a></code></td> + </tr> + <tr> + <td><a href="#files.28.29" title="En/DragDrop/DataTransfer#files"><code>files</code></a> {{ gecko_minversion_inline("1.9.2") }}</td> + <td>{{ domxref("FileList") }}</td> + </tr> + <tr> + <td><code><a href="#mozCursor" title="En/DragDrop/DataTransfer#mozCursor">mozCursor</a></code> {{ non-standard_inline() }} {{ gecko_minversion_inline("1.9.1") }}</td> + <td><code><a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String" title="en/String">String</a></code></td> + </tr> + <tr> + <td><code><a href="#mozItemCount.28.29" title="En/DragDrop/DataTransfer#mozItemCount">mozItemCount</a></code> {{ non-standard_inline() }}</td> + <td><code>unsigned long</code></td> + </tr> + <tr> + <td><a href="#mozSourceNode" title="En/DragDrop/DataTransfer#mozSourceNode"><code>mozSourceNode</code></a> {{ non-standard_inline() }} {{ gecko_minversion_inline("2") }}</td> + <td>{{ domxref("Node") }}</td> + </tr> + <tr> + <td><a href="#mozUserCancelled" title="En/DragDrop/DataTransfer#mozUserCancelled"><code>mozUserCancelled</code></a></td> + <td><a href="/en/JavaScript/Reference/Global_Objects/Boolean" title="en/Core JavaScript 1.5 Reference/Global Objects/Boolean"><code>Boolean</code></a></td> + </tr> + <tr> + <td><code><a href="#types.28.29" title="En/DragDrop/DataTransfer#types">types</a></code></td> + <td><code><a href="/en-US/docs/Web/API/DOMStringList" title="en-US/docs/Web/API/DOMStringList">DOMStringList</a></code></td> + </tr> + </tbody> +</table> + +<h2 id="Method_overview" name="Method_overview">Lista de métodos</h2> + +<table class="standard-table"> + <tbody> + <tr> + <td><code>void <a href="#addElement.28.29">addElement</a>(in <a href="/en/XPCOM_Interface_Reference/nsIDOMElement" title="en/nsIDOMElement">Element</a> element)</code></td> + </tr> + <tr> + <td><code>void <a href="#clearData.28.29">clearData</a>([in <a href="/en/String" title="en/String">String</a> type])</code></td> + </tr> + <tr> + <td><code><a href="/en/String" title="en/String">String</a> <a href="#getData.28.29">getData</a>(in <a href="/en/String" title="en/String">String</a> type)</code></td> + </tr> + <tr> + <td><code>void <a href="#setData.28.29">setData</a>(in <a href="/en/String" title="en/String">String</a> type, in <a href="/en/String" title="en/String">String</a> data)</code></td> + </tr> + <tr> + <td><code>void <a href="#setDragImage.28.29">setDragImage</a>(in <a href="/en/XPCOM_Interface_Reference/nsIDOMElement" title="en/nsIDOMElement">nsIDOMElement</a> image, in long x, in long y)</code></td> + </tr> + <tr> + <td><code>void <a href="#mozClearDataAt.28.29">mozClearDataAt</a>([in <a href="/en/String" title="en/String">String</a> type, in unsigned long index])</code></td> + </tr> + <tr> + <td><code><a href="/en/XPCOM_Interface_Reference/NsIVariant" title="en/nsIVariant">nsIVariant</a> <a href="#mozGetDataAt.28.29">mozGetDataAt</a>(in <a href="/en/String" title="en/String">String</a> type, in unsigned long index)</code></td> + </tr> + <tr> + <td><code>void <a href="#mozSetDataAt.28.29">mozSetDataAt</a>(in <a href="/en/String" title="en/String">String</a> type, in <a href="/en/XPCOM_Interface_Reference/NsIVariant" title="en/nsIVariant">nsIVariant</a> data, in unsigned long index)</code></td> + </tr> + <tr> + <td><code><a href="/en/StringList" title="en/StringList">StringList</a> <a href="#mozTypesAt.28.29">mozTypesAt</a>([in unsigned long index])</code></td> + </tr> + </tbody> +</table> + +<h2 id="Properties" name="Properties">Propiedades</h2> + +<h3 id="dropEffect.28.29" name="dropEffect.28.29">dropEffect</h3> + +<p>The actual effect that will be used, and should always be one of the possible values of <code>effectAllowed</code>.</p> + +<p>For the <code>dragenter</code> and <code>dragover</code> events, the <code>dropEffect</code> will be initialized based on what action the user is requesting. How this is determined is platform specific, but typically the user can press modifier keys to adjust which action is desired. Within an event handler for the <code>dragenter</code> and <code>dragover</code> events, the <code>dropEffect</code> should be modified if the action the user is requesting is not the one that is desired.</p> + +<p>For <code>dragstart</code>, <code>drag</code>, and <code>dragleave</code> events, the <code>dropEffect</code> is initialized to "none". Any value assigned to the <code>dropEffect</code> will be set, but the value isn't used for anything.</p> + +<p>For the <code>drop</code> and <code>dragend</code> events, the <code>dropEffect</code> will be initialized to the action that was desired, which will be the value that the <code>dropEffect</code> had after the last <code>dragenter</code> or <code>dragover</code> event.</p> + +<p>Possible values:</p> + +<ul> + <li><strong>copy</strong>: A copy of the source item is made at the new location.</li> + <li><strong>move</strong>: An item is moved to a new location.</li> + <li><strong>link</strong>: A link is established to the source at the new location.</li> + <li><strong>none</strong>: The item may not be dropped.</li> +</ul> + +<p>Assigning any other value has no effect and retains the old value.</p> + +<h3 id="effectAllowed.28.29" name="effectAllowed.28.29">effectAllowed</h3> + +<p>Specifies the effects that are allowed for this drag. You may set this in the <code>dragstart</code> event to set the desired effects for the source, and within the <code>dragenter</code> and <code>dragover</code> events to set the desired effects for the target. The value is not used for other events.</p> + +<p>Possible values:</p> + +<ul> + <li><strong>copy</strong>: A copy of the source item may be made at the new location.</li> + <li><strong>move</strong>: An item may be moved to a new location.</li> + <li><strong>link</strong>: A link may be established to the source at the new location.</li> + <li><strong>copyLink</strong>: A copy or link operation is permitted.</li> + <li><strong>copyMove</strong>: A copy or move operation is permitted.</li> + <li><strong>linkMove</strong>: A link or move operation is permitted.</li> + <li><strong>all</strong>: All operations are permitted.</li> + <li><strong>none</strong>: the item may not be dropped.</li> + <li><strong>uninitialized</strong>: the default value when the effect has not been set, equivalent to all.</li> +</ul> + +<p>Assigning any other value has no effect and retains the old value.</p> + +<h3 id="files.28.29" name="files.28.29">files</h3> + +<p>{{ gecko_minversion_header("1.9.2") }}</p> + +<p>Contains a list of all the local files available on the data transfer. If the drag operation doesn't involve dragging files, this property is an empty list. An invalid index access on the {{ domxref("FileList") }} specified by this property will return <code>null</code>.</p> + +<h4 id="Example">Example</h4> + +<p>This example dumps the list of files dragged into the browser window: <a class="external" href="http://jsfiddle.net/9C2EF/" title="http://jsfiddle.net/9C2EF/">http://jsfiddle.net/9C2EF/</a></p> + +<h3 id="types.28.29" name="types.28.29">types</h3> + +<p>Holds a list of the format types of the data that is stored for the first item, in the same order the data was added. An empty list will be returned if no data was added.</p> + +<p>{{ gecko_minversion_note("1.9.2", 'The string "Files" is included in this list if files are included in the drag.') }}</p> + +<p>{{ h3_gecko_minversion("mozCursor", "1.9.1", "mozCursor") }}</p> + +<p>The drag cursor's state. This is primarily used to control the cursor during tab drags.</p> + +<div class="note"><strong>Note:</strong> This method is currently only implemented on Windows.</div> + +<h4 id="Possible_values">Possible values</h4> + +<dl> + <dt><code>auto</code></dt> + <dd>Uses the default system behavior.</dd> + <dt><code>default</code></dt> + <dd>Uses the default Gecko behavior, which is to set the cursor to an arrow during the drag operation.</dd> +</dl> + +<div class="note"><strong>Note:</strong> If you specify any value other than "default", "auto" is assumed.</div> + +<h3 id="mozItemCount.28.29" name="mozItemCount.28.29">mozItemCount</h3> + +<p>The number of items being dragged.</p> + +<div class="note"><strong>Note:</strong> This property is Gecko-specific.</div> + +<h3 id="mozSourceNode">mozSourceNode</h3> + +<p>{{ gecko_minversion_header("2") }}</p> + +<p>The {{ domxref("Node") }} over which the mouse cursor was located when the button was pressed to initiate the drag operation. This value is <code>null</code> for external drags or if the caller can't access the node.</p> + +<div class="note"><strong>Note:</strong> This property is Gecko-specific.</div> + +<h3 id="mozItemCount.28.29" name="mozItemCount.28.29">mozUserCancelled</h3> + +<p>This property applies only to the <code>dragend</code> event, and is <code>true</code> if the user canceled the drag operation by pressing escape. It will be <code>false</code> in all other cases, including if the drag failed for any other reason, for instance due to a drop over an invalid location. This property is not currently implemented on Linux.</p> + +<div class="note"><strong>Note:</strong> This property is Gecko-specific.</div> + +<h2 id="Methods" name="Methods">Métodos</h2> + +<h3 id="addElement.28.29" name="addElement.28.29">addElement()</h3> + +<p>Set the drag source. Usually you would not change this, but it will affect which node the drag and dragend events are fired at. The default target is the node that was dragged.</p> + +<pre class="eval"> void addElement( + in Element element + ); +</pre> + +<h6 id="Parameters_addElement" name="Parameters_addElement">Parameters</h6> + +<dl> + <dt><code>element </code></dt> + <dd>The element to add.</dd> +</dl> + +<h3 id="clearData.28.29" name="clearData.28.29">clearData()</h3> + +<p>Remove the data associated with a given type. The type argument is optional. If the type is empty or not specified, the data associated with all types is removed. If data for the specified type does not exist, or the data transfer contains no data, this method will have no effect.</p> + +<pre class="eval"> void clearData( + [optional] in String type + ); +</pre> + +<h6 id="Parameters_clearData" name="Parameters_clearData">Parameters</h6> + +<dl> + <dt><code>type </code></dt> + <dd>The type of data to remove.</dd> +</dl> + +<h3 id="getData.28.29" name="getData.28.29">getData()</h3> + +<p>Retrieves the data for a given type, or an empty string if data for that type does not exist or the data transfer contains no data.</p> + +<p>A security error will occur if you attempt to retrieve data during a drag that was set from a different domain, or the caller would otherwise not have access to. This data will only be available once a drop occurs during the drop event.</p> + +<pre class="eval"> String getData( + in String type + ); +</pre> + +<h6 id="Parameters_getData" name="Parameters_getData">Parameters</h6> + +<dl> + <dt><code>type </code></dt> + <dd>The type of data to retrieve.</dd> +</dl> + +<h3 id="setData.28.29" name="setData.28.29">setData()</h3> + +<p>Set the data for a given type. If data for the type does not exist, it is added at the end, such that the last item in the types list will be the new format. If data for the type already exists, the existing data is replaced in the same position. That is, the order of the types list is not changed when replacing data of the same type.</p> + +<pre class="eval"> void setData( + in String type, + in String data + ); +</pre> + +<h6 id="Parameters_setData" name="Parameters_setData">Parameters</h6> + +<dl> + <dt><code>type </code></dt> + <dd>The type of data to add.</dd> + <dt><code>data </code></dt> + <dd>The data to add.</dd> +</dl> + +<h3 id="setDragImage.28.29" name="setDragImage.28.29">setDragImage()</h3> + +<p>Set the image to be used for dragging if a custom one is desired. Most of the time, this would not be set, as a default image is created from the node that was dragged.</p> + +<p>If the node is an HTML img element, an HTML canvas element or a XUL image element, the image data is used. Otherwise, image should be a visible node and the drag image will be created from this. If image is null, any custom drag image is cleared and the default is used instead.</p> + +<p>The coordinates specify the offset into the image where the mouse cursor should be. To center the image, for instance, use values that are half the width and height of the image.</p> + +<pre class="eval"> void setDragImage( + in Element image, + in long x, + in long y + ); +</pre> + +<h6 id="Parameters_setDragImage" name="Parameters_setDragImage">Parameters</h6> + +<dl> + <dt><code>image </code></dt> + <dd>An element to use as the drag feedback image</dd> + <dt><code>x </code></dt> + <dd>Horizontal offset within the image.</dd> + <dt><code>y </code></dt> + <dd>Vertical offset within the image.</dd> +</dl> + +<h3 id="mozClearDataAt.28.29" name="mozClearDataAt.28.29">mozClearDataAt()</h3> + +<p>Removes the data associated with the given format for an item at the specified index. The index is in the range from zero to the number of items minus one.</p> + +<p>If the last format for the item is removed, the entire item is removed, reducing <code>mozItemCount</code> by one.</p> + +<p>If the <code>format</code> list is empty, then the data associated with all formats is removed. If the format is not found, then this method has no effect.</p> + +<div class="note"><strong>Note:</strong> This method is Gecko-specific.</div> + +<pre class="eval"> void mozClearDataAt( + [optional] in String type, + in unsigned long index + ); +</pre> + +<h6 id="Parameters_mozClearDataAt" name="Parameters_mozClearDataAt">Parameters</h6> + +<dl> + <dt><code>type </code></dt> + <dd>The type of data to remove.</dd> + <dt><code>index </code></dt> + <dd>The index of the data to remove.</dd> +</dl> + +<h3 id="mozGetDataAt.28.29" name="mozGetDataAt.28.29">mozGetDataAt()</h3> + +<p>Retrieves the data associated with the given format for an item at the specified index, or null if it does not exist. The index should be in the range from zero to the number of items minus one.</p> + +<div class="note"><strong>Note:</strong> This method is Gecko-specific.</div> + +<pre class="eval"> nsIVariant mozGetDataAt( + [optional] in String type, + in unsigned long index + ); +</pre> + +<h6 id="Parameters_mozClearDataAt" name="Parameters_mozClearDataAt">Parameters</h6> + +<dl> + <dt><code>type </code></dt> + <dd>The type of data to retrieve.</dd> + <dt><code>index </code></dt> + <dd>The index of the data to retrieve.</dd> +</dl> + +<h3 id="mozSetDataAt.28.29" name="mozSetDataAt.28.29">mozSetDataAt()</h3> + +<p>A data transfer may store multiple items, each at a given zero-based index. <code>mozSetDataAt()</code> may only be called with an index argument less than <code>mozItemCount</code> in which case an existing item is modified, or equal to <code>mozItemCount</code> in which case a new item is added, and the <code>mozItemCount</code> is incremented by one.</p> + +<p>Data should be added in order of preference, with the most specific format added first and the least specific format added last. If data of the given format already exists, it is replaced in the same position as the old data.</p> + +<p>The data should be either a string, a primitive boolean or number type (which will be converted into a string) or an {{ interface("nsISupports") }}.</p> + +<div class="note"><strong>Note:</strong> This method is Gecko-specific.</div> + +<pre class="eval"> void mozSetDataAt( + [optional] in String type, + in nsIVariant data, + in unsigned long index + ); +</pre> + +<h6 id="Parameters_mozSetDataAt" name="Parameters_mozSetDataAt">Parameters</h6> + +<dl> + <dt><code>type </code></dt> + <dd>The type of data to add.</dd> + <dt><code>data </code></dt> + <dd>The data to add.</dd> + <dt><code>index </code></dt> + <dd>The index of the data to add.</dd> +</dl> + +<h3 id="mozTypesAt.28.29" name="mozTypesAt.28.29">mozTypesAt()</h3> + +<p>Holds a list of the format types of the data that is stored for an item at the specified index. If the index is not in the range from 0 to the number of items minus one, an empty string list is returned.</p> + +<div class="note"><strong>Note:</strong> This method is Gecko-specific.</div> + +<pre class="eval"> nsIVariant mozTypesAt( + in unsigned long index + ); +</pre> + +<h6 id="Parameters_mozTypesAt" name="Parameters_mozTypesAt">Parameters</h6> + +<dl> + <dt><code>index </code></dt> + <dd>The index of the data for which to retrieve the types.</dd> +</dl> + +<h2 id="See_also" name="See_also">Mira también</h2> + +<p><a class="internal" href="/En/DragDrop/Drag_and_Drop" title="Drag and Drop">Drag and Drop</a></p> + +<p>{{ languages( { "ja": "Ja/DragDrop/DataTransfer" } ) }}</p> diff --git a/files/es/web/api/detecting_device_orientation/index.html b/files/es/web/api/detecting_device_orientation/index.html new file mode 100644 index 0000000000..60302ae643 --- /dev/null +++ b/files/es/web/api/detecting_device_orientation/index.html @@ -0,0 +1,278 @@ +--- +title: Detectando la orientación del dispositivo +slug: Web/API/Detecting_device_orientation +translation_of: Web/API/Detecting_device_orientation +--- +<div>{{SeeCompatTable}}</div> + +<h2 id="Resumen">Resumen</h2> + +<p>Cada vez más, los dispositivos habilitados para la web son capaces de determinar su <strong>orientación</strong>; esto hace que estos puedan reportar datos indicando los cambios de su orientación con relación a la fuerza de gravedad. In particular, dispositivos de mano como los teléfonos móviles pueden usar esta información para rotar la pantalla automaticamente para mostrar información en de forma vertical, presentando un vista extendida del contenido de la web cuando el dispositivo de forma que el ancho es mayor que el alto. </p> + +<p>Hay dos eventos JavaScript que manejan la información de orientación. El primero es {{domxref("DeviceOrientationEvent")}}, que es enviado cuando el aceleromentro detecta un cambio de orientación del dispositivo. Recibiendo y procesando los datos reportados por el evento es posible responder interactivamente a la rotación y aplicar cambios correspondientes al movimiento del dispositivo.</p> + +<p>El segundo evento es {{domxref("DeviceMotionEvent")}}, que es enviado cuando un cambio de la aceleración fue añadido. Esto es diferente de {{domxref("DeviceOrientationEvent")}} por que está escuchando cambios de aceleración mas no de orientación. Los sensores son comunmente capaces de detetar {{domxref("DeviceMotionEvent")}} incluso aquellos sensores de laptops que protegen del movimiento a los disposivitos de almacenamiento. {{domxref("DeviceOrientationEvent")}} es comunmente encontrado en dispositivos móviles.</p> + +<h2 id="Trabajando_con_eventos_de_orientación">Trabajando con eventos de orientación</h2> + +<p>Todo lo que necesitas hacer para empezar a recibir cambios de orientación es escuchar el evento {{ event("deviceorientation") }}:</p> + +<pre class="brush: js notranslate">window.addEventListener("deviceorientation", handleOrientation, true); +</pre> + +<p>Después de registrar el evento de escucha (en este caso, una función de JavaScript llamada handleOrientation()), tu función de escucha periodicamente será invocada con una actualización de datos.</p> + +<p>La información del evento contiene 4 valores:</p> + +<ul> + <li>{{ domxref("DeviceOrientationEvent.absolute") }}</li> + <li>{{ domxref("DeviceOrientationEvent.alpha") }}</li> + <li>{{ domxref("DeviceOrientationEvent.beta") }}</li> + <li>{{ domxref("DeviceOrientationEvent.gamma") }}</li> +</ul> + +<p>El manejador del evento puede ser similar a lo siguiente:</p> + +<pre class="brush: js notranslate">function handleOrientation(event) { + var absolute = event.absolute; + var alpha = event.alpha; + var beta = event.beta; + var gamma = event.gamma; + + // Do stuff with the new orientation data +} +</pre> + +<h3 id="Explicación_de_los_Valores_de_Orientación">Explicación de los Valores de Orientación</h3> + +<p>El valor reportado para cada eje indica la cantidad de rotación alrededor de un eje dado, con referencia a un estandar marco de coordenadas. El siguiente enlace describe con mayor detalle la <a href="/en-US/DOM/Orientation_and_motion_data_explained" title="Orientation and motion data explained">Orientacíon y datos del movimiento explicado</a> que es resumido abajo. </p> + +<ul> + <li>{{ domxref("DeviceOrientationEvent.alpha") }} representa el movimiento alrededor del eje z, representado en grados con valores que van desde 0 a 360.</li> + <li>{{ domxref("DeviceOrientationEvent.beta") }} representa el movimiento del dispositivo alrededor del eje x, representado en grados con valores que van desde -180 a 180. Esto representa un movimiento de frente hacia atrás del dispositivo.</li> + <li>{{ domxref("DeviceOrientationEvent.gamma") }} representa el movimiento del dispositivo alrededor del eje y, representado en grados con valores que van de -90 a 90. Esto representa un movimiento de izquierda a derecha del dispositivo.</li> +</ul> + +<h3 id="Ejemplo_de_orientación">Ejemplo de orientación</h3> + +<p>Este ejemplo va a funcionar en cualquier nevegador que soporte el evento {{event("deviceorientation")}} y funcione en un dispositivo con capacidades de detectar la orientación.</p> + +<p>Imaginemos una pelota en un jardin:</p> + +<pre class="brush: html notranslate"><div class="garden"> + <div class="ball"></div> +</div> + +<pre class="output"></pre> +</pre> + +<p>Este jardin tiene 200 pixeles de ancho (Si, es uno pequeño), y la pelota esta en el centro:</p> + +<pre class="brush: css notranslate">.garden { + position: relative; + width : 200px; + height: 200px; + border: 5px solid #CCC; + border-radius: 10px; +} + +.ball { + position: absolute; + top : 90px; + left : 90px; + width : 20px; + height: 20px; + background: green; + border-radius: 100%; +} +</pre> + +<p>Ahora, si nosotros movemos nuestro dispositivo, la pelota va a moverse acorde a este:</p> + +<pre class="brush: js notranslate">var ball = document.querySelector('.ball'); +var garden = document.querySelector('.garden'); +var output = document.querySelector('.output'); + +var maxX = garden.clientWidth - ball.clientWidth; +var maxY = garden.clientHeight - ball.clientHeight; + +function handleOrientation(event) { + var x = event.beta; // In degree in the range [-180,180] + var y = event.gamma; // In degree in the range [-90,90] + + output.innerHTML = "beta : " + x + "\n"; + output.innerHTML += "gamma: " + y + "\n"; + + // Because we don't want to have the device upside down + // We constrain the x value to the range [-90,90] + if (x > 90) { x = 90}; + if (x < -90) { x = -90}; + + // To make computation easier we shift the range of + // x and y to [0,180] + x += 90; + y += 90; + + // 10 is half the size of the ball + // It center the positioning point to the center of the ball + ball.style.top = (maxX*x/180 - 10) + "px"; + ball.style.left = (maxY*y/180 - 10) + "px"; +} + +window.addEventListener('deviceorientation', handleOrientation); +</pre> + +<p>Aqui el resultado en vivo:</p> + +<div>{{ EmbedLiveSample('Orientation_example', '230', '260') }}</div> + +<div class="warning"> +<p><strong>Tener en cuenta:</strong> Chrome y Firefox no manejan los angulos de la misma forma, asi que en algunos ejes la dirección se invierte.</p> +</div> + +<h2 id="Procesando_eventos_de_movimiento">Procesando eventos de movimiento</h2> + +<p>Eventos de movimiento son manejados de la misma manera que la orientación, con la excepción de que estos tienen sus propios nombres de evento: {{ event("devicemotion") }}</p> + +<pre class="brush: js notranslate">window.addEventListener("devicemotion", <em>handleMotion</em>, true);</pre> + +<p>Lo que realmente ha cambiado es la información proporcionada en {{ domxref("DeviceMotionEvent") }} objeto pasado como parametro de la función <em>HandleMotion.</em></p> + +<p>El evento de movimiento tiene cuatro propiedades:</p> + +<ul> + <li>{{ domxref("DeviceMotionEvent.acceleration") }}</li> + <li>{{ domxref("DeviceMotionEvent.accelerationIncludingGravity") }}</li> + <li>{{ domxref("DeviceMotionEvent.rotationRate") }}</li> + <li>{{ domxref("DeviceMotionEvent.interval") }}</li> +</ul> + +<h3 id="Valores_de_movimiento_explicados">Valores de movimiento explicados</h3> + +<p>{{ domxref("DeviceMotionEvent") }} proporciona a los desarrolladores web información sobre la velocidad de los cambios de la posición y orientación del dispositivo. Los cambios son proporcionados por sus tres ejes (ver <a href="/en-US/docs/Web/Guide/DOM/Events/Orientation_and_motion_data_explained" title="/en-US/docs/Web/Guide/DOM/Events/Orientation_and_motion_data_explained">Datos de orientación y movimiento explicados</a> por más detalles).</p> + +<p>Para {{domxref("DeviceMotionEvent.acceleration","acceleration")}} y {{domxref("DeviceMotionEvent.accelerationIncludingGravity","accelerationIncludingGravity")}}, los ejes corresponden a lo siguiente:</p> + +<ul> + <li><code>x</code>: Representa el eje de oeste a este.</li> + <li><code>y</code>: Representa el eje de sur a norte.</li> + <li><code>z</code>: Representa el eje perpendicular al suelo.</li> +</ul> + +<p>Para {{domxref("DeviceMotionEvent.rotationRate","rotationRate")}}, la situación es un poco diferente; la información corresponde a lo siguiente en cada caso:</p> + +<ul> + <li><code>alpha</code>: Representa la velocidad de rotación a lo largo del eje perpendicular a la pantalla ( teclado para desktop).</li> + <li><code>beta</code>: Representa la velocidad de rotación a lo largo del eje que va de la izquierda a la derecha del plano de la pantalla (o teclado para desktop).</li> + <li><code>gamma</code>: Representa la velocidad de rotación a lo largo del eje que va desde la parte inferior a la parte superrior del plano de la pantalla (o teclado para desktop).</li> +</ul> + +<p>Finalmente, {{domxref("DeviceMotionEvent.interval","interval")}} representa el intervalo de tiempo, en milisegundos, en el que los datos han sido obtenidos del dispositivo.</p> + +<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('Device Orientation')}}</td> + <td>{{Spec2('Device Orientation')}}</td> + <td>Especificación inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>{{domxref("DeviceOrientationEvent")}}</td> + <td>7.0</td> + <td>3.6<sup>[1]</sup><br> + 6</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + </tr> + <tr> + <td>{{domxref("DeviceMotionEvent")}}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>6</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</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 Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>{{domxref("DeviceOrientationEvent")}}</td> + <td>3.0</td> + <td>3.6<sup>[1]</sup><br> + 6</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>4.2</td> + </tr> + <tr> + <td>{{domxref("DeviceMotionEvent")}}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>6</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<div class="note"> +<p><strong>Note</strong>: <a href="https://github.com/dorukeker/gyronorm.js">gyronorm.js</a> es un <em>polyfill</em> para normalizar los datos del acelerómetro y giroscopio en dispositivos móviles. Esto es útil para superar algunas de las diferencias en la compatibilidad del dispositivo con la orientación del dispositivo..</p> +</div> + +<h3 id="Gecko_implementation_notes">Gecko implementation notes</h3> + +<ol> + <li>Firefox 3.6, 4, and 5 supported <a href="/en-US/DOM/MozOrientation" title="MozOrientation">mozOrientation </a>versus the standard {{domxref("DeviceOrientationEvent")}} event</li> +</ol> + +<h2 id="Vea_también">Vea también</h2> + +<ul> + <li>{{domxref("DeviceOrientationEvent")}}</li> + <li>{{domxref("DeviceMotionEvent")}}</li> + <li>The legacy <code><a href="/en-US/DOM/MozOrientation" title="en-US/DOM/MozOrientation">MozOrientation</a></code> event.</li> + <li><a href="/en-US/docs/Web/Guide/DOM/Events/Orientation_and_motion_data_explained" title="Orientation and motion data explained">Orientation and motion data explained</a></li> + <li><a href="/en-US/docs/Web/Guide/DOM/Events/Using_device_orientation_with_3D_transforms" title="Using Deviceorientation In 3D Transforms">Using deviceorientation in 3D Transforms</a></li> + <li><a href="/en-US/docs/Games/Workflows/HTML5_Gamedev_Phaser_Device_Orientation" title="2D maze game with device orientation">Cyber Orb: 2D maze game with device orientation</a></li> +</ul> diff --git a/files/es/web/api/devicemotionevent/index.html b/files/es/web/api/devicemotionevent/index.html new file mode 100644 index 0000000000..a8820d1173 --- /dev/null +++ b/files/es/web/api/devicemotionevent/index.html @@ -0,0 +1,73 @@ +--- +title: DeviceMotionEvent +slug: Web/API/DeviceMotionEvent +translation_of: Web/API/DeviceMotionEvent +--- +<p>{{APIRef("Device Orientation Events")}}{{SeeCompatTable}}</p> + +<p>El evento <code>DeviceMotionEvent</code> proporciona a los desarrolladores información acerca de la velocidad de los cambios en la posición y orientación del dispositivo.</p> + +<div class="warning"> +<p><strong>Aviso:</strong> Acualmente, Firefox and Chrome no manejan las corrdenadas de la misma forma. Tenga en cuenta esto cuando lo use.</p> +</div> + +<h2 id="Constructor">Constructor</h2> + +<dl> + <dt>{{DOMxRef("DeviceMotionEvent.DeviceMotionEvent()")}} {{Non-standard_Inline}}</dt> + <dd>Crea un nuevo <code>DeviceMotionEvent</code>.</dd> +</dl> + +<h2 id="Properties">Properties</h2> + +<dl> + <dt>{{DOMxRef("DeviceMotionEvent.acceleration")}}{{ReadOnlyInline}}</dt> + <dd>Objeto que nos proporciona la aceleración del dispositivo en los ejes X, Y y Z. La aceleración está expresada en <a href="https://en.wikipedia.org/wiki/Meter_per_second_squared" title="https://en.wikipedia.org/wiki/Meter_per_second_squared">m/s<sup>2</sup></a>.</dd> + <dt>{{DOMxRef("DeviceMotionEvent.accelerationIncludingGravity")}}{{ReadOnlyInline}}</dt> + <dd>Objeto que nos proporciona la aceleración del dispositivo en los ejes X, Y y Z con el efecto de la gravedad. La aceleración está expresada en <a href="https://en.wikipedia.org/wiki/Meter_per_second_squared" title="https://en.wikipedia.org/wiki/Meter_per_second_squared">m/s<sup>2</sup></a>.</dd> + <dt>{{DOMxRef("DeviceMotionEvent.rotationRate")}}{{ReadOnlyInline}}</dt> + <dd>Objeto que nos proporciona los cambios en la orientación del dispositivo en los ejes alpha, beta y gamma. La velocidad de rotación se expresa en grados por segundo</dd> + <dt>{{DOMxRef("DeviceMotionEvent.interval")}}{{ReadOnlyInline}}</dt> + <dd>Número que representa el intervalo de tiempo, en milisegundos, en el que se obtienen los datos del dispositivo..</dd> +</dl> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush: js">window.addEventListener('devicemotion', function(event) { + console.log(event.acceleration.x + ' m/s2'); +});</pre> + +<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("Device Orientation", "#devicemotionevent", "DeviceMotionEvent")}}</td> + <td>{{Spec2("Device Orientation")}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Compativilidad_con_los_navegadores">Compativilidad con los navegadores</h2> + + + +<p>{{Compat("api.DeviceMotionEvent")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{Event("deviceorientation")}}</li> + <li>{{DOMxRef("DeviceOrientationEvent")}}</li> + <li>{{Event("devicemotion")}}</li> + <li><a href="/en-US/docs/WebAPI/Detecting_device_orientation" title="/en-US/docs/WebAPI/Detecting_device_orientation">Detecting device orientation</a></li> + <li><a href="https://developer.mozilla.org/en/DOM/Orientation_and_motion_data_explained" title="Orientation and motion data explained">Orientation and motion data explained</a></li> +</ul> diff --git a/files/es/web/api/document/abrir/index.html b/files/es/web/api/document/abrir/index.html new file mode 100644 index 0000000000..13b541561d --- /dev/null +++ b/files/es/web/api/document/abrir/index.html @@ -0,0 +1,109 @@ +--- +title: Document.open() +slug: Web/API/Document/abrir +translation_of: Web/API/Document/open +--- +<div>{{APIRef("DOM")}}</div> + +<p>El método <strong><code>Document.open()</code></strong> abre un documento para escritura (<a href="/en-US/docs/Web/API/Document/write" title="en/DOM/document.write">writing</a>)</p> + +<p>Esto viene con algunos efectos secundarios. Por ejemplo:</p> + +<ul> + <li>Todos las atenciones de eventos actualmente registrados en el documento, los nodos dentro del documento o la ventana del documento son eliminados.</li> + <li>Todos los nodos existentes se eliminan del documento.</li> +</ul> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox notranslate">document.open(); +</pre> + +<h3 id="Parametros">Parametros</h3> + +<p>Ninguno.</p> + +<h3 id="Valor_devuelto">Valor devuelto</h3> + +<p>Una instancia del objeto Document (<code>Document)</code>.</p> + +<h2 id="Example" name="Example">Ejemplos</h2> + +<p>El código simple a continuación abre el documento y reemplaza su contenido con un número de diferentes fragmentos HTML antes de cerrarlo nuevamente.</p> + +<pre class="notranslate">document.open(); +document.write("<p>Hola mundo!</p>"); +document.write("<p>Soy un pez</p>"); +document.write("<p>El numero es 42</p>"); +document.close();</pre> + +<h2 id="Notes" name="Notes">Notas</h2> + +<div class="blockIndicator note"> +<p>Traducción pendiente para el texto que sigue</p> +</div> + +<p>An automatic <code>document.open()</code> call happens when {{domxref("document.write()")}} is called after the page has loaded.</p> + +<p>For years Firefox and Internet Explorer additionally erased all JavaScript variables, etc., in addition to removing all nodes. This is no longer the case.<span class="comment">document non-spec'ed parameters to document.open</span></p> + +<h3 id="Gecko-specific_notes">Gecko-specific notes</h3> + +<p>Starting with Gecko 1.9, this method is subject to the same same-origin policy as other properties, and does not work if doing so would change the document's origin.</p> + +<p>Starting with Gecko 1.9.2, <code>document.open()</code> uses the <a href="/docs/Security_check_basics">principal</a> of the document whose URI it uses, instead of fetching the principal off the stack. As a result, you can no longer call {{domxref("document.write()")}} into an untrusted document from chrome, even using <a class="internal" href="/en/wrappedJSObject"><code>wrappedJSObject</code></a>. See <a href="/en/Security_check_basics" title="en/Security check basics">Security check basics</a> for more about principals.</p> + +<h2 id="Example" name="Example">Three-argument document.open()</h2> + +<p>There is a lesser-known and little-used three-argument version of <code>document.open()</code> , which is an alias of {{domxref("Window.open()")}} (see its page for full details).</p> + +<p>This call, for example opens github.com in a new window, with its opener set to <code>null</code>:</p> + +<pre class="brush: js notranslate"><span class="message-body-wrapper"><span class="message-flex-body"><span class="devtools-monospace message-body"><span class="cm-variable">document</span>.<span class="cm-property">open</span>(<span class="cm-string">'https://www.github.com'</span>,<span class="cm-string">''</span>, <span class="cm-string">'noopener=true'</span>)</span></span></span></pre> + +<h2 id="Two-argument_document.open"><span class="message-body-wrapper"><span class="message-flex-body"><span class="devtools-monospace message-body">Two-argument document.open()</span></span></span></h2> + +<p><span class="message-body-wrapper"><span class="message-flex-body"><span class="devtools-monospace message-body">Browsers used to support a two-argument <code>document.open()</code>, with the following signature:</span></span></span></p> + +<pre class="brush: js notranslate">document.open(<em>type</em>, <em>replace</em>)</pre> + +<p>Where <code>type</code> specified the MIME type of the data you are writing (e.g. <code>text/html</code>) and replace if set (i.e. a string of <code>"replace"</code>) specified that the history entry for the new document would replace the current history entry of the document being written to.</p> + +<p>This form is now obsolete; it won't throw an error, but instead just forwards to <code>document.open()</code> (i.e. is the equivalent of just running it with no arguments). The history-replacement behavior now always happens.</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("HTML WHATWG", "#dom-document-open", "document.open()")}}</td> + <td>{{Spec2("HTML WHATWG")}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName("DOM2 HTML", "html.html#ID-72161170", "document.open()")}}</td> + <td>{{Spec2("DOM2 HTML")}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("api.Document.open")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{domxref("Document")}}</li> + <li>{{domxref("Window.open()")}}</li> +</ul> diff --git a/files/es/web/api/document/adoptnode/index.html b/files/es/web/api/document/adoptnode/index.html new file mode 100644 index 0000000000..0a90679756 --- /dev/null +++ b/files/es/web/api/document/adoptnode/index.html @@ -0,0 +1,61 @@ +--- +title: Document.adoptNode() +slug: Web/API/Document/adoptNode +tags: + - API + - DOM + - DOM Reference + - Referencia + - metodo +translation_of: Web/API/Document/adoptNode +--- +<div>{{ ApiRef("DOM") }}</div> + +<p><strong><code>Document.adoptNode()</code></strong> transfiere un {{Glossary("node/dom", "node")}} desde otro {{domxref("Document", "document", "", "1")}} al documento del método. El nodo adoptado y sus subnodos se eliminan del documento original (si lo hubiera), encuentra y su {{domxref("Node.ownerDocument", "ownerDocument")}} se cambia por el documento actual. El nodo puede entoces ser insertado en el documento actual.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><em>node</em> = <em>document</em>.adoptNode(<em>externalNode</em>); +</pre> + +<dl> + <dt><code>node</code></dt> + <dd>El nodo adoptado que ahora tiene este documento como su {{domxref("Node.ownerDocument", "ownerDocument")}}. El {{domxref("Node.parentNode", "parentNode")}} del nodo es <code>null</code>, esto se debe a que aún no a sido insertado en el árbol del documento. Tenga en cuenta que <code>node</code> y <code>externalNode</code> son el mismo objeto después de esta llamada.</dd> + <dt><code>externalNode</code></dt> + <dd>El nodo a ser adoptado desde otro documento.</dd> +</dl> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush: js">var iframe = document.querySelector('iframe'); +var iframeImages = iframe.contentDocument.querySelectorAll('img'); +var newParent = document.getElementById('images'); + +iframeImages.forEach(function(imgEl) { + newParent.appendChild(document.adoptNode(imgEl)); +}); +</pre> + +<h2 id="Notas">Notas</h2> + +<p>Los nodos de documentos externos deberían ser clonados utilizando {{domxref("document.importNode()")}} (o adoptado utilizando <code>document.adoptNode()</code>) antes de que puedan ser insertados en el documento actual. Para más incidencias sobre {{domxref("Node.ownerDocument")}}, vea el <a class="external" href="http://www.w3.org/DOM/faq.html#ownerdoc" rel="noopener">W3C DOM FAQ</a>.</p> + +<p>Firefox actualmente no obliga a cumplir esta regla (lo hizo un tiempo durante el desarrollo de Firefox 3, pero muchos sitios se rompían cuando esta regla era obligatoria). Animamos a los desarrolladores web a que corrijan su código para seguir esta regla con el fin de mejorar la compatibilidad futura.</p> + +<h2 id="Epecificación">Epecificación</h2> + +<ul> + <li><a href="http://www.w3.org/TR/DOM-Level-3-Core/core.html#Document3-adoptNode">DOM Level 3 Core: Document.adoptNode</a></li> +</ul> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<div class="hidden">La tabla de compatibilidad en esta página se genera a partir de datos estructurados .Si desea contribuir con los datos, por favor ingrese a <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> y envie una solicitud para adicionar los datos.</div> + +<p>{{Compat("api.Document.adoptNode")}}</p> + +<h2 id="Vea_también">Vea también</h2> + +<ul> + <li>{{domxref("document.importNode")}}</li> +</ul> diff --git a/files/es/web/api/document/alinkcolor/index.html b/files/es/web/api/document/alinkcolor/index.html new file mode 100644 index 0000000000..f270799c53 --- /dev/null +++ b/files/es/web/api/document/alinkcolor/index.html @@ -0,0 +1,36 @@ +--- +title: document.alinkColor +slug: Web/API/Document/alinkColor +translation_of: Web/API/Document/alinkColor +--- +<p>{{APIRef("DOM")}}</p> + +<div class="warning"> +<p><strong>Desaprobado</strong></p> +</div> + +<p>Devuelve o define el color que tendrán los vínculos activos en el cuerpo (elemento <code>body</code> del documento. Un vínculo está activo durante el tiempo entre los eventos <code>mousedown</code> (cuando se presiona el botón izquierdo del "mouse" sobre el vínculo) y <code>mouseup</code> (cuando se deja de presionar el vínculo al soltar el botón izquierdo del "mouse").</p> + +<h2 id="Sintaxis" name="Sintaxis">Sintaxis</h2> + +<pre class="eval"><em>color</em> = document.alinkColor +document.alinkColor =<em>color</em> +</pre> + +<p><code>color</code> es un texto que deberá llevar el nombre del color en inglés(e.g., <code>"blue"</code>, <code>"darkblue"</code>, etc.) o el valor hexadecimal del color (e.g., <code>#0000FF</code>)</p> + +<h2 id="Notas" name="Notas">Notas</h2> + +<p>El valor por defecto de esta propiedad en Mozilla es rojo (<code>#ee0000</code> en hexadecimal).</p> + +<p><code>document.alinkColor</code> es obsoleto en <a class="external" href="http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-26809268">DOM Level 2 HTML</a>. Una alternativa es el selector CSS {{ Cssxref(":active") }}.</p> + +<p>Otra alternativa es <code>document.body.aLink</code>, sin embargo éste es <a class="external" href="http://www.w3.org/TR/html401/struct/global.html#adef-alink">desaprobado en HTML 4.01</a> a favor de la alternativa CSS.</p> + +<p><a href="es/Gecko">Gecko</a> soporta tanto <code>alinkColor</code>/<code>:active</code> como {{ Cssxref(":focus") }}. Internet Explorer 6 y 7 soportan <code>alinkColor</code>/<code>:active</code> sólo para <a href="es/HTML/Element/a"> vínculos de ancla (<a>) HTML</a> y el comportamiento es el mismo que <code>:focus</code> bajo Gecko. En IE (Internet Explorer) no hay soporte para <code>:focus</code>.</p> + +<h2 id="Especificaci.C3.B3n" name="Especificaci.C3.B3n">Especificación</h2> + +<p>DOM Nivel 0. No es parte de ningún estándar.</p> + +<p><a class="external" href="http://msdn.microsoft.com/workshop/author/dhtml/reference/properties/alinkcolor.asp">MSDN: alinkColor property</a></p> diff --git a/files/es/web/api/document/anchors/index.html b/files/es/web/api/document/anchors/index.html new file mode 100644 index 0000000000..fbcd8eea0e --- /dev/null +++ b/files/es/web/api/document/anchors/index.html @@ -0,0 +1,95 @@ +--- +title: document.anchors +slug: Web/API/Document/anchors +tags: + - API + - Desaprobado + - Documento + - HTML DOM + - Propiedad + - Referencia +translation_of: Web/API/Document/anchors +--- +<div>{{APIRef("DOM")}}{{deprecated_header()}}</div> + +<div>La propiedad de solo lectura <strong><code>anchors</code></strong> de la interfaz {{domxref("Document")}} devuelve una lista de todas las anclas (anchors) del documento.</div> + +<h2 id="Sintaxis" name="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><em>nodeList</em> = document.anchors; +</pre> + +<h3 id="Valor">Valor</h3> + +<p>Una {{domxref("HTMLCollection")}}.</p> + +<h2 id="Ejemplo" name="Ejemplo">Ejemplo</h2> + +<pre class="eval">if ( document.anchors.length >= 5 ) { + dump("dump found too many anchors"); + window.location = "http<span class="nowiki">:</span>//www.google.com"; +} +</pre> + +<p>Lo siguiente es un ejemplo que puebla una Tabla de Contenido con cada ancla en la página:</p> + +<pre class="brush:html line-numbers language-html"><code class="language-html"><span class="doctype token"><!DOCTYPE html></span> +<span class="tag token"><span class="tag token"><span class="punctuation token"><</span>html</span> <span class="attr-name token">lang</span><span class="attr-value token"><span class="punctuation token">=</span><span class="punctuation token">"</span>en<span class="punctuation token">"</span></span><span class="punctuation token">></span></span> +<span class="tag token"><span class="tag token"><span class="punctuation token"><</span>head</span><span class="punctuation token">></span></span> +<span class="tag token"><span class="tag token"><span class="punctuation token"><</span>meta</span> <span class="attr-name token">charset</span><span class="attr-value token"><span class="punctuation token">=</span><span class="punctuation token">"</span>UTF-8<span class="punctuation token">"</span></span> <span class="punctuation token">/></span></span> +<span class="tag token"><span class="tag token"><span class="punctuation token"><</span>title</span><span class="punctuation token">></span></span>Test<span class="tag token"><span class="tag token"><span class="punctuation token"></</span>title</span><span class="punctuation token">></span></span> +<span class="tag token"><span class="tag token"><span class="punctuation token"><</span>script</span><span class="punctuation token">></span></span><span class="script token"><span class="language-javascript token"> +<span class="keyword token">function</span> <span class="function token">init</span><span class="punctuation token">(</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="keyword token">var</span> toc <span class="operator token">=</span> document<span class="punctuation token">.</span><span class="function token">getElementById</span><span class="punctuation token">(</span><span class="string token">"toc"</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + <span class="keyword token">var</span> i<span class="punctuation token">,</span> li<span class="punctuation token">,</span> newAnchor<span class="punctuation token">;</span> + <span class="keyword token">for</span> <span class="punctuation token">(</span>i <span class="operator token">=</span> <span class="number token">0</span><span class="punctuation token">;</span> i <span class="operator token"><</span> document<span class="punctuation token">.</span>anchors<span class="punctuation token">.</span>length<span class="punctuation token">;</span> i<span class="operator token">++</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + li <span class="operator token">=</span> document<span class="punctuation token">.</span><span class="function token">createElement</span><span class="punctuation token">(</span><span class="string token">"li"</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + newAnchor <span class="operator token">=</span> document<span class="punctuation token">.</span><span class="function token">createElement</span><span class="punctuation token">(</span><span class="string token">'a'</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + newAnchor<span class="punctuation token">.</span>href <span class="operator token">=</span> <span class="string token">"#"</span> <span class="operator token">+</span> document<span class="punctuation token">.</span>anchors<span class="punctuation token">[</span>i<span class="punctuation token">]</span><span class="punctuation token">.</span>name<span class="punctuation token">;</span> + newAnchor<span class="punctuation token">.</span>innerHTML <span class="operator token">=</span> document<span class="punctuation token">.</span>anchors<span class="punctuation token">[</span>i<span class="punctuation token">]</span><span class="punctuation token">.</span>text<span class="punctuation token">;</span> + li<span class="punctuation token">.</span><span class="function token">appendChild</span><span class="punctuation token">(</span>newAnchor<span class="punctuation token">)</span><span class="punctuation token">;</span> + toc<span class="punctuation token">.</span><span class="function token">appendChild</span><span class="punctuation token">(</span>li<span class="punctuation token">)</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span> +<span class="punctuation token">}</span> +</span></span><span class="tag token"><span class="tag token"><span class="punctuation token"></</span>script</span><span class="punctuation token">></span></span> +<span class="tag token"><span class="tag token"><span class="punctuation token"></</span>head</span><span class="punctuation token">></span></span> +<span class="tag token"><span class="tag token"><span class="punctuation token"><</span>body</span> <span class="attr-name token">onload</span><span class="attr-value token"><span class="punctuation token">=</span><span class="punctuation token">"</span>init()<span class="punctuation token">"</span></span><span class="punctuation token">></span></span> + +<span class="tag token"><span class="tag token"><span class="punctuation token"><</span>h1</span><span class="punctuation token">></span></span>Title<span class="tag token"><span class="tag token"><span class="punctuation token"></</span>h1</span><span class="punctuation token">></span></span> +<span class="tag token"><span class="tag token"><span class="punctuation token"><</span>h2</span><span class="punctuation token">></span></span><span class="tag token"><span class="tag token"><span class="punctuation token"><</span>a</span> <span class="attr-name token">name</span><span class="attr-value token"><span class="punctuation token">=</span><span class="punctuation token">"</span>contents<span class="punctuation token">"</span></span><span class="punctuation token">></span></span>Contents<span class="tag token"><span class="tag token"><span class="punctuation token"></</span>a</span><span class="punctuation token">></span></span><span class="tag token"><span class="tag token"><span class="punctuation token"></</span>h2</span><span class="punctuation token">></span></span> +<span class="tag token"><span class="tag token"><span class="punctuation token"><</span>ul</span> <span class="attr-name token">id</span><span class="attr-value token"><span class="punctuation token">=</span><span class="punctuation token">"</span>toc<span class="punctuation token">"</span></span><span class="punctuation token">></span></span><span class="tag token"><span class="tag token"><span class="punctuation token"></</span>ul</span><span class="punctuation token">></span></span> + +<span class="tag token"><span class="tag token"><span class="punctuation token"><</span>h2</span><span class="punctuation token">></span></span><span class="tag token"><span class="tag token"><span class="punctuation token"><</span>a</span> <span class="attr-name token">name</span><span class="attr-value token"><span class="punctuation token">=</span><span class="punctuation token">"</span>plants<span class="punctuation token">"</span></span><span class="punctuation token">></span></span>Plants<span class="tag token"><span class="tag token"><span class="punctuation token"></</span>a</span><span class="punctuation token">></span></span><span class="tag token"><span class="tag token"><span class="punctuation token"></</span>h2</span><span class="punctuation token">></span></span> +<span class="tag token"><span class="tag token"><span class="punctuation token"><</span>ol</span><span class="punctuation token">></span></span> + <span class="tag token"><span class="tag token"><span class="punctuation token"><</span>li</span><span class="punctuation token">></span></span>Apples<span class="tag token"><span class="tag token"><span class="punctuation token"></</span>li</span><span class="punctuation token">></span></span> + <span class="tag token"><span class="tag token"><span class="punctuation token"><</span>li</span><span class="punctuation token">></span></span>Oranges<span class="tag token"><span class="tag token"><span class="punctuation token"></</span>li</span><span class="punctuation token">></span></span> + <span class="tag token"><span class="tag token"><span class="punctuation token"><</span>li</span><span class="punctuation token">></span></span>Pears<span class="tag token"><span class="tag token"><span class="punctuation token"></</span>li</span><span class="punctuation token">></span></span> +<span class="tag token"><span class="tag token"><span class="punctuation token"></</span>ol</span><span class="punctuation token">></span></span> + +<span class="tag token"><span class="tag token"><span class="punctuation token"><</span>h2</span><span class="punctuation token">></span></span><span class="tag token"><span class="tag token"><span class="punctuation token"><</span>a</span> <span class="attr-name token">name</span><span class="attr-value token"><span class="punctuation token">=</span><span class="punctuation token">"</span>veggies<span class="punctuation token">"</span></span><span class="punctuation token">></span></span>Veggies<span class="tag token"><span class="tag token"><span class="punctuation token"></</span>a</span><span class="punctuation token">></span></span><span class="tag token"><span class="tag token"><span class="punctuation token"></</span>h2</span><span class="punctuation token">></span></span> +<span class="tag token"><span class="tag token"><span class="punctuation token"><</span>ol</span><span class="punctuation token">></span></span> + <span class="tag token"><span class="tag token"><span class="punctuation token"><</span>li</span><span class="punctuation token">></span></span>Carrots<span class="tag token"><span class="tag token"><span class="punctuation token"></</span>li</span><span class="punctuation token">></span></span> + <span class="tag token"><span class="tag token"><span class="punctuation token"><</span>li</span><span class="punctuation token">></span></span>Celery<span class="tag token"><span class="tag token"><span class="punctuation token"></</span>li</span><span class="punctuation token">></span></span> + <span class="tag token"><span class="tag token"><span class="punctuation token"><</span>li</span><span class="punctuation token">></span></span>Beats<span class="tag token"><span class="tag token"><span class="punctuation token"></</span>li</span><span class="punctuation token">></span></span> +<span class="tag token"><span class="tag token"><span class="punctuation token"></</span>ol</span><span class="punctuation token">></span></span> + +<span class="tag token"><span class="tag token"><span class="punctuation token"></</span>body</span><span class="punctuation token">></span></span> +<span class="tag token"><span class="tag token"><span class="punctuation token"></</span>html</span><span class="punctuation token">></span></span></code></pre> + +<p><a href="https://jsfiddle.net/S4yNp">Ver en JSFiddle</a></p> + +<h2 id="Notas" name="Notas">Notas</h2> + +<p>Por razones de retrocompatibilidad, el conjunto de anclas devuelto sólo contiene aquellas anclas creadas con el atribuo <code>name</code>, y no aquellas creadas con el atributo <code>id</code>.</p> + +<h2 id="Especificaci.C3.B3n" name="Especificaci.C3.B3n">Especificaciones</h2> + +<p><a class="external" href="http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-7577272">DOM Level 2 HTML: anchors</a></p> + +<p>{{ languages( { "en": "en/DOM/document.anchors", "pl": "pl/DOM/document.anchors", "ja": "ja/DOM/document.anchors" } ) }}</p> + +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2> + + + +<div>{{Compat("api.Document.anchors")}}</div> diff --git a/files/es/web/api/document/applets/index.html b/files/es/web/api/document/applets/index.html new file mode 100644 index 0000000000..e6ecf71b60 --- /dev/null +++ b/files/es/web/api/document/applets/index.html @@ -0,0 +1,30 @@ +--- +title: document.applets +slug: Web/API/Document/applets +translation_of: Web/API/Document/applets +--- +<p>{{APIRef("DOM")}}</p> + +<h3 id="Resumen" name="Resumen">Resumen</h3> + +<p><code>applets</code> Devuelve una lista ordenada de los + + <i>applets</i> + del documento.</p> + +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> + +<pre class="eval"><i>nodeList</i> = document.applets +</pre> + +<h3 id="Ejemplo" name="Ejemplo">Ejemplo</h3> + +<pre class="eval">// ( Cuando sabes que el segundo<i>applet</i> es el que quieres ) +my_java_app = document.applets[1]; +</pre> + +<h3 id="Especificaci.C3.B3n" name="Especificaci.C3.B3n">Especificación</h3> + +<p><a class="external" href="http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-85113862">DOM Level 2 HTML: applets</a></p> + +<p>{{ languages( { "en": "en/DOM/document.applets", "pl": "pl/DOM/document.applets" } ) }}</p> diff --git a/files/es/web/api/document/async/index.html b/files/es/web/api/document/async/index.html new file mode 100644 index 0000000000..132fd106e1 --- /dev/null +++ b/files/es/web/api/document/async/index.html @@ -0,0 +1,33 @@ +--- +title: Document.async +slug: Web/API/Document/async +translation_of: Web/API/XMLDocument/async +--- +<p><code>document.async</code> es utilizado para indicar cuándo un llamado de {{domxref("document.load")}} debe ser sincrónico o asincrónico. <code>true</code> es su valor por defecto, indicando que el documento se cargó asincrónicamente.</p> + +<p>(Desde la versión 1.4 alpha es posible cargar documentos sincrónicamente)</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush:js">function loadXMLData(e) { + alert(new XMLSerializer().serializeToString(e.target)); // Devuelve los contenidos de querydata.xml como un string +} + +var xmlDoc = document.implementation.createDocument("", "test", null); + +xmlDoc.async = false; +xmlDoc.onload = loadXMLData; +xmlDoc.load('querydata.xml');</pre> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<ul> + <li><a href="http://www.w3.org/TR/DOM-Level-3-LS/load-save.html#LS-DocumentLS">DOM Level 3 Load & Save module</a></li> +</ul> + +<h2 id="Véase_también">Véase también</h2> + +<ul> + <li><a href="/en-US/docs/XML_in_Mozilla" title="XML_in_Mozilla">XML in Mozilla</a></li> + <li>{{domxref("document.load")}}</li> +</ul> diff --git a/files/es/web/api/document/bgcolor/index.html b/files/es/web/api/document/bgcolor/index.html new file mode 100644 index 0000000000..7baf9c893b --- /dev/null +++ b/files/es/web/api/document/bgcolor/index.html @@ -0,0 +1,39 @@ +--- +title: document.bgColor +slug: Web/API/Document/bgColor +translation_of: Web/API/Document/bgColor +--- +<p>{{APIRef("DOM")}}{{ Deprecated_header() }}</p> + +<p><code>bgColor</code> da/define el color de fondo (bgColor) del documento actual.</p> + +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> + +<pre class="eval"><i>color</i> = document.bgColor +document.bgColor = +<i>color</i> +</pre> + +<h3 id="Par.C3.A1metros" name="Par.C3.A1metros">Parámetros</h3> + +<ul> + <li><code>color</code> es un texto representando el color como una palabra en inglés (e.j., "red") o en valor hexadecimal (e.j., "<code>#ff0000</code>").</li> +</ul> + +<h3 id="Ejemplos" name="Ejemplos">Ejemplos</h3> + +<pre class="eval"># document.bgColor = "darkblue"; +# document.bgColor = "#ff00ff"; +</pre> + +<h3 id="Notas" name="Notas">Notas</h3> + +<p>El valor por defecto de esta propiedad en Mozilla Firefox es blanco (<code>#ffffff</code> en hexadecimal).</p> + +<p><code>document.bgColor</code> está desaprobado en <a class="external" href="http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-26809268">DOM Level 2 HTML</a>. La alternativa recomendada es el uso del estilo <a href="es/CSS/background-color"> background-color</a> de CSS el cual puede ser accesado a través del DOM con <code>document.body.style.backgroundColor</code>. Otra alternativa es <code>document.body.bgColor</code>, sin embargo, ésta última también está desaprobada en HTML 4.01 a favor de la alternativa CSS.</p> + +<h3 id="Especificaci.C3.B3n" name="Especificaci.C3.B3n">Especificación</h3> + +<p>DOM Nivel 0. No es parte de ningún estándar.</p> + +<p>{{ languages( { "en": "en/DOM/document.bgColor", "pl": "pl/DOM/document.bgColor" } ) }}</p> diff --git a/files/es/web/api/document/body/index.html b/files/es/web/api/document/body/index.html new file mode 100644 index 0000000000..724ee899b2 --- /dev/null +++ b/files/es/web/api/document/body/index.html @@ -0,0 +1,39 @@ +--- +title: document.body +slug: Web/API/Document/body +translation_of: Web/API/Document/body +--- +<div>{{APIRef("DOM")}}</div> + +<h3 id="Resumen" name="Resumen">Resumen</h3> + +<p>Devuelve el nodo del <code><body></code> o el nodo del <code><frameset></code> del documento.</p> + +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> + +<pre class="eval"><i>objRef</i> = document.body +document.body = +<i>objRef</i> +</pre> + +<h3 id="Ejemplo" name="Ejemplo">Ejemplo</h3> + +<pre class="eval">// en HTML: <body id="oldBodyElement"></body> +alert(document.body.id); // "oldBodyElement" +var aNewBodyElement = document.createElement("body"); +aNewBodyElement.id = "newBodyElement"; +document.body = aNewBodyElement; +alert(document.body.id); // "newBodyElement" +</pre> + +<h3 id="Notas" name="Notas">Notas</h3> + +<p><code>document.body</code> es el elemento que contiene el contenido para el documento. En documentos con contenidos <code><body></code>, devuelven el elemento <code><body></code>, y en documentos de marco de sistema, esto devuelve el elemento extremo <code><frameset></code>.</p> + +<p>Aunque <code>body</code> es programable, colocando un nuevo cuerpo en un documento efectivamente quitará a todos los hijos actuales del elemento existente <code><body></code>.</p> + +<h3 id="Especificaci.C3.B3n" name="Especificaci.C3.B3n">Especificación</h3> + +<p><a class="external" href="http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-56360201">DOM Level 2 HTML: HTMLDocument.body</a></p> + +<p>{{ languages( { "en": "en/DOM/document.body", "pl": "pl/DOM/document.body" } ) }}</p> diff --git a/files/es/web/api/document/characterset/index.html b/files/es/web/api/document/characterset/index.html new file mode 100644 index 0000000000..b4fb1e2551 --- /dev/null +++ b/files/es/web/api/document/characterset/index.html @@ -0,0 +1,36 @@ +--- +title: document.characterSet +slug: Web/API/Document/characterSet +translation_of: Web/API/Document/characterSet +--- +<p>{{ ApiRef("DOM") }}</p> + +<h3 id="Resumen" name="Resumen">Resumen</h3> + +<p>Devuelve la codificación de caracteres (conjunto de caracteres) usado en el documento.</p> + +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> + +<pre class="eval"><i>string</i> = document.characterSet +</pre> + +<h3 id="Ejemplo" name="Ejemplo">Ejemplo</h3> + +<pre class="eval"><button onclick="alert(document.characterSet);" +>Mostrar conjunto de caracteres</button> +// devuelve el conjunto de caracteres del documento, por ejemplo "ISO-8859-1 o UTF-8" +</pre> + +<h3 id="Notas" name="Notas">Notas</h3> + +<p>La codificación de caracteres es el conjunto de caracteres usados para interpretar el documento, el cual puede ser diferente a la codificación especificada por la página (el usuario puede omitir la codificación).</p> + +<p>Para una lista completa de juegos/conjuntos de caracteres, visite: <a class="external" href="http://www.iana.org/assignments/character-sets" rel="freelink">http://www.iana.org/assignments/character-sets</a>.</p> + +<h3 id="Especificaci.C3.B3n" name="Especificaci.C3.B3n">Especificación</h3> + +<p>DOM Nivel 0. No es parte de ningún estándar.</p> + +<div class="noinclude"> </div> + +<p>{{ languages( { "en": "en/DOM/document.characterSet", "pl": "pl/DOM/document.characterSet" } ) }}</p> diff --git a/files/es/web/api/document/clear/index.html b/files/es/web/api/document/clear/index.html new file mode 100644 index 0000000000..6208e48885 --- /dev/null +++ b/files/es/web/api/document/clear/index.html @@ -0,0 +1,31 @@ +--- +title: Document.clear() +slug: Web/API/Document/clear +tags: + - API + - Document + - HTML DOM + - Method + - NeedsCompatTable + - NeedsExample + - NeedsMarkupWork + - NeedsSpectTable + - Referencia +translation_of: Web/API/Document/clear +--- +<p>{{APIRef("DOM")}}{{ Deprecated_header() }}</p> + +<p>Método que se usa en versiones anterior a las 1.0 de Mozilla para para limpiar el documento completo.</p> + +<p>No hace nada en versiones más recientes basado en Mozilla así como en Internet Explorer y Netscape 4.</p> + +<h2 id="Síntaxis">Síntaxis</h2> + +<pre class="eval">document.clear() +</pre> + +<h2 id="Especificación">Especificación</h2> + +<ul> + <li><a class="external" href="http://www.whatwg.org/html/#dom-document-clear" title="http://www.whatwg.org/html/#dom-document-clear">HTML5</a></li> +</ul> diff --git a/files/es/web/api/document/close/index.html b/files/es/web/api/document/close/index.html new file mode 100644 index 0000000000..313678de2c --- /dev/null +++ b/files/es/web/api/document/close/index.html @@ -0,0 +1,27 @@ +--- +title: Document.close() +slug: Web/API/Document/close +translation_of: Web/API/Document/close +--- +<p>{{APIRef("DOM")}}</p> + +<p>El método <code>document.close()</code> finaliza la escritura de un documento abierta con <a href="/en/DOM/document.open" title="en/DOM/document.open">document.open()</a>.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="eval">document.close(); +</pre> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre>// Abrir un documento. +// Escribir contenido en el documento. +// Cerrar el documento. +document.open(); +document.write("<p>El único contenido.</p>"); +document.close(); +</pre> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<p><a class="external" href="http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-98948567">DOM Level 2 HTML: <code>close()</code> Method</a></p> diff --git a/files/es/web/api/document/contenttype/index.html b/files/es/web/api/document/contenttype/index.html new file mode 100644 index 0000000000..f385843676 --- /dev/null +++ b/files/es/web/api/document/contenttype/index.html @@ -0,0 +1,25 @@ +--- +title: Document.contentType +slug: Web/API/Document/contentType +translation_of: Web/API/Document/contentType +--- +<p>{{ ApiRef("DOM") }}{{Non-standard_header}}</p> + +<p>Devuelve el tipo MIME con el que el documento está siendo renderizado. Puede obtenerlo a partir de los encabezados HTTP (Headers) o de otras fuentes de información MIME, y puede ser afectado por conversiones automáticas inferidas tanto por el navegador como por cualquiera de sus extensiones.</p> + +<h2 id="Notes" name="Notes">Sintáxis</h2> + +<pre class="eval"><var>contentType</var> = <var>document</var>.contentType; +</pre> + +<p><code>contentType</code> es una propiedad de sólo lectura.</p> + +<h2 id="Notes" name="Notes">Notas</h2> + +<p>Esta propiedad no es afectada por los tags meta.</p> + +<h2 id="Specification" name="Specification">Especificaciones</h2> + +<p>No estándar, sólo soportada por <a href="/en/Gecko" title="en/Gecko">Gecko</a>.</p> + +<p> </p> diff --git a/files/es/web/api/document/crearatributo/index.html b/files/es/web/api/document/crearatributo/index.html new file mode 100644 index 0000000000..22f769d577 --- /dev/null +++ b/files/es/web/api/document/crearatributo/index.html @@ -0,0 +1,91 @@ +--- +title: Document.createAttribute() +slug: Web/API/Document/crearAtributo +tags: + - Atributos + - Crear Atributo + - JavaScript + - Métodos +translation_of: Web/API/Document/createAttribute +--- +<div>{{ ApiRef("DOM") }}</div> + +<p>El método <code><strong>Document.createAttribute()</strong></code> crea un nuevo nodo de tipo atributo (attr), y lo retorna. El objeto crea un nodo implementando la interfaz {{domxref("Attr")}}. El DOM no impone que tipo de atributos pueden ser agregados a un particular elemento de esta forma.</p> + +<div class="note"> +<p>El texto pasado como parametro es convertido a minusculas.</p> +</div> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox"><em>atributo</em> = document.createAttribute(nombre) +</pre> + +<h3 id="Parameters" name="Parameters">Parametros</h3> + +<ul> + <li><code>nombre</code> es un string conteniendo el nombre del atributo.</li> +</ul> + +<h3 id="Valor_que_retorna">Valor que retorna</h3> + +<p>Un nodo {{domxref("Attr")}} nodo.</p> + +<h3 id="Excepciones">Excepciones</h3> + +<ul> + <li><code>INVALID_CHARACTER_ERR</code> si el parametro contiene caracteres invalidos para un atributo XML .</li> +</ul> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre class="brush:js">var nodo = document.getElementById("div1"); +var a = document.createAttribute("miAtributo"); +a.value = "nuevoVal"; +nodo.setAttributeNode(a); +console.log(nodo.getAttribute("miAtributo")); // "nuevoVal" +</pre> + +<h2 id="Specification" name="Specification">Especificaciones</h2> + +<table class="spectable standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estatus</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('DOM WHATWG','#dom-document-createattribute','Document.createAttribute()')}}</td> + <td>{{Spec2("DOM WHATWG")}}</td> + <td>Comportamiento preciso con caracteres en mayuscula </td> + </tr> + <tr> + <td>{{SpecName('DOM3 Core','core.html#ID-1084891198','Document.createAttribute()')}}</td> + <td>{{Spec2('DOM3 Core')}}</td> + <td>Sin cambios</td> + </tr> + <tr> + <td>{{SpecName('DOM2 Core','core.html#ID-1084891198','Document.createAttribute()')}}</td> + <td>{{Spec2('DOM2 Core')}}</td> + <td>Sin cambios</td> + </tr> + <tr> + <td>{{SpecName('DOM1','level-one-core.html#ID-1084891198','Document.createAttribute()')}}</td> + <td>{{Spec2('DOM1')}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_del_buscador">Compatibilidad del buscador</h2> + +<div class="hidden">La tabla de compatibilidad en esta página es generada desde estructuras de datos. Sí le gustaría contribuir con estos datos, por favor revisar <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> y enviarnos un pull request.</div> + +<p>{{Compat("api.Document.createAttribute")}}</p> + +<h2 id="Ver_ademas">Ver ademas</h2> + +<ul> + <li>{{domxref("Document.createElement()")}}</li> +</ul> diff --git a/files/es/web/api/document/createdocumentfragment/index.html b/files/es/web/api/document/createdocumentfragment/index.html new file mode 100644 index 0000000000..5137778ee7 --- /dev/null +++ b/files/es/web/api/document/createdocumentfragment/index.html @@ -0,0 +1,119 @@ +--- +title: Document.createDocumentFragment() +slug: Web/API/Document/createDocumentFragment +translation_of: Web/API/Document/createDocumentFragment +--- +<div>{{ ApiRef("DOM") }}</div> + +<div></div> + +<p>Crea un nuevo <code><a href="/en-US/docs/DOM/DocumentFragment" title="DOM/DocumentFragment">DocumentFragment</a></code> vacio, dentro del cual un nodo del DOM puede ser adicionado para construir un nuevo arbol DOM fuera de pantalla.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox notranslate">var fragment = document.createDocumentFragment(); +</pre> + +<p>Se crea un objeto<a href="/en-US/docs/DOM/DocumentFragment" title="DOM/DocumentFragment"> DocumentFragment</a> vacio, el cual queda listo para que pueda insertarseles nodos en el.</p> + +<h2 id="Notas_de_uso">Notas de uso</h2> + +<p><a href="/en-US/docs/DOM/DocumentFragment" title="DOM/DocumentFragment"><code>DocumentFragment</code></a> son Nodos del DOM que nunca forman parte del arbol DOM. El caso de uso mas comun es crear un <em>document fragment</em>, agregar elementos al <em>document fragment</em> y luego agregar dicho <em>document fragment</em> al arbol del DOM. En el arbol del DOM, el <em>document fragment</em> es remplazado por todos sus hijos.</p> + +<p>Dado que el <em>document fragment </em>es generado en memoria y no como parte del arbol del DOM, agregar elementos al mismo no causan <a href="http://code.google.com/speed/articles/reflow.html">reflow</a> (computo de la posicion y geometria de los elementos) en la pagina. Como consecuencia, usar <em>document fragments</em> usualmente resultan en <a href="http://ejohn.org/blog/dom-documentfragments/">mejor performance</a>.</p> + +<p>Tambien puede utilizarse el constructor {{domxref("documentFragment")}} para crear un nuevo fragmento:</p> + +<pre class="syntaxbox notranslate">let fragment = new DocumentFragment();</pre> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<p>Este ejemplo crea una lista de los principales navegadores web en un <em>DocumentFragment</em>, y luego adiciona el nuevo subarbol DOM al document para ser mostrado.</p> + +<p>HTML</p> + +<pre class="notranslate"><ul id="ul"> +</ul></pre> + +<p>JavaScript</p> + +<pre class="notranslate">var element = document.getElementById('ul'); // assuming ul exists +var fragment = document.createDocumentFragment(); +var browsers = ['Firefox', 'Chrome', 'Opera', + 'Safari', 'Internet Explorer']; + +browsers.forEach(function(browser) { + var li = document.createElement('li'); + li.textContent = browser; + fragment.appendChild(li); +}); + +element.appendChild(fragment);</pre> + +<p>Resultado</p> + +<p>{{EmbedLiveSample("Example", 600, 140)}}</p> + +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Firefox (Gecko)</th> + <th>Chrome</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte Basico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</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>Firefox Mobile (Gecko)</th> + <th>Android</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte Basico</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Specification" name="Specification">Especificaciónes</h2> + +<ul> + <li>DOM Level 2: <a href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-35CB04B5">createDocumentFragment</a></li> + <li>DOM Level 3: <a href="http://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-35CB04B5">createDocumentFragment</a></li> +</ul> + +<h2 id="See_also" name="See_also">Vea También</h2> + +<ul> + <li>{{domxref("DOMImplementation.createDocument", "document.implementation.createDocument()")}}</li> + <li>{{domxref("documentFragment")}}</li> +</ul> diff --git a/files/es/web/api/document/createelement/index.html b/files/es/web/api/document/createelement/index.html new file mode 100644 index 0000000000..cb7b3d175b --- /dev/null +++ b/files/es/web/api/document/createelement/index.html @@ -0,0 +1,180 @@ +--- +title: Document.createElement() +slug: Web/API/Document/createElement +tags: + - API + - DOM + - Documento + - Referencia + - metodo +translation_of: Web/API/Document/createElement +--- +<div>{{APIRef("DOM")}}</div> + +<p>En un documento <a href="/en-US/docs/Web/HTML">HTML</a>, el método <strong><code>Document.createElement()</code></strong> crea un elemento HTML especificado por su <code>tagName</code>, o un {{domxref("HTMLUnknownElement")}} si su <code>tagName</code> no se reconoce. En un documento <a href="/en-US/docs/Mozilla/Tech/XUL">XUL</a>, crea el elemento XUL especificado. En otros documentos, crea un elemento con un namespace URI <code>null</code>.</p> + +<p>Para declarar el namespace URI del elemento, utiliza <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/createElementNS" title="Creates an element with the specified namespace URI and qualified name."><code>document.createElementNS()</code></a>.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="brush: js"><var>var <em>element</em></var> = <var>document</var>.createElement(<em><var>tagName, [options]</var></em>); +</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code>tagName</code></dt> +</dl> + +<p>Cadena que especifica el tipo de elemento a crear. El {{domxref("Node.nodeName", "nodeName")}} del elemento creado se inicializa con el valor de <code>tagName</code>. No utilizar nombres reservados (como "html:a") con este método. Al ser invocado en un documento HTML, <code>createElement()</code> convierte <code>tagName</code> a minúsculas antes de crear el elemento. En Firefox, Opera, y Chrome, <code>createElement(null)</code> funciona como <code>createElement("null")</code>.</p> + +<dl> + <dt><code>options</code>{{optional_inline}}</dt> + <dd>Un objeto opcional <code>ElementCreationOptions</code> que contiene una única propiedad llamada <code>is</code>, cuyo valor es el de la etiqueta name de un elemento personalizado definido previamente utilizando <code>customElements.define()</code>. Para compatibilidad con versiones anteriores de<a href="https://www.w3.org/TR/custom-elements/"> Elements specification</a>, algunos navegadores podrían permitir pasar una cadena aquí en vez de un objeto, donde el valor de la cadena es la etiqueta name del elemento creado. Ver <a href="https://developers.google.com/web/fundamentals/primers/customelements/#extendhtml">Extending native HTML elements</a> para más información sobre como usar este parámetro.</dd> + <dd>El nuevo elemento recibirá el atributo cuyo valor es la etiqueta name del elemento personalizado. Los elementos personalizados son una característica experimental solo disponible en algunos navegadores.</dd> +</dl> + +<h3 id="Retorna">Retorna</h3> + +<p>El nuevo <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element" title="The Element interface represents an object of a Document. This interface describes methods and properties common to all kinds of elements. Specific behaviors are described in interfaces which inherit from Element but add additional functionality."><code>Element</code></a>.</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>Crea un nuevo <code><div></code> y lo inserta antes del elemento con ID "<code>div1</code>".</p> + +<h3 id="HTML">HTML</h3> + +<pre class="brush:html"><!DOCTYPE html> +<html> +<head> + <title>||Trabajando con elementos||</title> +</head> +<body> + <div id="div1">El texto superior se ha creado dinámicamente.</div> +</body> +</html> +</pre> + +<h3 id="JavaScript"><span style="line-height: normal;">JavaScript</span></h3> + +<pre class="brush:js">document.body.onload = addElement; + +function addElement () { + // crea un nuevo div + // y añade contenido + var newDiv = document.createElement("div"); + var newContent = document.createTextNode("Hola!¿Qué tal?"); + newDiv.appendChild(newContent); //añade texto al div creado. + + // añade el elemento creado y su contenido al DOM + var currentDiv = document.getElementById("div1"); + document.body.insertBefore(newDiv, currentDiv); +}</pre> + +<p>{{EmbedLiveSample("Example", 500, 50)}}</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('DOM WHATWG', "#dom-document-createelement", "Document.createElement")}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}<sup>[1][2]</sup></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Parámetro <code>options</code></td> + <td>{{CompatVersionUnknown}}<sup>[3]</sup></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop(50)}}<sup>[4][5]</sup></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Desde Gecko 22.0 {{geckoRelease("22.0")}} <code>createElement()</code> no utiliza {{domxref("HTMLSpanElement")}} interface cuando el argumento es "bgsounds", "multicol", o "image". En cambio, <code>HTMLUnknownElement</code> se utiliza para "bgsound" y "multicol" y {{domxref("HTMLElement")}} <code>HTMLElement</code> se utiliza para "image".</p> + +<p>[2] La implementación en Gecko de <code>createElement</code> no cumple la especificación DOM para documentos XUL y XHTML: <code>localName</code> y <code>namespaceURI</code> no son inicializados como <code>null </code>en el elemento creado. Consúltese el {{ Bug(280692) }} para más información.</p> + +<p>[3] En versiones anteriores de la especificación, este argumento era solamente una cadena cuyo valor era la etiqueta <code>name</code> del elemento personalizado. Por ejemplo: Podia recibir <code>document.createElement("button", "mi-boton")</code> en lugar de <code>document.createElement("button", {id: "mi-boton"})</code>. Por razones de compatibilidad, Chrome acepta ambas formas.</p> + +<p>[4] Consultar [3] arriba: como Chrome, Firefox acepta una cadena en vez de un objeto en esta posición, pero solamente desde la versión 51 en adelante. En la versión 50, <code>options</code> debe ser un objeto.</p> + +<p>[5] Para experimentar con elementos personalizados<code> </code>en Firefox, deben establecerse las preferencias <code>dom.webcomponents.enabled</code> y <code>dom.webcomponents.customelements.enabled </code>a <code>true</code>.</p> + +<h3 id="Notas_de_CSS_Quantum">Notas de CSS Quantum</h3> + +<ul> + <li>En Gecko, cuando creas un subarbol separado (por ejemplo, un {{htmlelement("div")}} creado usando <code><strong>createElement()</strong></code> que aún no ha sido insertado en el DOM), el elemento raíz del subarbol es insertado como un elemento "block". En el nuevo motor paralelo de CSS de Firefox (tambien conocido como <a href="https://wiki.mozilla.org/Quantum">Quantum CSS</a> o <a href="https://wiki.mozilla.org/Quantum/Stylo">Stylo</a>, planeado para ser publicado en Firefox 57), el elemento es insertado como "inline", según se especifica en {{bug(1374994)}}.</li> +</ul> + +<h2 id="See_also" name="See_also">Ver también</h2> + +<ul> + <li>{{domxref("Node.removeChild()")}}</li> + <li>{{domxref("Node.replaceChild()")}}</li> + <li>{{domxref("Node.appendChild()")}}</li> + <li>{{domxref("Node.insertBefore()")}}</li> + <li>{{domxref("Node.hasChildNodes()")}}</li> +</ul> diff --git a/files/es/web/api/document/createelementns/index.html b/files/es/web/api/document/createelementns/index.html new file mode 100644 index 0000000000..29571b0978 --- /dev/null +++ b/files/es/web/api/document/createelementns/index.html @@ -0,0 +1,168 @@ +--- +title: Document.createElementNS() +slug: Web/API/Document/createElementNS +translation_of: Web/API/Document/createElementNS +--- +<div>{{ApiRef("DOM")}}</div> + +<p>Crea un elemento del DOM con el espacio de nombres URI y un nombre calificado.</p> + +<p>Para crear un elemento sin especificar un espacio de nombre URI usa el método <a href="createElement" title="createElement">createElement</a>.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="brush: js"><var>var element</var> = <var>document</var>.createElementNS(<var>namespaceURI</var>, <var>qualifiedName</var>[, options]); +</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code>namespaceURI</code></dt> + <dd><em>String </em>que especifica el <a class="external" href="http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/glossary.html#dt-namespaceURI">namespace URI</a> a asociar con el elemento. La propiedad <a href="/en-US/docs/DOM/element.namespaceURI">namespaceURI</a> del elemento creado es inicializada con el valor del <code>namespaceURI</code>. Ver <a href="/en-US/docs/Web/API/Document/createElementNS#Valid_Namespace_URI's">Namespace URIs válidos</a>.</dd> + <dt><code>qualifiedName</code></dt> + <dd><em>String</em> que especifica el tipo del elemento a ser creado. La propiedad <a href="/en-US/docs/DOM/element.nodeName">nodeName</a> del elemento creado es inicializada con el valor <code>qualifiedName</code>.</dd> + <dt><code>options</code><span class="inlineIndicator optional optionalInline">Opcional</span></dt> + <dd>Un objeto opcional <code>ElementCreationOptions</code> que contiene una sola propiedad llamada <code>is</code>, cuyo valor es el nombre de la etiqueta para un elemento personalizado previamente definido usando <code>customElements.define()</code>. Para retro compatibilidad con versiones previas de la <a href="https://www.w3.org/TR/custom-elements/">Especificación de Elementos Personalizados</a>, algunos navegadores te permitirán pasar un <em>String</em> aquí en lugar de un <em>Objeto</em>, donde el valor del <em>String</em> es el nombre de la etiqueta del elemento personalizado. Ver <a href="https://developers.google.com/web/fundamentals/primers/customelements/#extendhtml">Extendiendo elementos HTML nativos</a> para más información sobre como usar este parámetro.</dd> + <dd>Al nuevo elemento le será dado un atributo <code>is</code> cuyo valor es el nombre de la etiqueta del elemento personalizado. Los elementos personalizados son una característica experimental disponible solo en algunos navegadores.</dd> +</dl> + +<h3 id="Valor_de_Retorno">Valor de Retorno</h3> + +<p>El nuevo <code><a href="https://developer.mozilla.org/en-US/docs/Web/API/Element">Elemento</a></code>.</p> + +<h2 id="Example" name="Example">Namespace URIs válidos</h2> + +<ul> + <li>HTML - Usa <code>http://www.w3.org/1999/xhtml</code></li> + <li>SVG - Usa <code>http://www.w3.org/2000/svg</code></li> + <li>XBL - Usa <code>http://www.mozilla.org/xbl</code></li> + <li>XUL - Usa <code>http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul</code></li> +</ul> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<p>El código siguiente crea un elemento <div> nuevo en el namespace <a href="/en-US/docs/XHTML" title="XHTML">XHTML</a> y lo agrega al elemento vbox. Aunque no es un documento <a href="/en-US/docs/XUL" title="XUL">XUL</a> extremamente útil esto demuestra el uso de los elementos de dos namespaces distintos dentro de un solo documento:</p> + +<pre class="brush:xml"><?xml version="1.0"?> +<page xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" + xmlns:html="http://www.w3.org/1999/xhtml" + title="||Trabajando con elementos||" + onload="init()"> + +<script type="text/javascript"><![CDATA[ + var container; + var newdiv; + var txtnode; + + function init(){ + container = document.getElementById("ContainerBox"); + newdiv = document.createElementNS("http://www.w3.org/1999/xhtml","div"); + txtnode = document.createTextNode("Este es el texto que fue construido dinámicamente con createElementNS y createTextNode y luego insertado dentro del documento usando appendChild."); + newdiv.appendChild(txtnode); + container.appendChild(newdiv); + } + +]]></script> + + <vbox id='ContainerBox' flex='1'> + <html:div> + El script en esta página agregará contenido dinámico debajo: + </html:div> + </vbox> + +</page> +</pre> + +<div class="note"> +<p>El ejemplo dado arriba usa script en linea lo cúal no es recomendable en documentos XHTML. Este ejemplo en particular es un documento XUL con XHTML embedido, de cualquier forma la recomendación aplica.</p> +</div> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estatus</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('DOM WHATWG', "#dom-document-createelementns", "Document.createElement")}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Soporte</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>argumento <code>options</code> </td> + <td>{{CompatVersionUnknown}}<sup>[1]</sup></td> + <td>{{CompatGeckoDesktop(50)}}<sup>[2][3]</sup></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Soporte</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] En versiones previas de la especificación el argumento fue solo un String cuyo valor fue el nombre de etiqueta del elemento personalizado. Por motivo de retro compatibilidad Chrome acepta ambas formas.</p> + +<p>[2] Ver [1] arriba: Firefox al igual que Chrome acepta un string en lugar de un objeto, pero solo de la version 51 en adelante. En la version 50 <code>options</code> debe ser un objeto.</p> + +<p>[3] Para experimentar con elementos personalizados en Firefox debes establecer las preferencias <code>dom.webcomponents.enabled</code> y <code>dom.webcomponents.customelements.enabled</code> como <code>true</code>.</p> + +<h2 id="See_also" name="See_also">Ver también</h2> + +<ul> + <li><a href="createElement">document.createElement</a></li> + <li><a href="createTextNode">document.createTextNode</a></li> + <li><a href="../Node/namespaceURI">Node.namespaceURI</a></li> + <li><a class="external" href="http://www.w3.org/TR/1999/REC-xml-names-19990114">Namespaces in XML</a></li> +</ul> diff --git a/files/es/web/api/document/createrange/index.html b/files/es/web/api/document/createrange/index.html new file mode 100644 index 0000000000..8c0cc63391 --- /dev/null +++ b/files/es/web/api/document/createrange/index.html @@ -0,0 +1,42 @@ +--- +title: document.createRange +slug: Web/API/Document/createRange +tags: + - Rango + - Referencia_DOM_de_Gecko + - crear rango +translation_of: Web/API/Document/createRange +--- +<p>{{ ApiRef() }}</p> + +<h3 id="Resumen" name="Resumen">Resumen</h3> + +<p>Retorna un nuevo objeto <code><a href="https://developer.mozilla.org/es/docs/Web/API/Range">Rango</a></code>.</p> + +<h3 id="Sint.C3.A1xis" name="Sint.C3.A1xis">Sintáxis</h3> + +<pre class="eval"><var>range</var> = <var>document</var>.createRange(); +</pre> + +<p>En este ejemplo, <code>range</code> es el nuevo objeto <a href="https://developer.mozilla.org/es/docs/Web/API/Range">rango</a> creado.</p> + +<h3 id="Ejemplo" name="Ejemplo">Ejemplo</h3> + +<pre class="eval">var range = document.createRange(); +range.setStart(startNode, startOffset); +range.setEnd(endNode, endOffset); +</pre> + +<h3 id="Notas" name="Notas">Notas</h3> + +<p>Una vez que se ha creado un objeto <code>Rango</code>, se necesita configurar sus puntos límites antes de hacer uso de la mayoría de sus métodos.</p> + +<h3 id="Especificaci.C3.B3n" name="Especificaci.C3.B3n">Especificación</h3> + +<p><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html#Level2-DocumentRange-method-createRange">DOM Level 2 Range: DocumentRange.createRange</a></p> + + + +<div class="noinclude"></div> + +<p>{{ languages( { "en": "en/DOM/document.createRange", "pl": "pl/DOM/document.createRange" } ) }}</p> diff --git a/files/es/web/api/document/createtextnode/index.html b/files/es/web/api/document/createtextnode/index.html new file mode 100644 index 0000000000..fc1b1488f4 --- /dev/null +++ b/files/es/web/api/document/createtextnode/index.html @@ -0,0 +1,78 @@ +--- +title: Document.createTextNode() +slug: Web/API/Document/createTextNode +tags: + - API + - DOM + - Documento + - Referencia + - createTextNode + - metodo +translation_of: Web/API/Document/createTextNode +--- +<div>{{APIRef("DOM")}}</div> + +<p>Crea un nuevo nodo de texto. Este método puede ser usado para escapar caracteres HTML.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var <var>text</var> = document.createTextNode(<var>data</var>); +</pre> + +<ul> + <li><var>text</var> es un nodo Text.</li> + <li><var>data</var> es una cadena de texto <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String">string</a> que contiene los datos a poner en el nodo de texto.</li> +</ul> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush: html"><!DOCTYPE html> +<html lang="en"> +<head> +<title>createTextNode example</title> +<script> +function addTextNode(text) { + var newtext = document.createTextNode(text), + p1 = document.getElementById("p1"); + + p1.appendChild(newtext); +} +</script> +</head> + +<body> + <button onclick="addTextNode('YES! ');">YES!</button> + <button onclick="addTextNode('NO! ');">NO!</button> + <button onclick="addTextNode('WE CAN! ');">WE CAN!</button> + + <hr /> + + <p id="p1">First line of paragraph.</p> +</body> +</html> +</pre> + +<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('DOM WHATWG', '#dom-document-createtextnode', 'Document: createTextNode')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + + + +<p>{{Compat("api.Document.createTextNode")}}</p> diff --git a/files/es/web/api/document/defaultview/index.html b/files/es/web/api/document/defaultview/index.html new file mode 100644 index 0000000000..e2b44cdd71 --- /dev/null +++ b/files/es/web/api/document/defaultview/index.html @@ -0,0 +1,35 @@ +--- +title: Document.defaultView +slug: Web/API/Document/defaultView +tags: + - API + - Document + - HTML DOM + - NeedsUpdate + - Property + - Reference +translation_of: Web/API/Document/defaultView +--- +<div>{{ ApiRef() }}</div> + +<h2 id="Summary" name="Summary">Resumen</h2> + +<p>En los navegadores devuelve el objeto <a href="/en-US/docs/DOM/window" title="DOM/window">window</a> asociado con el <code>document </code>o <code>null</code> si no está disponible.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox">var win = document.defaultView;</pre> + +<p>Esta propiedad es de solo lectura.</p> + +<h2 id="Notes" name="Notes">Notas</h2> + +<p>De acuerco con <a class="external" href="http://www.quirksmode.org/dom/w3c_html.html">quirksmode</a>, <code>defaultView</code> no está soportado en IE hasta su version 9.</p> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<ul> + <li><a href="/en-US/docs/HTML/HTML5" title="HTML/HTML5">HTML5: defaultView</a></li> + <li><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Views/views.html#Views-DocumentView-defaultView">DOM Level 2 Views: defaultView</a></li> + <li><a class="external" href="http://www.w3.org/TR/DOM-Level-3-Views/" title="http://www.w3.org/TR/DOM-Level-3-Views/">DOM Level 3 Views</a> (Actualmente en desarrolo como "Working Group Note" en W3C y aún no está implementado)</li> +</ul> diff --git a/files/es/web/api/document/designmode/index.html b/files/es/web/api/document/designmode/index.html new file mode 100644 index 0000000000..cf234abee9 --- /dev/null +++ b/files/es/web/api/document/designmode/index.html @@ -0,0 +1,56 @@ +--- +title: Document.designMode +slug: Web/API/Document/designMode +tags: + - API + - Documento + - HTML DOM + - Propiedad + - Referencia + - editor +translation_of: Web/API/Document/designMode +--- +<div>{{ ApiRef() }}</div> + +<p><strong><code>document.designMode</code></strong> controla la posibilidad de editar un documento entero. Los valores válidos son <code>"on"</code> y <code>"off"</code>. De acuerdo a las especificaciones, el valor predeterminado de esta propiedad es <code>"off"</code>. Firefox sigue este estándar. El valor predeterminado de versiones anteriores de Chrome y IE es <code>"inherit"</code>. En IE6-10, el valor se escribe con mayúscula.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var mode = document.designMode; +document.designMode = "on" || "off";</pre> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>Hacer un documento {{HTMLElement("iframe")}} editable:</p> + +<pre class="brush: js">iframeNode.contentDocument.designMode = "on"; +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', '#making-entire-documents-editable:-the-designmode-idl-attribute', 'designMode')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_Navegadores">Compatibilidad de Navegadores</h2> + +<p>{{Compat("api.Document.designMode")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/Rich-Text_Editing_in_Mozilla">Editando text enriquecido en Mozilla</a></li> + <li>{{domxref("HTMLElement.contentEditable")}}</li> + <li><a href="https://msdn.microsoft.com/en-us/library/ms533720(v=vs.85).aspx">propiedad designMode</a> en MSDN</li> +</ul> diff --git a/files/es/web/api/document/dir/index.html b/files/es/web/api/document/dir/index.html new file mode 100644 index 0000000000..61c8a2d637 --- /dev/null +++ b/files/es/web/api/document/dir/index.html @@ -0,0 +1,76 @@ +--- +title: Document.dir +slug: Web/API/Document/dir +translation_of: Web/API/Document/dir +--- +<p>{{ApiRef("")}}{{non-standard_header}}</p> + +<p>La propiedad <code><strong>Document.dir</strong></code> es una {{domxref("DOMString")}} que representa la dirección del texto del documento, ya sea de izquierda a derecha o de derecha a izquierda, siendo la primera el valor por defecto. Sus valores posibles son <em>rtl </em>(Right To Left) o <em>ltr </em>(Left To Right).</p> + +<h2 id="Sintáxis">Sintáxis</h2> + +<pre class="syntaxbox"><em>dirStr</em> = <em>document.</em>dir; +<em>document.dir</em> = <em>dirStr;</em> +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<p>HTML5 WHATWG</p> + +<h2 id="Compatibilidad_de_Navegadores">Compatibilidad de Navegadores</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 (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}} [1]</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</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 Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatUnknown() }}</td> + <td>{{CompatVersionUnknown}} [1]</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Antes de Firefox 23, la propiedad <code>Document.dir</code> devolvía "ltr" independientemente del valor de su elemento {{htmlelement("html")}} raíz.</p> + +<h2 id="Véase_también">Véase también</h2> + +<ul> + <li><a class="external" href="http://msdn.microsoft.com/en-us/library/ms533731.aspx" rel="freelink">http://msdn.microsoft.com/en-us/library/ms533731.aspx</a></li> +</ul> diff --git a/files/es/web/api/document/doctype/index.html b/files/es/web/api/document/doctype/index.html new file mode 100644 index 0000000000..145ca57300 --- /dev/null +++ b/files/es/web/api/document/doctype/index.html @@ -0,0 +1,65 @@ +--- +title: Document.doctype +slug: Web/API/Document/doctype +tags: + - API + - DOCTYPE + - DOM + - Document + - Propiedad + - Referencia +translation_of: Web/API/Document/doctype +--- +<div>{{ApiRef("DOM")}}</div> + +<p>Devuelve la Declaración de tipo de documento (Document Type Declaration (DTD)), asociada al documento actual. El objeto devuelto implementa la interfaz {{domxref("DocumentType")}}. Utilice {{domxref("DOMImplementation.createDocumentType()")}} para crear un <code>DocumentType</code>.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><var>doctype</var> = <var>document</var>.doctype; +</pre> + +<ul> + <li><code>doctype</code> es una propiedad de sólo lectura.</li> +</ul> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush:js">var doctypeObj = document.doctype; + +console.log( + "doctypeObj.name: " + doctypeObj.name + "\n" + + "doctypeObj.internalSubset: " + doctypeObj.internalSubset + "\n" + + "doctypeObj.publicId: " + doctypeObj.publicId + "\n" + + "doctypeObj.systemId: " + doctypeObj.systemId +);</pre> + +<h2 id="Notas">Notas</h2> + +<p>La propiedad devuelve <code>null</code> si no hay DTD asociada al documento actual.</p> + +<p>El nivel 2 de DOM no soporta la edición de la declaración de tipo de documento.</p> + +<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("DOM3 Core", "core.html#ID-B63ED1A31", "Document.doctype")}}</td> + <td>{{Spec2("DOM3 Core")}}</td> + <td>Cambiado el valor de retorno para documentos HTML sin el elemento {{HTMLElement("html")}}. Define que el tipo de documento puede ser modificado.</td> + </tr> + <tr> + <td>{{SpecName("DOM2 Core", "core.html#ID-B63ED1A31", "Document.doctype")}}</td> + <td>{{Spec2("DOM2 Core")}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> diff --git a/files/es/web/api/document/documentelement/index.html b/files/es/web/api/document/documentelement/index.html new file mode 100644 index 0000000000..30453050f7 --- /dev/null +++ b/files/es/web/api/document/documentelement/index.html @@ -0,0 +1,42 @@ +--- +title: document.documentElement +slug: Web/API/Document/documentElement +tags: + - Referencia_DOM_de_Gecko +translation_of: Web/API/Document/documentElement +--- +<p>{{ ApiRef("DOM") }}</p> + +<h3 id="Resumen" name="Resumen">Resumen</h3> + +<p><strong>Solo-lectura</strong></p> + +<p>Devuelve el <code><a href="es/DOM/element">Element</a></code> que es el elemento raíz de <a href="es/DOM/document">document</a> (por ejemplo, devuelve el elemento <code><html></code> en los documentos HTML).</p> + +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> + +<pre class="eval">var<em>element</em> = document.documentElement; +</pre> + +<h3 id="Ejemplo" name="Ejemplo">Ejemplo</h3> + +<pre class="eval">var rootElement = document.documentElement; +var firstTier = rootElement.childNodes; +// firstTier el la NodeList de los hijos directos del elemento raízof the direct children of the root element +for (var i = 0; i < firstTier.length; i++) { + // hacer algo con cada uno de los hijos directos del elemento raíz + // como firstTier[i] +} +</pre> + +<h3 id="Notas" name="Notas">Notas</h3> + +<p>Esta propiedad es de sólo-lectura, facilitada para obtener el elemento raíz de cualquier documento.</p> + +<p>Los documentos HTML contienen normalmente un único hijo directo, <code><html></code>, quizá con una declaración DOCTYPE antes que él. Los documento XML contienen a menudo, múltiples hijos: el elemento raíz, la declaración DOCTYPE y <a href="es/DOM/ProcessingInstruction"> processing instructions</a>.</p> + +<p>Por tanto, deberías usar <code>document.documentElement</code> en lugar de {{ Domxref("document.firstChild") }} para obtener el elemento raíz.</p> + +<h3 id="Especificaci.C3.B3n" name="Especificaci.C3.B3n">Especificación</h3> + +<p><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-87CD092">DOM Level 2 Core: Document.documentElement</a></p> diff --git a/files/es/web/api/document/documenturi/index.html b/files/es/web/api/document/documenturi/index.html new file mode 100644 index 0000000000..4ff365a258 --- /dev/null +++ b/files/es/web/api/document/documenturi/index.html @@ -0,0 +1,121 @@ +--- +title: Document.documentURI +slug: Web/API/Document/documentURI +tags: + - API + - ContenidoNecesario + - DOM + - EjemploNecesario + - Propiedad + - Referencia + - UbicaciónDocumento +translation_of: Web/API/Document/documentURI +--- +<div>{{ApiRef("DOM")}}</div> + +<p>La propiedad <code><strong>documentURI</strong></code> de la interfaz del documento ({{domxref("Document")}}) devuelve la ubicación del documento como un <em>string</em>.</p> + +<p>Originalmente DOM3 fue definido como un atributo de lectura/escritura. En DOM4 se especifica unicamente como de lectura.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="brush: js"><code>var string = document.documentURI;</code> +</pre> + +<h2 id="Notas">Notas</h2> + +<p>Los documentos HTML tienen una propiedad {{domxref("document.URL")}} la cual devuelve el mismo valor (ubicación del documento). A diferencia de <code>URL</code>, <code>documentURI</code> está disponible para todos los tipos de documentos web.</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('DOM4', '#dom-document-documenturi','documentURI')}}</td> + <td>{{Spec2('DOM4')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('DOM3 Core', '#Document3-documentURI', 'documentURI')}}</td> + <td>{{Spec2('DOM3 Core')}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</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 (WebKit)</th> + </tr> + <tr> + <td>Funcionamiento DOM3</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Funcionamiento DOM4</td> + <td>{{CompatChrome(43.0)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</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>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Funcionamiento DOM3</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Funcionamiento DOM4</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatChrome(43.0)}}</td> + </tr> + </tbody> +</table> +</div> diff --git a/files/es/web/api/document/documenturiobject/index.html b/files/es/web/api/document/documenturiobject/index.html new file mode 100644 index 0000000000..fe28ca825f --- /dev/null +++ b/files/es/web/api/document/documenturiobject/index.html @@ -0,0 +1,39 @@ +--- +title: document.documentURIObject +slug: Web/API/Document/documentURIObject +tags: + - Referencia_DOM_de_Gecko +translation_of: Web/API/Document/documentURIObject +--- +<p>{{ ApiRef("DOM") }}</p> + +<h3 id="Resumen" name="Resumen">Resumen</h3> + +<p><strong>Read-only</strong></p> + +<p>Devuelve un objeto {{ Interface("nsIURI") }} que representa la URI de <a href="es/DOM/document">document</a>.</p> + +<p>Esto sólo funciona para programas con privilegios (UniversalXPConnect) incluidas las extensiones. Para páginas web, esta propiedad no tiene significado especial y puede usarse de igual forma que cualquier otra propiedad del usuario.</p> + +<p>El código con privilegios, debe tener cuidado de no leer o escribir esta propiedad en un objeto no controlado (e.g. on a <code>wrappedJSObject</code> of an <code><a href="es/XPCNativeWrapper">XPCNativeWrapper</a></code>). Ver {{ Bug(324464) }}para más detalles.</p> + +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> + +<pre class="eval">var<em>uri</em> =<em>doc</em>.documentURIObject; +</pre> + +<h3 id="Ejemplo" name="Ejemplo">Ejemplo</h3> + +<pre class="eval">// Comprueba que el esquema URI de la pestaña de Firefox es 'http', +// asumiendo que este código se ejecuta dentro de browser.xul +var uriObj = content.document.documentURIObject; +var uriPort = uriObj.port; + +if (uriObj.schemeIs('http')) { + ... +} +</pre> + +<h3 id="Especificaci.C3.B3n" name="Especificaci.C3.B3n">Especificación</h3> + +<p>No forma parte de ninguna especificación W3C.</p> diff --git a/files/es/web/api/document/dragover_event/index.html b/files/es/web/api/document/dragover_event/index.html new file mode 100644 index 0000000000..c4fe204135 --- /dev/null +++ b/files/es/web/api/document/dragover_event/index.html @@ -0,0 +1,338 @@ +--- +title: dragover +slug: Web/API/Document/dragover_event +translation_of: Web/API/Document/dragover_event +--- +<div>{{APIRef}}</div> + +<p>El evento <code>dragover</code> se activa cuando un elemento o texto se arrastra a un objetivo válido (cada pocos cientos de milisegundos).</p> + +<p> </p> + +<p>El evento se activa en la caída al objetivo.</p> + +<h2 id="General_info">General info</h2> + +<table class="properties"> + <tbody> + <tr> + <td>Bubbles</td> + <td>Yes</td> + </tr> + <tr> + <td>Cancelable</td> + <td>Yes</td> + </tr> + <tr> + <td>Target objects</td> + <td>{{domxref("Document")}}, {{domxref("Element")}}</td> + </tr> + <tr> + <td>Interface</td> + <td>{{domxref("DragEvent")}}</td> + </tr> + <tr> + <td>Default Action</td> + <td>Reset the current drag operation to "none".</td> + </tr> + </tbody> +</table> + +<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><a href="/en-US/docs/Web/API/EventTarget" title="EventTarget is an interface implemented by objects that can receive events and may have listeners for them."><code>EventTarget</code></a></td> + <td>El elemento que se encontraba bajo el elemento que está siendo arrastrado.</td> + </tr> + <tr> + <td><code>type</code> {{readonlyInline}}</td> + <td><a href="/en-US/docs/Web/API/DOMString" title="DOMString is a UTF-16 String. As JavaScript already uses such strings, DOMString is mapped directly to a String."><code>DOMString</code></a></td> + <td>El tipo de evento.</td> + </tr> + <tr> + <td><code>bubbles</code> {{readonlyInline}}</td> + <td><a href="/en-US/docs/Web/API/Boolean" title="The Boolean object is an object wrapper for a boolean value."><code>Boolean</code></a></td> + <td>Si el evento se propaga normalmente o no.</td> + </tr> + <tr> + <td><code>cancelable</code> {{readonlyInline}}</td> + <td><a href="/en-US/docs/Web/API/Boolean" title="The Boolean object is an object wrapper for a boolean value."><code>Boolean</code></a></td> + <td>Si el evento es cancelable o no.</td> + </tr> + <tr> + <td><code>view</code> {{readonlyInline}}</td> + <td><a class="new" href="/en-US/docs/Web/API/WindowProxy" rel="nofollow" title="The documentation about this has not yet been written; please consider contributing!"><code>WindowProxy</code></a></td> + <td><a href="/en-US/docs/Web/API/Document/defaultView" title="In browsers, document.defaultView returns the window object associated with a document, or null if none is available."><code>document.defaultView</code></a> (<code>window</code> del documento)</td> + </tr> + <tr> + <td><code>detail</code> {{readonlyInline}}</td> + <td><code>long</code> (<code>float</code>)</td> + <td>0.</td> + </tr> + <tr> + <td><code>dataTransfer</code></td> + <td>DataTransfer</td> + <td>Los datos que subyacen a la operación de drag-and-drop , conocidas como <a href="/en-US/docs/Web/API/DataTransfer">drag data store</a>. Modo protegido.</td> + </tr> + <tr> + <td><code>currentTarget</code> {{readonlyInline}}</td> + <td>EventTarget</td> + <td>El nodo que tiene adjunto el detector de eventos.</td> + </tr> + <tr> + <td><code>relatedTarget</code> {{readonlyInline}}</td> + <td>EventTarget</td> + <td>Para los eventos de <code>mouseover</code>, <code>mouseout</code>, <code>mouseenter</code> y <code>mouseleave</code>:El objetivo del evento complementario (el objetivo <code>mouseleave</code> en el caso del evento <code>mouseenter</code>). <code>null</code> sino.</td> + </tr> + <tr> + <td><code>screenX</code> {{readonlyInline}}</td> + <td>long</td> + <td>La coordinada X del puntro del ratón en coordenadas globales (de pantalla).</td> + </tr> + <tr> + <td><code>screenY</code> {{readonlyInline}}</td> + <td>long</td> + <td>La coordinada Y del puntero del ratón en coordenadas globales (en pantalla).</td> + </tr> + <tr> + <td><code>clientX</code> {{readonlyInline}}</td> + <td>long</td> + <td>La coordinada X del puntro del ratón en coordenadas locales (DOM content).</td> + </tr> + <tr> + <td><code>clientY</code> {{readonlyInline}}</td> + <td>long</td> + <td>La coordinada Y del puntro del ratón en coordenadas locales (DOM content).</td> + </tr> + <tr> + <td><code>button</code> {{readonlyInline}}</td> + <td>unsigned short</td> + <td> + <p>El número de botón que se preionó cuando el ecento fue ectivado: Botón izquierdo=0, botón del medio=1(en caso de que esté presente), botón derecho=2. Para ratones configurados para zurdos donde laas acciones están configuradas al contrario los valores se leerán de derecha a izquierda.</p> + </td> + </tr> + <tr> + <td><code>buttons</code> {{readonlyInline}}</td> + <td>unsigned short</td> + <td> + <p>Los botones presionados cuando el evento de ratón se activa: botón izquierdo=1,botón derecho=2, botón medio (rueda)=4, 4º botón (tipo "hacia atrás del navegador"=8, 5º botón ("tipo hacia delante en el navegador"=16. Si dos o más botones se presionan, devolverá la suma lógica de los valores. Ej: si se presionan los botones izquierdo y derecho, devolverá 3 (=1|2). <a href="/en-US/docs/Web/API/MouseEvent">M</a>ás información.</p> + </td> + </tr> + <tr> + <td><code>mozPressure</code> {{readonlyInline}}</td> + <td>float</td> + <td> + <p>La cantidad de presión aplicada en dispositivos táctiles cuando se genera el evento; Este valor tiene un rango entre 0.0 (mínima presión) y 1.0 (máxima presión)</p> + </td> + </tr> + <tr> + <td><code>ctrlKey</code> {{readonlyInline}}</td> + <td>boolean</td> + <td><code>true</code> si la tecla control estaba pulsada cuando el evento se lanzó <code>false</code> en cualquier otro caso.</td> + </tr> + <tr> + <td><code>shiftKey</code> {{readonlyInline}}</td> + <td>boolean</td> + <td><code>true</code> si la tecla shift estaba pulsada cuando el evento de lanzó. <code>false</code> en otro caso.</td> + </tr> + <tr> + <td><code>altKey</code> {{readonlyInline}}</td> + <td>boolean</td> + <td><code>true</code> si la tecla alt estaba pulsada cuando el evento se lanzó. <code>false</code> si no.</td> + </tr> + <tr> + <td><code>metaKey</code> {{readonlyInline}}</td> + <td>boolean</td> + <td><code>true</code> si la tecla meta estaba presionada cuando el evento se disparó. <code>false</code> si no.</td> + </tr> + </tbody> +</table> + +<h2 id="Example">Example</h2> + +<pre class="brush: js"><div class="dropzone"> + <div id="draggable" draggable="true" ondragstart="event.dataTransfer.setData('text/plain',null)"> + This div is draggable + </div> +</div> +<div class="dropzone"></div> +<div class="dropzone"></div> +<div class="dropzone"></div> + +<style> + #draggable { + width: 200px; + height: 20px; + text-align: center; + background: white; + } + + .dropzone { + width: 200px; + height: 20px; + background: blueviolet; + margin-bottom: 10px; + padding: 10px; + } +</style> + +<script> + var dragged; + + /* events fired on the draggable target */ + document.addEventListener("drag", function( event ) { + + }, false); + + document.addEventListener("dragstart", function( event ) { + // store a ref. on the dragged elem + dragged = event.target; + // make it half transparent + event.target.style.opacity = .5; + }, false); + + document.addEventListener("dragend", function( event ) { + // reset the transparency + event.target.style.opacity = ""; + }, false); + + /* events fired on the drop targets */ + document.addEventListener("dragover", function( event ) { + // prevent default to allow drop + event.preventDefault(); + }, false); + + document.addEventListener("dragenter", function( event ) { + // highlight potential drop target when the draggable element enters it + if ( event.target.className == "dropzone" ) { + event.target.style.background = "purple"; + } + + }, false); + + document.addEventListener("dragleave", function( event ) { + // reset background of potential drop target when the draggable element leaves it + if ( event.target.className == "dropzone" ) { + event.target.style.background = ""; + } + + }, false); + + document.addEventListener("drop", function( event ) { + // prevent default action (open as link for some elements) + event.preventDefault(); + // move dragged elem to the selected drop target + if ( event.target.className == "dropzone" ) { + event.target.style.background = ""; + dragged.parentNode.removeChild( dragged ); + event.target.appendChild( dragged ); + } + + }, false); +</script> +</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", "interaction.html#dndevents", "dragover")}}</td> + <td>{{Spec2("HTML WHATWG")}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName("HTML5.1", "editing.html#dndevents", "dragover")}}</td> + <td>{{Spec2("HTML5.1")}}</td> + <td>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>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>4</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("1.9.1")}}</td> + <td>10</td> + <td>12</td> + <td>3.1</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Android Webview</th> + <th>Chrome for Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</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>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatIE("10")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{event("drag")}}</li> + <li>{{event("dragstart")}}</li> + <li>{{event("dragend")}}</li> + <li>{{event("dragover")}}</li> + <li>{{event("dragenter")}}</li> + <li>{{event("dragleave")}}</li> + <li>{{event("dragexit")}}</li> + <li>{{event("drop")}}</li> +</ul> diff --git a/files/es/web/api/document/embeds/index.html b/files/es/web/api/document/embeds/index.html new file mode 100644 index 0000000000..865efdb2fd --- /dev/null +++ b/files/es/web/api/document/embeds/index.html @@ -0,0 +1,48 @@ +--- +title: Document.embeds +slug: Web/API/Document/embeds +tags: + - API + - Documento + - Ejemplo + - HTML DOM + - Propiedad +translation_of: Web/API/Document/embeds +--- +<div>{{ApiRef}}</div> + +<p><strong><code>embeds</code></strong> es una propiedad de sólo lectura de la interfaz de {{domxref("Document")}}. Devuelve una lista con los elementos {{htmlelement("object")}} incrustados dentro del documento actual.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><var>nodeList</var> = document.embeds +</pre> + +<h3 id="Valor">Valor</h3> + +<p>Una {{domxref("HTMLCollection")}}.</p> + +<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('HTML WHATWG', '#dom-document-embeds', 'Document.embeds')}}</td> + <td>{{ Spec2('HTML WHATWG') }}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_Navegadores">Compatibilidad con Navegadores</h2> + +<div class="hidden">La tabla de compatibilidad de esta página se genera a partir de structured data. Si usted quiere contribuir, por favor visite <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> y envíenos un pull request.</div> + +<div>{{Compat("api.Document.embeds")}}</div> diff --git a/files/es/web/api/document/evaluate/index.html b/files/es/web/api/document/evaluate/index.html new file mode 100644 index 0000000000..67bc5d432e --- /dev/null +++ b/files/es/web/api/document/evaluate/index.html @@ -0,0 +1,211 @@ +--- +title: Document.evaluate() +slug: Web/API/Document/evaluate +translation_of: Web/API/Document/evaluate +--- +<div>{{ ApiRef("DOM") }}</div> + +<p>Retorna <code><a href="/en-US/docs/XPathResult" title="XPathResult">XPathResult</a></code> basado en una expresión <a href="/en-US/docs/XPath" title="XPath">XPath</a> y otros parametros dados .</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox">var xpathResult = document.evaluate( + xpathExpression, + contextNode, + namespaceResolver, + resultType, + result +);</pre> + +<ul> + <li><code>XpathExpression es una cadena que representa el XPath que se va a evaluar.</code></li> + <li><code>contextNode</code> specifies the <em>context node</em> for the query (see the [<a class="external" href="http://www.w3.org/TR/xpath" rel="freelink">http://www.w3.org/TR/xpath</a> XPath specification). It's common to pass <code>document</code> as the context node.</li> + <li><code>namespaceResolver</code> is a function that will be passed any namespace prefixes and should return a string representing the namespace URI associated with that prefix. It will be used to resolve prefixes within the XPath itself, so that they can be matched with the document. <code>null</code> is common for HTML documents or when no namespace prefixes are used.</li> + <li><code>resultType</code> is an integer that corresponds to the type of result <code>XPathResult</code> to return. Use <a href="#Result_types">named constant properties</a>, such as <code>XPathResult.ANY_TYPE</code>, of the XPathResult constructor, which correspond to integers from 0 to 9.</li> + <li><code>result</code> is an existing <code>XPathResult</code> to use for the results. <code>null</code> is the most common and will create a new <code>XPathResult</code></li> +</ul> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre class="brush: js">var headings = document.evaluate("/html/body//h2", document, null, XPathResult.ANY_TYPE, null); +/* Search the document for all h2 elements. + * The result will likely be an unordered node iterator. */ +var thisHeading = headings.iterateNext(); +var alertText = "Level 2 headings in this document are:\n"; +while (thisHeading) { + alertText += thisHeading.textContent + "\n"; + thisHeading = headings.iterateNext(); +} +alert(alertText); // Alerts the text of all h2 elements +</pre> + +<p>Note, in the above example, a more verbose XPath is preferred over common shortcuts such as <code>//h2</code>. Generally, more specific XPath selectors as in the above example usually gives a significant performance improvement, especially on very large documents. This is because the evaluation of the query spends does not waste time visiting unnecessary nodes. Using // is generally slow as it visits <em>every</em> node from the root and all subnodes looking for possible matches.</p> + +<p>Further optimization can be achieved by careful use of the context parameter. For example, if you know the content you are looking for is somewhere inside the body tag, you can use this:</p> + +<pre class="brush: js">document.evaluate(".//h2", document.body, null, XPathResult.ANY_TYPE, null); +</pre> + +<p>Notice in the above <code>document.body</code> has been used as the context instead of <code>document</code> so the XPath starts from the body element. (In this example, the <code>"."</code> is important to indicate that the querying should start from the context node, document.body. If the "." was left out (leaving <code>//h2</code>) the query would start from the root node (<code>html</code>) which would be more wasteful.)</p> + +<p>See <a href="/en-US/docs/Introduction_to_using_XPath_in_JavaScript" title="Introduction to using XPath in JavaScript">Introduction to using XPath in JavaScript</a> for more information.</p> + +<h2 id="Notes" name="Notes">Nota</h2> + +<ul> + <li>XPath expressions can be evaluated on HTML and XML documents.</li> + <li>While using document.evaluate() works in FF2, in FF3 one must use someXMLDoc.evaluate() if evaluating against something other than the current document.</li> +</ul> + +<h2 id="Result_types" name="Result_types">Tipos de resultados</h2> + +<p>(Merge with <a href="/Template:XPathResultConstants" title="Template:XPathResultConstants">Template:XPathResultConstants</a>?</p> + +<p>These are supported values for the <code>resultType</code> parameter of the <code>evaluate</code> method:</p> + +<table class="standard-table"> + <tbody> + <tr> + <td class="header">Result Type</td> + <td class="header">Value</td> + <td class="header">Description</td> + </tr> + <tr> + <td><code>ANY_TYPE</code></td> + <td>0</td> + <td>Whatever type naturally results from the given expression.</td> + </tr> + <tr> + <td><code>NUMBER_TYPE</code></td> + <td>1</td> + <td>A result set containing a single number. Useful, for example, in an XPath expression using the <code>count()</code> function.</td> + </tr> + <tr> + <td><code>STRING_TYPE</code></td> + <td>2</td> + <td>A result set containing a single string.</td> + </tr> + <tr> + <td><code>BOOLEAN_TYPE</code></td> + <td>3</td> + <td>A result set containing a single boolean value. Useful, for example, an an XPath expression using the <code>not()</code> function.</td> + </tr> + <tr> + <td><code>UNORDERED_NODE_ITERATOR_TYPE</code></td> + <td>4</td> + <td>A result set containing all the nodes matching the expression. The nodes in the result set are not necessarily in the same order they appear in the document.</td> + </tr> + <tr> + <td><code>ORDERED_NODE_ITERATOR_TYPE</code></td> + <td>5</td> + <td>A result set containing all the nodes matching the expression. The nodes in the result set are in the same order they appear in the document.</td> + </tr> + <tr> + <td><code>UNORDERED_NODE_SNAPSHOT_TYPE</code></td> + <td>6</td> + <td>A result set containing snapshots of all the nodes matching the expression. The nodes in the result set are not necessarily in the same order they appear in the document.</td> + </tr> + <tr> + <td><code>ORDERED_NODE_SNAPSHOT_TYPE</code></td> + <td>7</td> + <td>A result set containing snapshots of all the nodes matching the expression. The nodes in the result set are in the same order they appear in the document.</td> + </tr> + <tr> + <td><code>ANY_UNORDERED_NODE_TYPE</code></td> + <td>8</td> + <td>A result set containing any single node that matches the expression. The node is not necessarily the first node in the document that matches the expression.</td> + </tr> + <tr> + <td><code>FIRST_ORDERED_NODE_TYPE</code></td> + <td>9</td> + <td>A result set containing the first node in the document that matches the expression.</td> + </tr> + </tbody> +</table> + +<p>Results of <code>NODE_ITERATOR</code> types contain references to nodes in the document. Modifying a node will invalidate the iterator. After modifying a node, attempting to iterate through the results will result in an error.</p> + +<p>Results of <code>NODE_SNAPSHOT</code> types are snapshots, which are essentially lists of matched nodes. You can make changes to the document by altering snapshot nodes. Modifying the document doesn't invalidate the snapshot; however, if the document is changed, the snapshot may not correspond to the current state of the document, since nodes may have moved, been changed, added, or removed.</p> + +<h2 id="Specifications" name="Specifications">Especificaciones</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("DOM3 XPath", "xpath.html#XPathEvaluator-evaluate", "Document.evaluate")}}</td> + <td>{{Spec2("DOM3 XPath")}}</td> + <td>Initial specification</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">Compatibilidad del navegador</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>XPath 1.0</td> + <td>{{CompatChrome(1.0)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(1.8)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatOpera(9.0)}}</td> + <td>{{CompatVersionUnknown}}<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>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>XPath 1.0</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Implemented in WebKit 5.0 (531) or earlier.</p> + +<h2 id="See_also" name="See_also">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/DOM/document.createExpression" title="DOM/document.createExpression">DOM:document.createExpression</a></li> + <li><a href="/en-US/docs/Code_snippets/XPath" title="Code_snippets/XPath">XPath Code Snippets</a></li> + <li><a href="http://codepen.io/johan/full/ckFgn">Check for browser support</a></li> +</ul> diff --git a/files/es/web/api/document/execcommand/index.html b/files/es/web/api/document/execcommand/index.html new file mode 100644 index 0000000000..2102597c22 --- /dev/null +++ b/files/es/web/api/document/execcommand/index.html @@ -0,0 +1,288 @@ +--- +title: Document.execCommand() +slug: Web/API/Document/execCommand +tags: + - API + - DOM + - Método(2) + - NecesitaEjemplo + - Referencia + - editor +translation_of: Web/API/Document/execCommand +--- +<div>{{ApiRef("DOM")}}</div> + +<h2 id="Summary" name="Summary"><span id="result_box" lang="es"><span title="Summary">Resumen</span></span></h2> + +<p><span id="result_box" lang="es"><span title="When an HTML document has been switched to designMode, the document object exposes the execCommand method which allows one to run commands to manipulate the contents of the editable region.">Cuando un documento HTML se ha cambiado a <code>designMode</code>, el objeto de documento expone el método</span></span> <code>execCommand</code> <span id="result_box" lang="es"><span title="When an HTML document has been switched to designMode, the document object exposes the execCommand method which allows one to run commands to manipulate the contents of the editable region.">lo que permite ejecutar comandos para manipular el contenido de la región editable. </span><span title="Most commands affect the document's selection (bold, italics, etc), while others insert new elements (adding a link) or affect an entire line (indenting).">La mayoría de los comandos afectan a la selección de documento (negrita, cursiva, etc.), mientras que otros insertar nuevos elementos (añadiendo un enlace) o afectan a toda una línea (sangría). </span><span title="When using contentEditable, calling execCommand will affect the currently active editable element. +">Al usar</span></span> <code>contentEditable</code>, la llamada a <code>execCommand</code> afectará el elemento editable activo actual.</p> + +<h2 id="Syntax" name="Syntax"><span id="result_box" lang="es"><span title="Syntax">Sintaxis</span></span></h2> + +<pre class="brush: js">execCommand(aCommandName, aShowDefaultUI, aValueArgument) +</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt>aCommandName</dt> + <dd><span id="result_box" lang="es"><span title='A {{domxref("DOMString")}} specifying the name of the command to execute.'>Una {{domxref("DOMString")}} que especifica el nombre del comando a ejecutar. Vea {{anch("Comandos")}} para una lista de posibles comandos.</span></span></dd> + <dt>aShowDefaultUI</dt> + <dd><span id="result_box" lang="es"><span title='A {{jsxref("Boolean")}} indicating whether the default user interface should be shown.'>Un {{jsxref("Boolean")}} que indica si la interfaz de usuario por defecto se debe mostrar. </span><span title="This is not implemented in Mozilla.">Esto no se ha implementado en Mozilla.</span></span></dd> + <dt>aValueArgument</dt> + <dd><span id="result_box" lang="es"><span title='A {{domxref("DOMString")}} For commands which require an input argument (such as insertImage, for which this is the URL of the image to insert), this is a {{domxref("DOMString")}} providing that information.'>Una {{domxref("DOMString")}} representando algunos comandos (como <code>insertImage</code>) requiere un argumento valor extra (url de la imagen). </span><span title="Pass an argument of null if no argument is needed. + +">Pasar un argumento de</span></span> <code>null</code> <span id="result_box" lang="es"><span title="Pass an argument of null if no argument is needed. + +">si no se necesita ningún argumento</span></span>.</dd> +</dl> + +<h3 id="Comandos"><span id="result_box" lang="es"><span title="Commands + +">Comandos</span></span></h3> + +<dl> + <dt>backColor</dt> + <dd><span id="result_box" lang="es"><span title="backColor + "> </span><span title="Changes the document background color.">Cambia el color de fondo del documento</span></span>. <span id="result_box" lang="es"><span title="In styleWithCss mode, it affects the background color of the containing block instead.">En el modo styleWithCss, afecta el color de fondo del bloque que contiene. </span><span title="This requires a color value string to be passed in as a value argument.">Esto requiere una cadena con el valor del color de fondo que se pasa como un valor de </span></span><span lang="es"><span title="This requires a color value string to be passed in as a value argument.">argumento. </span><span title="(Internet Explorer uses this to set text background color.) +">(Internet Explorer utiliza esta opción para definir el color de fondo del texto.)</span></span></dd> + <dt>bold</dt> + <dd>Pone las negritas o las quita <span id="result_box" lang="es"><span title="Toggles bold on/off for the selection or at the insertion point.">para la selección o en el punto de inserción. </span><span title="(Internet Explorer uses the STRONG tag instead of B.) +">(Internet Explorer utiliza la etiqueta STRONG en lugar de B.)</span></span></dd> + <dt>contentReadOnly</dt> + <dd><span id="result_box" lang="es"><span title="Makes the content document either read-only or editable.">Hace que el documento de contenido, ya sea de sólo lectura o editable. </span><span title="This requires a boolean true/false to be passed in as a value argument.">Esto requiere un booleano verdadero / falso que se pasa como un valor de </span></span><span lang="es"><span title="This requires a boolean true/false to be passed in as a value argument.">argumento. </span><span title="(Not supported by Internet Explorer.) +">(No es compatible con Internet Explorer.)</span></span></dd> + <dt>copy</dt> + <dd><span id="result_box" lang="es"><span title="Copies the current selection to the clipboard.">Copia la selección actual en el portapapeles. </span><span title="Clipboard capability must be enabled in the user.js preference file.">Capacidad del Portapapeles debe estar habilitado en el archivo de preferencias user.js. Vea</span></span></dd> + <dt>createLink</dt> + <dd><span id="result_box" lang="es"><span title="Creates an anchor link from the selection, only if there is a selection.">Crea un vínculo de anclaje a partir de la selección, sólo si hay una selección. </span><span title="This requires the HREF URI string to be passed in as a value argument.">Esto requiere la cadena HREF URI que se pasa como un argumento de valor. </span><span title="The URI must contain at least a single character, which may be a white space.">El URI debe contener al menos un solo carácter, el cual puede ser un espacio en blanco. </span><span title="(Internet Explorer will create a link with a null URI value.) +">(Internet Explorer creará un enlace con un nulo valor URI.)</span></span></dd> + <dt>cut</dt> + <dd><span id="result_box" lang="es"><span title="Cuts the current selection and copies it to the clipboard.">Corta la selección y lo copia en el portapapeles actual. </span><span title="Clipboard capability must be enabled in the user.js preference file.">Capacidad del Portapapeles debe estar habilitado en el archivo de preferencias user.js. </span><span title="See +">Vea </span></span></dd> + <dt>decreaseFontSize</dt> + <dd><span id="result_box" lang="es"><span title="Adds a SMALL tag around the selection or at the insertion point.">Añade una etiqueta SMALL alrededor de la selección o en el punto de inserción. </span><span title="(Not supported by Internet Explorer.) +">(No es compatible con Internet Explorer.)</span></span></dd> + <dt>delete</dt> + <dd><span id="result_box" lang="es"><span title="Deletes the current selection. +">Elimina la selección actual.</span></span></dd> + <dt>enableInlineTableEditing</dt> + <dd><span id="result_box" lang="es"><span title="Enables or disables the table row and column insertion and deletion controls.">Activa o desactiva la fila de la tabla y los controles de inserción y supresión de columna</span></span><span lang="es"><span title="Enables or disables the table row and column insertion and deletion controls.">. </span><span title="(Not supported by Internet Explorer.) +">(No es compatible con Internet Explorer.)</span></span></dd> + <dt>enableObjectResizing</dt> + <dd><span id="result_box" lang="es"><span title="Enables or disables the resize handles on images and other resizable objects.">Activa o desactiva los controladores de tamaño en imágenes y otros objetos de tamaño variable. </span><span title="(Not supported by Internet Explorer.) +">(No es compatible con Internet Explorer.)</span></span></dd> + <dt>fontName</dt> + <dd><span id="result_box" lang="es"><span title="Changes the font name for the selection or at the insertion point.">Cambia el nombre de la fuente para la selección o en el punto de inserción. </span><span title='This requires a font name string ("Arial" for example) to be passed in as a value argument. +'>Esto requiere una cadena de nombre de la fuente ("Arial", por ejemplo) que se pasa como un valor de </span></span><span lang="es"><span title='This requires a font name string ("Arial" for example) to be passed in as a value argument. +'>argumento.</span></span></dd> + <dt>fontSize</dt> + <dd><span id="result_box" lang="es"><span title="Changes the font size for the selection or at the insertion point.">Cambia el tamaño de fuente para la selección o en el punto de inserción. </span><span title="This requires an HTML font size (1-7) to be passed in as a value argument. +">Esto requiere un tamaño de fuente HTML (1-7) que se pasa como un valor de </span></span><span lang="es"><span title="This requires an HTML font size (1-7) to be passed in as a value argument. +">argumento.</span></span></dd> + <dt>foreColor</dt> + <dd><span id="result_box" lang="es"><span title="Changes a font color for the selection or at the insertion point.">Cambia un color de fuente para la selección o en el punto de inserción. </span><span title="This requires a color value string to be passed in as a value argument. +">Esto requiere una cadena de valor de color que se pasa como un valor de </span></span><span lang="es"><span title="This requires a color value string to be passed in as a value argument. +">argumento.</span></span></dd> + <dt>formatBlock</dt> + <dd><span id="result_box" lang="es"><span title="Adds an HTML block-style tag around the line containing the current selection, replacing the block element containing the line if one exists (in Firefox, BLOCKQUOTE is the exception - it will wrap any containing block element).">Añade una etiqueta HTML de estilo bloque alrededor de la línea que contiene la selección actual, reemplazando el elemento de bloque que contiene la línea si existe (en Firefox, BLOCKQUOTE es la excepción - que envolverá cualquier elemento de bloque que contiene). </span><span title="Requires a tag-name string to be passed in as a value argument.">Requiere una cadena de etiqueta-nombre que se pasa como un argumento de valor. </span><span title='Virtually all block style tags can be used (eg. "H1", "P", "DL", "BLOCKQUOTE").'>Prácticamente todas las etiquetas de estilo bloque se pueden utilizar (por ejemplo. "H1", "P", "DL", "BLOCKQUOTE"). </span><span title='(Internet Explorer supports only heading tags H1 - H6, ADDRESS, and PRE, which must also include the tag delimiters &lt; >, such as "&lt;H1>".) +'>(Internet Explorer sólo admite etiquetas de título H1 - H6, dirección y PRE, que también debe incluir los delimitadores de etiquetas <>, como "<H1>".)</span></span></dd> + <dt>forwardDelete</dt> + <dd><span id="result_box" lang="es"><span title="Deletes the character ahead of the cursor's position.">Elimina el </span></span>character <span id="result_box" lang="es"><span title="Deletes the character ahead of the cursor's position.">delante de la posición del cursor</span></span> <a href="http://en.wikipedia.org/wiki/Cursor_%28computers%29" title="Cursor (computers)">cursor</a>. <span id="result_box" lang="es"><span title="It is the same as hitting the delete key. +">Es lo mismo que pulsar la tecla</span></span> suprimir.</dd> + <dt>heading</dt> + <dd><span id="result_box" lang="es"><span title="Adds a heading tag around a selection, or insertion point line.">Añade una etiqueta de encabezado en torno a una selección, o la línea en el punto de inserción. </span><span title='Requires the tag-name string to be passed in as a value argument (ie "H1", "H6").'>Requiere la cadena de nombre de etiqueta que se pasa como un valor de </span></span><span lang="es"><span title='Requires the tag-name string to be passed in as a value argument (ie "H1", "H6").'>argumento (es decir, "H1", "H6"). </span><span title="(Not supported by Internet Explorer and Safari.) +">(No es compatible con Internet Explorer y Safari.)</span></span></dd> + <dt>hiliteColor</dt> + <dd><span id="result_box" lang="es"><span title="Changes the background color for the selection or at the insertion point.">Cambia el color de fondo para la selección o el punto de inserción. </span><span title="Requires a color value string to be passed in as a value argument.">Requiere una cadena de valores de color que se pasa como un valor de </span></span><span lang="es"><span title="Requires a color value string to be passed in as a value argument.">argumento. </span><span title="UseCSS must be turned on for this to function.">UseCSS debe estar encendido para que esto funcione. </span><span title="(Not supported by Internet Explorer.) +">(No es compatible con Internet Explorer.)</span></span></dd> + <dt>increaseFontSize</dt> + <dd><span id="result_box" lang="es"><span title="Adds a BIG tag around the selection or at the insertion point.">Añade una etiqueta BIG alrededor de la selección o en el punto de inserción. </span><span title="(Not supported by Internet Explorer.) +">(No es compatible con Internet Explorer.)</span></span></dd> + <dt>indent</dt> + <dd><span id="result_box" lang="es"><span class="alt-edited hps">Indenta</span> <span class="alt-edited hps">la línea</span> <span class="hps">que contiene el</span> <span class="hps">punto de selección</span> <span class="hps">o inserción</span><span>.</span> <span class="hps">En Firefox</span><span>, si la selección</span> <span class="hps">abarca varias</span> <span class="hps">líneas</span> <span class="hps">en los diferentes niveles</span> <span class="hps">de</span> <span class="alt-edited hps">indentación</span> <span class="hps">serán</span> <span class="alt-edited hps">indentadas</span> <span class="hps">sólo las líneas</span> <span class="hps">menos</span> <span class="alt-edited hps">indentadas</span> <span class="hps">en</span> <span class="hps">la selección.</span></span></dd> + <dt>insertBrOnReturn</dt> + <dd><span id="result_box" lang="es"><span title="Controls whether the Enter key inserts a br tag or splits the current block element into two.">Controla si la tecla Intro inserta una etiqueta br o divide el elemento de bloque actual en dos. </span><span title="(Not supported by Internet Explorer.) +">(No es compatible con Internet Explorer.)</span></span></dd> + <dt>insertHorizontalRule</dt> + <dd><span id="result_box" lang="es"><span title="insertHorizontalRule + "> </span><span title="Inserts a horizontal rule at the insertion point (deletes selection). +">Inserta una regla horizontal en el punto de inserción (borra la selección).</span></span></dd> + <dt>insertHTML</dt> + <dd><span id="result_box" lang="es"><span title="Inserts an HTML string at the insertion point (deletes selection).">Inserta una cadena HTML en el punto de inserción (borra la selección). </span><span title="Requires a valid HTML string to be passed in as a value argument.">Requiere una cadena HTML válido que se ha pasado como un valor de </span></span><span lang="es"><span title="Requires a valid HTML string to be passed in as a value argument.">argumento. </span><span title="(Not supported by Internet Explorer.) +">(No es compatible con Internet Explorer.)</span></span></dd> + <dt>insertImage</dt> + <dd><span id="result_box" lang="es"><span class="hps">Inserta</span> <span class="hps">una imagen</span> <span class="hps">en</span> <span class="hps">el punto de inserción</span> <span class="hps">(borra</span> <span class="hps">la selección</span><span>)</span><span>.</span> <span class="hps">Requiere</span> <span class="hps">la cadena </span></span>de <span lang="es"><span class="hps">imagen</span> <span class="hps">SRC</span> <span class="hps">URI</span> <span class="hps">que se</span> <span class="hps">pasa como</span> <span class="hps">un</span> <span class="hps">argumento de valor</span><span>.</span> <span class="hps">El</span> <span class="hps">URI</span> <span class="hps">debe contener al menos</span> <span class="hps">un solo carácter,</span> <span class="hps">que puede ser un</span> <span class="hps">espacio en blanco.</span> <span class="hps">(Internet Explorer</span> <span class="hps">creará un enlace</span> <span class="hps">con un nulo</span> <span class="hps">valor</span> <span class="hps">URI</span><span>.</span><span>)</span></span></dd> + <dt>insertOrderedList</dt> + <dd><span id="result_box" lang="es"><span title="Creates a numbered ordered list for the selection or at the insertion point. +">Crea una lista ordenada con números para la selección o en el punto de inserción.</span></span></dd> + <dt>insertUnorderedList</dt> + <dd><span id="result_box" lang="es"><span title="Creates a bulleted unordered list for the selection or at the insertion point. +">Crea una lista desordenada con viñetas para la selección o en el punto de inserción.</span></span></dd> + <dt>insertParagraph</dt> + <dd><span id="result_box" lang="es"><span title="insertParagraph + "> </span><span title="Inserts a paragraph around the selection or the current line.">Inserta un párrafo en torno a la selección o la línea actual. </span><span title="(Internet Explorer inserts a paragraph at the insertion point and deletes the selection.) +">(Internet Explorer inserta un párrafo en el punto de inserción y elimina la selección.)</span></span></dd> + <dt>insertText</dt> + <dd><span id="result_box" lang="es"><span title="Inserts the given plain text at the insertion point (deletes selection). +">Inserta el texto plano expedido en el punto de inserción (borra la selección).</span></span></dd> + <dt>italic</dt> + <dd><span id="result_box" lang="es"><span title="Toggles italics on/off for the selection or at the insertion point.">Alterna cursiva para la selección o el punto de inserción. </span><span title="(Internet Explorer uses the EM tag instead of I.) +">(Internet Explorer utiliza la etiqueta de EM en lugar de I.)</span></span></dd> + <dt>justifyCenter</dt> + <dd><span id="result_box" lang="es"><span title="justifyCenter + "> </span><span title="Centers the selection or insertion point. +">Centra el punto de selección o inserción.</span></span></dd> + <dt>justifyFull</dt> + <dd><span id="result_box" lang="es"><span title="Justifies the selection or insertion point. +">Justifica el punto de selección o inserción.</span></span></dd> + <dt>justifyLeft</dt> + <dd><span id="result_box" lang="es"><span title="Justifies the selection or insertion point to the left. +">Justifica la selección o inserción punto a la izquierda.</span></span></dd> + <dt>justifyRight</dt> + <dd><span id="result_box" lang="es"><span title="Right-justifies the selection or the insertion point. +">Justifica la selección o el punto de inserción a la derecha.</span></span></dd> + <dt>outdent</dt> + <dd><span id="result_box" lang="es"><span class="alt-edited hps">Anula la sangría</span> <span class="alt-edited hps">de la línea que contiene</span> <span class="alt-edited hps">la selección</span> <span class="alt-edited hps">o el punto de inserción</span><span>.</span></span></dd> + <dt>paste</dt> + <dd><span id="result_box" lang="es"><span title="Pastes the clipboard contents at the insertion point (replaces current selection).">Pega el contenido del portapapeles en el punto de inserción (reemplaza la selección actual). </span><span title="Clipboard capability must be enabled in the user.js preference file.">Capacidad del Portapapeles debe estar habilitado en el archivo de preferencias user.js. </span><span title="See +">Ver</span></span></dd> + <dt>redo</dt> + <dd><span id="result_box" lang="es"><span title="Redoes the previous undo command. +">Rehace el anterior comando deshecho.</span></span></dd> + <dt>removeFormat</dt> + <dd><span id="result_box" lang="es"><span title="Removes all formatting from the current selection. +">Quita todo el formato de la selección actual.</span></span></dd> + <dt>selectAll</dt> + <dd><span id="result_box" lang="es"><span title="Selects all of the content of the editable region. +">Selecciona todo el contenido de la región editable.</span></span></dd> + <dt>strikeThrough</dt> + <dd><span id="result_box" lang="es"><span title="Toggles strikethrough on/off for the selection or at the insertion point. +">Alterna tachado para la selección o el punto de inserción.</span></span></dd> + <dt>subscript</dt> + <dd><span id="result_box" lang="es"><span title="Toggles subscript on/off for the selection or at the insertion point. +">Alterna subíndice para la selección o el punto de inserción.</span></span></dd> + <dt>superscript</dt> + <dd><span id="result_box" lang="es"><span title="Toggles superscript on/off for the selection or at the insertion point. +">Alterna exponente para la selección o el punto de inserción.</span></span></dd> + <dt>underline</dt> + <dd><span id="result_box" lang="es"><span title="Toggles underline on/off for the selection or at the insertion point. +">Alterna subrayado para la selección o el punto de inserción.</span></span></dd> + <dt>undo</dt> + <dd><span id="result_box" lang="es"><span title="Undoes the last executed command. +">Deshace el último comando ejecutado.</span></span></dd> + <dt>unlink</dt> + <dd><span id="result_box" lang="es"><span title="unlink + "> </span><span title="Removes the anchor tag from a selected anchor link. +">Elimina la etiqueta de ancla de un enlace ancla seleccionado.</span></span></dd> + <dt>useCSS {{ Deprecated_inline() }}</dt> + <dd><span id="result_box" lang="es"><span title="Toggles the use of HTML tags or CSS for the generated markup.">Alterna el uso de etiquetas HTML o CSS para el marcado generado. </span><span title="Requires a boolean true/false as a value argument.">Requiere un booleano verdadero / falso como valor del </span></span><span lang="es"><span title="Requires a boolean true/false as a value argument.">argumento. </span><span title="NOTE: This argument is logically backwards (ie use false to use CSS, true to use HTML).">NOTA: Este argumento es lógicamente hacia atrás (es decir, si se usa falso a usar CSS, entonces es verdadero a usar HTML). </span><span title="(Not supported by Internet Explorer.) This has been deprecated;">(No compatible con Internet Explorer.) Esto ha quedado obsoleto; </span><span title="use the styleWithCSS command instead. +">utilice el comando <em>styleWithCSS</em> en su lugar.</span></span></dd> + <dt>styleWithCSS</dt> + <dd><span id="result_box" lang="es"><span class="hps">Reemplaza</span> <span class="hps">el comando</span> <em><span class="hps">useCSS</span></em><span>;</span> <span class="alt-edited hps">el argumento funciona</span> <span class="alt-edited hps">como se esperaba</span><span>,</span> <span class="hps">es decir,</span> <span class="alt-edited hps">si es verdadero</span> <span class="hps">modifica</span> <span class="hps">/</span> <span class="hps">genera</span> <span class="hps">atributos</span> <span class="hps">de estilo</span> <span class="hps">en el marcado</span><span>,</span> <span class="hps">falso</span> <span class="hps">genera</span> <span class="hps">elementos de formato</span><span>.</span></span></dd> +</dl> + +<h2 id="Example" name="Example"><span id="result_box" lang="es"><span title="Example + +">Ejemplo</span></span></h2> + +<p>(<span id="result_box" lang="es"><span title="(This article is currently incomplete and lacks an example.) +">Este artículo está actualmente incompleto y carece de un ejemplo</span></span>.)</p> + +<h2 id="Browser_Compatibility" name="Browser_Compatibility"><span id="result_box" lang="es"><span title="Browser compatibility + +">Compatibilidad del navegador</span></span></h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th><span id="result_box" lang="es"><span title="Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari +">Característica</span></span></th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td><span id="result_box" lang="es"><span title="Basic support {{ CompatUnknown() }} {{ CompatUnknown() }} {{ CompatVersionUnknown() }} {{ CompatUnknown() }} {{ CompatUnknown() }} {{ CompatUnknown() }}">Soporte básico</span></span></td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + <tr> + <td>insertBrOnReturn</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatVersionUnknown() }}</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><span id="result_box" lang="es"><span title="Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari +">Característica</span></span></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><span id="result_box" lang="es"><span title="Basic support {{ CompatUnknown() }} {{ CompatUnknown() }} {{ CompatVersionUnknown() }} {{ CompatUnknown() }} {{ CompatUnknown() }} {{ CompatUnknown() }}">Soporte básico</span></span></td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + </tr> + </tbody> +</table> + +<p><span id="result_box" lang="es"><span title="See Scribe's "Browser Inconsistencies" documentation for a list of many browser bugs related to document.execCommand. +">Consulte la </span></span><a href="https://github.com/guardian/scribe/blob/master/BROWSERINCONSISTENCIES.md">Scribe's "Browser Inconsistencies" documentation</a><span lang="es"><span title="See Scribe's "Browser Inconsistencies" documentation for a list of many browser bugs related to document.execCommand. +"> para obtener una lista de los muchos errores del navegador relacionadas con</span></span> <code>document.execCommand</code>.</p> +</div> + +<h2 id="Specification" name="Specification"><span id="result_box" lang="es"><span title="Specification +">Especificación</span></span></h2> + +<table class="spectable standard-table"> + <tbody> + <tr> + <th scope="col"><span id="result_box" lang="es"><span title="Specification Status Comment + +">Especificación</span></span></th> + <th scope="col"><span id="result_box" lang="es"><span title="Status">Estado</span></span></th> + <th scope="col"><span id="result_box" lang="es"><span title="Status Comment + +">Comentario</span></span></th> + </tr> + <tr> + <td>{{SpecName('HTML Editing','#execcommand()','execCommand')}}</td> + <td>{{Spec2('HTML Editing')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="See_also" name="See_also"><span id="result_box" lang="es"><span title="See also">Vea también</span></span></h2> + +<ul> + <li>{{domxref("document.contentEditable")}}</li> + <li>{{domxref("document.designMode")}}</li> + <li><a href="/en-US/docs/Rich-Text_Editing_in_Mozilla">Edición de texto enriquecido en Mozilla</a></li> +</ul> diff --git a/files/es/web/api/document/exitfullscreen/index.html b/files/es/web/api/document/exitfullscreen/index.html new file mode 100644 index 0000000000..cd90147d82 --- /dev/null +++ b/files/es/web/api/document/exitfullscreen/index.html @@ -0,0 +1,75 @@ +--- +title: Document.exitFullscreen() +slug: Web/API/Document/exitFullscreen +translation_of: Web/API/Document/exitFullscreen +--- +<div>{{ApiRef("Fullscreen API")}}</div> + +<p><span class="seoSummary">El método <code><strong>exitFullscreen()</strong></code> de {{domxref("Document")}} </span>solicita que el elemento de este documento que se presenta actualmente en modo de pantalla completa se retire del modo de pantalla completa, restaurando el estado anterior de la pantalla. Esto generalmente revierte los efectos de una llamada previa a {{domxref("Element.requestFullscreen()")}}.</p> + +<p>La excepción es si otro elemento ya estaba en modo de pantalla completa cuando el elemento actual se colocó en modo de pantalla completa usando <code>requestFullscreen()</code>. En ese caso, el elemento de pantalla completa anterior se restaura al estado de pantalla completa. En esencia, se mantiene un {{interwiki("wikipedia", "Stack_(abstract_data_type)", "stack")}} de elementos de pantalla completa.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><em>exitPromise</em> = <em>document</em>.exitFullscreen(); +</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<p>Ninguno.</p> + +<h3 id="Valor_de_retorno">Valor de retorno</h3> + +<p>Un {{jsxref("Promise")}} que se resuelve una vez que el {{Glossary("user agent")}} a terminado de salir del modo de pantalla completa. Si se produce un error al intentar salir del modo de pantalla completa, se llama al controlador <code>catch()</code> para la promesa.</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>Este ejemplo hace que el documento actual entre y salga de una presentación a pantalla completa cada vez que se hace clic dentro del botón del mouse.</p> + +<pre class="brush: js">document.onclick = function (event) { + if (document.fullscreenElement) { + document.exitFullscreen() + } else { + document.documentElement.requestFullscreen() + } +};</pre> + +<div class="note"> +<p><strong>Nota:</strong> Para un ejemplo más completo, vea {{SectionOnPage("/en-US/docs/Web/API/Element/requestFullScreen", "Example")}}.</p> +</div> + +<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">Comentarios</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("Fullscreen", "#dom-document-exitfullscreen", "Document.exitFullscreen()")}}</td> + <td>{{Spec2("Fullscreen")}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_del_navegador">Compatibilidad del navegador</h2> + +<div class="hidden">La tabla de compatibilidad en esta página se genera a partir de datos estructurados. Si desea contribuir con los datos, consulte <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> y envíenos un pull request.</div> + +<p>{{Compat("api.Document.exitFullscreen")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Fullscreen_API">Fullscreen API</a></li> + <li><a href="/en-US/docs/Web/API/Fullscreen_API/Guide">Guide to the Fullscreen API</a></li> + <li>{{ domxref("Element.requestFullscreen()") }}</li> + <li>{{ domxref("Document.fullscreenElement") }}</li> + <li>{{ cssxref(":fullscreen") }} and {{cssxref("::backdrop")}}</li> + <li>The {{HTMLElement("iframe")}} {{ HTMLAttrXRef("allowfullscreen", "iframe") }} attribute</li> +</ul> diff --git a/files/es/web/api/document/getelementbyid/index.html b/files/es/web/api/document/getelementbyid/index.html new file mode 100644 index 0000000000..1232df45b4 --- /dev/null +++ b/files/es/web/api/document/getelementbyid/index.html @@ -0,0 +1,200 @@ +--- +title: document.getElementById +slug: Web/API/Document/getElementById +tags: + - API + - DOM + - Documento + - Elementos + - Referencia + - Web + - id + - metodo +translation_of: Web/API/Document/getElementById +--- +<div>{{ ApiRef("DOM") }}</div> + +<div> </div> + +<p>Devuelve una referencia al elemento por su <a href="/en-US/docs/DOM/element.id" title="en-US/docs/DOM/element.id">ID</a>.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="brush: js">elemento = document.getElementById(<em>id</em>); +</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code><strong>id</strong></code></dt> + <dd>Es una cadena sensible a mayúsculas referida al ID único del elemento buscado.</dd> +</dl> + +<h3 id="Valor_Retornado"><strong>Valor Retornado</strong></h3> + +<dl> + <dt><code><strong>element</strong></code></dt> + <dd>Es una referencia a un objeto {{domxref("Element")}}, o <code>null</code> si un elemento con el ID especificado no se encuentra en el documento.</dd> + <dt> + <h2 id="Ejemplo">Ejemplo</h2> + + <h3 id="HTML">HTML</h3> + + <pre class="brush: html"><html> +<head> + <title>Ejemplo getElementById</title> +</head> +<body> + <p id="para">Cualquier texto acá</p> + <button onclick="changeColor('blue');">Azul</button> + <button onclick="changeColor('red');">Rojo</button> +</body> +</html> +</pre> + + <h3 id="JavaScript">JavaScript</h3> + + <pre class="brush: js">function changeColor(newColor) { + var elem = document.getElementById('para'); + elem.style.color = newColor; +} +</pre> + + <h3 id="Resultado">Resultado</h3> + + <p>{{EmbedLiveSample('Ejemplo', 250, 100)}}</p> + </dt> +</dl> + +<h2 id="Notes" name="Notes">Notas</h2> + +<p>Los usuarios nuevos deberían notar que escribir en mayúsculas 'Id' en el nombre de este método <em>debe ser corregida</em> para que el código sea válido - 'getElementByID' no funcionará a pesar de que parezca natural.</p> + +<p>A diferencia de otros métodos similares, getElementById sólo está disponible como un método del objeto global document, y no se encuentra disponible como un método en todos los objetos del DOM. Como los valores ID deben ser únicos a traves del documento, no existe necesidad para versiones "locales" de la función.</p> + +<h2 id="Ejemplo_2">Ejemplo</h2> + +<pre class="brush: html"><!doctype html> +<html> +<head> + <meta charset="UTF-8"> + <title>Documento</title> +</head> +<body> + <div id="parent-id"> + <p>Hola Mundo 1</p> + <p id="test1">Hola Mundo 2</p> + <p>Hola palabra 3</p> + <p>Hola palabra 4</p> + </div> + <script> + var parentDOM = document.getElementById('parent-id'); + var test1=parentDOM.getElementById('test1'); + //lanza error + //Uncaught TypeError: parentDOM.getElementById is not a function + </script> +</body> +</html></pre> + +<p>Si no existe un elemento con la <code>id</code> solicitada, esta función devuelve <code>null</code>. Note que el parámetro <code>id</code> es sensible a mayúsculas, así que <code>document.getElementById("Main")</code> devolverá <code>null</code> dentro del elemento <code><div id="main"></code> porque "M" y "m" son diferentes para los propósitos de este método.</p> + +<p><strong>Elementos que no se encuentren</strong> en el documento no serán buscados por <code>getElementById()</code>. Cuando se cree un elemento y se le asigne un ID, debe insertar el elemento dentro del árbol del documento con {{domxref("Node.insertBefore()")}} u otro método similar antes de que se pueda acceder a el con <code>getElementById()</code>:</p> + +<div id="<strong>m</strong>ain"> +<pre class="brush: js">var element = document.createElement("div"); +element.id = 'testqq'; +var el = document.getElementById('testqq'); // el será null! +</pre> + +<p><strong>Documentos no-HTML</strong>. La implementación de DOM debe tener información que diga que atributos son del tipo ID. Los atributos con el nombre "id" son son del tipo ID a menos que se los defina en el DTD del documento. El atributo <code>id</code> es definido para ser del tipo ID en los casos comunes de <a href="https://developer.mozilla.org/en-US/docs/XHTML">XHTML</a>, <a href="/es/docs/Mozilla/Tech/XUL">XUL</a>, y otros. Las implementaciones que no sepan si los atributos son o no del tipo ID se espera que retornen null.</p> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<table> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Status</th> + <th scope="col">Comentarios</th> + </tr> + <tr> + <td>{{SpecName('DOM1','level-one-html.html#method-getElementById','getElementById')}}</td> + <td>{{Spec2('DOM1')}}</td> + <td>Definición inicial para la interfase</td> + </tr> + <tr> + <td>{{SpecName('DOM2 Core','core.html#ID-getElBId','getElementById')}}</td> + <td>{{Spec2('DOM2 Core')}}</td> + <td>Supersede DOM 1</td> + </tr> + <tr> + <td>{{SpecName('DOM3 Core','core.html#ID-getElBId','getElementById')}}</td> + <td>{{Spec2('DOM3 Core')}}</td> + <td>Supersede DOM 2</td> + </tr> + <tr> + <td>{{SpecName('DOM WHATWG','#interface-nonelementparentnode','getElementById')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Intend to supersede DOM 3</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_Compatibility" name="Browser_Compatibility">Compatibilidad con navegadores</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 (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>1.0</td> + <td>{{ CompatGeckoDesktop(1.0) }}</td> + <td>5.5</td> + <td>7.0</td> + <td>1.0</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 Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>1.0</td> + <td>{{ CompatGeckoMobile(1.0) }}</td> + <td>6.0</td> + <td>6.0</td> + <td>1.0</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also" name="See_also">Ver también</h2> + +<ul> + <li>La referencia <a href="/en-US/docs/DOM/document" title="en-US/docs/DOM/document">document</a> para otros métodos y propiedades que se pueden usar para obtener referencias a elementos en el documento.</li> + <li><a href="/en-US/docs/Web/API/document.querySelector">document.querySelector()</a> para selectores via consultas como <code>'div.myclass'</code></li> + <li><a href="/en-US/docs/xml/xml:id" title="en-US/docs/xml/id">xml:id</a> - tiene un método utilitario para permitir que <code>getElementById()</code> obtenga 'xml:id' en documentos XML documents (como los retornados por llamadas Ajax.</li> +</ul> +</div> diff --git a/files/es/web/api/document/getelementsbyclassname/index.html b/files/es/web/api/document/getelementsbyclassname/index.html new file mode 100644 index 0000000000..b3a7179e4d --- /dev/null +++ b/files/es/web/api/document/getelementsbyclassname/index.html @@ -0,0 +1,96 @@ +--- +title: Document.getElementsByClassName() +slug: Web/API/Document/getElementsByClassName +translation_of: Web/API/Document/getElementsByClassName +--- +<p id="Summary">{{APIRef("DOM")}}</p> + +<p>Retorna un objecto similar a un array de los elementos hijos que tengan todos los nombres de clase indicados. Cuando es llamado sobre el objeto document , la busqueda se realiza en todo el document, incluido el nodo raíz. También puedes llamar {{domxref("Element.getElementsByClassName", "getElementsByClassName()")}} sobre cualquier elemento; en ese caso retornara sólo los elementos hijos del elemento raíz indicado que contengan los nombres de clase indicados.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox"><var>var elementos</var> = document.getElementsByClassName(<em>nombres</em>); // ó : +<var>var elementos</var> = elementoRaiz.getElementsByClassName(<em>nombres</em>);</pre> + +<ul> + <li><var>elementos es una</var> {{ domxref("HTMLCollection") }} de los elementos encontrados.</li> + <li><var>nombres es un string que representa la lista de nombres de clase a buscar; los nombres de clase se separan con un espacio.</var></li> + <li>getElementsByClassName se puede llamar sobre cualquier elemento, no solo sobre document. El elemento sobre el que se llama será usado como la raíz de la busqueda.</li> +</ul> + +<h2 id="Examples" name="Examples">Ejemplos</h2> + +<p>Obtener todos los elementos de la clase 'prueba'</p> + +<pre class="brush: js">document.getElementsByClassName('prueba');</pre> + +<p>Obtener todos los elementos que tengan al mismo tiempo las clases 'rojo' y 'prueba'</p> + +<pre class="brush: js">document.getElementsByClassName('rojo prueba');</pre> + +<p>Obtener todos los elementos que tengan la clase 'prueba' y que estén dentro de un elemento de ID 'principal'</p> + +<pre class="brush: js">document.getElementById('principal').getElementsByClassName('prueba');</pre> + +<p>También podemos usar los metodos de Array.prototype en cualquier {{ domxref("HTMLCollection") }} pasando el <em>HTMLCollection</em> como el valor <em>this</em> del método. Aquí buscaremos todos los elementos div de la clase 'test':</p> + +<pre class="brush: js">var testElements = document.getElementsByClassName('test'); +var testDivs = Array.prototype.filter.call(testElements, function(testElement){ + return testElement.nodeName === 'DIV'; +});</pre> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</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>{{ CompatVersionUnknown() }}</td> + <td>3.0</td> + <td>9.0</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>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Specification" name="Specification">Especifiación</h2> + +<ul> + <li><a href="https://dvcs.w3.org/hg/domcore/raw-file/tip/Overview.html#dom-document-getelementsbyclassname" title="https://dvcs.w3.org/hg/domcore/raw-file/tip/Overview.html#dom-document-getelementsbyclassname"><span class="external">W3C: getElementsByClassName</span></a></li> +</ul> diff --git a/files/es/web/api/document/getelementsbyname/index.html b/files/es/web/api/document/getelementsbyname/index.html new file mode 100644 index 0000000000..50350fe0ec --- /dev/null +++ b/files/es/web/api/document/getelementsbyname/index.html @@ -0,0 +1,81 @@ +--- +title: Document.getElementsByName() +slug: Web/API/Document/getElementsByName +translation_of: Web/API/Document/getElementsByName +--- +<div>{{APIRef("DOM")}}</div> + +<p>Returns a nodelist collection with a given {{domxref("element.name","name")}} in the (X)HTML document.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox"><em>elements</em> = document.getElementsByName(<em>name</em>) +</pre> + +<ul> + <li><code>elements</code> es una colección existente de {{domxref("NodeList")}}</li> + <li><code>name</code> es el valor del atributo <code>name</code> del elemento.</li> +</ul> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre class="brush:html"><!DOCTYPE html> +<html lang="en"> +<head> + ... +</head> + +<body> +<form name="up"><input type="text"></form> +<div name="down"><input type="text"></div> + +<script> +var up_forms = document.getElementsByName("up"); +console.log(up_forms[0].tagName); // returns "FORM" +</script> +</body> +</html> +</pre> + +<h2 id="Notes" name="Notes">Notas</h2> + +<p>El atributo <a href="/en-US/docs/DOM/element.name"><code>name</code></a> es solamente aplicable al documento (X)HTML. El método retorna una colección existente de {{domxref("NodeList")}} que contiene todos los elementos con el valor dado para el atributo <code>name</code>, tanto {{htmlelement("meta")}} o {{htmlelement("object")}} o en caso que <code>name</code> sea colocado en elementos que no soportan un atributo de atributo del todo.</p> + +<p>El método <strong>getElementsByName</strong> trabaja de diferente manera en diferentes navegadires. En IE < 10, el método getElementsByName() tambipen retornará elementos que tienen un atributo <code>id</code> con el valor especificado. Entonces, debería tener cuidado de no usar el mismo string como <code>name</code> y <code>ID</code>.</p> + +<h2 id="Specifications" name="Specifications">Especificaciones</h2> + +<ul> + <li><a href="http://www.w3.org/TR/DOM-Level-2-HTML/">DOM Level 2 HTML: getElementsByName</a></li> + <li><a href="http://www.whatwg.org/html/#dom-document-getelementsbyname" title="http://www.whatwg.org/html/">HTML5: getElementsByName</a></li> +</ul> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificaciones</th> + <th scope="col">estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', '#dom-document-getelementsbyname', "Document.getElementsByName()")}}</td> + <td>{{ Spec2('HTML WHATWG') }}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName("DOM2 HTML", "html.html#ID-71555259", "Document.getElementsByName()")}}</td> + <td>{{Spec2("DOM2 HTML")}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="See_also" name="See_also">Mira también</h2> + +<ul> + <li>{{domxref("document.getElementById()")}} para retornar una referencia de un elemento por su <code>id</code></li> + <li>{{domxref("document.getElementsByTagName()")}} para retornar referencias de elementos por el nombre de sus etiquetas</li> + <li>{{domxref("document.querySelector()")}} for powerful selectors via queries like <code>'div.myclass'</code></li> +</ul> diff --git a/files/es/web/api/document/getelementsbytagname/index.html b/files/es/web/api/document/getelementsbytagname/index.html new file mode 100644 index 0000000000..7be48858c0 --- /dev/null +++ b/files/es/web/api/document/getelementsbytagname/index.html @@ -0,0 +1,104 @@ +--- +title: document.getElementsByTagName +slug: Web/API/Document/getElementsByTagName +tags: + - Referencia_DOM_de_Gecko +translation_of: Web/API/Document/getElementsByTagName +--- +<p>{{ ApiRef("DOM") }}</p> + +<h3 id="Resumen" name="Resumen">Resumen</h3> + +<p>Devuelve una lista de elementos con un nombre determinado. Se busca en todo el documento, incluyendo el nodo raíz.</p> + +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> + +<pre class="eval"><em>elements</em> = document.getElementsByTagName(<em>name</em>) +</pre> + +<ul> + <li><code>elements</code> es una lista 'viva' (<code>NodeList</code>) de los elementos encontrados en el orden en que han aparecido en el árbol.</li> + <li><code>name</code> es una cadena que representa el nombre de los elementos. La cadena especial "*" representa a todos los elementos.</li> +</ul> + +<h3 id="Ejemplo" name="Ejemplo">Ejemplo</h3> + +<p>En el siguiente ejemplo, <code>getElementsByTagName</code> empieza por el elemento padre y busca hacia abajo recurrentemente a lo largo de todo el DOM por ese elemento padre, buscando por hijos que cumplan con el criterio: nombre = <code>name</code>.</p> + +<p>Ten en cuenta que cuando el nodo en el que se invoca <code>getElementsByTagName</code>, no es el nodo <code>document</code>, en realidad se está usando el método <a href="es/DOM/element.getElementsByTagName">element.getElementsByTagName</a>.</p> + +<pre><html> + +<head> +<title>ejemplo de getElementsByTagName</title> + +<script type="text/javascript"> + +function getAllParaElems() +{ + var allParas = document.getElementsByTagName("p"); + + var num = allParas.length; + + alert("Hay " + num + " <p> elementos en este documento"); +} + + +function div1ParaElems() +{ + var div1 = document.getElementById("div1") + var div1Paras = div1.getElementsByTagName("p"); + + var num = div1Paras.length; + + alert("Hay " + num + " <p> elementos en el elemento div1"); +} + + +function div2ParaElems() +{ + var div2 = document.getElementById("div2") + var div2Paras = div2.getElementsByTagName("p"); + + var num = div2Paras.length; + + alert("Hay " + num + " <p> elementos en el elemento div2"); +} + +</script> +</head> + +<body style="border: solid green 3px"> +<p>Algo de texto</p> +<p>Algo de texto</p> + + <div id="div1" style="border: solid blue 3px"> + <p>Algo de texto en div1</p> + <p>Algo de texto en div1</p> + <p>Algo de texto en div1</p> + + <div id="div2" style="border: solid red 3px"> + <p>Algo de texto en div2</p> + <p>Algo de texto en div2</p> + </div> + </div> + +<p>Algo de texto</p> +<p>Algo de texto</p> + +<button onclick="getAllParaElems();"> + muestra todos los elementos p en el documento</button><br /> + +<button onclick="div1ParaElems();"> + muestra todos los elementos p en div1</button><br /> + +<button onclick="div2ParaElems();"> + muestra todos los elementos p en div2</button> + +</body> +</html> +</pre> + +<h3 id="Especificaci.C3.B3n" name="Especificaci.C3.B3n">Especificación</h3> + +<p><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-A6C9094">DOM Level 2 Core: Document.getElementsByTagName</a></p> diff --git a/files/es/web/api/document/getelementsbytagnamens/index.html b/files/es/web/api/document/getelementsbytagnamens/index.html new file mode 100644 index 0000000000..d97657647b --- /dev/null +++ b/files/es/web/api/document/getelementsbytagnamens/index.html @@ -0,0 +1,107 @@ +--- +title: document.getElementsByTagNameNS +slug: Web/API/Document/getElementsByTagNameNS +tags: + - Referencia_DOM_de_Gecko +translation_of: Web/API/Document/getElementsByTagNameNS +--- +<p>{{ ApiRef() }}</p> + +<h3 id="Resumen" name="Resumen">Resumen</h3> + +<p>Devuelve una lista de elementos cuyo nombre pertenece a un determinado 'namespace'. La búsqueda se realiza en todo el documento, incluyendo el elemento raíz.</p> + +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> + +<pre class="eval"><em>elements</em> = document.getElementsByTagNameNS(<em>namespace</em>,<em>name</em>) +</pre> + +<ul> + <li><code>elements</code> es una lista del tipo <code>NodeList</code> de los elementos encontrados, en el orden en el que aparecen en el árbol.</li> + <li><code>namespace</code> es el nombre URI en el que buscamos. (Véase <code><a href="es/DOM/element.namespaceURI">element.namespaceURI</a></code>).</li> + <li><code>name</code> es bien el nombre local por el que buscamos, o bien el valor especial <code>"*"</code>, que representa todos los elementos (véase <code><a href="es/DOM/element.localName">element.localName</a></code>).</li> +</ul> + +<h3 id="Ejemplo" name="Ejemplo">Ejemplo</h3> + +<p>En el siguiente ejemplo, <code>getElementsByTagNameNS</code> comienza por un elemento padre determinado y busca recurrentemente, hacia abajo, por los elementos que tienen el parámetro <code>name</code> que concuerda.</p> + +<p>Es importante tener en cuenta que cuando el nodo en el que se invoca <code>getElementsByTagName</code>, no es el nodo <code>document</code>, en realidad estamos usando el método <a href="es/DOM/element.getElementsByTagNameNS">element.getElementsByTagNameNS</a>.</p> + +<p>Para usar el siguiente ejemplo, copia y pega en un documento con la extensión xhtml.</p> + +<pre><html xmlns="http://www.w3.org/1999/xhtml"> + +<head> +<title>ejemplo de getElementsByTagNameNS</title> + +<script type="text/javascript"> + +function getAllParaElems() +{ + var allParas = document.getElementsByTagNameNS("http://www.w3.org/1999/xhtml", "p"); + + var num = allParas.length; + + alert("Hay " + num + " &lt;p&gt; elementos en este documento"); +} + + +function div1ParaElems() +{ + var div1 = document.getElementById("div1") + var div1Paras = div1.getElementsByTagNameNS("http://www.w3.org/1999/xhtml", "p"); + + var num = div1Paras.length; + + alert("Hay " + num + " &lt;p&gt; elementos en el elemento div1"); +} + + +function div2ParaElems() +{ + var div2 = document.getElementById("div2") + var div2Paras = div2.getElementsByTagNameNS("http://www.w3.org/1999/xhtml", "p"); + + var num = div2Paras.length; + + alert("Hay " + num + " &lt;p&gt; elementos en el elemento div2"); +} + +</script> +</head> + +<body style="border: solid green 3px"> +<p>Algo de texto exterior</p> +<p>Algo de texto exterior</p> + + <div id="div1" style="border: solid blue 3px"> + <p>Algo de texto en div1</p> + <p>Algo de texto en div1</p> + <p>Algo de texto en div1</p> + + <div id="div2" style="border: solid red 3px"> + <p>Algo de texto en div2</p> + <p>Algo de texto en div2</p> + </div> + </div> + +<p>Algo de texto exterior</p> +<p>Algo de texto exterior</p> + +<button onclick="getAllParaElems();"> + muestra todos los elementos p en el documento</button><br /> + +<button onclick="div1ParaElems();"> + muestra todos los elementos p en el div1</button><br /> + +<button onclick="div2ParaElems();"> + muestra todos los elementos p en el div2</button> + +</body> +</html> +</pre> + +<h3 id="Especificaci.C3.B3n" name="Especificaci.C3.B3n">Especificación</h3> + +<p><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-getElBTNNS">DOM Level 2 Core: Document.getElementsByTagNameNS</a></p> diff --git a/files/es/web/api/document/getselection/index.html b/files/es/web/api/document/getselection/index.html new file mode 100644 index 0000000000..494ded4250 --- /dev/null +++ b/files/es/web/api/document/getselection/index.html @@ -0,0 +1,12 @@ +--- +title: Document.getSelection() +slug: Web/API/Document/getSelection +tags: + - Referencia + - Selección + - metodo +translation_of: Web/API/DocumentOrShadowRoot/getSelection +--- +<p>{{APIRef("DOM")}}</p> + +<p>Este método funciona exactamente igual que {{domxref("Window.getSelection()")}}; devuelve un objeto {{domxref("Selection")}} que representa el texto que se ha seleccionado en el documento.</p> diff --git a/files/es/web/api/document/hasfocus/index.html b/files/es/web/api/document/hasfocus/index.html new file mode 100644 index 0000000000..a3f4a7ce9e --- /dev/null +++ b/files/es/web/api/document/hasfocus/index.html @@ -0,0 +1,23 @@ +--- +title: element.hasFocus +slug: Web/API/Document/hasFocus +tags: + - Referencia_DOM_de_Gecko +translation_of: Web/API/Document/hasFocus +--- +<p>{{ ApiRef() }}</p> + +<h3 id="Resumen" name="Resumen">Resumen</h3> + +<p>El atributo <code>hasFocus</code> devuelve <code>true</code> si el foco está en en algún sitio del documento activo. Este atributo es parte de la especificación HTML 5 actualmente en desarrollo.</p> + +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> + +<pre class="eval">focused = element.hasFocus +</pre> + +<h3 id="Ejemplo" name="Ejemplo">Ejemplo</h3> + +<h3 id="Especificaci.C3.B3n" name="Especificaci.C3.B3n">Especificación</h3> + +<p><a class="external" href="http://www.whatwg.org/specs/web-apps/current-work/#focus-management">Focus management </a></p> diff --git a/files/es/web/api/document/head/index.html b/files/es/web/api/document/head/index.html new file mode 100644 index 0000000000..a135b5cf3e --- /dev/null +++ b/files/es/web/api/document/head/index.html @@ -0,0 +1,83 @@ +--- +title: Document.head +slug: Web/API/Document/head +translation_of: Web/API/Document/head +--- +<p>{{APIRef("DOM")}}</p> + +<p>Devuelve el elemento {{HTMLElement("head")}} del documento actual. Si hay más de un elemento <code><head></code>, devuelve el primero de estos.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox"><em>var objRef</em> = document.head; +</pre> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre class="brush: js">// en el HTML: <head id="my-document-head"> +var aHead = document.head; + +alert(aHead.id); // "my-document-head"; + +alert( document.head === document.querySelector("head") ); // true +</pre> + +<h2 id="Example" name="Example">Notas</h2> + +<p><code>document.head</code> is de sólo lectura. Cualquier intento de asignar un valor a esta propiedad fallará silenciosamente o, en caso de que se encuentre en <a href="/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/Strict_mode">Modo estricto de ECMAScript</a> en un navegador Gecko, lanzará un <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError"><code>TypeError</code></a>.</p> + +<h2 id="Browser_Compatibility" name="Browser_Compatibility" style="line-height: 30px; font-size: 2.14285714285714rem;">Compatibilidad con navegadores</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</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>4.0</td> + <td>{{CompatGeckoDesktop("2")}}</td> + <td>9.0</td> + <td>11.0</td> + <td>5.0</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>Soporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("2")}}</td> + <td>9.0</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<ul> + <li><a href="http://www.w3.org/TR/html5/dom.html#dom-tree-accessors" title="http://www.w3.org/TR/html5/dom.html#dom-document-head">HTML5: DOM Tree Accessors</a></li> +</ul> diff --git a/files/es/web/api/document/height/index.html b/files/es/web/api/document/height/index.html new file mode 100644 index 0000000000..1bc2852c58 --- /dev/null +++ b/files/es/web/api/document/height/index.html @@ -0,0 +1,44 @@ +--- +title: Document.height +slug: Web/API/Document/height +translation_of: Web/API/Document/height +--- +<div>{{APIRef("DOM")}} {{Obsolete_header}}</div> + +<div class="note"> +<p><strong>Note:</strong> Comenzando en {{Gecko("6.0")}},<code> document.height </code>no es soportada. En lugar usar <code>document.body.clientHeight</code>. Ver {{domxref("element.clientHeight")}}.</p> +</div> + +<h2 id="Summary">Summary</h2> + +<p>Devuelve la altura del objeto {{domxref("document")}} . En la mayoría de los casos, esto equivale al elemento {{HTMLElement("body")}} del documento actual.</p> + +<h2 id="Syntax" name="Syntax">Syntax</h2> + +<pre class="syntaxbox"><em>height_value</em> = document.height +</pre> + +<h2 id="Example">Example</h2> + +<pre class="brush: js">// alert document height +alert(document.height); +</pre> + +<h2 id="Alternatives">Alternatives</h2> + +<pre class="syntaxbox">document.body.clientHeight +document.documentElement.clientHeight +document.documentElement.scrollHeight +</pre> + +<h2 id="Specification">Specification</h2> + +<p>HTML5</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{domxref("document.width")}}</li> + <li>{{domxref("Element.clientHeight")}}</li> + <li>{{domxref("Element.scrollHeight")}}</li> +</ul> diff --git a/files/es/web/api/document/hidden/index.html b/files/es/web/api/document/hidden/index.html new file mode 100644 index 0000000000..e90970233b --- /dev/null +++ b/files/es/web/api/document/hidden/index.html @@ -0,0 +1,43 @@ +--- +title: Document.hidden +slug: Web/API/Document/hidden +translation_of: Web/API/Document/hidden +--- +<p>{{ ApiRef("DOM") }}</p> + +<p>El <code><strong>Document.hidden</strong></code> Es una propiedad solo de lectura, retorna un valor Booleano que indica si la pagina esta conciderada oculta o no.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var <em>boolean</em> = document.hidden</pre> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush:js;">document.addEventListener("visibilitychange", function() { + console.log( document.hidden ); + // Modify behavior... +}); +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th>Especificacion</th> + <th>Estado</th> + <th>Comentario</th> + </tr> + <tr> + <td>{{SpecName('Page Visibility API','#dom-document-hidden', 'Document.hidden')}}</td> + <td>{{Spec2('Page Visibility API')}}</td> + <td>definicion inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_Navegadores">Compatibilidad con Navegadores</h2> + + + +<p>{{Compat("api.Document.hidden")}}</p> diff --git a/files/es/web/api/document/importnode/index.html b/files/es/web/api/document/importnode/index.html new file mode 100644 index 0000000000..ea34cd33be --- /dev/null +++ b/files/es/web/api/document/importnode/index.html @@ -0,0 +1,84 @@ +--- +title: Document.importNode() +slug: Web/API/Document/importNode +translation_of: Web/API/Document/importNode +--- +<p id="Summary">{{APIRef("DOM")}}</p> + +<p>Crea una copia de un nodo desde un documento externo para ser insertado en el documento actual.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox">var <em>node</em> = <em>document</em>.importNode(<em>externalNode</em>, <em>deep</em>); +</pre> + +<dl> + <dt><code>node</code></dt> + <dd>El nuevo nodo importado al documento actual. El <code><a href="/en-US/docs/DOM/Node.parentNode" title="DOM/Node.parentNode">parentNode</a></code> del nuevo nodo es <code>null</code>, ya que aun no ha sido insertado en el arbol del documento.</dd> + <dt><code>externalNode</code></dt> + <dd>El nodo externo a ser importado</dd> + <dt><code>deep</code></dt> + <dd>Un booleano que indica si los descendientes del nodo deben ser importados también.</dd> +</dl> + +<div class="note"> +<p><strong>Nota:</strong> En la especificación DOM4 (tal y como se ha implementado en Gecko 13.0 {{geckoRelease(13)}}), <code>deep</code> es un argumento opcional. En el caso de ser omitido, adopta el valor de <strong><code>true</code></strong>, por lo que se hace una <em>deep copy</em> por defecto. Para realizar una copia superficial (<em>shallow copy</em>), <em>deep</em> debe ser <strong><code>false</code></strong>.</p> + +<p>Este comportamiento ha cambiado en la ultima especificación, por lo que si se omite el parámetro <em>deep,</em> éste adopta el valor <strong><code>false</code></strong>. Aunque aún es opcional, debería ser siempre provisto por razones de compatibilidad. Con Gecko 28.0 {{geckoRelease(28)}}, la consola advertia a los desarrolladores de no omitir el argumento. Empezando con Gecko 29.0 {{geckoRelease(29)}}), se realiza una copia superficial (<em>shallow copy</em>) por defecto.</p> +</div> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre class="brush: js">var iframe = document.getElementsByTagName("iframe")[0]; +var oldNode = iframe.contentWindow.document.getElementById("myNode"); +var newNode = document.importNode(oldNode, true); +document.getElementById("container").appendChild(newNode); +</pre> + +<h2 id="Notes" name="Notes">Notas</h2> + +<p>El nodo original no se borra del documento. El nodo importado es un clon del original.</p> + +<p> </p> + +<p>Nodes from external documents should be cloned using <a href="/es/docs/Web/API/Document/importNode" title="Crea una copia de un nodo desde un documento externo para ser insertado en el documento actual."><code>document.importNode()</code></a> (or adopted using <a href="/es/docs/Web/API/Document/adoptNode" title="Adopta un nodo extreno. El nodo y sub subnodos son quitados del documento en que se encuentra y su nuevo ownerDocument se cambia por el actual. El nodo puede entoces ser insertado en el documento actual."><code>document.adoptNode()</code></a>) before they can be inserted into the current document. For more on the <a href="/es/docs/Web/API/Node/ownerDocument" title="La propiedad de lectura Nodo.ownerDocument devuelve el objecto Document de más alto nivel/jerarquia para ese nodo."><code>Node.ownerDocument</code></a> issues, see the <a class="external" href="http://www.w3.org/DOM/faq.html#ownerdoc" rel="noopener">W3C DOM FAQ</a>.</p> + +<p>Firefox doesn't currently enforce this rule (it did for a while during the development of Firefox 3, but too many sites break when this rule is enforced). We encourage Web developers to fix their code to follow this rule for improved future compatibility.</p> + +<p> </p> + +<h2 id="Especificaciones">Especificaciones</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("DOM WHATWG", "#dom-document-importnode", "document.importNode()")}}</td> + <td>{{Spec2("DOM WHATWG")}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName("DOM2 Core", "core.html#Core-Document-importNode", "document.importNode()")}}</td> + <td>{{Spec2("DOM2 Core")}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_navegadores">Compatibilidad navegadores</h2> + +<div> + + +<p>{{Compat("api.Document.importNode")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{domxref("document.adoptNode()")}}</li> +</ul> diff --git a/files/es/web/api/document/index.html b/files/es/web/api/document/index.html new file mode 100644 index 0000000000..5b72f5850e --- /dev/null +++ b/files/es/web/api/document/index.html @@ -0,0 +1,390 @@ +--- +title: Documento +slug: Web/API/Document +tags: + - páginas_a_traducir +translation_of: Web/API/Document +--- +<div>{{ ApiRef }}</div> + +<div> </div> + +<p><span class="seoSummary">La interfaz <strong><code>Document</code></strong> representa cualquer página web cargada en el navegador y sirve como punto de entrada al contenido de la página (El árbol <a href="/es/docs/Uso_del_núcleo_del_nivel_1_del_DOM" title="Using_the_W3C_DOM_Level_1_Core">DOM</a>).</span> El DOM incluye elementos como {{HTMLElement("body")}} y {{HTMLElement("table")}}), entre <a href="/es/docs/Web/HTML/Element">muchos otros</a>, y proporciona funcionalidad que es global al documento, como obtener la URL de la página y crear nuevos elementos en el documento.</p> + +<p>{{inheritanceDiagram}}</p> + +<p>La interfaz <code>Document</code> describe los métodos y propiedade comunes para cualquier clase de documento. Dependiento del tipo de documento (ej. <a href="/es/docs/Web/HTML" title="HTML">HTML</a>, <a href="https://developer.mozilla.org/en-US/docs/XML" title="XML">XML</a>, SVG, …), hay disponible una API más extensa: los documentos HTML, que se sirven con el tipo de contenido <code>text/html</code>, también implementan la interfaz {{domxref("HTMLDocument")}}, mientras que los documentos XML y SVG implementan la interfaz {{domxref("XMLDocument")}}.</p> + +<h2 id="Properties" name="Properties">Propiedades</h2> + +<div class="note"> +<p><strong>Nota:</strong> La interfaz <code>Document</code> también hereda de las interfaces {{domxref("Node")}} y {{domxref("EventTarget")}}.</p> +</div> + +<dl> + <dt>{{domxref("Document.all")}} {{Deprecated_inline}} {{non-standard_inline}}</dt> + <dd>Da acceso a todos los elementos del documento. Es una interfaz no estándar y no se debería utilizar.</dd> + <dt>{{domxref("Document.async")}} {{Deprecated_inline}}</dt> + <dd>Se utiliza con {{domxref("document.load")}} para indicar una petición asíncrona.</dd> + <dt>{{domxref("Document.characterSet")}} {{readonlyinline}}</dt> + <dd>Devuelve el juego de caracteres que utiliza el documento.</dd> + <dt>{{domxref("Document.charset")}} {{readonlyinline}} {{Deprecated_inline}}</dt> + <dd>Es un alias de {{domxref("Document.characterSet")}}. Utilice esta propiedad en su lugar.</dd> + <dt>{{domxref("Document.compatMode")}} {{experimental_inline}}</dt> + <dd>Indicates whether the document is rendered in Quirks or Strict mode.</dd> + <dt>{{domxref("Document.contentType")}} {{experimental_inline}}</dt> + <dd>Returns the Content-Type from the MIME Header of the current document.</dd> + <dt>{{domxref("Document.doctype")}}</dt> + <dd>Returns the Document Type Definition (DTD) of the current document.</dd> + <dt>{{domxref("Document.documentElement")}}</dt> + <dd>Returns the Element that is a direct child of the document. For HTML documents, this is normally the HTML element.</dd> + <dt>{{domxref("Document.documentURI")}}</dt> + <dd>Returns the document URL.</dd> + <dt>{{domxref("Document.domConfig")}} {{Deprecated_inline}}</dt> + <dd>Should return a {{domxref("DOMConfiguration")}} object.</dd> + <dt>{{domxref("Document.implementation")}}</dt> + <dd>Returns the DOM implementation associated with the current document.</dd> + <dt>{{domxref("Document.inputEncoding")}} {{Deprecated_inline}}</dt> + <dd>Returns the encoding used when the document was parsed.</dd> + <dt>{{domxref("Document.lastStyleSheetSet")}}</dt> + <dd>Returns the name of the style sheet set that was last enabled. Has the value <code>null</code> until the style sheet is changed by setting the value of {{domxref("Document.selectedStyleSheetSet","selectedStyleSheetSet")}}.</dd> + <dt>{{domxref("Document.mozSyntheticDocument")}} {{non-standard_inline}} {{gecko_minversion_inline("8.0")}}</dt> + <dd><code>true</code> if this document is synthetic, such as a standalone image, video, audio file, or the like.</dd> + <dt>{{domxref("Document.mozFullScreen")}} {{non-standard_inline}} {{gecko_minversion_inline("9.0")}}</dt> + <dd><code>true</code> when the document is in {{domxref("Using_full-screen_mode","full-screen mode")}}.</dd> + <dt>{{domxref("Document.mozFullScreenElement")}} {{non-standard_inline}} {{gecko_minversion_inline("9.0")}}</dt> + <dd>The element that's currently in full screen mode for this document.</dd> + <dt>{{domxref("Document.mozFullScreenEnabled")}} {{non-standard_inline}} {{gecko_minversion_inline("9.0")}}</dt> + <dd><code>true</code> if calling {{domxref("element.mozRequestFullscreen()")}} would succeed in the curent document.</dd> + <dt>{{domxref("Document.pointerLockElement")}} {{experimental_inline}}</dt> + <dd>Returns the element set as the target for mouse events while the pointer is locked. <code>null</code> if lock is pending, pointer is unlocked, or if the target is in another document.</dd> + <dt>{{domxref("Document.preferredStyleSheetSet")}}</dt> + <dd>Returns the preferred style sheet set as specified by the page author.</dd> + <dt>{{domxref("Document.selectedStyleSheetSet")}}</dt> + <dd>Returns which style sheet set is currently in use.</dd> + <dt>{{domxref("Document.styleSheets")}}</dt> + <dd>Returns a list of the style sheet objects on the current document.</dd> + <dt>{{domxref("Document.styleSheetSets")}}</dt> + <dd>Returns a list of the style sheet sets available on the document.</dd> + <dt>{{domxref("Document.xmlEncoding")}} {{Deprecated_inline}}</dt> + <dd>Returns the encoding as determined by the XML declaration.</dd> + <dt>{{domxref("Document.xmlStandalone")}} {{obsolete_inline("10.0")}}</dt> + <dd>Returns <code>true</code> if the XML declaration specifies the document to be standalone (<em>e.g.,</em> An external part of the DTD affects the document's content), else <code>false</code>.</dd> + <dt>{{domxref("Document.xmlVersion")}} {{obsolete_inline("10.0")}}</dt> + <dd>Returns the version number as specified in the XML declaration or <code>"1.0"</code> if the declaration is absent.</dd> +</dl> + +<p>The <code>Document</code> interface is extended with the {{domxref("ParentNode")}} interface:</p> + +<p>{{page("/en-US/docs/Web/API/ParentNode","Properties")}}</p> + +<h3 id="Extension_for_HTML_documents">Extension for HTML documents</h3> + +<p>The <code>Document</code> interface for HTML documents inherit from the {{domxref("HTMLDocument")}} interface or, since HTML5, is extended for such documents:</p> + +<dl> + <dt>{{domxref("Document.activeElement")}}</dt> + <dd>Returns the currently focused element.</dd> + <dt>{{domxref("Document.alinkColor")}} {{Deprecated_inline}}</dt> + <dd>Returns or sets the color of active links in the document body.</dd> + <dt>{{domxref("Document.anchors")}}</dt> + <dd>Returns a list of all of the anchors in the document.</dd> + <dt>{{domxref("Document.applets")}} {{Deprecated_inline}}</dt> + <dd>Returns an ordered list of the applets within a document.</dd> + <dt>{{domxref("Document.bgColor")}} {{Deprecated_inline}}</dt> + <dd>Gets/sets the background color of the current document.</dd> + <dt>{{domxref("Document.body")}}</dt> + <dd>Returns the {{HTMLElement("body")}} element of the current document.</dd> + <dt>{{domxref("Document.cookie")}}</dt> + <dd>Returns a semicolon-separated list of the cookies for that document or sets a single cookie.</dd> + <dt>{{domxref("Document.defaultView")}}</dt> + <dd>Returns a reference to the window object.</dd> + <dt>{{domxref("Document.designMode")}}</dt> + <dd>Gets/sets the ability to edit the whole document.</dd> + <dt>{{domxref("Document.dir")}}</dt> + <dd>Gets/sets directionality (rtl/ltr) of the document.</dd> + <dt>{{domxref("Document.domain")}}</dt> + <dd>Returns the domain of the current document.</dd> + <dt>{{domxref("Document.embeds")}}</dt> + <dd>Returns a list of the embedded {{HTMLElement('embed')}} elements within the current document.</dd> + <dt>{{domxref("Document.fgColor")}} {{Deprecated_inline}}</dt> + <dd>Gets/sets the foreground color, or text color, of the current document.</dd> + <dt>{{domxref("Document.forms")}}</dt> + <dd>Returns a list of the {{HTMLElement("form")}} elements within the current document.</dd> + <dt>{{domxref("Document.head")}}</dt> + <dd>Returns the {{HTMLElement("head")}} element of the current document.</dd> + <dt>{{domxref("Document.height")}} {{non-standard_inline}} {{obsolete_inline}}</dt> + <dd>Gets/sets the height of the current document.</dd> + <dt>{{domxref("Document.images")}}</dt> + <dd>Returns a list of the images in the current document.</dd> + <dt>{{domxref("Document.lastModified")}}</dt> + <dd>Returns the date on which the document was last modified.</dd> + <dt>{{domxref("Document.linkColor")}} {{Deprecated_inline}}</dt> + <dd>Gets/sets the color of hyperlinks in the document.</dd> + <dt>{{domxref("Document.links")}}</dt> + <dd>Returns a list of all the hyperlinks in the document.</dd> + <dt>{{domxref("Document.location")}}</dt> + <dd>Returns the URI of the current document.</dd> + <dt>{{domxref("Document.plugins")}}</dt> + <dd>Returns a list of the available plugins.</dd> + <dt>{{domxref("Document.readyState")}} {{gecko_minversion_inline("1.9.2")}}</dt> + <dd>Returns loading status of the document.</dd> + <dt>{{domxref("Document.referrer")}}</dt> + <dd>Returns the URI of the page that linked to this page.</dd> + <dt>{{domxref("Document.scripts")}}</dt> + <dd>Returns all the {{HTMLElement("script")}} elements on the document.</dd> + <dt>{{domxref("Document.title")}}</dt> + <dd>Returns the title of the current document.</dd> + <dt>{{domxref("Document.URL")}}</dt> + <dd>Returns a string containing the URL of the current document.</dd> + <dt>{{domxref("Document.vlinkColor")}} {{Deprecated_inline}}</dt> + <dd>Gets/sets the color of visited hyperlinks.</dd> + <dt>{{domxref("Document.width")}} {{non-standard_inline}} {{obsolete_inline}}</dt> + <dd>Returns the width of the current document.</dd> +</dl> + +<h3 id="Event_handlers" name="Event_handlers">Event handlers</h3> + +<dl> + <dt>{{domxref("Document.onpointerlockchange")}} {{experimental_inline}}</dt> + <dd>Returns the event handling code for the {{event("pointerlockchange")}} event.</dd> + <dt>{{domxref("Document.onpointerlockerror")}} {{experimental_inline}}</dt> + <dd>Returns the event handling code for the {{event("pointerlockerror")}} event.</dd> + <dt>{{domxref("Document.onreadystatechange")}} {{gecko_minversion_inline("1.9.2")}}</dt> + <dd>Returns the event handling code for the <code>readystatechange</code> event.</dd> +</dl> + +<h2 id="Methods" name="Methods">Methods</h2> + +<div class="note"> +<p><strong>Note:</strong> The <code>Document</code> interface also inherits from the {{domxref("Node")}} and {{domxref("EventTarget")}} interfaces.</p> +</div> + +<dl> + <dt>{{domxref("Document.adoptNode","Document.adoptNode(Node node)")}}</dt> + <dd>Adopt node from an external document.</dd> + <dt>{{domxref("Document.captureEvents","Document.captureEvents(String eventName)")}} {{Deprecated_inline}}</dt> + <dd>See {{domxref("window.captureEvents")}}.</dd> + <dt>{{domxref("Document.caretPositionFromPoint","Document.caretPositionFromPoint(Number x, Number y)")}}</dt> + <dd>Gets a {{domxref("CaretPosition")}} based on two coordinates.</dd> + <dt>{{domxref("Document.createAttribute","Document.createAttribute(String name)")}}</dt> + <dd>Creates a new {{domxref("Attr")}} object and returns it.</dd> + <dt>{{domxref("Document.createAttributeNS","Document.createAttributeNS(String namespace, String name)")}}</dt> + <dd>Creates a new attribute node in a given namespace and returns it.</dd> + <dt>{{domxref("Document.createCDATASection","Document.createCDATASection(String data)")}}</dt> + <dd>Creates a new CDATA node and returns it.</dd> + <dt>{{domxref("Document.createComment","Document.createComment(String comment)")}}</dt> + <dd>Creates a new comment node and returns it.</dd> + <dt>{{domxref("Document.createDocumentFragment()")}}</dt> + <dd>Creates a new document fragment.</dd> + <dt>{{domxref("Document.createElement","Document.createElement(String name)")}}</dt> + <dd>Creates a new element with the given tag name.</dd> + <dt>{{domxref("Document.createElementNS","Document.createElementNS(String namespace, String name)")}}</dt> + <dd>Creates a new element with the given tag name and namespace URI.</dd> + <dt>{{domxref("Document.createEntityReference","Document.createEntityReference(String name)")}} {{obsolete_inline}}</dt> + <dd>Creates a new entity reference object and returns it.</dd> + <dt>{{domxref("Document.createEvent","Document.createEvent(String interface)")}}</dt> + <dd>Creates an event object.</dd> + <dt>{{domxref("Document.createNodeIterator","Document.createNodeIterator(Node root[, Number whatToShow[, NodeFilter filter]])")}}</dt> + <dd>Creates a {{domxref("NodeIterator")}} object.</dd> + <dt>{{domxref("Document.createProcessingInstruction","Document.createProcessingInstruction(String target, String data)")}}</dt> + <dd>Creates a new {{domxref("ProcessingInstruction")}} object.</dd> + <dt>{{domxref("Document.createRange()")}}</dt> + <dd>Creates a {{domxref("Range")}} object.</dd> + <dt>{{domxref("Document.createTextNode","Document.createTextNode(String text)")}}</dt> + <dd>Creates a text node.</dd> + <dt>{{domxref("Document.createTreeWalker","Document.createTreeWalker(Node root[, Number whatToShow[, NodeFilter filter]])")}}</dt> + <dd>Creates a {{domxref("TreeWalker")}} object.</dd> + <dt>{{domxref("Document.elementFromPoint","Document.elementFromPoint(Number x, Number y)")}}</dt> + <dd>Returns the element visible at the specified coordinates.</dd> + <dt>{{domxref("Document.enableStyleSheetsForSet","Document.enableStyleSheetsForSet(String name)")}}</dt> + <dd>Enables the style sheets for the specified style sheet set.</dd> + <dt>{{domxref("Document.exitPointerLock()")}} {{experimental_inline}}</dt> + <dd>Release the pointer lock.</dd> + <dt>{{domxref("Document.getElementsByClassName","Document.getElementsByClassName(String className)")}}</dt> + <dd>Returns a list of elements with the given class name.</dd> + <dt>{{domxref("Document.getElementsByTagName","Document.getElementsByTagName(String tagName)")}}</dt> + <dd>Returns a list of elements with the given tag name.</dd> + <dt>{{domxref("Document.getElementsByTagNameNS","Document.getElementsByTagNameNS(String namespace, String tagName)")}}</dt> + <dd>Returns a list of elements with the given tag name and namespace.</dd> + <dt>{{domxref("Document.importNode","Document.importNode(Node node, Boolean deep)")}}</dt> + <dd>Returns a clone of a node from an external document.</dd> + <dt>{{domxref("document.mozSetImageElement")}} {{non-standard_inline}} {{gecko_minversion_inline("2.0")}}</dt> + <dd>Allows you to change the element being used as the background image for a specified element ID.</dd> + <dt>{{domxref("Document.normalizeDocument()")}} {{obsolete_inline}}</dt> + <dd>Replaces entities, normalizes text nodes, etc.</dd> + <dt>{{domxref("Document.releaseCapture()")}} {{non-standard_inline}} {{gecko_minversion_inline("2.0")}}</dt> + <dd>Releases the current mouse capture if it's on an element in this document.</dd> + <dt>{{domxref("Document.releaseEvents")}} {{non-standard_inline}} {{Deprecated_inline}}</dt> + <dd>See {{domxref("window.releaseEvents")}}.</dd> + <dt>{{domxref("document.routeEvent")}} {{non-standard_inline}} {{obsolete_inline(24)}}</dt> + <dd>See {{domxref("window.routeEvent")}}.</dd> +</dl> + +<p>The <code>Document</code> interface is extended with the {{domxref("ParentNode")}} interface:</p> + +<dl> + <dt>{{domxref("Document.getElementById","Document.getElementById(String id)")}}</dt> + <dd>Returns an object reference to the identified element.</dd> + <dt>{{domxref("Document.querySelector","Document.querySelector(String selector)")}} {{gecko_minversion_inline("1.9.1")}}</dt> + <dd>Returns the first Element node within the document, in document order, that matches the specified selectors.</dd> + <dt>{{domxref("Document.querySelectorAll","Document.querySelectorAll(String selector)")}} {{gecko_minversion_inline("1.9.1")}}</dt> + <dd>Returns a list of all the Element nodes within the document that match the specified selectors.</dd> +</dl> + +<p>The <code>Document</code> interface is extended with the {{domxref("XPathEvaluator")}} interface:</p> + +<dl> + <dt>{{domxref("Document.createExpression","Document.createExpression(String expression, XPathNSResolver resolver)")}}</dt> + <dd>Compiles an <code><a href="/en-US/docs/XPathExpression" title="XPathExpression">XPathExpression</a></code> which can then be used for (repeated) evaluations.</dd> + <dt>{{domxref("Document.createNSResolver","Document.createNSResolver(Node resolver)")}}</dt> + <dd>Creates an {{domxref("XPathNSResolver")}} object.</dd> + <dt>{{domxref("Document.evaluate","Document.evaluate(String expression, Node contextNode, XPathNSResolver resolver, Number type, Object result)")}}</dt> + <dd>Evaluates an XPath expression.</dd> +</dl> + +<h3 id="Extension_for_HTML_documents_2">Extension for HTML documents</h3> + +<p>The <code>Document</code> interface for HTML documents inherit from the {{domxref("HTMLDocument")}} interface or, since HTML5, is extended for such documents:</p> + +<dl> + <dt>{{domxref("Document.clear()")}} {{non-standard_inline}} {{Deprecated_inline}}</dt> + <dd>In majority of modern browsers, including recent versions of Firefox and Internet Explorer, this method does nothing.</dd> + <dt>{{domxref("Document.close()")}}</dt> + <dd>Closes a document stream for writing.</dd> + <dt>{{domxref("Document.execCommand","Document.execCommand(String command[, Boolean showUI[, String value]])")}}</dt> + <dd>On an editable document, executes a formating command.</dd> + <dt>{{domxref("Document.getElementsByName","Document.getElementsByName(String name)")}}</dt> + <dd>Returns a list of elements with the given name.</dd> + <dt>{{domxref("Document.getSelection()")}}</dt> + <dd>Returns a {{domxref("Selection")}} object related to text selected in the document.</dd> + <dt>{{domxref("Document.hasFocus()")}}</dt> + <dd>Returns <code>true</code> if the focus is currently located anywhere inside the specified document.</dd> + <dt>{{domxref("Document.open()")}}</dt> + <dd>Opens a document stream for writing.</dd> + <dt>{{domxref("Document.queryCommandEnabled","Document.queryCommandEnabled(String command)")}}</dt> + <dd>Returns true if the formating command can be executed on the current range.</dd> + <dt>{{domxref("Document.queryCommandIndeterm","Document.queryCommandIndeterm(String command)")}}</dt> + <dd>Returns true if the formating command is in an indeterminate state on the current range.</dd> + <dt>{{domxref("Document.queryCommandState","Document.queryCommandState(String command)")}}</dt> + <dd>Returns true if the formating command has been executed on the current range.</dd> + <dt>{{domxref("Document.queryCommandSupported","Document.queryCommandSupported(String command)")}}</dt> + <dd>Returns true if the formating command is supported on the current range.</dd> + <dt>{{domxref("Document.queryCommandValue","Document.queryCommandValue(String command)")}}</dt> + <dd>Returns the current value of the current range for a formatting command.</dd> + <dt>{{domxref("Document.registerElement","Document.registerElement(String tagname[, Object options])")}}</dt> + <dd>Registers a new custom element in the browser and returns a constructor for the new element.</dd> + <dt>{{domxref("Document.write","Document.write(String text)")}}</dt> + <dd>Writes text in a document.</dd> + <dt>{{domxref("Document.writeln","Document.writeln(String text)")}}</dt> + <dd>Writes a line of text in a document.</dd> +</dl> + +<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('DOM1','#i-Document','Document')}}</td> + <td>{{Spec2('DOM1')}}</td> + <td>Initial definition for the interface</td> + </tr> + <tr> + <td>{{SpecName('DOM2 Core','#i-Document','Document')}}</td> + <td>{{Spec2('DOM2 Core')}}</td> + <td>Supersede DOM 1</td> + </tr> + <tr> + <td>{{SpecName('DOM3 Core','#i-Document','Document')}}</td> + <td>{{Spec2('DOM3 Core')}}</td> + <td>Supersede DOM 2</td> + </tr> + <tr> + <td>{{SpecName('DOM WHATWG','#interface-document','Document')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Intend to supersede DOM 3</td> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG','dom.html#the-document-object','Document')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>Turn the {{domxref("HTMLDocument")}} interface into a <code>Document</code> extension.</td> + </tr> + <tr> + <td>{{SpecName('DOM3 XPath','xpath.html#XPathEvaluator','XPathEvaluator')}}</td> + <td>{{Spec2('DOM3 XPath')}}</td> + <td>Define the {{domxref("XPathEvaluator")}} interface which extend <code>Document</code>.</td> + </tr> + <tr> + <td>{{SpecName('HTML Editing','#dom-document-getselection','Document')}}</td> + <td>{{Spec2('HTML Editing')}}</td> + <td>Extend the <code>Document</code> interface</td> + </tr> + <tr> + <td>{{SpecName('CSSOM View','#extensions-to-the-document-interface','Document')}}</td> + <td>{{Spec2('CSSOM View')}}</td> + <td>Extend the <code>Document</code> interface</td> + </tr> + <tr> + <td>{{SpecName('CSSOM','#extensions-to-the-document-interface','Document')}}</td> + <td>{{Spec2('CSSOM')}}</td> + <td>Extend the <code>Document</code> interface</td> + </tr> + <tr> + <td>{{SpecName('Pointer Lock','#extensions-to-the-document-interface','Document')}}</td> + <td>{{Spec2('Pointer Lock')}}</td> + <td>Extend the <code>Document</code> interface</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<h3 id="Firefox_notes">Firefox notes</h3> + +<p>Mozilla defines a set of non-standard properties made only for XUL content:</p> + +<dl> + <dt>{{domxref("document.currentScript")}} {{gecko_minversion_inline("2.0")}}</dt> + <dd>Returns the {{HTMLElement("script")}} element that is currently executing.</dd> + <dt>{{domxref("document.documentURIObject")}} {{gecko_minversion_inline("1.9")}}</dt> + <dd>(<strong>Mozilla add-ons only!</strong>) Returns the {{Interface("nsIURI")}} object representing the URI of the document. This property only has special meaning in privileged JavaScript code (with UniversalXPConnect privileges).</dd> + <dt>{{domxref("document.popupNode")}}</dt> + <dd>Returns the node upon which a popup was invoked.</dd> + <dt>{{domxref("document.tooltipNode")}}</dt> + <dd>Returns the node which is the target of the current tooltip.</dd> +</dl> + +<p>Mozilla also define some non-standard methods:</p> + +<dl> + <dt>{{domxref("Document.execCommandShowHelp")}} {{obsolete_inline("14.0")}}</dt> + <dd>This method never did anything and always threw an exception, so it was removed in Gecko 14.0 {{geckoRelease("14.0")}}.</dd> + <dt>{{domxref("Document.getBoxObjectFor")}} {{obsolete_inline}}</dt> + <dd>Use the {{domxref("Element.getBoundingClientRect()")}} method instead.</dd> + <dt>{{domxref("Document.loadOverlay")}} {{Fx_minversion_inline("1.5")}}</dt> + <dd>Loads a <a href="/en-US/docs/XUL_Overlays" title="XUL_Overlays">XUL overlay</a> dynamically. This only works in XUL documents.</dd> + <dt>{{domxref("document.queryCommandText")}} {{obsolete_inline("14.0")}}</dt> + <dd>This method never did anything but throw an exception, and was removed in Gecko 14.0 {{geckoRelease("14.0")}}.</dd> +</dl> + +<h3 id="Internet_Explorer_notes">Internet Explorer notes</h3> + +<p>Microsoft defines some non-standard properties:</p> + +<dl> + <dt>{{domxref("document.fileSize")}}* {{non-standard_inline}} {{obsolete_inline}}</dt> + <dd>Returns size in bytes of the document. Starting with Internet Explorer 11, that property is no longer supported. See <a href="http://msdn.microsoft.com/en-us/library/ms533752%28v=VS.85%29.aspx" title="http://msdn.microsoft.com/en-us/library/ms533752%28v=VS.85%29.aspx">MSDN</a>.</dd> + <dt><span style="font-weight: normal; line-height: 1.5;">Internet Explorer does not support all methods from the <code>Node</code> interface in the <code>Document</code> interface:</span></dt> +</dl> + +<dl> + <dt>{{domxref("document.contains")}}</dt> + <dd>As a work-around, <code>document.body.contains()</code> can be used.</dd> +</dl> + +<p> </p> diff --git a/files/es/web/api/document/keydown_event/index.html b/files/es/web/api/document/keydown_event/index.html new file mode 100644 index 0000000000..57dc4336a5 --- /dev/null +++ b/files/es/web/api/document/keydown_event/index.html @@ -0,0 +1,178 @@ +--- +title: keydown +slug: Web/API/Document/keydown_event +tags: + - Evento + - keydown +translation_of: Web/API/Document/keydown_event +--- +<p>El evento <code>keydown</code> se produce cuando se presiona una tecla.</p> + +<p>A diferencia del evento <code><a href="/en-US/docs/Web/Events/keypress">keypress</a></code>, el evento <code>keydown</code> es producido por todas las teclas, independientemente de si estas son caracteres o no.</p> + +<h2 id="Información_general">Información general</h2> + +<dl> + <dt style="float: left; text-align: right; width: 120px;">Especificación</dt> + <dd style="margin: 0 0 0 120px;"><a class="external" href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-keydown">DOM L3</a></dd> + <dt style="float: left; text-align: right; width: 120px;">Interfaz</dt> + <dd style="margin: 0 0 0 120px;"><a href="/en-US/docs/DOM/KeyboardEvent" title="/en-US/docs/DOM/KeyboardEvent">KeyboardEvent</a></dd> + <dt style="float: left; text-align: right; width: 120px;">Burbuja</dt> + <dd style="margin: 0 0 0 120px;">Si</dd> + <dt style="float: left; text-align: right; width: 120px;">Cancelable</dt> + <dd style="margin: 0 0 0 120px;">Si</dd> + <dt style="float: left; text-align: right; width: 120px;">Objetivo</dt> + <dd style="margin: 0 0 0 120px;">Document, Element</dd> + <dt style="float: left; text-align: right; width: 120px;">Acción</dt> + <dd style="margin: 0 0 0 120px;">Varía: evento <code>keypress</code>; lanza el sistema de composición de texto; eventos <code>blur</code> y <code>focus</code>; <code>DOMActivate</code> evento; otro evento</dd> +</dl> + +<h2 id="Propiedades">Propiedades</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>EventTarget</td> + <td>The event target (the topmost target in the DOM tree).</td> + </tr> + <tr> + <td><code>type</code> {{readonlyInline}}</td> + <td>DOMString</td> + <td>The type of event.</td> + </tr> + <tr> + <td><code>bubbles</code> {{readonlyInline}}</td> + <td>Boolean</td> + <td>Whether the event normally bubbles or not</td> + </tr> + <tr> + <td><code>cancelable</code> {{readonlyInline}}</td> + <td>Boolean</td> + <td>Whether the event is cancellable or not?</td> + </tr> + <tr> + <td><code>view</code> {{readonlyInline}}</td> + <td>WindowProxy</td> + <td><a href="/en-US/docs/Web/API/Document/defaultView" title="In browsers, document.defaultView returns the window object associated with a document, or null if none is available."><code>document.defaultView</code></a> (<code>window</code> of the document)</td> + </tr> + <tr> + <td><code>detail</code> {{readonlyInline}}</td> + <td><code>long</code> (<code>float</code>)</td> + <td>0.</td> + </tr> + <tr> + <td><code>target</code> {{readonlyInline}}</td> + <td>EventTarget (DOM element)</td> + <td>Focused element processing the key event, root element if no suitable input element focused.</td> + </tr> + <tr> + <td><code>char</code> {{readonlyInline}}</td> + <td>DOMString (string)</td> + <td>The character value of the key. If the key corresponds to a printable character, this value is a non-empty Unicode string containing that character. If the key doesn't have a printable representation, this is an empty string. See <a href="/en-US/docs/Web/API/KeyboardEvent#Key_names_and_Char_values">key names and char values</a> for the detail. + <div class="note"><strong>Note:</strong> If the key is used as a macro that inserts multiple characters, this attribute's value is the entire string, not just the first character.</div> + </td> + </tr> + <tr> + <td><code>key</code> {{readonlyInline}}</td> + <td>DOMString (string)</td> + <td>The key value of the key represented by the event. If the value has a printed representation, this attribute's value is the same as the <code>char</code> attribute. Otherwise, it's one of the key value strings specified in {{ anch("Key values") }}. If the key can't be identified, this is the string "Unidentified". See <a href="/en-US/docs/Web/API/KeyboardEvent#Key_names_and_Char_values">key names and char values</a> for the detail. Read Only.</td> + </tr> + <tr> + <td><code>charCode</code> {{readonlyInline}}</td> + <td>Unsigned long (int)</td> + <td>The Unicode reference number of the key; this attribute is used only by the <a href="/en-US/docs/Mozilla_event_reference/keypress"><code>keypress</code></a> event. For keys whose <code>char</code> attribute contains multiple characters, this is the Unicode value of the first character in that attribute. + <div class="warning"><strong>Warning:</strong> This attribute is deprecated; you should use <code>char</code> instead, if available.</div> + </td> + </tr> + <tr> + <td><code>keyCode</code> {{readonlyInline}}</td> + <td>Unsigned long (int)</td> + <td>A system and implementation dependent numerical code identifying the unmodified value of the pressed key. This is usually the decimal ASCII ({{ RFC(20) }}) or Windows 1252 code corresponding to the key; see {{ anch("Virtual key codes") }} for a list of common values. If the key can't be identified, this value is 0. + <div class="warning"><strong>Warning:</strong> This attribute is deprecated; you should use <code>key</code> instead, if available.</div> + </td> + </tr> + <tr> + <td><code>which</code> {{readonlyInline}}</td> + <td>Unsigned long (int)</td> + <td>A system and implementation dependent numeric code identifying the unmodified value of the pressed key; this is usually the same as <code>keyCode</code>. + <div class="warning"><strong>Warning:</strong> This attribute is deprecated; you should use <code>key</code> instead, if available.</div> + </td> + </tr> + <tr> + <td><code>location</code> {{readonlyInline}}</td> + <td>long (float)</td> + <td>The location of the key on the device.</td> + </tr> + <tr> + <td><code>repeat</code> {{readonlyInline}}</td> + <td>boolean</td> + <td><code>true</code> if a key has been depressed long enough to trigger key repetition, otherwise <code>false</code>.</td> + </tr> + <tr> + <td><code>locale</code> {{readonlyInline}}</td> + <td>string</td> + <td>The language code for the key event, if available; otherwise, the empty string.</td> + </tr> + <tr> + <td><code>ctrlKey</code> {{readonlyInline}}</td> + <td>boolean</td> + <td><code>true</code> if the control key was down when the event was fired. <code>false</code> otherwise.</td> + </tr> + <tr> + <td><code>shiftKey</code> {{readonlyInline}}</td> + <td>boolean</td> + <td><code>true</code> if the shift key was down when the event was fired. <code>false</code> otherwise.</td> + </tr> + <tr> + <td><code>altKey</code> {{readonlyInline}}</td> + <td>boolean</td> + <td><code>true</code> if the alt key was down when the event was fired. <code>false</code> otherwise.</td> + </tr> + <tr> + <td><code>metaKey</code> {{readonlyInline}}</td> + <td>boolean</td> + <td><code>true</code> if the meta key was down when the event was fired. <code>false</code> otherwise.</td> + </tr> + </tbody> +</table> + +<h2 id="preventDefault_del_evento_keydown"><code>preventDefault()</code> del evento <code>keydown</code></h2> + +<p>Empezando desde Gecko 25, una llamada a <code>preventDefault()</code> del evento <code>keydown</code> impide la emisión del consiguiente evento <code>keypress</code>. Este es un comportamiento válido para la especificación D3E y otros navegadores importantes que se comportan de esta misma forma. Por otro lado, Gecko 24 y anteriores emiten el evento <code>keypress</code> aunque se haya llamado a <code>preventDefault()</code> del evento <code>keydown</code> predecesor. Aunque el atributo <code>defaultPrevented</code> del evento <code>keypress</code> sea <code>true</code> en este caso.</p> + +<h2 id="Eventos_relacionados">Eventos relacionados</h2> + +<ul> + <li>{{event("keydown")}}</li> + <li>{{event("keyup")}}</li> + <li>{{event("keypress")}}</li> + <li>{{event("input")}}</li> +</ul> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre><!DOCTYPE html> +<html> +<head> +<script> + +'use strict'; + +document.addEventListener('keydown', (event) => { + const keyName = event.key; + alert('keydown event\n\n' + 'key: ' + keyName); +}); + +</script> +</head> +<body> +</body> +</html></pre> diff --git a/files/es/web/api/document/keyup_event/index.html b/files/es/web/api/document/keyup_event/index.html new file mode 100644 index 0000000000..350629e9ab --- /dev/null +++ b/files/es/web/api/document/keyup_event/index.html @@ -0,0 +1,149 @@ +--- +title: Tecla Arriba +slug: Web/API/Document/keyup_event +translation_of: Web/API/Document/keyup_event +--- +<p>El evento es iniciado cuando la tecla es soltada.</p> + +<h2 id="Información_General">Información General</h2> + +<dl> + <dt style="float: left; text-align: right; width: 120px;">Specification</dt> + <dd style="margin: 0 0 0 120px;"><a class="external" href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-keyup">DOM L3</a></dd> + <dt style="float: left; text-align: right; width: 120px;">Interface</dt> + <dd style="margin: 0 0 0 120px;"><a href="http://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent" title="http://en-US/docs/DOM/KeyboardEvent">KeyboardEvent</a></dd> + <dt style="float: left; text-align: right; width: 120px;">Bubbles</dt> + <dd style="margin: 0 0 0 120px;">Si</dd> + <dt style="float: left; text-align: right; width: 120px;">Cancelable</dt> + <dd style="margin: 0 0 0 120px;">Si</dd> + <dt style="float: left; text-align: right; width: 120px;">Target</dt> + <dd style="margin: 0 0 0 120px;">Document, Element</dd> + <dt style="float: left; text-align: right; width: 120px;">Default Action</dt> + <dd style="margin: 0 0 0 120px;">Ninguna</dd> +</dl> + +<h2 id="Propiedades">Propiedades</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>EventTarget</td> + <td>The event target (the topmost target in the DOM tree).</td> + </tr> + <tr> + <td><code>type</code> {{readonlyInline}}</td> + <td>DOMString</td> + <td>The type of event.</td> + </tr> + <tr> + <td><code>bubbles</code> {{readonlyInline}}</td> + <td>Boolean</td> + <td>Whether the event normally bubbles or not</td> + </tr> + <tr> + <td><code>cancelable</code> {{readonlyInline}}</td> + <td>Boolean</td> + <td>Whether the event is cancellable or not?</td> + </tr> + <tr> + <td><code>view</code> {{readonlyInline}}</td> + <td>WindowProxy</td> + <td><a href="/en-US/docs/Web/API/Document/defaultView" title="In browsers, document.defaultView returns the window object associated with a document, or null if none is available."><code>document.defaultView</code></a> (<code>window</code> of the document)</td> + </tr> + <tr> + <td><code>detail</code> {{readonlyInline}}</td> + <td><code>long</code> (<code>float</code>)</td> + <td>0.</td> + </tr> + <tr> + <td><code>target</code> {{readonlyInline}}</td> + <td>EventTarget (DOM element)</td> + <td>Focused element processing the key event, root element if no suitable input element focused.</td> + </tr> + <tr> + <td><code>char</code> {{readonlyInline}}</td> + <td>DOMString (string)</td> + <td>The character value of the key. If the key corresponds to a printable character, this value is a non-empty Unicode string containing that character. If the key doesn't have a printable representation, this is an empty string. See <a href="/en-US/docs/Web/API/KeyboardEvent#Key_names_and_Char_values">key names and char values</a> for the detail. + <div class="note"><strong>Note:</strong> If the key is used as a macro that inserts multiple characters, this attribute's value is the entire string, not just the first character.</div> + </td> + </tr> + <tr> + <td><code>key</code> {{readonlyInline}}</td> + <td>DOMString (string)</td> + <td>The key value of the key represented by the event. If the value has a printed representation, this attribute's value is the same as the <code>char</code> attribute. Otherwise, it's one of the key value strings specified in {{ anch("Key values") }}. If the key can't be identified, this is the string "Unidentified". See <a href="/en-US/docs/Web/API/KeyboardEvent#Key_names_and_Char_values">key names and char values</a> for the detail. Read Only.</td> + </tr> + <tr> + <td><code>charCode</code> {{readonlyInline}}</td> + <td>Unsigned long (int)</td> + <td>The Unicode reference number of the key; this attribute is used only by the <a href="/en-US/docs/Mozilla_event_reference/keypress"><code>keypress</code></a> event. For keys whose <code>char</code> attribute contains multiple characters, this is the Unicode value of the first character in that attribute. + <div class="warning"><strong>Warning:</strong> This attribute is deprecated; you should use <code>char</code> instead, if available.</div> + </td> + </tr> + <tr> + <td><code>keyCode</code> {{readonlyInline}}</td> + <td>Unsigned long (int)</td> + <td>A system and implementation dependent numerical code identifying the unmodified value of the pressed key. This is usually the decimal ASCII ({{ RFC(20) }}) or Windows 1252 code corresponding to the key; see {{ anch("Virtual key codes") }} for a list of common values. If the key can't be identified, this value is 0. + <div class="warning"><strong>Warning:</strong> This attribute is deprecated; you should use <code>key</code> instead, if available.</div> + </td> + </tr> + <tr> + <td><code>which</code> {{readonlyInline}}</td> + <td>Unsigned long (int)</td> + <td>A system and implementation dependent numeric code identifying the unmodified value of the pressed key; this is usually the same as <code>keyCode</code>. + <div class="warning"><strong>Warning:</strong> This attribute is deprecated; you should use <code>key</code> instead, if available.</div> + </td> + </tr> + <tr> + <td><code>location</code> {{readonlyInline}}</td> + <td>long (float)</td> + <td>The location of the key on the device.</td> + </tr> + <tr> + <td><code>repeat</code> {{readonlyInline}}</td> + <td>boolean</td> + <td><code>true</code> if a key has been depressed long enough to trigger key repetition, otherwise <code>false</code>.</td> + </tr> + <tr> + <td><code>locale</code> {{readonlyInline}}</td> + <td>string</td> + <td>The language code for the key event, if available; otherwise, the empty string.</td> + </tr> + <tr> + <td><code>ctrlKey</code> {{readonlyInline}}</td> + <td>boolean</td> + <td><code>true</code> if the control key was down when the event was fired. <code>false</code> otherwise.</td> + </tr> + <tr> + <td><code>shiftKey</code> {{readonlyInline}}</td> + <td>boolean</td> + <td><code>true</code> if the shift key was down when the event was fired. <code>false</code> otherwise.</td> + </tr> + <tr> + <td><code>altKey</code> {{readonlyInline}}</td> + <td>boolean</td> + <td><code>true</code> if the alt key was down when the event was fired. <code>false</code> otherwise.</td> + </tr> + <tr> + <td><code>metaKey</code> {{readonlyInline}}</td> + <td>boolean</td> + <td><code>true</code> if the meta key was down when the event was fired. <code>false</code> otherwise.</td> + </tr> + </tbody> +</table> + +<h2 id="Eventos_Relacionados">Eventos Relacionados</h2> + +<ul> + <li>{{event("keydown")}}</li> + <li>{{event("keyup")}}</li> + <li>{{event("keypress")}}</li> + <li>{{event("input")}}</li> +</ul> diff --git a/files/es/web/api/document/pointerlockelement/index.html b/files/es/web/api/document/pointerlockelement/index.html new file mode 100644 index 0000000000..cc5d490e5c --- /dev/null +++ b/files/es/web/api/document/pointerlockelement/index.html @@ -0,0 +1,105 @@ +--- +title: Document.pointerLockElement +slug: Web/API/Document/pointerLockElement +translation_of: Web/API/DocumentOrShadowRoot/pointerLockElement +--- +<div>{{APIRef("DOM")}}</div> + +<p>La propiedad <code>pointerLockElement</code> conserva el elemento adquirido, para el evento del mouse, mientras el bloqueo se encuentre activo . Es <code>null</code> si el bloqueo se encuentra en estado pendiente para bloqueo, o si el bloqueo se ha liberado, es decir ya no se encuentra en estado bloqueado, o si el elemento bloqueado se encuentra en otro documento.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var elemento = document.pointerLockElement; +</pre> + +<h3 id="Valor_retornado">Valor retornado</h3> + +<p>Un {{domxref("Element")}} o <code>null</code>.</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('Bloquear puntero','l#extension-to-the-document-interface','Document')}}</td> + <td>{{Spec2('Pointer lock')}}</td> + <td>Extiende de la interfaz <code>Document</code></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">Compatibilidad del Navegador</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>{{ CompatVersionUnknown() }} {{property_prefix("webkit")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{ CompatVersionUnknown() }} {{property_prefix("moz")}}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + </tr> + <tr> + <td>Soporte sin prefijar</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop(50)}}</td> + <td> </td> + <td> </td> + <td> </td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>{{ CompatUnknown() }}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Véase_también">Véase también:</h2> + +<ul> + <li>{{ domxref("Document.exitPointerLock()") }}</li> + <li>{{ domxref("Element.requestPointerLock()") }}</li> + <li><a href="/en-US/docs/WebAPI/Pointer_Lock">Pointer Lock</a></li> +</ul> diff --git a/files/es/web/api/document/queryselector/index.html b/files/es/web/api/document/queryselector/index.html new file mode 100644 index 0000000000..b442ba5bbb --- /dev/null +++ b/files/es/web/api/document/queryselector/index.html @@ -0,0 +1,136 @@ +--- +title: Document.querySelector() +slug: Web/API/Document/querySelector +tags: + - API + - Consulta + - DOM + - Referencias(2) + - Referências + - Selectores + - metodo +translation_of: Web/API/Document/querySelector +--- +<div>{{ ApiRef("DOM") }}</div> + +<div>Devuelve el primer elemento del documento (utilizando un <a href="http://en.wikipedia.org/wiki/Tree_traversal#Pre-order_2">recorrido primero en profundidad pre ordenado</a> de los nodos del documento) que coincida con el grupo especificado de selectores.</div> + +<div> </div> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="brush: js">element = document.querySelector(selectores); +</pre> + +<p>Donde:</p> + +<ul> + <li><code>element</code> es un objeto de tipo <a href="/en-US/docs/DOM/element" title="en-US/docs/DOM/element">element</a>.</li> + <li><code>selectores</code> es una cadena de caracteres que contiene uno o más <a href="/en-US/docs/Web/Guide/CSS/Getting_Started/Selectors">selectores CSS</a> separados por coma.</li> +</ul> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<p>En este ejemplo, obtendremos el primer elemento del documento con la clase "miClase":</p> + +<pre class="brush: js">var el = document.querySelector(".miClase"); +</pre> + +<h2 id="Notes" name="Notes">Ejemplo más útil</h2> + +<p>Los <em>Selectores</em> pueden ser muy útiles como se demostrará en el siguiente ejemplo. Aquí, será retornado el primer elemento <code><input name="login" /></code> dentro de <code><div class="user-panel main"></code>.</p> + +<pre class="brush: js">var el = document.querySelector("div.user-panel.main input[name='login']");</pre> + +<h2 id="Notes" name="Notes">Notas</h2> + +<ul> + <li>Devuelve <code>null</code> si no se encuentran coincidencias, de lo contrario, retorna el primer elemento encontrado.</li> + <li>Si el selector coincide con un ID y este ID es usado erróneamente varias veces en el documento, devuelve el primer elemento encontrado.</li> + <li>Lanza una excepción de tipo SYNTAX_ERR si el grupo de selectores especificado es no es válido.</li> + <li><span style="font-family: Consolas,Monaco,'Andale Mono',monospace;">querySelector() se introdujo en la <a href="http://www.w3.org/TR/selectors-api/">API Selectors</a>.</span></li> + <li>La cadena de caracteres que se pasa como argumento a <code><span style="font-family: Consolas,Monaco,'Andale Mono',monospace;">querySelector debe seguir la sintaxis CSS.</span></code></li> + <li>Las Pseudo-clases CSS nunca devolverán elementos, tal y como está especificado en la <code><a href="http://www.w3.org/TR/selectors-api/#grammar">API Selectors</a></code>.</li> + <li>Para que coincidan ID's o selectores que no siguen la sintáxis CSS (usando inapropiadamente dos puntos o un espacio por ejemplo), se debe 'escapar' el carácter con una barra invertida (\). Como la barra invertida es un carácter de 'escape' en JavaScript, si estás indicando una cadena de caracteres literal, debes 'escaparla' dos veces (una para la cadena de caracteres JavaScript y otra para el querySelector): </li> +</ul> + +<pre class="brush: html"><div id="foo\bar"></div> +<div id="foo:bar"></div> + +<script> + console.log('#foo\bar'); // "#fooar" + document.querySelector('#foo\bar'); // No coincide con nada + + console.log('#foo\\bar'); // "#foo\bar" + console.log('#foo\\\\bar'); // "#foo\\bar" + document.querySelector('#foo\\\\bar'); // Coincide con el primer div + + document.querySelector('#foo:bar'); // No coincide con nada + document.querySelector('#foo\\:bar'); // Coincide con el segundo div +</script> +</pre> + +<h2 id="Browser_Compatibility" name="Browser_Compatibility">Compatibilidad en los navegadores</h2> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Plataforma</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Soporte Basico</td> + <td>1</td> + <td>3.5 (1.9.1)<br> + {{bug(416317)}}</td> + <td>8</td> + <td>10</td> + <td>3.2 (525.3)<br> + {{Webkitbug("16587")}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Plataforma</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte Basico</td> + <td>2.1</td> + <td>Si</td> + <td>9</td> + <td>10.0</td> + <td>3.2</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Specification" name="Specification">Especificaciones</h2> + +<ul> + <li><a class="external" href="http://www.w3.org/TR/selectors-api/" title="http://www.w3.org/TR/selectors-api/">Selectors API</a></li> +</ul> + +<h2 id="See_also" name="See_also">Vea también</h2> + +<ul> + <li>{{domxref("document.querySelectorAll()")}}</li> + <li>{{domxref("element.querySelector()")}}</li> + <li>{{domxref("element.querySelectorAll()")}}</li> + <li><a href="/en-US/docs/Code_snippets/QuerySelector" title="en-US/docs/Code snippets/QuerySelector">Snippets para querySelector</a></li> +</ul> diff --git a/files/es/web/api/document/queryselectorall/index.html b/files/es/web/api/document/queryselectorall/index.html new file mode 100644 index 0000000000..7f041b6e84 --- /dev/null +++ b/files/es/web/api/document/queryselectorall/index.html @@ -0,0 +1,179 @@ +--- +title: Document.querySelectorAll() +slug: Web/API/Document/querySelectorAll +tags: + - API + - Buscando Elementos + - DOM + - Document + - Encontrando Elementos + - Localizando Elementos + - Métodos + - Referencia + - Seleccionando Elementos + - Selectores + - Selectores CSS + - querySelectorAll +translation_of: Web/API/Document/querySelectorAll +--- +<div>{{ ApiRef("DOM") }}</div> + +<p>El método <strong><code>querySelectorAll()</code></strong> de un {{domxref("Element")}} devuelve una {{domxref("NodeList")}} estática (no viva) que representa una lista de elementos del documento que coinciden con el grupo de selectores indicados.</p> + +<div class="note"> +<p><strong>Nota:</strong> Esto método se implementa en base al método {{domxref("ParentNode.querySelectorAll", "querySelectorAll()")}} del mixin {{domxref("ParentNode")}}.</p> +</div> + +<h2 id="Sintaxis" name="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><var>elementList</var> = <em>parentNode</em>.querySelectorAll(<var>selectors</var>); +</pre> + +<h3 id="Parámetros" name="Parámetros">Parámetros</h3> + +<dl> + <dt><code>selectors</code></dt> + <dd>Un {{domxref("DOMString")}} que contiene uno o más selectores para buscar coincidencias. Esta cadena de texto debe ser una cadena <a href="/en-US/docs/Web/CSS/CSS_Selectors">CSS selector</a> válida; si no lo es, se lanzará una excepción <code>SyntaxError</code>. Vea <a href="/en-US/docs/Web/API/Document_object_model/Locating_DOM_elements_using_selectors">Locating DOM elements using selectors</a> para más información acerca de utilizar selectores para identificar elementos. Se pueden especificar varios selectores separándolos utilizando comas.</dd> +</dl> + +<div class="note"> +<p><strong>Nota:</strong> Los caracteres que no son parte de la sintaxis estándar de CSS deben ser escapados utilizando el caracter de barra invertida. Dado que JavaScript también utiliza el escapado por retroceso, se debe tener especial cuidado al escribir cadenas de texto literales utilizando estos caracteres. Vea {{anch("Escapando caracteres especiales")}} para más información.</p> +</div> + +<h3 id="Valor_devuelto">Valor devuelto</h3> + +<p>Una {{domxref("NodeList")}} <em>no viva</em> que contenga un objeto {{domxref("Element")}} para cada elemento que coincida con al menos uno de los selectores especificados o una {{domxref("NodeList")}} vacía en caso de que no haya coincidencias.</p> + +<div class="note"> +<p><strong>Nota:</strong> Si los selectores indicados incluyen un <a href="/en-US/docs/Web/CSS/Pseudo-elements">pseudo-elemento CSS</a>, la lista devuelta siempre estará vacía.</p> +</div> + +<h3 id="Excepciones">Excepciones</h3> + +<dl> + <dt><code>SyntaxError</code></dt> + <dd>La sintaxis de la cadena de texto <code>selectors</code> no es válida.</dd> +</dl> + +<h2 id="Ejemplos">Ejemplos</h2> + +<h3 id="Obteniendo_una_lista_de_coincidencias">Obteniendo una lista de coincidencias</h3> + +<p>Para obtener una {{domxref("NodeList")}} de todos los elementos {{HTMLElement("p")}} en el documento:</p> + +<pre class="brush: js">var matches = document.querySelectorAll('p');</pre> + +<p>Este ejemplo devuelve una lista de todos los elementos {{HTMLElement("div")}} del documento con una clase "<code>nota</code>" o "<code>alerta</code>":</p> + +<pre class="brush: js">var matches = document.querySelectorAll('div.nota, div.alerta'); +</pre> + +<p>Aquí, se obtiene una lista de elementos <code><p></code> cuyo elemento padre inmediato es un {{domxref("div")}} con la clase <code>"highlighted"</code> y que está ubicado dentro de un contenedor cuyo ID es <code>"test"</code>.</p> + +<pre class="brush: js">var container = document.querySelector('#test'); +var matches = container.querySelectorAll('div.highlighted > p');</pre> + +<p>Este ejemplo usa un <a href="es/docs/Web/CSS/Selectores_atributo">selector de atributos</a> para devolver una lista de elementos {{domxref("iframe")}} en el documento que contienen un atributo llamado <code>"data-src"</code>:</p> + +<pre class="brush: js">var matches = document.querySelectorAll('iframe[data-src]');</pre> + +<p>Aquí, un selector de atributo se utiliza para devolver una lista de los elementos de una lista cuyo ID es <code>"userlist"</code> que tiene un atributo <code>"data-active"</code> cuyo valor es <code>"1"</code>:</p> + +<pre class="brush: js">var container = document.querySelector('#userlist'); +var matches = container.querySelectorAll('li[data-active="1"]');</pre> + +<h3 id="Accediendo_a_las_coincidencias">Accediendo a las coincidencias</h3> + +<p>Una vez que se devuelve la {{domxref("NodeList")}} de los elementos que coinciden, se puede examinar como cualquier <code>array</code>. Si el array está vacío (lo que significa que su propiedad <code>length</code> es 0), entonces es que no se encontraron coincidencias.</p> + +<p>En cualquier caso, se puede simplemente utilizar la notación estándar de los arrays para acceder al contenido de la lista. Se puede usar cualquier sentencia de iteración, como por ejemplo:</p> + +<pre class="brush: js">var highlightedItems = userList.querySelectorAll('.highlighted'); + +highlightedItems.forEach(function(userItem) { + deleteUser(userItem); +});</pre> + +<h2 id="Notas_de_usuario">Notas de usuario</h2> + +<p><code>querySelectorAll()</code> se comporta de forma diferente que la mayoría de librerías DOM de JavaScript, que pueden llevar a resultados inesperados.</p> + +<h3 id="HTML">HTML</h3> + +<p>Considere este HTML, con sus tres bloques anidados {{HTMLElement("div")}}.</p> + +<pre class="brush: html"><div class="outer"> + <div class="select"> + <div class="inner"> + </div> + </div> +</div></pre> + +<h3 id="JavaScript">JavaScript</h3> + +<pre class="brush: js">var select = document.querySelector('.select'); +var inner = select.querySelectorAll('.outer .inner'); +inner.length; // 1, not 0! +</pre> + +<p>En este ejemplo, cuando se selecciona <code>".outer .inner"</code> en el contexto el <code><div></code> con la clase <code>"select"</code>, el elemento con la clase <code>".inner"</code> todavía es encontrado, aun sabiendo que <code>.outer</code> no es descendiente del elemento base sobre el que se realiza la búsqueda (<code>".select"</code>). Por defecto, <code>querySelectorAll()</code> sólo verifica que el último elemento en el selector se encuentra dentro del rango de búsqueda.</p> + +<p>La pseudo-clase {{cssxref(":scope")}} recupera el comportamiento esperado, encontrando coincidencias sólo en selectores descendientes del elemento base:</p> + +<pre class="brush: js">var select = document.querySelector('.select'); +var inner = select.querySelectorAll(':scope .outer .inner'); +inner.length; // 0 +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName("DOM WHATWG", "#dom-parentnode-queryselectorall", "ParentNode.querySelectorAll()")}}</td> + <td>{{Spec2("DOM WHATWG")}}</td> + <td>Estándar vivo</td> + </tr> + <tr> + <td>{{SpecName("Selectors API Level 2", "#dom-parentnode-queryselectorall", "ParentNode.querySelectorAll()")}}</td> + <td>{{Spec2("Selectors API Level 2")}}</td> + <td>Sin cambios</td> + </tr> + <tr> + <td>{{SpecName("DOM4", "#dom-parentnode-queryselectorall", "ParentNode.querySelectorAll()")}}</td> + <td>{{Spec2("DOM4")}}</td> + <td>Definición inicial</td> + </tr> + <tr> + <td>{{SpecName("Selectors API Level 1", "#interface-definitions", "document.querySelector()")}}</td> + <td>{{Spec2("Selectors API Level 1")}}</td> + <td>Definición original</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_navegadores">Compatibilidad en navegadores</h2> + +<div> + + +<p>{{Compat("api.Document.querySelectorAll")}}</p> +</div> + +<h2 id="Ver_también" name="Ver también">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Document_object_model/Locating_DOM_elements_using_selectors">Localizando elementos DOM utilizando selectores</a></li> + <li><a href="/es/docs/Web/CSS/Selectores_atributo">Selectores de atributo</a></li> + <li><a href="/es/docs/Learn/CSS/Introduction_to_CSS/Selectores_de_Atributos">Selectores de atributo</a> en el área de aprendizaje de MDN</li> + <li>{{domxref("Element.querySelector()")}} y {{domxref("Element.querySelectorAll()")}}</li> + <li>{{domxref("Document.querySelector()")}}</li> + <li>{{domxref("DocumentFragment.querySelector()")}} y {{domxref("DocumentFragment.querySelectorAll()")}}</li> + <li>{{domxref("ParentNode.querySelector()")}} y {{domxref("ParentNode.querySelectorAll()")}}</li> + <li><a href="/en-US/docs/Code_snippets/QuerySelector" title="Code_snippets/QuerySelector">Snippets de código para <code>querySelector()</code></a></li> +</ul> diff --git a/files/es/web/api/document/readystate/index.html b/files/es/web/api/document/readystate/index.html new file mode 100644 index 0000000000..7e5a24c5d8 --- /dev/null +++ b/files/es/web/api/document/readystate/index.html @@ -0,0 +1,104 @@ +--- +title: Document.readyState +slug: Web/API/Document/readyState +translation_of: Web/API/Document/readyState +--- +<div>{{APIRef("DOM")}} {{ gecko_minversion_header("1.9.2") }}</div> + +<h2 id="Summary" name="Summary">Resumen</h2> + +<p>La propiedad <strong>Document.readyState</strong> de un {{ domxref("document") }} describe el estado de carga del documento.</p> + +<h3 id="Valores">Valores</h3> + +<p>El readyState de un documento puede tener uno de los siguientes valores:</p> + +<dl> + <dt>loading</dt> + <dd>El {{ domxref("document") }} todavía esta cargando.</dd> + <dt>interactive</dt> + <dd>El documento ha terminado de cargar y ha sido analizado pero los sub-recursos como imágenes, estilos y frames aún siguen cargando. El estado indica que el evento {{event("DOMContentLoaded")}} ha sido disparado.</dd> + <dt>complete</dt> + <dd>El documento y todos los sub-recursos han cargado completamente. El estado indica que el evento {{event("load")}} ha sido disparado.</dd> +</dl> + +<p>Cuando el valor de esta propiedad cambia, un evento {{event("readystatechange")}} se dispara en el objecto {{ domxref("document") }}.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="brush: js"><em>var string</em> = document.readyState; +</pre> + +<h2 id="Ejemplos"><span>Ejemplos</span></h2> + +<h3 id="Diferentes_estados_del_readyState">Diferentes estados del readyState</h3> + +<pre class="brush: js"><span>switch (document.readyState) { + case "loading": + // The document is still loading. + break; + case "interactive": + // The document has finished loading. We can now access the DOM elements. + var span = document.createElement("span"); + span.textContent = "A <span> element."; + document.body.appendChild(span); + break; + case "complete": + // The page is fully loaded. + console.log("The first CSS rule is: " + document.styleSheets[0].cssRules[0].cssText); + break; +}</span> +</pre> + +<h3 id="readystatechange_como_alternativa_al_evento_DOMContentLoaded">readystatechange como alternativa al evento DOMContentLoaded</h3> + +<pre class="brush:js">// alternative to DOMContentLoaded event +document.onreadystatechange = function () { + if (document.readyState == "interactive") { + initApplication(); + } +}</pre> + +<h3 id="readystatechange_como_alternativa_al_evento_load">readystatechange como alternativa al evento load</h3> + +<pre class="brush: js">// alternative to load event +document.onreadystatechange = function () { + if (document.readyState == "complete") { + initApplication(); + } +}</pre> + +<h2 id="Especificación">Especificación</h2> + +<table class="spectable standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName("HTML WHATWG", "#current-document-readiness", "Document readiness")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName("HTML5.1", "#current-document-readiness", "Document readiness")}}</td> + <td>{{Spec2('HTML5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName("HTML5 W3C", "#current-document-readiness", "Document readiness")}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>Especificación inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>Evento {{event("readystatechange")}}</li> + <li>Evento {{event("DOMContentLoaded")}}</li> + <li>Evento {{event("load")}}</li> +</ul> diff --git a/files/es/web/api/document/registerelement/index.html b/files/es/web/api/document/registerelement/index.html new file mode 100644 index 0000000000..504cf8314b --- /dev/null +++ b/files/es/web/api/document/registerelement/index.html @@ -0,0 +1,115 @@ +--- +title: Document.registerElement() +slug: Web/API/Document/registerElement +translation_of: Web/API/Document/registerElement +--- +<p>{{APIRef("DOM")}}{{Deprecated_header}}{{draft()}}</p> + +<p>El <code><strong>Document.registerElement()</strong></code> registra un nuevo <a href="/en-US/docs/Web/Web_Components/Custom_Elements">elemento personalizado</a> en el navegador y devuelve un constructor para el nuevo elemento.</p> + +<div class="note"> +<p><strong>Nota:</strong> Esta es una tecnología experimental. El navegador que utilice debe ser compatible con Web Components. Ver <a href="/en-US/docs/Web/Web_Components#Enabling_Web_Components_in_Firefox">Web Components habilitados en Firefox</a>.</p> +</div> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var <em>constructor</em> = document.registerElement(<em>tag-name</em>, <em>options</em>);</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><em>tag-name</em></dt> + <dd>El nombre del elemento personalizado. El nombre debe contener un guión (-), por ejemplo <code>my-tag</code>.</dd> + <dt><em>options {{optional_inline}}</em></dt> + <dd>Un objeto que da nombre al prototipo que sirve de base para el elemento personalizado, y una etiqueta existente para extender. Ambos son opcionales.</dd> +</dl> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>Aquí hay un ejemplo muy simple:</p> + +<pre class="brush: js">var Mytag = document.registerElement('my-tag'); +</pre> + +<p>Ahora el nuevo tag se ha registrado en el navegador. La variable MyTag contiene un constructor que lo puedes usar para crear un elemento my-tag en el documento de la siguiente manera:</p> + +<pre class="brush: js">document.body.appendChild(new Mytag());</pre> + +<p>Esto inserta un elemento my-tag vacío que será visible si utiliza las herramientas de desarrollo del navegador. No será visible si usa la capacidad de ver el código fuente del navegador. Y no será visible en el navegador a menos que agregue algún contenido para la etiqueta. Esta es la manera de agregar contenido a la nueva etiqueta:</p> + +<pre class="brush: js">var mytag = document.getElementsByTagName("my-tag")[0]; +mytag.textContent = "I am a my-tag element."; +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('Custom Elements')}}</td> + <td>{{Spec2('Custom Elements')}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_del_navegador">Compatibilidad del navegador</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>35</td> + <td>31 (behind a flag)</td> + <td>{{CompatNo}}</td> + <td>25</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>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>4.4.4</td> + <td>31 (behind a flag)</td> + <td>{{CompatNo}}</td> + <td>25</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a dir="ltr" href="https://developer.mozilla.org/en-US/docs/Web/Web_Components/Custom_Elements">Custom Elements</a></li> +</ul> diff --git a/files/es/web/api/document/scripts/index.html b/files/es/web/api/document/scripts/index.html new file mode 100644 index 0000000000..254df25276 --- /dev/null +++ b/files/es/web/api/document/scripts/index.html @@ -0,0 +1,84 @@ +--- +title: Document.scripts +slug: Web/API/Document/scripts +translation_of: Web/API/Document/scripts +--- +<div>{{APIRef("DOM")}}</div> + +<p>Devuelve una lista de elementos {{HTMLElement("script")}} ubicados en el documento. El objeto devuelto es una colección {{domxref("HTMLCollection")}}.</p> + +<h2 id="Syntax" name="Syntax">Sintáxis</h2> + +<pre class="syntaxbox"><code>var <em>scriptList</em></code> = document.scripts; +</pre> + +<p>El objeto <code>scriptList</code> devuelto es una {{domxref("HTMLCollection")}}. Se puede utilizar como un array corriente para acceder a sus elementos.</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>Este ejemplo busca demostrar la existencia de objetos {{HTMLElement("script")}} en el documento.</p> + +<pre class="brush:js">var scripts = document.scripts; + +if (scripts.length) { + alert("This page has scripts!"); +} +</pre> + +<h2 id="Specification" name="Specification">Compatibilidad de navegadores</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</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("9.0")}}</td> + <td>{{CompatVersionUnknown}}</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>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("9.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Specification" name="Specification"> </h2> + +<h2 id="Specification" name="Specification">Especificaciones</h2> + +<ul> + <li>{{spec("http://www.whatwg.org/specs/web-apps/current-work/multipage/dom.html#dom-document-scripts", "DOM: document scripts")}}</li> +</ul> diff --git a/files/es/web/api/document/scroll_event/index.html b/files/es/web/api/document/scroll_event/index.html new file mode 100644 index 0000000000..944d539834 --- /dev/null +++ b/files/es/web/api/document/scroll_event/index.html @@ -0,0 +1,104 @@ +--- +title: scroll +slug: Web/API/Document/scroll_event +translation_of: Web/API/Document/scroll_event +--- +<p>El evento <strong><code>scroll</code></strong> se produce cuando la vista del documento o un elemento es deslizado.</p> + +<h2 id="Información_General">Información General</h2> + +<dl> + <dt style="float: left; text-align: right; width: 120px;">Especificación</dt> + <dd style="margin: 0 0 0 120px;"><a class="external" href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-scroll">DOM L3</a>, <a href="http://www.w3.org/TR/cssom-view/#scrolling-0">CSSOM View</a></dd> + <dt style="float: left; text-align: right; width: 120px;">Interfaz</dt> + <dd style="margin: 0 0 0 120px;">UIEvent</dd> + <dt style="float: left; text-align: right; width: 120px;">Bubbles</dt> + <dd style="margin: 0 0 0 120px;">No en elementos, pero burbujea a la vista default cuando se ejecuta en el documento</dd> + <dt style="float: left; text-align: right; width: 120px;">Cancelable</dt> + <dd style="margin: 0 0 0 120px;">No</dd> + <dt style="float: left; text-align: right; width: 120px;">Objetivo</dt> + <dd style="margin: 0 0 0 120px;">defaultView, Document, Element</dd> + <dt style="float: left; text-align: right; width: 120px;">Acción por defecto</dt> + <dd style="margin: 0 0 0 120px;">Ninguna</dd> + <dt style="margin: 0px 0px 0px 120px;"></dt> +</dl> + +<h2 id="Propiedades">Propiedades</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><a href="/en-US/docs/Web/API/EventTarget" title="EventTarget is an interface implemented by objects that can receive events and may have listeners for them."><code>EventTarget</code></a></td> + <td>El objetivo de evento (el objetivo superior en el árbol DOM).</td> + </tr> + <tr> + <td><code>type</code> {{readonlyInline}}</td> + <td><a href="/en-US/docs/Web/API/DOMString" title="DOMString is a UTF-16 String. As JavaScript already uses such strings, DOMString is mapped directly to a String."><code>DOMString</code></a></td> + <td>El tipo de evento.</td> + </tr> + <tr> + <td><code>bubbles</code> {{readonlyInline}}</td> + <td><a href="/en-US/docs/Web/API/Boolean" title="The Boolean object is an object wrapper for a boolean value."><code>Boolean</code></a></td> + <td>Si el evento burbujea o no.</td> + </tr> + <tr> + <td><code>cancelable</code> {{readonlyInline}}</td> + <td><a href="/en-US/docs/Web/API/Boolean" title="The Boolean object is an object wrapper for a boolean value."><code>Boolean</code></a></td> + <td>Si el evento puede ser cancelado o no.</td> + </tr> + <tr> + <td><code>view</code> {{readonlyInline}}</td> + <td><a class="new" href="/en-US/docs/Web/API/WindowProxy" rel="nofollow" title="The documentation about this has not yet been written; please consider contributing!"><code>WindowProxy</code></a></td> + <td><a href="/en-US/docs/Web/API/Document/defaultView" title="In browsers, document.defaultView returns the window object associated with a document, or null if none is available."><code>document.defaultView</code></a> (<code>window</code> de el documento)</td> + </tr> + <tr> + <td><code>detail</code> {{readonlyInline}}</td> + <td><code>long</code> (<code>float</code>)</td> + <td>0.</td> + </tr> + </tbody> +</table> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>Dado que los eventos <code>scroll</code> pueden ejecutarse a un ritmo elevado, el <em>event handler</em> no debería ejecutar operaciones computacionalmente costosas como modificaciones en el DOM. En cambio, se recomienda acelerar el evento utilizando <a href="/en-US/docs/DOM/window.requestAnimationFrame" title="/en-US/docs/DOM/window.requestAnimationFrame">requestAnimationFrame</a>, <a href="/en-US/docs/Web/API/WindowTimers/setTimeout">setTimeout</a> or <a href="/en-US/docs/Web/API/CustomEvent">customEvent</a>, de este modo:</p> + +<h4 id="Optimización_de_Scroll_con_window.requestAnimationFrame">Optimización de Scroll con window.requestAnimationFrame</h4> + +<pre class="brush: js">// Referencia: http://www.html5rocks.com/en/tutorials/speed/animations/ + +var last_known_scroll_position = 0; +var ticking = false; + +function doSomething(scroll_pos) { + // Hacer algo con la posición del scroll +} + +window.addEventListener('scroll', function(e) { + last_known_scroll_position = window.scrollY; + if (!ticking) { + window.requestAnimationFrame(function() { + doSomething(last_known_scroll_position); + ticking = false; + }); + } + ticking = true; +});</pre> + + + +<p>Más ejemplos se pueden ver en el evento <a href="/en-US/docs/Web/Events/resize#Example">resize</a>.</p> + +<h2 id="Compatibilidad_en_navegadores">Compatibilidad en navegadores</h2> + +<h3 id="iOS_UIWebView">iOS UIWebView</h3> + +<p>En iOS UIWebViews, los eventos <code>scroll</code> no se ejecutan mientras el <em>escroleo/deslizamiento</em> se lleva a cabo; solo son ejecutados cuando el deslizamiento terminó. Ver <a href="https://github.com/twbs/bootstrap/issues/16202">Bootstrap issue #16202</a>. Safari y WKWebViews no se ven afectados por este bug.</p> diff --git a/files/es/web/api/document/stylesheets/index.html b/files/es/web/api/document/stylesheets/index.html new file mode 100644 index 0000000000..0cc8e47181 --- /dev/null +++ b/files/es/web/api/document/stylesheets/index.html @@ -0,0 +1,21 @@ +--- +title: Document.styleSheets +slug: Web/API/Document/styleSheets +translation_of: Web/API/DocumentOrShadowRoot/styleSheets +--- +<p>{{ ApiRef() }}</p> +<h3 id="Summary" name="Summary">Resumen</h3> +<p>Devuelve una lista de objetos de tipo <a href="/es/DOM/stylesheet" title="es/DOM/stylesheet">stylesheet</a> para las hojas de estilo que están específicamente enlazadas o contenidas en el documento.</p> +<h3 id="Properties" name="Properties">Propiedades</h3> +<p><code>styleSheetList.length</code> - devuelve el número de objetos de tipo stylesheet contenidos en el objeto.</p> +<h3 id="Syntax" name="Syntax">Sintaxis</h3> +<pre class="eval"><em>styleSheetList</em> = <em>document</em>.styleSheets +</pre> +<p>El objeto devuelto es del tipo <a class="external" href="http://www.w3.org/TR/DOM-Level-2-Style/stylesheets.html#StyleSheets-DocumentStyle-styleSheets">StyleSheetList</a>.</p> +<p>Es una colección ordenada de objetos de tipo <a href="/es/DOM/stylesheet" title="es/DOM/stylesheet">stylesheet</a>. <code><em>styleSheetList</em>.item(<em>index</em>)</code> o simplemente <code><em>styleSheetList</em>{{ mediawiki.external(' + <i> + index</i> + ') }}</code> devuelve un único objeto de tipo stylesheet con el índice especificado (el índice es de origen 0).</p> +<h3 id="Specification" name="Specification">Especificación</h3> +<p><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Style/stylesheets.html#StyleSheets-DocumentStyle-styleSheets">DOM Level 2 Style: styleSheets</a></p> +<p>{{ languages( { "ja": "ja/DOM/document.styleSheets", "pl": "pl/DOM/document.styleSheets" } ) }}</p> diff --git a/files/es/web/api/document/url/index.html b/files/es/web/api/document/url/index.html new file mode 100644 index 0000000000..eec4361827 --- /dev/null +++ b/files/es/web/api/document/url/index.html @@ -0,0 +1,71 @@ +--- +title: document.URL +slug: Web/API/Document/URL +tags: + - API + - Documento + - HTML DOM + - Propiedad + - Referencia +translation_of: Web/API/Document/URL +--- +<div>{{APIRef("DOM")}}</div> + +<p>La propiedad de sólo lectura <strong><code>URL</code></strong> de la interfaz {{domxref("Document")}} devuelve la ubicación del documento como una cadena de texto.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var <var>string</var> = document.URL</pre> + +<h2 id="Ejemplo">Ejemplo</h2> + +<h3 id="JavaScript">JavaScript</h3> + +<pre class="brush: js">document.getElementById("url").textContent = document.URL;</pre> + +<h3 id="HTML">HTML</h3> + +<pre class="brush: html"><p id="urlText"> + URL:<br/> + <span id="url">La URL va aquí</span> +</p></pre> + +<h3 id="Resultado">Resultado</h3> + +<p>{{EmbedLiveSample("Example", "100%", 100)}}</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="spectable 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("DOM WHATWG", "#dom-document-url", "Document.URL")}}</td> + <td>{{Spec2("DOM WHATWG")}}</td> + <td>Define que la propiedad es una {{domxref("USVString")}} en lugar de un {{domxref("DOMString")}}.</td> + </tr> + <tr> + <td>{{SpecName("DOM1", "level-one-html.html#attribute-URL", "Document.URL")}}</td> + <td>{{Spec2("DOM1")}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<div> +<p>{{Compat("api.Document.URL")}}</p> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("HTMLDocument")}}</li> +</ul> diff --git a/files/es/web/api/document/write/index.html b/files/es/web/api/document/write/index.html new file mode 100644 index 0000000000..f07bd5c9a9 --- /dev/null +++ b/files/es/web/api/document/write/index.html @@ -0,0 +1,76 @@ +--- +title: Document.write() +slug: Web/API/Document/write +tags: + - API + - DOM + - Documentación + - Referencia + - metodo +translation_of: Web/API/Document/write +--- +<div>{{ ApiRef("DOM") }}</div> + +<p><br> + Escribe una cadena de texto dentro del hilo de un <code>document </code>abierto por <a href="/en-US/docs/Web/API/document.open">document.open()</a>.</p> + +<div class="note">Nota: dado que <code>document.write</code> escribe directo al hilo<strong> (stream</strong>) de un documento, la llamada a <code>document.write</code> en un documento ya cargado automáticamente ejecuta <code>document.open</code>, <a href="https://developer.mozilla.org/en-US/docs/Web/API/document.open#Notes">lo cual limpiará todo el contenido del documento en cuestión</a>.</div> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="brush: js">document.write(texto); +</pre> + +<p><code>texto </code>es una cadena de texto que contiene el texto a ser impreso en el documento.</p> + +<h3 id="Example">Example</h3> + +<pre class="brush: html"><html> + +<head> + <title>Ejemplo de write</title> + + <script> + function nuevoContenido() { + alert("carga el contenido nuevo"); + document.open(); + document.write("<h1>Quita el contenido viejo - Agrega el contenido nuevo!</h1>"); + document.close(); + } + </script> +</head> + +<body onload="nuevoContenido();"> + <p>Algo de contenido original del documento</p> +</body> + +</html></pre> + +<h2 id="Notas">Notas</h2> + +<p>Escribir a un documento que ya tiene contenido cargado previamente sin llamar a <a href="/en-US/docs/Web/API/document.open"><code>document.open()</code></a>, automáticamente hará una llamada a document.open(). Después de haber finalizado la escritura del documento, es recomendable llamar a <a href="/en-US/docs/Web/API/document.close"><code>document.close()</code></a>, para informar al navegador que la carga de la página ya ha terminado. El texto que escribas allí es convertido a la estructura tipificada de HTML dentro del modelo estructural del documento. En el ejemplo de más arriba, el elemento h1 se convierte en un nodo dentro del documento.</p> + +<p>Si la llamada a document.write() se ejecuta dentro de una etiqueta <code><script></code> incluído en el HTML, entonces la llamada a document.open() nunca ocurrirá. Por ejemplo:</p> + +<pre class="brush: html"><script> + document.write("<h1>Título Principal</h1>") +</script> +</pre> + +<div class="note"><strong>Nota:</strong> <code>document.write</code> y <code>document.writeln</code> <a href="/en-US/docs/Archive/Web/Writing_JavaScript_for_HTML">no funcionan dentro de un documento XHTML</a> (obtendrás un mensaje de error que dice "Operación no soportada" ("Operation is not supported") [<code>NS_ERROR_DOM_NOT_SUPPORTED_ERR</code>] en la consola). Esto sucede cuando abrimos un archivo local de extensión .xhtml o para cualquier document servido con un <a href="/en-US/docs/Glossary/MIME_type">MIME del tipo </a><code>application/xhtml+xml</code>. Hay más información disponible en <a class="external" href="http://www.w3.org/MarkUp/2004/xhtml-faq#docwrite">W3C XHTML FAQ</a>.</div> + +<div class="note"><strong>Nota:</strong> <code>document.write</code> en scripts de modo <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-defer">diferido</a> o <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-async">asyncrónico</a> serán ignorados, y recibirás un mensaje de error en la consola del tipo "Una llamada a document.write() desde un script cargado asincrónicamente fue ignorado" ("A call to <code>document.write()</code> from an asynchronously-loaded external script was ignored").</div> + +<h2 id="Especificaciones">Especificaciones</h2> + +<ul> + <li><a class="external" href="http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-75233634">DOM Level 2 HTML: <code>write()</code> Method</a></li> + <li><a class="external" href="http://www.w3.org/TR/2011/WD-html5-author-20110705/apis-in-html-documents.html#dynamic-markup-insertion">Dynamic markup insertion in HTML</a></li> +</ul> + +<h2 id="También_puedes_ver">También puedes ver</h2> + +<ul> + <li>{{ domxref("element.innerHTML") }}</li> + <li>{{ domxref("document.createElement()") }}</li> +</ul> diff --git a/files/es/web/api/document/writeln/index.html b/files/es/web/api/document/writeln/index.html new file mode 100644 index 0000000000..d9e0b72019 --- /dev/null +++ b/files/es/web/api/document/writeln/index.html @@ -0,0 +1,40 @@ +--- +title: Document.writeln() +slug: Web/API/Document/writeln +translation_of: Web/API/Document/writeln +--- +<p>{{ ApiRef("DOM") }}</p> + +<p>Escribe una cadena de texto en el documento, seguida de una nueva línea.</p> + +<div class="note"> +<p>Nota: dado que <code>document.writeln</code> (al igual que <code>document.write)</code> escribe directo al hilo<strong> </strong>(<code>stream</code>) de un documento, la llamada a <code>document.write</code> en un documento ya cargado automáticamente ejecuta <code>document.open</code>, <a href="https://developer.mozilla.org/en-US/docs/Web/API/document.open#Notes">lo cual limpiará todo el contenido del documento en cuestión</a>.</p> +</div> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="eval">document.writeln(<em>línea</em>); +</pre> + +<h3 id="Parameters" name="Parameters">Parámetros</h3> + +<ul> + <li><code>línea</code> es la cadena conteniendo una línea de texto.</li> +</ul> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre>document.writeln("<p>¡Hola mundo!</p>"); +</pre> + +<h2 id="Notes" name="Notes">Notas</h2> + +<p><strong>document.writeln</strong> actúa igual que <a href="/es/DOM/document.write" title="en/DOM/document.write">document.write</a> exepto que agrega un carácter de nueva línea (<code>\n</code>) al final del texto a escribir.</p> + +<div class="note"><strong>Nota:</strong> <code>document.write</code> y <code>document.writeln</code> <a href="https://developer.mozilla.org/en-US/docs/Archive/Web/Writing_JavaScript_for_HTML">no funcionan dentro de un documento XHTML</a> (obtendrás un mensaje de error que dice "Operación no soportada" ("Operation is not supported") [<code>NS_ERROR_DOM_NOT_SUPPORTED_ERR</code>] en la consola). Esto sucede cuando abrimos un archivo local de extensión .xhtml o para cualquier document servido con un <a href="https://developer.mozilla.org/es/docs/Glossary/MIME_type">MIME del tipo </a><code>application/xhtml+xml</code>. Hay más información disponible en <a class="external external-icon" href="http://www.w3.org/MarkUp/2004/xhtml-faq#docwrite">W3C XHTML FAQ</a>.</div> + +<div class="note"><strong>Nota:</strong> <code>document.writeln</code> y <code>document.write</code> en scripts de modo <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-defer">diferido</a> o <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-async">asyncrónico</a> serán ignorados, y recibirás un mensaje de error en la consola del tipo "Una llamada a document.write() desde un script cargado asincrónicamente fue ignorado" ("A call to <code>document.write()</code> from an asynchronously-loaded external script was ignored").</div> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<p><a class="external" href="http://www.w3.org/TR/2000/WD-DOM-Level-2-HTML-20001113/html.html#ID-35318390">writeln </a></p> diff --git a/files/es/web/api/document_object_model/using_the_w3c_dom_level_1_core/example/index.html b/files/es/web/api/document_object_model/using_the_w3c_dom_level_1_core/example/index.html new file mode 100644 index 0000000000..b93f8e1d7e --- /dev/null +++ b/files/es/web/api/document_object_model/using_the_w3c_dom_level_1_core/example/index.html @@ -0,0 +1,40 @@ +--- +title: Example +slug: Web/API/Document_object_model/Using_the_W3C_DOM_Level_1_Core/Example +tags: + - DOM + - Ejemplo +translation_of: Web/API/Document_object_model/Using_the_W3C_DOM_Level_1_Core/Example +--- +<pre> <html> + <head> + <title>Mi Documento</title> + <script type="text/javascript"> + function cambio() { + // document.getElementsByTagName("H1") retorna un NodeList de elementos + // h1 en el documento, y el primero es numero 0: + var header = document.getElementsByTagName("H1").item(0); + // El firstChild del encabezado es un nodo Text: + header.firstChild.data = "Un documento dinamico"; + // Ahora el encabezado es "Un documento dinamico". + var para = document.getElementsByTagName("P").item(0); + para.firstChild.data = "Este es el primer parrafo."; + // Crea un nuevo nodo Text para el segundo parrafo + var newText = document.createTextNode("Este es el segundo parrafo."); + // Crea un nuevo Element para que sea el segundo parrafo + var newElement = document.createElement("P"); + // Agrega el texto en el parrafo + newElement.appendChild(newText); + // Y agrega el parrafo al final del documento dentro del + // BODY (el cuál es el padre de "para") + para.parentNode.appendChild(newElement); + } + </script> + </head> + <body> + <input type="button" value="Cambia este documento." onclick="cambio()"> + <h1>Encabezado</h1> + <p>Parrafo</p> + </body> + </head> +</pre> diff --git a/files/es/web/api/documentfragment/index.html b/files/es/web/api/documentfragment/index.html new file mode 100644 index 0000000000..625ea1e2c9 --- /dev/null +++ b/files/es/web/api/documentfragment/index.html @@ -0,0 +1,129 @@ +--- +title: DocumentFragment +slug: Web/API/DocumentFragment +translation_of: Web/API/DocumentFragment +--- +<div>{{ APIRef("DOM") }}</div> + +<p>La interfaz <span class="seoSummary"><strong><code>DocumentFragment</code></strong></span> representa un objeto de documento mínimo que no tiene padre. Se utiliza como una versión ligera de <span class="seoSummary">{{domxref("Document")}}</span> que almacena un segmento de una estructura de documento compuesta de nodos como un documento estándar. La gran diferencia se debe al hecho de que el fragmento de documento no forma parte de la estructura de árbol del documento activo. Los cambios realizados en el fragmento no afectan el documento (incluso en {{Glossary("reflow")}}) ni inciden en el rendimiento cuando se realizan cambios. {{InheritanceDiagram}}</p> + +<h2 id="Constructor">Constructor</h2> + +<dl> + <dt>{{ domxref("DocumentFragment.DocumentFragment()", "DocumentFragment()") }}</dt> + <dd>Crea y devuelve un nuevo objeto <code>DocumentFragment</code>.</dd> +</dl> + +<h2 id="Propiedades">Propiedades</h2> + +<p>Esta interfaz no tiene propiedades específicas<em>, </em>pero hereda las de su padre<em>, {{domxref("Node")}}, </em>e implementa los de la interfaz <em>{{domxref("ParentNode")}}.</em></p> + +<dl> + <dt>{{ domxref("ParentNode.children") }} {{readonlyInline}}{{experimental_inline}}</dt> + <dd>Devuelve un {{domxref("HTMLCollection")}} que contiene los objetos de tipo {{domxref("Element")}} que son elementos secundarios del objeto <code>DocumentFragment</code>.</dd> + <dt>{{ domxref("ParentNode.firstElementChild") }} {{readonlyInline}}{{experimental_inline}}</dt> + <dd>Devuelve el {{domxref("Element")}} que es el primer hijo del objeto <code>DocumentFragment</code>, o <code>null</code> si no hay ninguno.</dd> + <dt>{{ domxref("ParentNode.lastElementChild") }} {{readonlyInline}}{{experimental_inline}}</dt> + <dd>Devuelve el {{domxref("Element")}} que es el último hijo del objeto <code>DocumentFragment</code>, o <code>null</code> si no hay ninguno.</dd> + <dt>{{ domxref("ParentNode.childElementCount") }} {{readonlyInline}}{{experimental_inline}}</dt> + <dd>Devuelve un <code>unsigned long</code> que indica cantidad de elementos secundarios que tiene el objeto <code>DocumentFragment</code>.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<p><em>Esta interfaz hereda los métodos de su padre</em>, <em>{{domxref("Node")}}<em>, e implementa los de la interfaz {{domxref("ParentNode")}}</em>.</em></p> + +<dl> + <dt>{{domxref("DocumentFragment.querySelector()")}}</dt> + <dd>Devuelve el primer nodo {{domxref("Element")}} dentro de <code>DocumentFragment</code>, en el orden del documento, que coincide con los selectores especificados.</dd> + <dt>{{domxref("DocumentFragment.querySelectorAll()")}}</dt> + <dd>Devuelve un {{domxref("NodeList")}} de todos los nodos {{domxref("Element")}} dentro de <code>DocumentFragment</code> que coincide con los selectores especificados.</dd> + <dt>{{domxref("DocumentFragment.getElementById()")}}</dt> + <dd>Devuelve el primer nodo{{domxref("Element")}} dentro de <code style="font-size: 14px;">DocumentFragment</code>, en el orden del documento, que coincide con el <strong>ID</strong> especificado. funcionalmente equivale a {{domxref("Document.getElementById()")}}.</dd> +</dl> + +<h2 id="Notas_de_uso">Notas de uso</h2> + +<p>A common use for <code>DocumentFragment</code> is to create one, assemble a DOM subtree within it, then append or insert the fragment into the DOM using {{domxref("Node")}} interface methods such as {{domxref("Node.appendChild", "appendChild()")}} or {{domxref("Node.insertBefore", "insertBefore()")}}. Doing this moves the fragment's nodes into the DOM, leaving behind an empty <code>DocumentFragment</code>. Because all of the nodes are inserted into the document at once, only one reflow and render is triggered instead of potentially one for each node inserted if they were inserted separately.</p> + +<p>This interface is also of great use with Web components: {{HTMLElement("template")}} elements contain a <code>DocumentFragment</code> in their {{domxref("HTMLTemplateElement.content")}} property.</p> + +<p>An empty <code>DocumentFragment</code> can be created using the {{domxref("document.createDocumentFragment()")}} method or the constructor.</p> + +<h2 id="Example">Example</h2> + +<h3 id="HTML">HTML</h3> + +<pre class="brush: html"><ul id="list"></ul> +</pre> + +<h3 id="JavaScript">JavaScript</h3> + +<pre class="brush: js">var list = document.querySelector('#list') +var fruits = ['Apple', 'Orange', 'Banana', 'Melon'] + +var fragment = new DocumentFragment() + +fruits.forEach(function (fruit) { + var li = document.createElement('li') + li.innerHTML = fruit + fragment.appendChild(li) +}) + +list.appendChild(fragment) +</pre> + +<h3 id="Result">Result</h3> + +<p>{{EmbedLiveSample('Example')}}</p> + +<h2 id="Specifications" name="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('DOM WHATWG', '#interface-documentfragment', 'DocumentFragment')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Added the constructor and the implementation of {{domxref("ParentNode")}}.</td> + </tr> + <tr> + <td>{{SpecName('Selectors API Level 1', '#the-apis', 'DocumentFragment')}}</td> + <td>{{Spec2('Selectors API Level 1')}}</td> + <td>Added the <code>querySelector()</code> and <code>querySelectorAll()</code> methods.</td> + </tr> + <tr> + <td>{{SpecName('DOM3 Core', 'core.html#ID-B63ED1A3', 'DocumentFragment')}}</td> + <td>{{Spec2('DOM3 Core')}}</td> + <td>No change from {{SpecName('DOM2 Core')}}</td> + </tr> + <tr> + <td>{{SpecName('DOM2 Core', 'core.html#ID-B63ED1A3', 'DocumentFragment')}}</td> + <td>{{Spec2('DOM2 Core')}}</td> + <td>No change from {{SpecName('DOM1')}}</td> + </tr> + <tr> + <td>{{SpecName('DOM1', 'level-one-core.html#ID-B63ED1A3', 'DocumentFragment')}}</td> + <td>{{Spec2('DOM1')}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("api.DocumentFragment")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Document_Object_Model">The DOM interfaces index.</a></li> +</ul> diff --git a/files/es/web/api/domapplicationsregistry/checkinstalled/index.html b/files/es/web/api/domapplicationsregistry/checkinstalled/index.html new file mode 100644 index 0000000000..5c2d298aa9 --- /dev/null +++ b/files/es/web/api/domapplicationsregistry/checkinstalled/index.html @@ -0,0 +1,49 @@ +--- +title: Apps.checkInstalled +slug: Web/API/DOMApplicationsRegistry/checkInstalled +tags: + - API + - Apps + - Apps API + - Firefox OS + - Procedimiento +translation_of: Archive/Marketplace/API/DOMApplicationsRegistry/checkInstalled +--- +<p>{{ ApiRef() }}</p> +<p>{{ non-standard_header() }}</p> +<h2 id="Resúmen">Resúmen</h2> +<p><span id="result_box" lang="es"><span class="hps">Obtiene</span> <span class="hps">información acerca de</span> <span class="hps">la aplicación</span> <span class="hps">dada.</span> <span class="hps">Esto puede ser usado</span> <span class="hps">para determinar</span> <span class="hps">si se ha instalado</span> <span class="hps">la aplicación.</span></span></p> +<h2 id="Sintaxis">Sintaxis</h2> +<pre><code>var request = window.navigator.mozApps.</code>checkInstalled<code>(url)</code>; +</pre> +<h2 id="Parámetros">Parámetros</h2> +<dl> + <dt> + <code>url</code></dt> + <dd> + Una <a href="/en-US/docs/JavaScript/Reference/Global_Objects/String">cadena</a> de URL <span id="result_box" lang="es"><span class="hps">que contiene</span> <span class="hps">la ubicación de el</span></span> <a href="/en-US/docs/Web/Apps/Manifest">manifiesto</a> de la aplicación.</dd> +</dl> +<h2 id="Returns" name="Returns">Resultados</h2> +<p>La función <code>checkInstalled()</code> devuelve un objeto {{ domxref("DOMRequest") }}. La propiedad <code>DOMRequest.result</code> contiene un <a href="/en-US/docs/Web/API/App"><code>App</code> object</a>, <span id="result_box" lang="es"><span class="hps">que es un objeto</span> <span class="hps">JavaScript</span> <span class="hps">que describe</span> <span class="hps">la aplicación</span> <span class="hps">instalada</span><span>.</span></span> Si la aplicación no se encuentra instalada, entonces <code>DOMRequest.result</code> es <code>null</code> (nulo).</p> +<h2 id="Ejemplo">Ejemplo</h2> +<pre class="brush: js">var request = window.navigator.mozApps.checkInstalled("http://ejemplo.com/manifest.webapp"); +request.onerror = function(e) { + alert("Error de llamada checkInstalled: " + request.error.name); +}; +request.onsuccess = function(e) { + if (request.result) { + console.log("La aplicación está instalada!"); + } + else { + console.log("La aplicación no está instalada!"); + } +};</pre> +<p>S<span id="result_box" lang="es"><span>e espera a las personas que llaman</span> <span class="hps">para establecer</span> <span class="hps">las</span> <span class="hps">propiedades</span> <span class="hps">de devolución de llamada</span></span> <code>onsuccess</code> y <code>onerror</code> del objeto devuelto, como se muestra en este ejemplo.<span id="result_box" lang="es"><span class="hps"> Si la llamada</span> <span class="hps">se realiza correctamente, </span> <span class="hps">un</span></span> <a href="/en-US/docs/Web/API/App"><code>App</code> object</a> se devuelve en la propiedad <code>result</code> del objeto devuelto. <span id="result_box" lang="es"><span class="hps">En</span> <span class="hps">el ejemplo esto es </span></span><code>request.result</code>.</p> +<h2 id="Errores">Errores</h2> +<p>La cadena <code>ERROR</code> <span class="short_text" id="result_box" lang="es"><span class="hps">pueden ser devueltos</span> <span class="hps">en</span></span> <code>DOMRequest.error</code>.</p> +<p><span id="result_box" lang="es"><span class="hps">Una excepción</span></span> <code>NS_ERROR_DOM_BAD_URI</code> <span id="result_box" lang="es"><span class="hps">se produce</span> <span class="hps">si</span> <span class="hps">el manifiesto</span> <span class="hps">está en un dominio</span> <span class="hps">diferente a</span> <span class="hps">la página</span> <span class="hps">en que se solicita la información</span></span>. <span id="result_box" lang="es"><span class="hps">Este</span> <span class="hps">se produce</span> <span class="hps">tan pronto como</span> <span class="hps">se invoca</span></span> <code>checkInstalled</code>.</p> +<h2 id="Temas_relacionados">Temas relacionados</h2> +<ul> + <li><a href="/en-US/docs/Web/API/App"><code>App</code> object</a></li> + <li><a href="/en-US/docs/Web/Apps/JavaScript_API">Apps JavaScript API</a></li> +</ul> diff --git a/files/es/web/api/domapplicationsregistry/getinstalled/index.html b/files/es/web/api/domapplicationsregistry/getinstalled/index.html new file mode 100644 index 0000000000..a1b96ee7ff --- /dev/null +++ b/files/es/web/api/domapplicationsregistry/getinstalled/index.html @@ -0,0 +1,40 @@ +--- +title: Apps.getInstalled +slug: Web/API/DOMApplicationsRegistry/getInstalled +tags: + - API + - Apps + - Apps API + - Firefox OS + - Procedimiento +translation_of: Archive/Marketplace/API/DOMApplicationsRegistry/getInstalled +--- +<p>{{ ApiRef() }}</p> +<p>{{ non-standard_header() }}</p> +<h2 id="Resumen">Resumen</h2> +<p><span id="result_box" lang="es"><span class="hps">Obtenga una lista de</span> <span class="hps">todas las aplicaciones instaladas</span> <span class="hps">desde</span> <span class="hps">este origen</span><span>.</span> <span class="hps">Por ejemplo</span><span>,</span> <span class="hps">si se llama a</span> <span class="hps">esto en el</span> <span class="hps">Firefox</span> <span class="hps">Marketplace,</span> <span class="hps">obtendrá</span> <span class="hps">la lista</span> <span class="hps">de aplicaciones instaladas</span> <span class="hps">por el</span> <span class="hps">Firefox</span> <span class="hps">Marketplace.</span></span></p> +<div class="note"> + <p><strong>Note:</strong> <span id="result_box" lang="es"><span class="hps">Múltiples</span> <span class="hps">aplicaciones</span> <span class="hps">por</span> <span class="hps">origen</span> <span class="hps">no son compatibles.</span> <span class="hps">Para alojar</span> <span class="hps">varias</span> <span class="hps">aplicaciones</span> <span class="hps">de un dominio</span></span>, <a href="/en-US/docs/Web/Apps/Adding_a_subdomain">establezca un subdominio para cada aplicación</a>; por ejemplo: <code>miapp.midominio.com</code>, <code>otraapp.midominio.com</code>, <span class="short_text" id="result_box" lang="es"><span class="hps">y así sucesivamente</span></span>.</p> +</div> +<h2 id="Sintaxis">Sintaxis</h2> +<pre><code>var request = window.navigator.mozApps.<code>getInstalled</code>()</code>; +</pre> +<h2 id="Parámetros">Parámetros</h2> +<p>Ninguno.</p> +<h2 id="Ejemplo">Ejemplo</h2> +<pre class="brush: js">var request = window.navigator.mozApps.getInstalled(); +request.onerror = function(e) { + alert("Error de llamada getInstalled: " + request.error.name); +}; +request.onsuccess = function(e) { + alert("Éxito, numero de apps: " + request.result.length); + var appsRecord = request.result; +};</pre> +<p>Se espera a las personas que llaman para establecer las propiedades de devolución <code>onsuccess</code> y <code>onerror</code> del objeto devuelto, como se muestra en este ejemplo. Si la llamada se realiza correctamente un array de <a href="/en-US/docs/Web/API/App"><code>App</code> objects</a> se devuelve en la propiedad <code>result</code> del objeto devuelto. En el ejemplo esto es <code>request.result</code>.</p> +<h2 id="Errores">Errores</h2> +<p>La cadena <code>ERROR</code> puede ser devuelta en <code>DOMRequest.error</code>.</p> +<h2 id="Temas_relacionados">Temas relacionados</h2> +<ul> + <li><a href="/en-US/docs/Web/API/App"><code>App</code> object</a></li> + <li><a href="/en-US/docs/Web/Apps/JavaScript_API">Apps JavaScript API</a></li> +</ul> diff --git a/files/es/web/api/domapplicationsregistry/index.html b/files/es/web/api/domapplicationsregistry/index.html new file mode 100644 index 0000000000..e9d68ecf20 --- /dev/null +++ b/files/es/web/api/domapplicationsregistry/index.html @@ -0,0 +1,89 @@ +--- +title: DOMApplicationsRegistry +slug: Web/API/DOMApplicationsRegistry +tags: + - API + - Apps + - B2G + - Firefox OS + - No estandar + - Referencia +translation_of: Archive/Marketplace/API/DOMApplicationsRegistry +--- +<p>{{ ApiRef("Apps") }}</p> + +<p>{{ non-standard_header() }}</p> + +<p>Provides support for installing, managing, and controlling Open Web apps in a browser. Currently implemented as {{ domxref('window.navigator.mozApps') }}.</p> + +<h2 id="Propiedad">Propiedad</h2> + +<dl> + <dt>{{domxref("DOMApplicationsRegistry.mgmt")}}</dt> + <dd>Un objeto <code>mgmt</code> que define funciones que le permiten a los tableros manejar y arrancar apps a favor del usuario.</dd> +</dl> + +<h2 id="Metodos">Metodos</h2> + +<dl> + <dt>{{ domxref("DOMApplicationsRegistry.checkInstalled()") }}</dt> + <dd>Verifica cuando una app se ha instalado tomando el manifiesto como su parametro.</dd> + <dt>{{ domxref("DOMApplicationsRegistry.install()") }}</dt> + <dd>Desencade la instalación de una app. Durante el proceso de instalación, la app es validada y se le pregunta al usuario si desea aprovar la instalación.</dd> + <dt>{{ domxref("DOMApplicationsRegistry.getSelf()") }}</dt> + <dd>Returna un objeto que contiene un {{ domxref('app') }} para la app.</dd> + <dt>{{ domxref("DOMApplicationsRegistry.getInstalled()") }}</dt> + <dd>Obtine una lista de todas las apps instaladas.</dd> +</dl> + +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</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 (WebKit)</th> + </tr> + <tr> + <td>Soporte basico</td> + <td>{{ CompatUnknown() }}</td> + <td>16.0</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</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 Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte basico</td> + <td>{{ CompatUnknown() }}</td> + <td>16.0</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<p> </p> diff --git a/files/es/web/api/domapplicationsregistry/install/index.html b/files/es/web/api/domapplicationsregistry/install/index.html new file mode 100644 index 0000000000..56f18e777b --- /dev/null +++ b/files/es/web/api/domapplicationsregistry/install/index.html @@ -0,0 +1,90 @@ +--- +title: Apps.install +slug: Web/API/DOMApplicationsRegistry/install +translation_of: Archive/Marketplace/API/DOMApplicationsRegistry/install +--- +<div> + {{ ApiRef() }} {{non-standard_header}}</div> +<h2 id="Summary" name="Summary">Resumen</h2> +<p>Activa la instalación de una aplicación. Durante este proceso la aplicación es validada y el usuario se le solicita aprovar la instalación .</p> +<p>Si la aplicación estaba previamente instalada desde el mismo dominio, llamando <code>install()</code>otra vez puede silenciosamente reescribir los datos de instalación. This can be used to modify the purchase receipt, for example, when a user upgrades from a free app to a premium app.</p> +<h2 id="Syntax" name="Syntax">Syntax</h2> +<pre class="syntaxbox"><code>var <em>request</em> = window.navigator.mozApps.install(<em>url</em>, <em>[receipt1, …]</em>)</code>;</pre> +<h3 id="Parameters" name="Parameters">Parameters</h3> +<div class="note"> + <strong>Note:</strong> There is currently (May 2012) a bug with passing a relative path in the <code>url</code> parameter. See {{ Bug("745928") }}.</div> +<dl> + <dt> + <code>url</code></dt> + <dd> + A <a href="/en-US/docs/JavaScript/Reference/Global_Objects/String"><code>string</code></a> URL containing the location of the <a href="/en-US/docs/Web/Apps/Manifest">manifest</a> to be installed. In the case of self distribution (where the installing origin is the same as the app origin), the installing site may omit the origin part of the URL and provide an absolute path (beginning with <code>/</code>).</dd> + <dt> + <code><strong>receipts</strong></code></dt> + <dd> + (Optional) An array of one or more receipts. Example:</dd> + <dd> + <pre>window.navigator.mozApps.install(url, ["receipt"])</pre> + </dd> + <dd> + If <code>receipts</code> is omitted it is treated as <code>null</code>. For more information see <a href="/en-US/docs/Web/Apps/Publishing/Validating_a_receipt">Validating a receipt</a>.</dd> +</dl> +<p>The <code>install()</code> function throws an exception if the required argument (<code>url</code>) is missing, or if unsupported arguments are present.</p> +<h2 id="Returns" name="Returns">Returns</h2> +<p>The <code>install()</code> function returns a {{ domxref("DOMRequest") }} object. The <code>DOMRequest.result</code> field contains an <a href="/en-US/docs/Web/API/App"><code>App</code> object</a>, which is a JavaScript object that describes the app that was just installed. Before the operation is finished, <code>DOMRequest.result</code> is <code>null</code>.</p> +<p>If the installation is not successful, <code>DOMRequest.error</code> contains a <a href="/en-US/docs/Web/Apps/JavaScript_API/Error_object"><code>DOMError</code> object</a>, which has information about the error.</p> +<h2 id="Example" name="Example">Example</h2> +<p>An example that shows how to use <code>install()</code> with the <code>DOMRequest.onsuccess</code> and <code>DOMRequest.onerror</code> callback properties.</p> +<pre class="brush: js">var request = window.navigator.mozApps.install(manifestUrl); +request.onsuccess = function () { + // Save the App object that is returned + var appRecord = this.result; + alert('Installation successful!'); +}; +request.onerror = function () { + // Display the error information from the DOMError object + alert('Install failed, error: ' + this.error.name); +}; +</pre> +<p>The <code>onsuccess</code> callback is called if the installation is successful. This means that the installation actions described <a href="/en-US/docs/Web/Apps/Platform-specific_details">here</a> have occurred.</p> +<p>If the installation is not successful the <code>onerror</code> callback is called. On a failed installation, <code>DOMRequest.error</code> contains a <code>DOMError</code> object that has information about the error.</p> +<p>The code above may look unusual to you, with listeners being added after the function has already been invoked. However, this is the way the <code>DOMRequest</code> object operates. The function invocation will wait until the listeners are defined, and then the listeners will fire appropriately. The <code>install()</code> function also works by itself, without the <code>.onsuccess</code> and <code>.onerror</code> listeners.</p> +<h2 id="Error" name="Error">Errors</h2> +<p>When the installation is unsuccessful, one of the following errors can be returned in <code>DOMRequest.error</code>.</p> +<dl> + <dt> + <code>DENIED</code></dt> + <dd> + The user cancelled the installation.</dd> + <dt> + <code>INVALID_MANIFEST</code></dt> + <dd> + The manifest, while well-formed JSON, does not have some required field or is somehow invalid.</dd> + <dt> + <code>MANIFEST_URL_ERROR</code></dt> + <dd> + Something other than an HTTP 200 status code was received, or some connection errors.</dd> + <dt> + <code>MANIFEST_PARSE_ERROR</code></dt> + <dd> + Bad JSON in the manifest.</dd> + <dt> + <code>NETWORK_ERROR</code></dt> + <dd> + Connection error.</dd> + <dt> + <code>REINSTALL_FORBIDDEN</code></dt> + <dd> + Reinstalls of apps are forbidden.</dd> + <dt> + <code>MULTIPLE_APPS_PER_ORIGIN_FORBIDDEN</code></dt> + <dd> + Installable apps have a "single app per origin" security policy; basically, you can't host more than one installable app per origin.</dd> +</dl> +<h2 id="Related_topics" name="Related_topics">Related topics</h2> +<ul> + <li><a href="/en-US/docs/Web/Apps/Publishing/Validating_a_receipt">Validating a receipt</a></li> + <li><a href="/en-US/docs/Web/Apps/Platform-specific_details">Platform-specific details</a></li> + <li><a href="/en-US/docs/Web/API/App">App object</a></li> + <li><a href="/en-US/docs/Web/API/DOMError">DOMError object</a></li> + <li><a href="/en-US/docs/Web/Apps/JavaScript_API">Apps JavaScript API</a></li> +</ul> diff --git a/files/es/web/api/domapplicationsregistry/installpackage/index.html b/files/es/web/api/domapplicationsregistry/installpackage/index.html new file mode 100644 index 0000000000..c269240c60 --- /dev/null +++ b/files/es/web/api/domapplicationsregistry/installpackage/index.html @@ -0,0 +1,36 @@ +--- +title: Apps.installPackage +slug: Web/API/DOMApplicationsRegistry/installPackage +translation_of: Archive/Marketplace/API/DOMApplicationsRegistry/installPackage +--- +<div> + {{ApiRef}} {{non-standard_header}}</div> +<h2 id="Resumen">Resumen</h2> +<p>Instala una <a href="/en-US/docs/Apps/Packaged_apps">aplicación empaquetada</a>.</p> +<div class="warning"> + Solo disponible en Firefox OS.</div> +<h2 id="Sintaxis">Sintaxis</h2> +<pre class="syntaxbox">installPackage: function(aURL[, aParams])</pre> +<h3 id="Parametros">Parametros</h3> +<ul> + <li><code>receipts</code>: Será utilizado para especificar los recibos de pago para esta instalación.</li> + <li><code>categories</code>: Será utilizado para especificar las categorías de la aplicación web.</li> +</ul> +<h2 id="Resultados">Resultados</h2> +<dl> + <dt> + <code>aURL</code></dt> + <dd> + El URL del paquete de aplicación a instalar. Esta debe ser una URL completa y absoluta.</dd> + <dt> + <code>aParams</code></dt> + <dd> + Opcionalmente, un objeto con información adicional:</dd> + <dt> + <code>DOMRequest</code></dt> +</dl> +<h2 id="Véase_también">Véase también</h2> +<ul> + <li>{{domxref("Apps.install()")}}</li> + <li><a href="/en-US/docs/Apps/Apps_JavaScript_API">Apps JavaScript API</a></li> +</ul> diff --git a/files/es/web/api/domerror/index.html b/files/es/web/api/domerror/index.html new file mode 100644 index 0000000000..d0768d0b41 --- /dev/null +++ b/files/es/web/api/domerror/index.html @@ -0,0 +1,130 @@ +--- +title: DOMError +slug: Web/API/DOMError +translation_of: Web/API/DOMError +--- +<p>{{ APIRef("DOM") }}</p> + +<p>La interfaz <strong><code>DOMError</code></strong> describe un objeto de error que contiene un nombre de error.</p> + +<h2 id="Propiedades">Propiedades</h2> + +<dl> + <dt>{{domxref("DOMError.name")}} {{readOnlyInline}}</dt> + <dd>Devuelve un {{ domxref("DOMString") }} representando uno de los tipos de errores listados a continuación.</dd> +</dl> + +<h2 id="Tipos_de_errores">Tipos de errores</h2> + +<table class="standard-table"> + <tbody> + <tr> + <td>Type</td> + <td>Description</td> + </tr> + <tr> + <td><code>IndexSizeError</code></td> + <td>Indice fuera de rango (Ej:. en un objeto {{ domxref("range") }}).</td> + </tr> + <tr> + <td><code>HierarchyRequestError</code></td> + <td>El árbol de jerarquías del nodo no es correcto.</td> + </tr> + <tr> + <td><code>WrongDocumentError</code></td> + <td>El objeto está en un {{ domxref("document") }} incorrecto.</td> + </tr> + <tr> + <td><code>InvalidCharacterError</code></td> + <td>El string contiene caracteres inválidos.</td> + </tr> + <tr> + <td><code>NoModificationAllowedError</code></td> + <td>El objeto no puede modificarse.</td> + </tr> + <tr> + <td><code>NotFoundError</code></td> + <td>El objeto no puede hallarse.</td> + </tr> + <tr> + <td><code>NotSupportedError</code></td> + <td>La operación no está permitida/soportada.</td> + </tr> + <tr> + <td><code>InvalidStateError</code></td> + <td>El objeto está inválido.</td> + </tr> + <tr> + <td><code>SyntaxError</code></td> + <td>El string no coincide con el patrón dado.</td> + </tr> + <tr> + <td><code>InvalidModificationError</code></td> + <td>El objeto no puede modificarse de esta manera.</td> + </tr> + <tr> + <td><code>NamespaceError</code></td> + <td>La operación no está permitida por Namespaces de XML.</td> + </tr> + <tr> + <td><code>InvalidAccessError</code></td> + <td>El objeto no soporta la operación o el argumento.</td> + </tr> + <tr> + <td><code>TypeMismatchError</code></td> + <td>El tipo de objeto no es el esperado.</td> + </tr> + <tr> + <td><code>SecurityError</code></td> + <td>La operación es insegura.</td> + </tr> + <tr> + <td><code>NetworkError</code></td> + <td>Error de red.</td> + </tr> + <tr> + <td><code>AbortError</code></td> + <td>La operación fue abortada.</td> + </tr> + <tr> + <td><code>URLMismatchError</code></td> + <td>La URL dada no coincide con otra URL a comparar.</td> + </tr> + <tr> + <td><code>QuotaExceededError</code></td> + <td>La quota ha sido excedida.</td> + </tr> + <tr> + <td><code>TimeoutError</code></td> + <td>La operación ha alcanzado su timeout.</td> + </tr> + <tr> + <td><code>InvalidNodeTypeError</code></td> + <td>El nodo (o uno de sus antecedentes) es incorrecto.</td> + </tr> + <tr> + <td><code>DataCloneError</code></td> + <td>El objeto no puede clonarse.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_Navegadores">Compatibilidad de Navegadores</h2> + + + +<p>{{Compat("api.DOMError")}}</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<p> </p> + +<ul> + <li>{{ spec("http://www.w3.org/TR/dom/#interface-domerror", "DOM 4 DOMError specification", "WD") }}</li> +</ul> + +<h2 id="Véase_también">Véase también</h2> + +<ul> + <li>{{ domxref("DOMException") }}</li> +</ul> diff --git a/files/es/web/api/domparser/index.html b/files/es/web/api/domparser/index.html new file mode 100644 index 0000000000..983d989f3e --- /dev/null +++ b/files/es/web/api/domparser/index.html @@ -0,0 +1,227 @@ +--- +title: DOMParser +slug: Web/API/DOMParser +translation_of: Web/API/DOMParser +--- +<p>{{APIRef("DOM")}}{{SeeCompatTable}}</p> + +<p><code>DOMParser</code> puede analizar gramaticalmente (parsear, en adelante) código XML o HTML almacenado en una cadena de texto y convertirlo en un <a href="/es/docs/Web/API/Document">Documento</a> DOM. <code>DOMParser</code> está especificado en <a href="https://w3c.github.io/DOM-Parsing/" title="http://html5.org/specs/dom-parsing.html">DOM Parsing and Serialization</a>.</p> + +<p>Tener en cuenta que <a href="/en-US/docs/DOM/XMLHttpRequest" title="DOM/XMLHttpRequest">XMLHttpRequest</a> soporta parsear XML y HTML desde recursos direccionables por URL.</p> + +<h2 id="Creando_un_DOMParser">Creando un DOMParser</h2> + +<p>Para crear un objeto <code>DOMParser </code>simplemente usar <code>new DOMParser()</code>.</p> + +<p>Para más información sobre crear un objeto <code>DOMParser</code> en extensiones Firefox, por favor vea la documentación de <a href="/en-US/docs/nsIDOMParser" title="nsIDOMParser"><code>nsIDOMParser</code></a>.</p> + +<h2 id="Parseando_XML">Parseando XML</h2> + +<p>Una vez creado el objeto parseador, puedes parsear XML desde una cadena de texto usando el método <code>parseFromString:</code></p> + +<pre class="brush: js">var parser = new DOMParser(); +var doc = parser.parseFromString(stringContainingXMLSource, "application/xml"); +</pre> + +<h3 id="Error_handling" name="Error_handling">Manejo de errores</h3> + +<p><code><font face="Open Sans, Arial, sans-serif">Es importante tener en cuenta que si el proceso de parseado falla, actualmente </font>DOMParser</code> no arroja una excepción, pero devuelve en cambio un documento de error (see {{Bug(45566)}}):</p> + +<pre class="brush:xml"><parsererror xmlns="http://www.mozilla.org/newlayout/xml/parsererror.xml"> +(error description) +<sourcetext>(a snippet of the source XML)</sourcetext> +</parsererror> +</pre> + +<p>Los errores de parseo son reportados también a la <a href="/en-US/docs/Consola_de_errores">Consola de errores</a>, con el URI del documento (ver debajo) como el origen del error.</p> + +<h2 id="Parseando_un_documento_SVG_o_HTML">Parseando un documento SVG o HTML</h2> + +<p>El <code>DOMParser</code> puede ser usado para parsear un documento SVG {{geckoRelease("10.0")}} o un documento HTML{{geckoRelease("12.0")}}. Hay 3 resultados diferentes posibles, dependiendo del tipo MIME dado. Si el tipo del MIME es <code>text/xml</code>, el objeto resultante será un <code>XMLDocument</code>, si el tipo MIME es <code>image/svg+xml</code> será un <code>SVGDocument,</code> y si el tipo MIME es <code>text/html</code> será un <code>HTMLDocument</code>.</p> + +<pre class="brush: js">var parser = new DOMParser(); +var doc = parser.parseFromString(stringContainingXMLSource, "application/xml"); +// returns a Document, but not a SVGDocument nor a HTMLDocument + +parser = new DOMParser(); +doc = parser.parseFromString(stringContainingXMLSource, "image/svg+xml"); +// returns a SVGDocument, which also is a Document. + +parser = new DOMParser(); +doc = parser.parseFromString(stringContainingHTMLSource, "text/html"); +// returns a HTMLDocument, which also is a Document. +</pre> + +<h3 id="Extensión_HTML_DOMParser_para_otros_navegadores">Extensión HTML DOMParser para otros navegadores</h3> + +<pre class="brush: js">/* + * DOMParser HTML extension + * 2012-09-04 + * + * By Eli Grey, http://eligrey.com + * Public domain. + * NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. + */ + +/*! @source https://gist.github.com/1129031 */ +/*global document, DOMParser*/ + +(function(DOMParser) { + "use strict"; + + var + proto = DOMParser.prototype + , nativeParse = <span style="font-size: 1rem;">proto</span><span style="font-size: 1rem;">.parseFromString</span> + ; + + // Firefox/Opera/IE throw errors on unsupported types + try { + // WebKit returns null on unsupported types + if ((new DOMParser()).parseFromString("", "text/html")) { + // text/html parsing is natively supported + return; + } + } catch (ex) {} + + <span style="font-size: 1rem;">proto</span><span style="font-size: 1rem;">.parseFromString = function(markup, type) {</span> + if (/^\s*text\/html\s*(?:;|$)/i.test(type)) { + var + doc = document.implementation.createHTMLDocument("") + ; + if (markup.toLowerCase().indexOf('<!doctype') > -1) { + doc.documentElement.innerHTML = markup; + } + else { + doc.body.innerHTML = markup; + } + return doc; + } else { + return <span style="font-size: 1rem;">nativeParse</span><span style="font-size: 1rem;">.apply(this, arguments);</span> + } + }; +}(DOMParser)); +</pre> + +<h3 id="DOMParser_de_ChromeJSMXPCOMPrivileged_Scope">DOMParser de Chrome/JSM/XPCOM/Privileged Scope</h3> + +<p>Ver artículo aquí: <a href="/en-US/docs/nsIDOMParser">nsIDOMParser</a></p> + +<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('DOM Parsing', '#the-domparser-interface', 'DOMParser')}}</td> + <td>{{Spec2('DOM Parsing')}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">Compatibilidad de navegadores</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>XML support</td> + <td>{{CompatChrome(1)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(1)}}</td> + <td>{{CompatIE(9)}}</td> + <td>{{CompatOpera(8)}}</td> + <td>{{CompatSafari(3.2)}}</td> + </tr> + <tr> + <td>SVG support</td> + <td>{{CompatChrome(4)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(10.0)}}</td> + <td>{{CompatIE(10)}}</td> + <td>{{CompatOpera(15)}}</td> + <td>{{CompatSafari(3.2)}}</td> + </tr> + <tr> + <td>HTML support</td> + <td>{{CompatChrome(30)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(12.0)}}</td> + <td>{{CompatIE(10)}}</td> + <td>{{CompatOpera(17)}}</td> + <td>{{CompatSafari(7.1)}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>XML support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>SVG support</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile(10.0)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>HTML support</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile(12.0)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also" name="See_also"> </h2> + +<h2 id="See_also" name="See_also">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/Parsing_and_serializing_XML" title="Parsing_and_serializing_XML">Parsing and serializing XML</a></li> + <li><a href="/en-US/docs/XMLHttpRequest">XMLHttpRequest</a></li> + <li><a href="/en-US/docs/XMLSerializer" title="XMLSerializer">XMLSerializer</a></li> + <li><a href="/en-US/Add-ons/Code_snippets/HTML_to_DOM">Parsing HTML to DOM</a></li> +</ul> diff --git a/files/es/web/api/domstring/cadenas_binarias/index.html b/files/es/web/api/domstring/cadenas_binarias/index.html new file mode 100644 index 0000000000..a52358f62c --- /dev/null +++ b/files/es/web/api/domstring/cadenas_binarias/index.html @@ -0,0 +1,31 @@ +--- +title: Cadenas binarias +slug: Web/API/DOMString/Cadenas_binarias +tags: + - Arreglos tipados JavaScript + - Cadena + - Cadena de caracteres + - DOM + - JavaScript + - Referencia + - String +translation_of: Web/API/DOMString/Binary +--- +<p>{{jsxref("String", "Cadenas JavaScript")}} son cadenas codificadas en UTF-16. Esto significa que cada unidad de código requiere dos bytes de memoria y puede representar <code>65535</code> puntos de código diferentes. Un subconjunto de estas cadenas está representado por cadenas UTF-16 que contienen solo caracteres ASCII (es decir, caracteres cuyo punto de código no excede <code>127</code>). Por ejemplo, la cadena <code>"¡Hola mundo!"</code> pertenece al subconjunto ASCII, mientras que la cadena <code>"ÀÈÌÒÙ"</code> no. Una <strong>cadena binaria</strong> es un concepto similar al subconjunto ASCII, pero en lugar de limitar el rango a <code>127</code>, permite hasta <code>255</code> puntos de código. Sin embargo, su propósito no es representar caracteres, sino datos binarios. El tamaño de los datos así representados es el doble de lo que sería en formato binario normal, sin embargo, esto no será visible para el usuario final, ya que la longitud de las cadenas de JavaScript se calcula usando dos bytes como unidad.</p> + +<p>Las cadenas binarias no forman parte del diseño del lenguaje JavaScript. Sin embargo, al menos una función nativa requiere cadenas binarias como entrada, {{domxref("WindowBase64.btoa", "btoa()")}}: invocarla en una cadena que contiene puntos de código mayores de <code>255</code> causará un error <code>Caracter fuera de rango</code>.</p> + +<p>La razón que llevó al uso de unidades de código UTF-16 como marcadores de posición para los números <code>uint8</code> es que a medida que las aplicaciones web se vuelven cada vez más poderosas (agregando funciones como manipulación de audio y video, acceso a datos sin procesar usando WebSockets, y así sucesivamente) ha quedado claro que hay ocasiones en las que sería útil que el código JavaScript pudiera manipular rápida y fácilmente datos binarios sin procesar.</p> + +<p>En el pasado, esto se tenía que simular tratando los datos sin procesar como <a href="https://developer.mozilla.org/es/docs/JavaScript/Reference/Global_Objects/String" title="JavaScript/Reference/Global_Objects/String">string</a> y utilizar el método <a href="https://developer.mozilla.org/es/docs/JavaScript/Reference/Global_Objects/String/charCodeAt" title="JavaScript/Reference/Global_Objects/String/charCodeAt"><code>charCodeAt()</code></a> para leer los bytes del búfer de datos (es decir, usando cadenas binarias). Sin embargo, esto es lento y propenso a errores, debido a la necesidad de múltiples conversiones (especialmente si los datos binarios en realidad no son datos en formato de bytes, sino, por ejemplo, enteros de 32 bits o flotantes).</p> + +<p>Los <a href="/es/docs/Web/JavaScript/Typed_arrays" title="/es/docs/Web/JavaScript/Typed_arrays">arreglos tipados en JavaScript</a> proporcionan un mecanismo para acceder a datos binarios sin procesar mucho más eficientemente. La API de <a href="/es/docs/Web/JavaScript/Typed_arrays/StringView" title="/es/docs/Web/JavaScript/Typed_arrays/StringView"><code>StringView</code></a> <span class="inlineIndicator" title="Esta API no es nativa"> cuyo constructor no es nativo</span> está un nivel por encima de los arreglos tipados y proporciona una interfaz para cadenas similar a la de <a class="external" href="http://en.wikipedia.org/wiki/C_(lenguaje_de_programación)">C</a>.</p> + +<h2 id="Ve_también">Ve también</h2> + +<ul> + <li><a href="/es/docs/Web/JavaScript/Typed_arrays" title="/es/docs/Web/JavaScript/Typed_arrays">Arreglos tipados</a></li> + <li><a href="/es/docs/Web/API/DOMString" title="/es/docs/Web/API/DOMString/Binary"><code>DOMString</code></a></li> + <li><a href="/es/docs/Web/JavaScript/Reference/Global_Objects/String" title="/es/docs/Web/API/DOMString">String</a></li> + <li><a href="/es/docs/Web/JavaScript/Typed_arrays/StringView" title="/es/docs/Web/JavaScript/Typed_arrays/String_view"><code>StringView</code></a></li> +</ul> diff --git a/files/es/web/api/domstring/index.html b/files/es/web/api/domstring/index.html new file mode 100644 index 0000000000..3809094105 --- /dev/null +++ b/files/es/web/api/domstring/index.html @@ -0,0 +1,60 @@ +--- +title: DOMString +slug: Web/API/DOMString +tags: + - API + - DOM + - Referencia + - Referencia DOM Gecko + - Referência DOM + - String + - WebAPI +translation_of: Web/API/DOMString +--- +<p>{{APIRef("DOM")}}</p> + +<p><strong><code>DOMString</code></strong> es un String UTF-16. Dado que JavaScript ya usa estos strings, se mapea <code>DOMString</code> directamente a {{jsxref("String")}}.</p> + +<p>Pasarle <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/null">null</a></code> a un método o parámetro que acepte un<code>DOMString</code> suele convertirse a texto como <code>"null"</code>.</p> + +<h2 id="Specification" name="Specification">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentarios</th> + </tr> + <tr> + <td>{{SpecName('WebIDL', '#idl-DOMString', 'DOMString')}}</td> + <td>{{Spec2('WebIDL')}}</td> + <td>Reescritura de la definición que elimina casos extraños.</td> + </tr> + <tr> + <td>{{SpecName('DOM3 Core', 'core.html#DOMString', 'DOMString')}}</td> + <td>{{Spec2('DOM3 Core')}}</td> + <td>Sin cambios desde {{SpecName('DOM2 Core')}}</td> + </tr> + <tr> + <td>{{SpecName('DOM2 Core', 'core.html#ID-C74D1578', 'DOMString')}}</td> + <td>{{Spec2('DOM2 Core')}}</td> + <td>Sin cambios desde {{SpecName('DOM1')}}</td> + </tr> + <tr> + <td>{{SpecName('DOM1', 'level-one-core.html#ID-C74D1578', 'DOMString')}}</td> + <td>{{Spec2('DOM1')}}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String" title="/en-US/docs/Web/API/DOMString">String</a></li> + <li>{{domxref("USVString")}}</li> + <li>{{domxref("CSSOMString")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Typed_arrays/String_view" title="/en-US/docs/Web/JavaScript/Typed_arrays/String_view"><code>StringView</code> – una representación en C de los strings basados en arrays tipados</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/DOMString/Binary">Strings binarios</a></li> +</ul> diff --git a/files/es/web/api/dragevent/index.html b/files/es/web/api/dragevent/index.html new file mode 100644 index 0000000000..8599ef6b93 --- /dev/null +++ b/files/es/web/api/dragevent/index.html @@ -0,0 +1,110 @@ +--- +title: DragEvent +slug: Web/API/DragEvent +tags: + - API + - DragEvent + - Referencia + - arrastrar y soltar + - drag and drop +translation_of: Web/API/DragEvent +--- +<div>{{APIRef("HTML Drag and Drop API")}}</div> + +<p>La interfaz <strong><code>DragEvent</code></strong> es un {{domxref("Event","evento DOM")}} que representa una interacción de arrastrar y soltar. El usuario inicia un arrastre posicionando un dispositivo puntero (como un ratón) en la superficie táctil y luego arrastra el puntero a una nueva posición (como como elemento del DOM). Las aplicaciones son libres de interpretar una interacción de arrastrar y soltar en una manera específica a la aplicación.</p> + +<p class="note">Esta interfaz hereda propiedades de {{domxref("MouseEvent")}} y {{domxref("Event")}}.</p> + +<h2 id="Propiedades">Propiedades</h2> + +<dl> + <dt>{{domxref('DragEvent.dataTransfer')}} {{readonlyInline}}</dt> + <dd>Los datos que son transferidos durante una interacción de arrastrar y soltar.</dd> +</dl> + +<h2 id="Constructores">Constructores</h2> + +<p class="note">A pesar que esta interfaz tiene un constructor, no es posible crear un objeto DataTransfer útil desde código, ya que los objetos {{domxref("DataTransfer")}} tienen un modelo de procesamiento y seguridad que está coordinado por el navegador durante el arrastrar y soltar.</p> + +<dl> + <dt>{{domxref("DragEvent.DragEvent", "DragEvent()")}}</dt> + <dd>Crea un DragEvent sintético y que no es de confianza.</dd> +</dl> + +<h2 id="Tipos_de_eventos">Tipos de eventos</h2> + +<dl> + <dt>{{event('drag')}}</dt> + <dd>Este evento es lanzado cuando un elemento o selección de texto está siendo arrastrado.</dd> + <dt>{{event('dragend')}}</dt> + <dd>Este evento es lanzado cuando la operación de arrastrar está siendo terminada (liberando el botón del ratón o pulsando la tecla de escape).</dd> + <dt>{{event('dragenter')}}</dt> + <dd>Este evento es lanzado cuando un elemento arrastrado ingresa a un destino de liberación válido.</dd> + <dt>{{event('dragexit')}}</dt> + <dd>Este evento es lanzado cuando un elemento ya no es el destino de selección inmediato de la operación de arrastre.</dd> + <dt>{{event('dragleave')}}</dt> + <dd>Este evento es lanzado cuando el elemento arrastrado o selección de texto deja un destino de liberación válido.</dd> + <dt>{{event('dragover')}}</dt> + <dd>Este evento es lanzado continuamente cuando un elemento o selección de texto está siendo arrastrado y el puntero del ratón está sobre un destino de liberación válido (cada 50 ms CUANDO el ratón no se está moviendo SINO más rápido entre 5 ms (movimiento lento) y 1 ms (movimiento rápido) aproximadamente. Este patrón de disparo es diferente que {{Event("mouseover")}}).</dd> + <dt>{{event('dragstart')}}</dt> + <dd>Este evento es lanzado cuando el usuario empieza a arrastrar un elemento o selección de texto.</dd> + <dt>{{event('drop')}}</dt> + <dd>Este evento es lanzado cuando un elemento o selección de texto es soltado en un destino válido.</dd> +</dl> + +<h2 id="GlobalEventHandlers">GlobalEventHandlers</h2> + +<dl> + <dt>{{domxref('GlobalEventHandlers.ondrag')}}</dt> + <dd>Un {{domxref('GlobalEventHandlers','manejador de evento global')}} para el evento {{event('drag')}}.</dd> + <dt>{{domxref('GlobalEventHandlers.ondragend')}}</dt> + <dd>Un {{domxref('GlobalEventHandlers','manejador de evento global')}} para el evento {{event('dragend')}}.</dd> + <dt>{{domxref('GlobalEventHandlers.ondragenter')}}</dt> + <dd>Un {{domxref('GlobalEventHandlers','manejador de evento global')}} para el evento {{event('dragenter')}}.</dd> + <dt>{{domxref('GlobalEventHandlers.ondragexit')}}</dt> + <dd>Un {{domxref('GlobalEventHandlers','manejador de evento global')}} para el evento {{event('dragexit')}}.</dd> + <dt>{{domxref('GlobalEventHandlers.ondragleave')}}</dt> + <dd>Un {{domxref('GlobalEventHandlers','manejador de evento global')}} para el evento {{event('dragleave')}}.</dd> + <dt>{{domxref('GlobalEventHandlers.ondragover')}}</dt> + <dd>Un {{domxref('GlobalEventHandlers','manejador de evento global')}} para el evento {{event('dragover')}}.</dd> + <dt>{{domxref('GlobalEventHandlers.ondragstart')}}</dt> + <dd>Un {{domxref('GlobalEventHandlers','manejador de evento global')}} para el evento {{event('dragstart')}}.</dd> + <dt>{{domxref('GlobalEventHandlers.ondrop')}}</dt> + <dd>Un {{domxref('GlobalEventHandlers','manejador de evento global')}} para el evento {{event('drop')}}.</dd> +</dl> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>Un ejemplo para cada propiedad, constructor, tipo de evento, y manejador de evento global están incluidos en sus respectivas páginas de referencia.</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificaciones</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName("HTML WHATWG", "#dragevent", "DragEvent")}}</td> + <td>{{Spec2("HTML WHATWG")}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName("HTML5.1", "editing.html#the-dragevent-interface", "DragEvent")}}</td> + <td>{{Spec2("HTML5.1")}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_entre_navegadores">Compatibilidad entre navegadores</h2> + +<div class="hidden">La tabla de compatibilidad en esta pagina es generado desde datos estructurados. Si gustas contribuir a los datos, por favor revisa <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> y envíanos un solicitud de cambios.</div> + +<p>{{Compat("api.DragEvent")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<p>{{page("/en-US/docs/Web/API/DataTransfer", "Ver también")}}</p> diff --git a/files/es/web/api/element/accesskey/index.html b/files/es/web/api/element/accesskey/index.html new file mode 100644 index 0000000000..a21970faa6 --- /dev/null +++ b/files/es/web/api/element/accesskey/index.html @@ -0,0 +1,22 @@ +--- +title: Element.accessKey +slug: Web/API/Element/accessKey +tags: + - API + - Propiedad + - necesidades de contenido +translation_of: Web/API/HTMLElement/accessKey +--- +<div>{{APIRef("DOM")}}</div> + +<div> </div> + +<p><span id="result_box" lang="es"><span>La propiedad</span> <strong><span>Element.accessKey</span></strong> <span>establece la pulsación</span><span> de teclado</span> <span>mediante el cual un</span> <span>usuario puede presionar</span> <span>para saltar a</span> <span>este elemento</span><span>.</span></span></p> + +<div class="note"> +<p><span id="result_box" lang="es"><span>Nota: la propiedad</span> <strong><span>Element.accessKey</span></strong> <span>se usa raramente</span> <span>debido a sus</span> <span>múltiples</span> <span>conflictos con las asociaciones de teclas</span> <span>que ya están presentes</span> <span>en los navegadores</span><span>.</span> <span>Para evitar</span> <span>esto,</span> <span>los navegadores implementan</span> <span>el comportamiento</span> <span>tecla de acceso</span> <span>si</span> <span>se pulsan las claves</span> <span>con otras teclas</span> <span>"cualificadas</span><span>" (como</span> <span>Alt</span> <span>+</span> <span>tecla de acceso</span><span>)</span><span>.</span></span></p> +</div> + +<p> </p> + +<p> </p> diff --git a/files/es/web/api/element/animate/index.html b/files/es/web/api/element/animate/index.html new file mode 100644 index 0000000000..e491efc0d7 --- /dev/null +++ b/files/es/web/api/element/animate/index.html @@ -0,0 +1,208 @@ +--- +title: Element.animate() +slug: Web/API/Element/animate +tags: + - API + - Animacion + - Elemento + - Experimental + - metodo + - waapi + - web animations api +translation_of: Web/API/Element/animate +--- +<div> +<p>{{APIRef('Web Animations')}} {{SeeCompatTable}}</p> + +<p>El método <strong><code>Element.animate()</code></strong> es un método abreviado para crear y reproducir una animación en un elemento. Devuelve la instancia creada de un objeto {{domxref("Animation")}} .</p> + +<h2 id="Síntaxis">Síntaxis</h2> + +<div class="syntaxbox"> +<pre class="brush: js"><var>element</var>.animate(<var>keyframes</var>, <var>options</var>); </pre> +</div> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code>keyframes</code></dt> + <dd> + <p>Un <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API/Keyframe_Formats">Objeto formateado para representar un conjunto de fotogramas clave</a>.</p> + </dd> + <dt><code>opciones</code></dt> + <dd>Puede ser un<strong> entero</strong> <strong>representando la duración de la animación</strong> (en milisegundos), <strong>o</strong> un Objeto conteniendo una o más propiedades de sincronización: </dd> + <dd> + <dl> + <dt><code>id {{optional_inline}}</code></dt> + <dd><code>Una propiedad única para animar()</code>: a <a href="https://developer.mozilla.org/en-US/docs/Web/API/DOMString" title="DOMString is a UTF-16 String. As JavaScript already uses such strings, DOMString is mapped directly to a String."><code>DOMString</code></a> con la cual se hace referencia a la animación.</dd> + </dl> + {{Page("/en-US/docs/Web/API/Web_Animations_API/Animation_timing_properties", "Properties")}}</dd> +</dl> + +<h4 id="Opciones_Futuras">Opciones Futuras</h4> + +<p><span id="result_box" lang="es"><span>Las</span> <span>siguientes</span> <span>opciones</span> <span>actualmente no</span> <span>se han enviado</span> <span>a todos los sitios</span><span>, pero</span> <span>se añadirán</span> <span>en un futuro próximo</span><span>.</span></span></p> + +<dl> + <dt><code>composite {{optional_inline}}</code></dt> + <dd>Determina como se combinan los valores entre esta animación y otra, animaciones independientes sin especificar la composición de su propia operación. <code>Valores predeterminados a reemplazar</code>. + <ul> + <li><code>añadir dicta un efecto aditivo</code>, donde cada iteración sucesiva se basa en la anterior. Por ejemplo con <code>transform</code>, a <code>translateX(-200px)</code> no anularía un valor anterior <code>rotate(20deg)</code> que resultaría <code>translateX(-200px) rotate(20deg)</code>.</li> + <li><code>acumular es similar pero un poco más inteligente</code>: <code>blur(2)</code> y <code>blur(5)</code> resultaría <code>blur(7)</code>, no <code>blur(2) blur(5)</code>.</li> + <li><code>remplazar sobreescribe el valor anterior con el nuevo</code>.</li> + </ul> + </dd> + <dt><code>iterationComposite {{optional_inline}}</code></dt> + <dd>Determina como se construyen los valores de una iteración a otra en esta animación. . <code>Se puede configurar para acumular o reemplazar</code> (ver arriba). <code>Valores predeterminados para reemplazar</code>.</dd> + <dt><code>spacing {{optional_inline}}</code></dt> + <dd>Determina como los keyframes sin compensación temporal deben ser distribuidos durante la duración de la animación. <code>Valores predeterminados para distribuir</code>. + <ul> + <li><code>distribuir las posiciones de los</code> keyframes para que la diferencia entre el anterior y el posterior estén compensadas por igual , lo que es como decir, sin ninguna compensación, esto distribuirá equitativamente los keyframes a traves del tiempo de ejecución.</li> + <li><code>situar las posiciones de los</code> keyframes de manera que igualen la diferencia entre los siguientes valores de una propiedad especifica sincronizada , lo que es como decir, que los keyframes estén más espaciados cuanto mayores sean los valores de sus propiedades.</li> + </ul> + + <p><img alt="" src="https://w3c.github.io/web-animations/img/spacing-distribute.svg" style="height: 210px; width: 200px;"> <img alt=" " src="https://w3c.github.io/web-animations/img/spacing-paced.svg" style="height: 210px; width: 200px;"></p> + </dd> +</dl> + +<h3 id="Valor_de_retorno">Valor de retorno</h3> + +<p>Returns an {{domxref("Animation")}}.</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>En la demostración <a href="https://codepen.io/rachelnabors/pen/rxpmJL/?editors=0010">Down the Rabbit Hole (con la Web Animation API)</a>, utilizamos el método conveniente, <code>animate()</code> para inmediatamente crear y ejecutar una animación en el elemento <code>#tunnel</code> para hacerlo fluir hacia arriba, indefinidamente. Observar el orden de paso de los objetos por los keyframes y también el bloque de opciones de sincronización.</p> + +<pre class="brush: js">document.getElementById("tunnel").animate([ + // keyframes + { transform: 'translateY(0px)' }, + { transform: 'translateY(-300px)' } +], { + // timing options + duration: 1000, + iterations: Infinity +}); +</pre> + +<h2 id="Especificaciones">Especificaciones</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 Animations', '#the-animatable-interface', 'animate()' )}}</td> + <td>{{Spec2('Web Animations')}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_los_Navegadores">Compatibilidad en los Navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome("36")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{ CompatGeckoDesktop("48.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>23</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>id</code> option</td> + <td>{{CompatChrome(50.0)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{ CompatGeckoDesktop("48.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>37</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>composite</code>, <code>iterationComposite</code>, and <code>spacing</code> options</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</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>Android Webview</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatChrome(39.0)}}</td> + <td>{{CompatChrome(39.0)}}</td> + <td>{{ CompatGeckoMobile("48.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>id</code> option</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(50.0)}}</td> + <td>{{CompatChrome(50.0)}}</td> + <td>{{ CompatGeckoMobile("48.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>composite</code>, <code>iterationComposite</code>, and <code>spacing</code> options</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_También">Ver También</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Web_Animations_API">Web Animations API</a></li> + <li>{{domxref("Animation")}}</li> +</ul> +</div> diff --git a/files/es/web/api/element/attachshadow/index.html b/files/es/web/api/element/attachshadow/index.html new file mode 100644 index 0000000000..33e1d119ae --- /dev/null +++ b/files/es/web/api/element/attachshadow/index.html @@ -0,0 +1,158 @@ +--- +title: Element.attachShadow() +slug: Web/API/Element/attachShadow +translation_of: Web/API/Element/attachShadow +--- +<div>{{APIRef('Shadow DOM')}}</div> + +<p>El método <strong><code>Element.attachShadow()</code></strong> adjunta un árbol DOM "sombra" al elemento especificado y devuelve una referencia a su raíz {{domxref("ShadowRoot")}}.</p> + +<h2 id="Elementos_a_los_que_puedes_adjuntar_un_DOM_sombra">Elementos a los que puedes adjuntar un DOM "sombra"</h2> + +<p>No se puede adjuntar un DOM "sombra" a cualquier tipo de elemento. Hay algunos que no pueden tenerlo por razones de seguridad (por ejemplo {{htmlelement("a")}}), y algunos más. Los siguientes elementos de la lista <strong>pueden</strong> adjuntar un DOM "sombra":</p> + +<ul> + <li>Cualquier elemento autónomo con un <a href="https://html.spec.whatwg.org/multipage/custom-elements.html#valid-custom-element-name" title="nombre válido">nombre válido</a></li> + <li>{{htmlelement("article")}}</li> + <li>{{htmlelement("aside")}}</li> + <li>{{htmlelement("blockquote")}}</li> + <li>{{htmlelement("body")}}</li> + <li>{{htmlelement("div")}}</li> + <li>{{htmlelement("footer")}}</li> + <li>{{htmlelement("h1")}}</li> + <li>{{htmlelement("h2")}}</li> + <li>{{htmlelement("h3")}}</li> + <li>{{htmlelement("h4")}}</li> + <li>{{htmlelement("h5")}}</li> + <li>{{htmlelement("h6")}}</li> + <li>{{htmlelement("header")}}</li> + <li>{{htmlelement("main")}}</li> + <li>{{htmlelement("nav")}}</li> + <li>{{htmlelement("p")}}</li> + <li>{{htmlelement("section")}}</li> + <li>{{htmlelement("span")}}</li> +</ul> + +<h2 id="Syntax" name="Syntax">Syntaxis</h2> + +<pre class="syntaxbox">var <var>shadowroot</var> = <var>element</var>.attachShadow(<var>shadowRootInit</var>); +</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code>shadowRootInit</code></dt> + <dd>Un diccionario <code>ShadowRootInit</code> , que puede contener los siguientes campos: + <dl> + <dt><code>mode</code></dt> + <dd> + <p>Una cadena que especifique el <em>modo de encapsulación</em> para el árbol DOM "sombra". Este puede tener uno de los siguientes valores:</p> + + <ul> + <li><code>open</code>: Los elementos del árbol son accesibles desde fuera del elemento, por ejemplo usando {{domxref("Element.shadowRoot")}}:<br> + + <pre>element.shadowRoot; // Returns a ShadowRoot obj</pre> + </li> + <li><code>closed</code>: Deniega el acceso a lo(s) nodo(s) desde fuera mediante JavaScript:<br> + + <pre>element.shadowRoot; // Returns null +</pre> + </li> + </ul> + </dd> + <dt><code>delegatesFocus</code></dt> + <dd>Un booleano que, si se establece a <code>true</code>, mitiga problemas de comportamiento relativos a la capacidad de tomar el foco. Cuando se hace click en una parte del DOM "sombra" que no puede tomar el foco, la primera parte del árbol que pueda tomar el foco lo hará, y le dará cualquier estilo disponible mediante CSS con <code>:focus</code>.</dd> + </dl> + </dd> +</dl> + +<h3 id="Valor_retorno">Valor retorno</h3> + +<p>Devuelve un objeto {{domxref("ShadowRoot")}}.</p> + +<h3 id="Excepciones">Excepciones</h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Excepción</th> + <th scope="col">Explicación</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>InvalidStateError</code></td> + <td>El elemento que estás intentando adjuntar ya tiene una DOM "sombra".</td> + </tr> + <tr> + <td><code>NotSupportedError</code></td> + <td>Estás intentando adjuntar DOM "sombra" a un elemento fuera del espacio de nombres HTML, o el elemento no puede tener una DOM "sombra". adjunta (ver abajo).</td> + </tr> + </tbody> +</table> + +<h2 id="Ejemplos">Ejemplos</h2> + +<p>Los siguientes ejemplos están tomados de la demo <a href="https://github.com/mdn/web-components-examples/tree/master/word-count-web-component">word-count-web-component</a> (<a href="https://mdn.github.io/web-components-examples/word-count-web-component/">verlo también en modo live</a>). Puedes ver que usamos <code>attachShadow()</code> en mitad del código para crear una DOM "sombra", a la que luego adjuntamos el contenido de nuesto elemento personalizado.</p> + +<pre class="brush: js">// Crear una clase para el elemento +class CuentaPalabras extends HTMLParagraphElement { + constructor() { + // Siemmpre llamar a super en el constructor + super(); + + // contar las palabras en el nodo padre + var cpPadre = this.parentNode; + + function cuentaPalabras(nodo){ + var texto = nodo.innerText || nodo.textContent + return texto.trim().split(/\s+/g).length; + } + + var cuenta = 'Palabras: ' + cuentaPalabras(cpPadre); + + // Crear un DOM "sombra" + var sombra = this.attachShadow({mode: 'open'}); + + // Crear el nodo de texto y añadirle el contador de palabras + var texto = document.createElement('span'); + texto.textContent = count; + + // Añadirlo a la sombra + sombra.appendChild(texto); + + // Actualizar el contador cuando el contenido del elemento cambie + setInterval(function() { + var cuenta = 'Palabras: ' + cuentaPalabras(cpPadre); + texto.textContent = cuenta; + }, 200) + } +} + +// Definir el nuevo elemento +customElements.define('cuenta-palabras', CuentaPalabras , { extends: 'p' });</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('DOM WHATWG', '#dom-element-attachshadow', 'attachShadow()')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_navegadores">Compatibilidad navegadores</h2> + + + +<p>{{Compat("api.Element.attachShadow")}}</p> diff --git a/files/es/web/api/element/attributes/index.html b/files/es/web/api/element/attributes/index.html new file mode 100644 index 0000000000..3b0f1da338 --- /dev/null +++ b/files/es/web/api/element/attributes/index.html @@ -0,0 +1,157 @@ +--- +title: Element.attributes +slug: Web/API/Element/attributes +translation_of: Web/API/Element/attributes +--- +<p>{{ APIRef("DOM") }}</p> + +<p>La propiedad <strong><code>Element.attributes</code></strong> retorna una colección "viva" cuyos nodos son todos los atributos registrados en el nodo especificado. Es un {{domxref("NamedNodeMap")}}, no un <code>Array</code>, así que no tiene los métodos de {{jsxref("Array")}} y los índices de nodo {{domxref("Attr")}} pueden diferir en cada navegador. Más concretamente <code>attributes</code> es un conjunto de pares de cadenas nombre/valor que representan la información relativa a cada atributo.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox">var <em>attr</em> =<em> element</em>.attributes; +</pre> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<h3 id="Ejemplos_básicos">Ejemplos básicos</h3> + +<pre class="brush: js">// Obtiene el primer elemento <p> en el documento +var para = document.getElementsByTagName("p")[0]; +var atts = para.attributes;</pre> + +<h3 id="Notes" name="Notes">Enumerando atributos de elemtentos</h3> + +<p>La indexación numérica es útil para recorrer de todos los atributos de un elemento.<br> + El siguiente ejemplo corre a través de los atributors del elemento con id "p1" en el documento, e imprime el valor de cada atributo.</p> + +<pre class="brush: html"><!DOCTYPE html> + +<html> + + <head> + <title>Attributes example</title> + <script type="text/javascript"> + function listAttributes() { + var paragraph = document.getElementById("paragraph"); + var result = document.getElementById("result"); + + // Primero, verifiquenmos que el párrafo tiene algún atributo + if (paragraph.hasAttributes()) { + var attrs = paragraph.attributes; + var output = ""; + for(var i = attrs.length - 1; i >= 0; i--) { + output += attrs[i].name + "->" + attrs[i].value; + } + result.value = output; + } else { + result.value = "No hay atributos que mostrar"; + } + } + </script> + </head> + +<body> + <p id="paragraph" style="color: green;">Párrafo de ejemplo</p> + <form action=""> + <p> + <input type="button" value="Muestra el nombre cada atributo y su valor" + onclick="listAttributes();"> + <input id="result" type="text" value=""> + </p> + </form> +</body> +</html></pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Observaciones</th> + </tr> + <tr> + <td>{{SpecName('DOM WHATWG', '#dom-element-attributes', 'Element.attributes')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>From {{SpecName('DOM3 Core')}}, moved from {{domxref("Node")}} a {{domxref("Element")}}</td> + </tr> + <tr> + <td>{{SpecName('DOM3 Core', 'core.html#ID-84CF096', 'Element.attributes')}}</td> + <td>{{Spec2('DOM3 Core')}}</td> + <td>Sin cambios desde {{SpecName('DOM2 Core')}}</td> + </tr> + <tr> + <td>{{SpecName('DOM2 Core', 'core.html#ID-84CF096', 'Element.attributes')}}</td> + <td>{{Spec2('DOM2 Core')}}</td> + <td>Sin cambios desde {{SpecName('DOM1')}}</td> + </tr> + <tr> + <td>{{SpecName('DOM1', 'level-one-core.html#ID-84CF096', 'Element.attributes')}}</td> + <td>{{Spec2('DOM1')}}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Prestación</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }} [1]</td> + <td>6.0 [2]</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Prestación</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }} [1]</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Anes de Firefox 22, este atributo era implementado en la interfaz {{domxref("Node")}} (heredada de {{domxref("Element")}}). Se trasladó a esta interfaz de acuerdo a la especificación y el uso en otros navegadores.</p> + +<p>[2] Internet Explorer 5.5 retorna un mapa conteniendo los valores en lugar de objetos attribute.</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("NamedNodeMap")}}, la interfaz del objeto retornado.</li> + <li>Consideracións sobre compatibilidad cruzada entre navegadores: en <a class="external" href="http://www.quirksmode.org/dom/w3c_core.html#attributes" title="http://www.quirksmode.org/dom/w3c_core.html#attributes">quirksmode</a></li> +</ul> diff --git a/files/es/web/api/element/classlist/index.html b/files/es/web/api/element/classlist/index.html new file mode 100644 index 0000000000..4d45dd2e31 --- /dev/null +++ b/files/es/web/api/element/classlist/index.html @@ -0,0 +1,215 @@ +--- +title: Element.classList +slug: Web/API/Element/classList +tags: + - API + - DOM + - Elemento + - Propiedad + - Referencia + - Sólo-Lectura +translation_of: Web/API/Element/classList +--- +<div>{{APIRef("DOM")}}</div> + +<p>La propiedad de sólo lectura <code><strong>Element.classList</strong></code> devuelve una colección activa de <a href="https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList" title="The DOMTokenList interface represents a set of space-separated tokens. Such a set is returned by Element.classList, HTMLLinkElement.relList, HTMLAnchorElement.relList or HTMLAreaElement.relList. It is indexed beginning with 0 as with JavaScript Array objects. DOMTokenList is always case-sensitive."><code>DOMTokenList</code></a> de los atributos de clase del elemento.</p> + +<p>Usar <code>classList</code> es una forma práctica de acceder a la lista de clases de un elemento como una cadena de texto delimitada por espacios a través de {{domxref("element.className")}}.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var <var>elementClasses</var> = elementNodeReference.classList; +</pre> + +<p><em>elementClasses</em> es un <a href="/en-US/docs/DOM/DOMTokenList">DOMTokenList</a> que representa el atributo clase de <em>elementNodeReference</em>. Si el atributo clase no está definido o está vacío, <em>elementClasses.length</em> devuelve 0. <code>element.classList</code> por sí mismo es de sólo lectura, aunque puede ser modificado usando los métodos<code> add()</code> y <code>remove()</code>.</p> + +<h2 id="Métodos">Métodos</h2> + +<dl> + <dt>add( String [, String] )</dt> + <dd>Añade las clases indicadas. Si estas clases existieran en el atributo del elemento serán ignoradas.</dd> + <dt>remove( String [, String] )</dt> + <dd>Elimina las clases indicadas.<br> + <strong>Nota:</strong> Eliminar una clase que no existe NO produce un error.</dd> + <dt><strong>item</strong>( Number )</dt> + <dd>Devuelve el valor de la clase por índice en la colección.</dd> + <dt><strong>toggle</strong>( String [, force] )</dt> + <dd>Cuando sólo hay un argumento presente: Alterna el valor de la clase; ej., si la clase existe la <u>elimina</u> y devuelve <code>false</code>, si no, la <u>añade</u> y devuelve <code>true</code>.<br> + Cuando el segundo argumento está presente: Si el segundo argumento se evalúa como <code>true</code>, se añade la clase indicada, y si se evalúa como <code>false</code>, la elimina.</dd> + <dt>contains( String )</dt> + <dd>Comprueba si la clase indicada existe en el atributo de clase del elemento.</dd> + <dt>replace( oldClass, newClass )</dt> + <dd>Reemplaza una clase existente por una nueva.</dd> +</dl> + +<h2 id="Ejemplos">Ejemplos</h2> + +<pre class="brush: js" dir="rtl">// div es una referencia de objeto al elemento <div> con class="foo bar" +div.classList.remove("foo"); +div.classList.add("anotherclass"); + +// si visible está presente la elimina, de lo contrario la añade +div.classList.toggle("visible"); + +// añadir/eliminar visible, dependiendo de la condición, i menor que 10 +div.classList.toggle("visible", i < 10 ); + +alert(div.classList.contains("foo")); + +// añadir o eliminar varias clases +div.classList.add("foo", "bar"); +div.classList.remove("foo", "bar"); + +// reemplazar la clase "foo" por "bar" +div.classList.replace("foo", "bar");</pre> + +<div class="note"> +<p>Las versiones de Firefox anteriores a la 26 no implementan el uso de múltiples argumentos en los métodos add/remove/toggle. Vea <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=814014">https://bugzilla.mozilla.org/show_bug.cgi?id=814014</a></p> +</div> + +<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("HTML WHATWG", "dom.html#dom-classlist", "Element.classList")}}</td> + <td>{{Spec2("HTML WHATWG")}}</td> + <td>Nota en la especificación de HTML relacionada con el atributo {{htmlattrxref("class")}}.</td> + </tr> + <tr> + <td>{{SpecName("DOM WHATWG", "#dom-element-classlist", "Element.classList")}}</td> + <td>{{Spec2("DOM WHATWG")}}</td> + <td>Definición inicial</td> + </tr> + <tr> + <td>{{SpecName("DOM4", "#dom-element-classlist", "Element.classList")}}</td> + <td>{{Spec2("DOM4")}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>8</td> + <td>12</td> + <td>{{CompatGeckoDesktop(1.9.2)}}</td> + <td>10<sup>[1]</sup></td> + <td>11.50</td> + <td>5.1</td> + </tr> + <tr> + <td>Segundo argumento del método <code>toggle()</code></td> + <td>24</td> + <td>12</td> + <td>{{CompatGeckoDesktop(24)}}</td> + <td>{{CompatNo}}<sup>[2]</sup></td> + <td>15</td> + <td>7</td> + </tr> + <tr> + <td>Múltiples argumentos para <code>add()</code> y <code>remove()</code></td> + <td>28</td> + <td>12</td> + <td>{{CompatGeckoDesktop(26)}}</td> + <td>{{CompatNo}}</td> + <td>15</td> + <td>7</td> + </tr> + <tr> + <td><code>replace()</code></td> + <td>61</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("49")}}</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>Característica</th> + <th>Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>3.0</td> + <td>12</td> + <td>{{CompatGeckoMobile(1.9.2)}}</td> + <td>10<sup>[1]</sup></td> + <td>11.10</td> + <td>5.0</td> + </tr> + <tr> + <td>Segundo argumento del método <code>toggle()</code></td> + <td>4.4</td> + <td>12</td> + <td>{{CompatGeckoMobile(24)}}</td> + <td>{{CompatNo}}<sup>[2]</sup></td> + <td>{{CompatUnknown}}</td> + <td>7.0</td> + </tr> + <tr> + <td>Múltiples argumentos para <code>add()</code> y <code>remove()</code></td> + <td>4.4</td> + <td>12</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>7.0</td> + </tr> + <tr> + <td><code>replace()</code></td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop("49")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] No soportado para elementos SVG. Vea <a href="https://connect.microsoft.com/IE/feedback/details/1046039/classlist-not-working-on-svg-elements">un informe de Microsoft acerca de esto</a>.<br> + [2] Internet Explorer no lo implementa actualmente. Vea <a href="https://connect.microsoft.com/IE/feedback/details/878564/element-classlist-toggle-does-not-support-second-parameter">un informe de Microsoft acerca de esto</a>.</p> + +<h2 id="Vea_también">Vea también</h2> + +<ul> + <li>{{domxref("element.className")}}</li> + <li>{{domxref("DOMTokenList")}};</li> +</ul> diff --git a/files/es/web/api/element/classname/index.html b/files/es/web/api/element/classname/index.html new file mode 100644 index 0000000000..be9b04b4b0 --- /dev/null +++ b/files/es/web/api/element/classname/index.html @@ -0,0 +1,130 @@ +--- +title: Element.className +slug: Web/API/Element/className +tags: + - API + - DOM + - Gecko + - Propiedad + - Referencia +translation_of: Web/API/Element/className +--- +<div>{{APIRef("DOM")}}</div> + +<h2 id="Resumen">Resumen</h2> + +<p><strong>className</strong> obtiene y establece el valor del atributo <code>class</code> del elemento especificado.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><var>var cName</var> = <var>elementNodeReference</var>.className; +<var>elementNodeReference</var>.className = <var>cName</var>;</pre> + +<ul> + <li><var>cName</var> es una variable de cadena representando la clase o la lista de clases separada por espacios, del elemento en cuestión.</li> +</ul> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush: js">let elm = document.getElementById('item'); + +if(elm.className === 'active'){ + elm.className = 'inactive'; +} else { + elm.className = 'active'; +}</pre> + +<h2 id="Notes" name="Notes">Notas</h2> + +<p>El nombre <code>className</code> es utilizado para esta propiedad en lugar de <code>class</code> para evitar conflictos con la palabra clave "class" existente en muchos de los lenguages que son usados para manipular el DOM.</p> + +<p><code>className</code> también puede ser una instancia de {{domxref("SVGAnimatedString")}} si <code>element</code> es un {{domxref("SVGElement")}}. Es mejor de obtener/establecer la propiedad <code>className</code> de un elemento utilizando {{domxref("Element.getAttribute")}} y {{domxref("Element.setAttribute")}} si estás tratando con elementos SVG.</p> + +<pre class="brush: js">elm.setAttribute('class', elm.getAttribute('class'))</pre> + +<p> </p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Observaciones</th> + </tr> + <tr> + <td>{{SpecName("DOM WHATWG", "#dom-element-classname", "element.className")}}</td> + <td>{{Spec2("DOM WHATWG")}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName("DOM4", "#dom-element-classname", "element.className")}}</td> + <td>{{Spec2("DOM4")}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName("DOM2 HTML", "html.html#ID-95362176", "element.className")}}</td> + <td>{{Spec2("DOM2 HTML")}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Chrome para Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("element.classList")}}</li> +</ul> diff --git a/files/es/web/api/element/click_event/index.html b/files/es/web/api/element/click_event/index.html new file mode 100644 index 0000000000..9a74553c13 --- /dev/null +++ b/files/es/web/api/element/click_event/index.html @@ -0,0 +1,280 @@ +--- +title: click +slug: Web/API/Element/click_event +translation_of: Web/API/Element/click_event +--- +<p>El evento "click" se dispara cuando se presiona el botón de un dispositivo de entrada (Mouse o Mousepad) sobre un elemento. </p> + +<h2 id="Información_General">Información General</h2> + +<dl> + <dt style="float: left; text-align: right; width: 120px;">Especificación</dt> + <dd style="margin: 0 0 0 120px;"><a class="external" href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-click">DOM L3</a></dd> + <dt style="float: left; text-align: right; width: 120px;">Interfaz</dt> + <dd style="margin: 0 0 0 120px;">{{domxref("MouseEvent")}}</dd> + <dt style="float: left; text-align: right; width: 120px;">Bubbles</dt> + <dd style="margin: 0 0 0 120px;">Yes</dd> + <dt style="float: left; text-align: right; width: 120px;">Cancelable</dt> + <dd style="margin: 0 0 0 120px;">Yes</dd> + <dt style="float: left; text-align: right; width: 120px;">Target</dt> + <dd style="margin: 0 0 0 120px;">Element</dd> + <dt style="float: left; text-align: right; width: 120px;">Default Action</dt> + <dd style="margin: 0 0 0 120px;">Varies</dd> +</dl> + +<h2 id="Propiedades">Propiedades</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><a href="/en-US/docs/Web/API/EventTarget" title="EventTarget is an interface implemented by objects that can receive events and may have listeners for them."><code>EventTarget</code></a></td> + <td>The event target (the topmost target in the DOM tree).</td> + </tr> + <tr> + <td><code>type</code> {{readonlyInline}}</td> + <td><a href="/en-US/docs/Web/API/DOMString" title="DOMString is a UTF-16 String. As JavaScript already uses such strings, DOMString is mapped directly to a String."><code>DOMString</code></a></td> + <td>The type of event.</td> + </tr> + <tr> + <td><code>bubbles</code> {{readonlyInline}}</td> + <td><a href="/en-US/docs/Web/API/Boolean" title="The Boolean object is an object wrapper for a boolean value."><code>Boolean</code></a></td> + <td>Whether the event normally bubbles or not</td> + </tr> + <tr> + <td><code>cancelable</code> {{readonlyInline}}</td> + <td><a href="/en-US/docs/Web/API/Boolean" title="The Boolean object is an object wrapper for a boolean value."><code>Boolean</code></a></td> + <td>Whether the event is cancellable or not?</td> + </tr> + <tr> + <td><code>view</code> {{readonlyInline}}</td> + <td><a class="new" href="/en-US/docs/Web/API/WindowProxy" rel="nofollow" title="The documentation about this has not yet been written; please consider contributing!"><code>WindowProxy</code></a></td> + <td><a href="/en-US/docs/Web/API/Document/defaultView" title="In browsers, document.defaultView returns the window object associated with a document, or null if none is available."><code>document.defaultView</code></a> (<code>window</code> of the document)</td> + </tr> + <tr> + <td><code>detail</code> {{readonlyInline}}</td> + <td><code>long</code> (<code>float</code>)</td> + <td>A count of consecutive clicks that happened in a short amount of time, incremented by one.</td> + </tr> + <tr> + <td><code>currentTarget</code> {{readonlyInline}}</td> + <td>EventTarget</td> + <td>The node that had the event listener attached.</td> + </tr> + <tr> + <td><code>relatedTarget</code> {{readonlyInline}}</td> + <td>EventTarget</td> + <td>For <code>mouseover</code>, <code>mouseout</code>, <code>mouseenter</code> and <code>mouseleave</code> events: the target of the complementary event (the <code>mouseleave</code> target in the case of a <code>mouseenter</code> event). <code>null</code> otherwise.</td> + </tr> + <tr> + <td><code>screenX</code> {{readonlyInline}}</td> + <td>long</td> + <td>The X coordinate of the mouse pointer in global (screen) coordinates.</td> + </tr> + <tr> + <td><code>screenY</code> {{readonlyInline}}</td> + <td>long</td> + <td>The Y coordinate of the mouse pointer in global (screen) coordinates.</td> + </tr> + <tr> + <td><code>clientX</code> {{readonlyInline}}</td> + <td>long</td> + <td>The X coordinate of the mouse pointer in local (DOM content) coordinates.</td> + </tr> + <tr> + <td><code>clientY</code> {{readonlyInline}}</td> + <td>long</td> + <td>The Y coordinate of the mouse pointer in local (DOM content) coordinates.</td> + </tr> + <tr> + <td><code>button</code> {{readonlyInline}}</td> + <td>unsigned short</td> + <td>The button number that was pressed when the mouse event was fired: Left button=0, middle button=1 (if present), right button=2. For mice configured for left handed use in which the button actions are reversed the values are instead read from right to left.</td> + </tr> + <tr> + <td><code>buttons</code> {{readonlyInline}}</td> + <td>unsigned short</td> + <td>The buttons being pressed when the mouse event was fired: Left button=1, Right button=2, Middle (wheel) button=4, 4th button (typically, "Browser Back" button)=8, 5th button (typically, "Browser Forward" button)=16. If two or more buttons are pressed, returns the logical sum of the values. E.g., if Left button and Right button are pressed, returns 3 (=1 | 2). <a href="/en-US/docs/Web/API/MouseEvent">More info</a>.</td> + </tr> + <tr> + <td><code>mozPressure</code> {{readonlyInline}}</td> + <td>float</td> + <td>The amount of pressure applied to a touch or tabdevice when generating the event; this value ranges between 0.0 (minimum pressure) and 1.0 (maximum pressure).</td> + </tr> + <tr> + <td><code>ctrlKey</code> {{readonlyInline}}</td> + <td>boolean</td> + <td><code>true</code> if the control key was down when the event was fired. <code>false</code> otherwise.</td> + </tr> + <tr> + <td><code>shiftKey</code> {{readonlyInline}}</td> + <td>boolean</td> + <td><code>true</code> if the shift key was down when the event was fired. <code>false</code> otherwise.</td> + </tr> + <tr> + <td><code>altKey</code> {{readonlyInline}}</td> + <td>boolean</td> + <td><code>true</code> if the alt key was down when the event was fired. <code>false</code> otherwise.</td> + </tr> + <tr> + <td><code>metaKey</code> {{readonlyInline}}</td> + <td>boolean</td> + <td><code>true</code> if the meta key was down when the event was fired. <code>false</code> otherwise.</td> + </tr> + </tbody> +</table> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush: js"><div id="prueba"></div> + +<script> + document.getElementById("prueba").addEventListener("click", function( event ) { + // presentar la cuenta de clicks realizados sobre el elemento con id "prueba" + event.target.innerHTML = "Conteo de Clicks: " + event.detail; + }, false); +</script> +</pre> + +<h2 id="Compatibilidad_con_Navegadores">Compatibilidad con Navegadores</h2> + +<h3 id="Internet_Explorer">Internet Explorer</h3> + +<p>Internet Explorer 8 & 9 tiene problemas con elementos con un valor {{cssxref("background-color")}} de <code><a href="/en-US/docs/Web/CSS/color_value#transparent_keyword">transparent</a> que es sobrepuesto a los demas elementos por lo que no les permite recibir el evento.</code></p> + +<p>Un ejemplo <a href="http://jsfiddle.net/YUKma/show/">aqui</a></p> + +<p>¿Cómo evitarlo?</p> + +<ul> + <li>Para IE9 only: + <ul> + <li>Asignar <code>{{cssxref("background-color")}}: <a href="/en-US/docs/Web/CSS/color_value#rgba()">rgba</a>(0,0,0,0)</code></li> + <li>Asignar <code>{{cssxref("opacity")}}: 0</code> y asignar explicitamente {{cssxref("background-color")}} un valor diferente a <a href="/en-US/docs/Web/CSS/color_value#transparent_keyword"><code>transparent</code></a></li> + </ul> + </li> + <li>Para IE8 and IE9: + <ul> + <li>Asignar <code><a href="http://msdn.microsoft.com/en-us/library/ms532847(v=vs.85).aspx">filter</a>: alpha(opacity=0);</code> y asignar explicitamente {{cssxref("background-color")}} un valor diferente a <a href="/en-US/docs/Web/CSS/color_value#transparent_keyword"><code>transparent</code></a></li> + </ul> + </li> +</ul> + +<h3 id="Safari_Mobile">Safari Mobile</h3> + +<p>En Safari Mobile 7.0+ ( también algunas versiones anteriores) <a href="https://bugs.webkit.org/show_bug.cgi?id=153887">presenta un problema</a> cuando se da click sobre elementos que no son tipicamente interactivos como es el caso de un div. </p> + +<p>¿Cómo evitarlo?</p> + +<ul> + <li>Asignar {{cssxref("cursor")}}<code>: pointer;</code> en el elemento o uno de sus contendores.</li> + <li>Ubicar un attributo <code>onclick="void(0)"</code> al elemento o cualquiera de sus elementos contenedores, menos {{HTMLElement("body")}}.</li> + <li>Usar elementos interactivos (e.g. {{HTMLElement("a")}}) en lugar de no interactivos (e.g. {{HTMLElement("div")}}).</li> + <li>No usar <a href="http://davidwalsh.name/event-delegate">delegacion del evento</a> click.</li> +</ul> + +<p>Lo siguientes elementos son considerados por Safari típicamente interactivos</p> + +<ul> + <li>{{HTMLElement("a")}} (but it must have an <code>href</code>)</li> + <li>{{HTMLElement("area")}} (but it must have an <code>href</code>)</li> + <li>{{HTMLElement("button")}}</li> + <li>{{HTMLElement("img")}}</li> + <li>{{HTMLElement("input")}}</li> + <li>{{HTMLElement("label")}} (but it must be associated with a form control)</li> + <li>{{HTMLElement("textarea")}}</li> + <li><em>This list is incomplete; you can help MDN by doing further testing/research and expanding it.</em></li> +</ul> + +<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>Edge</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>En elementos inhabilitados</td> + <td>{{CompatVersionUnknown}}<sup>[1]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}<sup>[2]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}<sup>[1]</sup></td> + <td>{{CompatUnknown}}</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>Soporte Básico</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>En elementos inhabilitados</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Sólo funciona para los tipos {{HTMLElement("textarea")}} elements and some {{HTMLElement("input")}} .</p> + +<p>[2] Internet Explorer sólo dispara el evento click en los elementos {{HTMLElement("input")}} tipo <code>checkbox</code> o <code>radio cuando se ha realizdo sobre ellos un doble click.</code></p> + +<h2 id="Véase_también">Véase también</h2> + +<ul> + <li>{{event("mousedown")}}</li> + <li>{{event("mouseup")}}</li> + <li>{{event("mousemove")}}</li> + <li>{{event("click")}}</li> + <li>{{event("dblclick")}}</li> + <li>{{event("mouseover")}}</li> + <li>{{event("mouseout")}}</li> + <li>{{event("mouseenter")}}</li> + <li>{{event("mouseleave")}}</li> + <li>{{event("contextmenu")}}</li> +</ul> diff --git a/files/es/web/api/element/clientheight/index.html b/files/es/web/api/element/clientheight/index.html new file mode 100644 index 0000000000..0784b49a36 --- /dev/null +++ b/files/es/web/api/element/clientheight/index.html @@ -0,0 +1,61 @@ +--- +title: Element.clientHeight +slug: Web/API/Element/clientHeight +tags: + - Propiedad +translation_of: Web/API/Element/clientHeight +--- +<p>{{ APIRef("DOM") }}</p> + +<p>La propiedad de sólo lectura <code><strong>Element.clientHeight</strong></code> devuelve la altura de un elemento en píxeles, incluyendo el padding pero no las barras horizontales, el borde o el margen.</p> + +<p><code>clientHeight</code> puede ser calculado como CSS <code>height</code> + CSS <code>padding</code> - alto de la barra horizontal (si existe).</p> + +<div class="note"> +<p><strong>Nota:</strong> Esta propiedad redondeará el valor a un entero. Si necesitas un valor fraccional usa {{ domxref("element.getBoundingClientRect()") }}.</p> +</div> + +<h2 id="Syntax_and_values" name="Syntax_and_values">Sintaxis</h2> + +<pre class="syntaxbox">var <var>h</var> = <var>element</var>.clientHeight;</pre> + +<p><code><var>h</var></code> es un entero que representa el alto de <em>element</em> en píxeles.</p> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<p> </p> + +<p> <img alt="Image:Dimensions-client.png" class="internal" src="/@api/deki/files/185/=Dimensions-client.png"></p> + + +<h2 id="Specification" name="Specification">Specification</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('CSSOM View', '#dom-htmlelement-clientheight', 'clientheight')}}</td> + <td>{{Spec2('CSSOM View')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h3 id="Notes" name="Notes">Notas</h3> + +<p><code>clientHeight</code> es una propiedad introducida en el modelo de objeto de Internet Explorer.</p> + +<h2 id="See_Also" name="See_Also">Ver también</h2> + +<ul> + <li>{{domxref("Element.offsetHeight")}}</li> + <li>{{domxref("Element.scrollHeight")}}</li> + <li><a href="/en-US/docs/Determining_the_dimensions_of_elements">Determining the dimensions of elements</a></li> + <li><a href="https://docs.microsoft.com/en-us/previous-versions//hh781509(v=vs.85)">MSDN: Measuring Element Dimension and Location</a></li> +</ul> diff --git a/files/es/web/api/element/clientleft/index.html b/files/es/web/api/element/clientleft/index.html new file mode 100644 index 0000000000..e6ffc24faf --- /dev/null +++ b/files/es/web/api/element/clientleft/index.html @@ -0,0 +1,58 @@ +--- +title: element.clientLeft +slug: Web/API/Element/clientLeft +tags: + - Referencia_DOM_de_Gecko +translation_of: Web/API/Element/clientLeft +--- +<p>{{ ApiRef("DOM") }}</p> + +<h3 id="Resumen" name="Resumen">Resumen</h3> + +<p>El ancho del borde izquierdo de un elemento en pixel. Incluye el ancho de la barra de desplazamiento vertical, si la dirección del texto es<em>rtl</em> (derecha a izquierda) y si hay un desbordamiento que provoque la aparición de la barra en el lado izquierdo. <code>clientLeft</code> NO incluye<em>margin-left</em> o padding-left<em>. <code>clientLeft</code> es de sólo lectura.</em></p> + +<p>Las aplicaciones "<a href="es/Gecko">Gecko</a>-based applications" implementan <code>clientLeft</code> a partir de Gecko 1.9 (<a href="es/Firefox_3">Firefox 3</a>, ver {{ Bug(111207) }}). Esta propiedad no está implementada en Firefox 2 o anteriores.</p> + +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> + +<pre class="eval">var <var>left</var> = <var>element</var>.clientLeft; +</pre> + +<h3 id="Ejemplo" name="Ejemplo">Ejemplo</h3> + +<div id="offsetContainer" style="margin: 26px 0px; background-color: rgb(255, 255, 204); border: 4px dashed black; color: black; position: absolute; left: 260px;"> +<div id="idDiv" style="margin: 24px 29px; border: 24px black solid; padding: 0px 28px; width: 199px; height: 102px; overflow: auto; background-color: white; font-size: 13px!important; font-family: Arial, sans-serif;"> +<p id="PaddingTopLabel" style="text-align: center; font-style: italic; font-weight: bold; font-size: 13px!important; font-family: Arial, sans-serif; margin: 0px;">padding-top</p> + +<p>Suave, individualista y muy leal, los gatos de Birmania tienen un carácter entre los persas y los siameses. Si le gustan los gatos que no son agresivos, disfrutan estar entre los humanos y son generalmente tranquilos, esta es la raza para usted.</p> + +<p><span style="float: right;"><img alt="Image:BirmanCat.jpg"></span>Todos los Birmanos tienen pintas y coloración obscura en la cara, orejas, patas y cola.</p> + +<p>La imagen del gato y el texto vienen de <a class="external" href="http://www.best-cat-art.com/">www.best-cat-art.com</a></p> + +<p id="PaddingBottomLabel" style="text-align: center; font-style: italic; font-weight: bold; font-size: 13px!important; font-family: Arial, sans-serif; margin: 0px;">padding-bottom</p> +</div> +<strong style="color: blue; font-family: Arial,sans-serif; font-size: 13px!important; font-weight: bold; left: -32px; position: absolute; top: 85px;">Left</strong><strong style="color: blue; font-family: Arial,sans-serif; font-size: 13px!important; font-weight: bold; left: 170px; position: absolute; top: -24px;">Top</strong><strong style="color: blue; font-family: Arial,sans-serif; font-size: 13px!important; font-weight: bold; left: 370px; position: absolute; top: 85px;">Right</strong><strong style="color: blue; font-family: Arial,sans-serif; font-size: 13px!important; font-weight: bold; left: 164px; position: absolute; top: 203px;">Bottom</strong><em>margin-top</em><em>margin-bottom</em><em>border-top</em><em>border-bottom</em><span class="comment">{{ mediawiki.external('if IE') }}><span id="MrgLeft" style="position: absolute; left: 8px; top: 65px; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl;">margin-left</span><span id="BrdLeft" style="position: absolute; left: 33px; top: 65px; color: white; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl;">border-left</span><span id="PdgLeft" style="position: absolute; left: 55px; top: 65px; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl;">padding-left</span><span id="PdgRight" style="position: absolute; left: 275px; top: 60px; color: black; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl; white-space: nowrap;">padding-right</span><span id="BrdRight" style="position: absolute; left: 310px; top: 65px; color: white; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl;">border-right</span><span id="MrgRight" style="position: absolute; left: 340px; top: 65px; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl;">margin-right</span><!{{ mediawiki.external('endif') }}</span></div> + +<p style="margin-top: 270px;"><img alt="Image:clientLeft.png"></p> + +<p><img alt="La barra de desplazamiento vertical en el lado izquierdo, aparece cuando la propiedad layout.scrollbar.side tiene el valor 1 o 3"></p> + +<p>Cuando la propiedad <a class="external" href="http://kb.mozillazine.org/Layout.scrollbar.side"><em>layout.scrollbar.side</em> </a> se establece a 1 o a 3 y la dirección de texto está puesta a RTL, <strong>entonces la barra de desplazamiento se pone a la izquierda</strong> y esto afecta a la forma en que se calcula clientLeft.</p> + +<h3 id="Especificaci.C3.B3n" name="Especificaci.C3.B3n">Especificación</h3> + +<p>No es parte de ninguna especificación W3C.</p> + +<h3 id="Notas" name="Notas">Notas</h3> + +<p><code>clientLeft</code> apareció por primera vez en el modelo de objetos de MS IE DHTML.</p> + +<p>La posición de la barra de desplazamiento vertical en textos<em>rtl</em> depende de la preferencias de <a class="external" href="http://kb.mozillazine.org/Layout.scrollbar.side"><em>layout.scrollbar.side</em> </a></p> + +<h3 id="Referencias" name="Referencias">Referencias</h3> + +<ul> + <li><a class="external" href="http://msdn.microsoft.com/workshop/author/dhtml/reference/properties/clientleft.asp?frame=true">MSDN's clientLeft definition</a></li> + <li><a class="external" href="http://msdn.microsoft.com/workshop/author/om/measuring.asp">MSDN's Measuring Element Dimension and Location</a></li> +</ul> diff --git a/files/es/web/api/element/clienttop/index.html b/files/es/web/api/element/clienttop/index.html new file mode 100644 index 0000000000..063ac86c13 --- /dev/null +++ b/files/es/web/api/element/clienttop/index.html @@ -0,0 +1,54 @@ +--- +title: element.clientTop +slug: Web/API/Element/clientTop +tags: + - Referencia_DOM_de_Gecko +translation_of: Web/API/Element/clientTop +--- +<p> </p> + +<p>{{ Fx_minversion_header(3) }} {{ ApiRef() }}</p> + +<h3 id="Resumen" name="Resumen">Resumen</h3> + +<p>El ancho del borde superior de un elemento en pixel. No incluye ni el<em>margin-top</em> , ni el<em>padding-top</em> . <code>clientTop</code> es de sólo lectura.</p> + +<p>Las aplicaciones "<a href="es/Gecko">Gecko</a>-based applications" implementan el uso de <code>clientTop</code> a partir de Gecko 1.9 (<a href="es/Firefox_3">Firefox 3</a>,ver {{ Bug(111207) }}). Esta propiedad no está disponible en Firefox 2 o anteriores.</p> + +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> + +<pre class="eval">var<em>top</em> = <var>element</var>.clientTop; +</pre> + +<h3 id="Ejemplo" name="Ejemplo">Ejemplo</h3> + +<div id="offsetContainer" style="margin: 26px 0px; background-color: rgb(255, 255, 204); border: 4px dashed black; color: black; position: absolute; left: 260px;"> +<div id="idDiv" style="margin: 24px 29px; border: 24px black solid; padding: 0px 28px; width: 199px; height: 102px; overflow: auto; background-color: white; font-size: 13px!important; font-family: Arial, sans-serif;"> +<p id="PaddingTopLabel" style="text-align: center; font-style: italic; font-weight: bold; font-size: 13px!important; font-family: Arial, sans-serif; margin: 0px;">padding-top</p> + +<p>Suave, individualista y muy leal, los gatos de Birmania tienen un carácter entre los persas y los siameses. Si le gustan los gatos que no son agresivos, disfrutan estar entre los humanos y son generalmente tranquilos, esta es la raza para usted.</p> + +<p><span style="float: right;"><img alt="Image:BirmanCat.jpg"></span>Todos los Birmanos tienen pintas y coloración obscura en la cara, orejas, patas y cola.</p> + +<p>La imagen del gato y el texto vienen de <a class="external" href="http://www.best-cat-art.com/">www.best-cat-art.com</a></p> + +<p id="PaddingBottomLabel" style="text-align: center; font-style: italic; font-weight: bold; font-size: 13px!important; font-family: Arial, sans-serif; margin: 0px;">padding-bottom</p> +</div> +<strong style="color: blue; font-family: Arial,sans-serif; font-size: 13px!important; font-weight: bold; left: -32px; position: absolute; top: 85px;">Left</strong><strong style="color: blue; font-family: Arial,sans-serif; font-size: 13px!important; font-weight: bold; left: 170px; position: absolute; top: -24px;">Top</strong><strong style="color: blue; font-family: Arial,sans-serif; font-size: 13px!important; font-weight: bold; left: 370px; position: absolute; top: 85px;">Right</strong><strong style="color: blue; font-family: Arial,sans-serif; font-size: 13px!important; font-weight: bold; left: 164px; position: absolute; top: 203px;">Bottom</strong><em>margin-top</em><em>margin-bottom</em><em>border-top</em><em>border-bottom</em><span class="comment">{{ mediawiki.external('if IE') }}><span id="MrgLeft" style="position: absolute; left: 8px; top: 65px; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl;">margin-left</span><span id="BrdLeft" style="position: absolute; left: 33px; top: 65px; color: white; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl;">border-left</span><span id="PdgLeft" style="position: absolute; left: 55px; top: 65px; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl;">padding-left</span><span id="PdgRight" style="position: absolute; left: 275px; top: 60px; color: black; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl; white-space: nowrap;">padding-right</span><span id="BrdRight" style="position: absolute; left: 310px; top: 65px; color: white; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl;">border-right</span><span id="MrgRight" style="position: absolute; left: 340px; top: 65px; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl;">margin-right</span><!{{ mediawiki.external('endif') }}</span></div> + +<p style="margin-top: 270px;"><img alt="Image:clientTop.png"></p> + +<h3 id="Especificaci.C3.B3n" name="Especificaci.C3.B3n">Especificación</h3> + +<p>No es parte de ninguna especificación W3C.</p> + +<h3 id="Notas" name="Notas">Notas</h3> + +<p><code>clientTop</code> se presento por primera vez en el modelo de objetos de MS IE DHTML.</p> + +<h3 id="Referencias" name="Referencias">Referencias</h3> + +<ul> + <li><a class="external" href="http://msdn.microsoft.com/workshop/author/dhtml/reference/properties/clienttop.asp?frame=true">MSDN's clientTop definition</a></li> + <li><a class="external" href="http://msdn.microsoft.com/workshop/author/om/measuring.asp">MSDN's Measuring Element Dimension and Location</a></li> +</ul> diff --git a/files/es/web/api/element/clientwidth/index.html b/files/es/web/api/element/clientwidth/index.html new file mode 100644 index 0000000000..bdf813c867 --- /dev/null +++ b/files/es/web/api/element/clientwidth/index.html @@ -0,0 +1,60 @@ +--- +title: Element.clientWidth +slug: Web/API/Element/clientWidth +translation_of: Web/API/Element/clientWidth +--- +<p>{{ APIRef("DOM") }}</p> + +<p>La propiedad <code><strong>Element.clientWidth</strong></code> es cero para elementos sin CSS o cajas de diseño (layout), en caso contrario es la anchura interior de un elemento en pixels, incluyendo la anchura de relleno (padding) pero no la anchura de la barra de desplazamiento vertical (si está presente, si está dibujada), el borde o el margen.</p> + +<div class="note"> +<p>El valor de esta propiedad será redondeado a un entero. Si necesita un valor fraccional, use {{ domxref("element.getBoundingClientRect()") }}.</p> +</div> + +<h2 id="Syntax_and_values" name="Syntax_and_values">Sintaxis</h2> + +<pre class="eval">var <var>intElemClientWidth</var> = <var>element</var>.clientWidth; +</pre> + +<p><var>intElemClientWidth</var> será un entero que corresponde con el <strong>clientWidth</strong> del <var>element</var>o en pixels. <strong>clientWidth</strong> es de sólo-lectura.</p> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<p> </p> + +<p> <img alt="Image:Dimensions-client.png" class="internal" src="/@api/deki/files/185/=Dimensions-client.png"></p> + + +<h2 id="Specification" name="Specification">Especificación</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Observaciones</th> + </tr> + <tr> + <td>{{SpecName('CSSOM View', '#dom-element-clientwidth', 'clientWidth')}}</td> + <td>{{Spec2("CSSOM View")}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h3 id="Notes" name="Notes">Notas</h3> + +<p><code>clientWidth</code> fue introducida en el modelo de objetos DHTML de MS IE.</p> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<p>{{Compat("api.Element.clientWidth")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("HTMLElement.offsetWidth")}}</li> + <li>{{domxref("Element.scrollWidth")}}</li> + <li><a href="/en-US/docs/Determining_the_dimensions_of_elements">Determining the dimensions of elements</a></li> + <li><a href="https://docs.microsoft.com/en-us/previous-versions//hh781509(v=vs.85)">MSDN Measuring Element Dimension and Location</a></li> +</ul> diff --git a/files/es/web/api/element/closest/index.html b/files/es/web/api/element/closest/index.html new file mode 100644 index 0000000000..ecf35158b5 --- /dev/null +++ b/files/es/web/api/element/closest/index.html @@ -0,0 +1,145 @@ +--- +title: Element.closest() +slug: Web/API/Element/closest +tags: + - API + - DOM + - Elemento + - Referencia + - metodo +translation_of: Web/API/Element/closest +--- +<div>{{APIRef('Shadow DOM')}}</div> + +<p>El método <code><strong>closest()</strong></code> de la interfaz {{domxref("Element")}} devuelve el ascendiente más cercano al elemento actual (o el propio elemento actual) que coincida con el selector proporcionado por parámetro. Si no existe dicho ascendiente, devuelve <code>null</code>.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var <em>closestElement = element</em>.closest(<em>selectors</em>); +</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<ul> + <li><em><code>selectors</code></em> es un {{domxref("DOMString")}} que contiene una lista de selectores como <code>"p:hover, .toto + q"</code></li> + <li><em><code>element</code></em> es el {{domxref("Element")}} en la parte superior del árbol de elementos a tratar.</li> +</ul> + +<h3 id="Valor_del_resultado">Valor del resultado</h3> + +<ul> + <li><code>closestElement</code> es el {{domxref("Element")}} ascendiente más cercano al elemento actual. Puede ser <code>null</code>.</li> +</ul> + +<h3 id="Excepciones">Excepciones</h3> + +<ul> + <li>Se lanza una excepción {{exception("SyntaxError")}} si <em><code>selectors</code></em> no es una lista de selectores válida.</li> +</ul> + +<h2 id="Ejemplo" name="Ejemplo">Ejemplo</h2> + +<h3 id="HTML">HTML</h3> + +<pre class="brush: html"><article> + <div id="div-01">Here is div-01 + <div id="div-02">Here is div-02 + <div id="div-03">Here is div-03</div> + </div> + </div> +</article></pre> + +<h3 id="JavaScript">JavaScript</h3> + +<pre class="brush: js">var el = document.getElementById('div-03'); + +var r1 = el.closest("#div-02"); +// returns the element with the id=div-02 + +var r2 = el.closest("div div"); +// returns the closest ancestor which is a div in div, here is div-03 itself + +var r3 = el.closest("article > div"); +// returns the closest ancestor which is a div and has a parent article, here is div-01 + +var r4 = el.closest(":not(div)"); +// returns the closest ancestor which is not a div, here is the outmost article</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>Para los navegadores que no tengan soporte para <code>Element.closest()</code>, pero sí lo tengan para <code>document.querySelectorAll()</code> (o un equivalente prefijado, es decir IE9+), existe un polyfill:</p> + +<pre class="brush: js">if (!Element.prototype.matches) { + Element.prototype.matches = Element.prototype.msMatchesSelector || + Element.prototype.webkitMatchesSelector; +} + +if (!Element.prototype.closest) { + Element.prototype.closest = function(s) { + var el = this; + + do { + if (el.matches(s)) return el; + el = el.parentElement || el.parentNode; + } while (el !== null && el.nodeType === 1); + return null; + }; +}</pre> + +<p>Sin embargo, si realmente se necesita soporte para IE 8, entonces el siguiente polyfill servirá para conseguirlo de forma muy lenta, pero lo hará. Sin embargo, sólo admitirá selectores CSS 2.1 en IE 8, puede causar picos severos de retraso en sitios web en producción.</p> + +<pre class="brush: js">if (window.Element && !Element.prototype.closest) { + Element.prototype.closest = + function(s) { + var matches = (this.document || this.ownerDocument).querySelectorAll(s), + i, + el = this; + do { + i = matches.length; + while (--i >= 0 && matches.item(i) !== el) {}; + } while ((i < 0) && (el = el.parentElement)); + return el; + }; +} +</pre> + +<h2 id="Especificacion" name="Especificacion">Especificación</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('DOM WHATWG', '#dom-element-closest', 'Element.closest()')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<div> +<p>{{Compat("api.Element.closest")}}</p> + +<h3 id="Notas_de_compatibilidad">Notas de compatibilidad</h3> + +<ul> + <li>En Edge <code>document.createElement(element).closest(element)</code> devolverá <code>null</code> si el elemento no es el primero del DOM</li> +</ul> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>La interfaz {{domxref("Element")}}.</li> + <li> + <div class="syntaxbox"><a href="/es/docs/Web/CSS/Introducción/Selectors">Sintaxis de los Selectores</a></div> + </li> + <li> + <div class="syntaxbox">Otros métodos que toman selectores: {{domxref("element.querySelector()")}} y {{domxref("element.matches()")}}.</div> + </li> +</ul> diff --git a/files/es/web/api/element/computedstylemap/index.html b/files/es/web/api/element/computedstylemap/index.html new file mode 100644 index 0000000000..656312b1f5 --- /dev/null +++ b/files/es/web/api/element/computedstylemap/index.html @@ -0,0 +1,99 @@ +--- +title: Element.computedStyleMap() +slug: Web/API/Element/computedStyleMap +tags: + - API + - CSS Typed Object Model API + - Element + - Experimental + - Houdini + - Method + - Reference + - StylePropertyMapReadOnly + - computedStyleMap() +translation_of: Web/API/Element/computedStyleMap +--- +<p>{{APIRef("CSS Typed Object Model API")}}{{SeeCompatTable}}</p> + +<p><span class="seoSummary">El método <strong><code>computedStyleMap()</code></strong> de la interfaz {{domxref("Element")}} devuelve una interfaz {{domxref("StylePropertyMapReadOnly")}} que provee una representación de solo-lectura de un bloque de declaración de CSS que es una alternativa a {{domxref("CSSStyleDeclaration")}}. </span></p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox notranslate">var <var>stylePropertyMapReadOnly</var> = Element.computedStyleMap()</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<p>Ninguno.</p> + +<h3 id="Valor_de_resultado">Valor de resultado</h3> + +<p>Una interfaz {{domxref("StylePropertyMapReadOnly")}}.</p> + +<h2 id="Ejemplos">Ejemplos</h2> + +<p>Comenzamos con algo de HTML simple: un párrafo con un enlace, y una lista de definición a la cual le añadiremos todos los pares de Propiedad CSS / Valor.</p> + +<pre class="brush: html notranslate"><p> + <a href="https://example.com">Link</a> +</p> +<dl id="regurgitation"></dl></pre> + +<p>Añadimos un poco de CSS</p> + +<pre class="brush: css notranslate">a { + --colour: red; + color: var(--colour); +}</pre> + +<p>Añadimos Javascript para tomar nuestro enlace y devolvemos una lista de definición de todos los valores de propiedades CSS usando <code>computedStyleMap().</code></p> + +<pre class="brush: js notranslate">// obtenemos el elemento +const myElement = document.querySelector('a'); + +// obtenemos la <dl> que llenaremos +const stylesList = document.querySelector('#regurgitation'); + +// recuperamos todos los estilos calculados con computedStyleMap() +const allComputedStyles = myElement.computedStyleMap(); + +// iteramos a través del mapa de todas las propiedades y valores, añadiendo un <dt> y <dd> para cada mapa +for (const [prop, val] of allComputedStyles) { + // propiedades + const cssProperty = document.createElement('dt'); + cssProperty.appendChild(document.createTextNode(prop)); + stylesList.appendChild(cssProperty); + + // valores + const cssValue = document.createElement('dd'); + cssValue.appendChild(document.createTextNode(val)); + stylesList.appendChild(cssValue); +}</pre> + +<p>En <a href="/en-US/docs/Web/API/Element/computedStyleMap#Browser_compatibility">navegadores que soportan <code>computedStyleMap()</code></a>, verás una lista de todas las propiedades CSS y valores. En otros navegadores verás un enlace.</p> + +<p>{{EmbedLiveSample("Examples", 300, 300)}}</p> + +<p>¿Te diste cuenta cuántas propiedades CSS por defecto tenía un enlace? Actualiza el '<code>a</code>' a un '<code>p</code>', y notarás una diferencia en los valores calculados por defecto del <code>margin-top</code> y <code>margin-bottom</code>.</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('CSS Typed OM','#dom-element-computedstylemap','computedStyleMap()')}}</td> + <td>{{Spec2('CSS Typed OM')}}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navedadores">Compatibilidad con navedadores</h2> + +<div class="hidden">La tabla de compatibilidad en esta página es generada desde datos estructurados, por favor revisa <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> y envíanos una "pull request".</div> + +<p>{{Compat("api.Element.computedStyleMap")}}</p> diff --git a/files/es/web/api/element/currentstyle/index.html b/files/es/web/api/element/currentstyle/index.html new file mode 100644 index 0000000000..620ff01129 --- /dev/null +++ b/files/es/web/api/element/currentstyle/index.html @@ -0,0 +1,80 @@ +--- +title: Element.currentStyle +slug: Web/API/Element/currentStyle +tags: + - API + - Compatibilidad en los navegadores móviles + - Property +translation_of: Web/API/Element/currentStyle +--- +<div>{{APIRef("DOM")}}</div> + +<p>{{ Non-standard_header() }}</p> + +<h2 id="Sumario">Sumario</h2> + +<p><strong><code>Element.currentStyle </code></strong><span lang="es"><span>es</span> <span>una propiedad</span> <span>que es una</span> <span>alternativa propietaria</span> <span>del método estandarizado</span></span> {{domxref("window.getComputedStyle")}} . <span id="result_box" lang="es"><span>Está disponible en</span> <span>las versiones anteriores de</span> <span>Microsoft</span> <span>Internet Explorer</span><span>.</span></span></p> + +<h2 id="Especificación">Especificación</h2> + +<p>No forma parte de ninguna especificación.</p> + +<p>Microsoft <a href="https://msdn.microsoft.com/en-us/library/ms535231(v=vs.85).aspx">tiene una descripción MSDN</a>.</p> + +<h2 id="Browser_Compatibility" name="Browser_Compatibility">Compatibilidad en los Navegadores</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Función</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 Básico</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>6</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>Función</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatNo() }}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_También">Ver También</h2> + +<ul> + <li>{{domxref("Element.runtimeStyle")}} </li> +</ul> diff --git a/files/es/web/api/element/getattribute/index.html b/files/es/web/api/element/getattribute/index.html new file mode 100644 index 0000000000..91f55e2c43 --- /dev/null +++ b/files/es/web/api/element/getattribute/index.html @@ -0,0 +1,48 @@ +--- +title: Element.getAttribute() +slug: Web/API/Element/getAttribute +tags: + - API + - DOM + - metodo +translation_of: Web/API/Element/getAttribute +--- +<div>{{APIRef("DOM")}}</div> + +<h2 id="Summary" name="Summary">Resumen</h2> + +<p><span class="seoSummary"><code>getAttribute()</code> devuelve el valor del atributo especificado en el elemento.</span> Si el atributo especificado no existe, el valor retornado puede ser tanto <code>null</code> como <code>""</code> (una cadena vacía); ver {{Anch("Notes")}} para más detalles.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox"><em>var atributo</em> = element.getAttribute(<em>nombreAtributo</em>); +</pre> + +<p>donde</p> + +<ul> + <li><code><em>atributo</em></code> es una cadena que contiene el valor del atributo <code><em>nombreAtributo</em></code>.</li> + <li><code><em>nombreAtributo</em></code> es el nombre del atributo del cual se quiere obtener el valor.</li> +</ul> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre class="brush:js">var div1 = document.getElementById("div1"); +var align = div1.getAttribute("align"); + +alert(align); // Muestra el valor de la alineación(align) del elemento con id="div1"</pre> + +<h2 id="Notes" name="Notes">Notas</h2> + +<p>Cuando es invocado en un elemento HTML desde un DOM marcado como documento HTML, <code>getAttribute()</code> convierte a minúsculas el argumento antes de proceder.</p> + +<p>Esencialmente todos los navegadores (Firefox, Internet Explorer, versiones recientes de Opera, Safari, Konqueror, y iCab, siendo una lista no exhaustiva) devuelven <code>null</code> cuando el atributo especificado no existe en el elemento especificado y esto es lo que establece <a href="http://dom.spec.whatwg.org/#dom-element-getattribute" title="http://dom.spec.whatwg.org/#dom-element-getattribute">el actual borrador de la especificación del DOM</a>. Por otra parte, la antigua especificación del DOM 3 Core dice que el valor correcto de retorno es de hecho una <em>cadena vacía</em>, y algunas implementaciones de DOM aplican este comportamiento. La implementación de getAttribute en XUL (Gecko) sigue la especificación de DOM 3 Core y retorna una cadena vacía. Por consiguiente, es recomendable usar {{domxref("element.hasAttribute()")}} para verificar la existencia de un atributo previo a la utilización de <code>getAttribute()</code> si es posible que el atributo requerido no exista en el elemento especificado.</p> + +<div>{{DOMAttributeMethods}}</div> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<ul> + <li><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-666EE0F9">DOM Level 2 Core: getAttribute</a> (introducido en <a class="external" href="http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#method-getAttribute">DOM Level 1 Core</a>)</li> + <li><a class="external" href="http://www.whatwg.org/specs/web-apps/current-work/multipage/dom.html#apis-in-html-documents">HTML 5: APIs in HTML documents</a></li> +</ul> diff --git a/files/es/web/api/element/getattributenodens/index.html b/files/es/web/api/element/getattributenodens/index.html new file mode 100644 index 0000000000..07ca649174 --- /dev/null +++ b/files/es/web/api/element/getattributenodens/index.html @@ -0,0 +1,38 @@ +--- +title: Element.getAttributeNodeNS() +slug: Web/API/Element/getAttributeNodeNS +tags: + - API + - DOM + - Referencia + - metodo +translation_of: Web/API/Element/getAttributeNodeNS +--- +<p>{{ APIRef("DOM") }}</p> + +<h2 id="Summary" name="Summary">Sumario</h2> + +<p>Dados namespace y nodeName del element, devuelve su <code>Attr</code> .</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="eval"><em>attributeNode</em> = element.getAttributeNodeNS(<em>namespace</em>,<em>nodeName</em>) +</pre> + +<ul> + <li><code>attributeNode</code> es el nodo para el atributo especificado.</li> + <li><code>namespace</code> es la cadena que define el namespace del atributo.</li> + <li><code>nodeName</code> es la cadena que define el name del atributo.</li> +</ul> + +<p><span class="comment">== Example == TBD The example needs to be fixed pre> // html: <div id="top" /> t = document.getElementById("top"); specialNode = t.getAttributeNodeNS( "<a class="external" href="http://www.mozilla.org/ns/specialspace" rel="freelink">http://www.mozilla.org/ns/specialspace</a>", "id"); // iNode.value = "full-top" </pre</span></p> + +<h2 id="Notes" name="Notes">Notas</h2> + +<p><code>getAttributeNodeNS</code> es más específica <a href="en/DOM/element.getAttributeNode">getAttributeNode</a> en el sentido de que puedes especificar atributos de un namespace en particular. Su método setter es <a href="en/DOM/element.setAttributeNodeNS">setAttributeNodeNS</a>.</p> + +<p>{{ DOMAttributeMethods() }}</p> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<p><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-ElGetAtNodeNS">DOM Level 2 Core: getAttributeNodeNS</a></p> diff --git a/files/es/web/api/element/getboundingclientrect/index.html b/files/es/web/api/element/getboundingclientrect/index.html new file mode 100644 index 0000000000..9d1b6ae4bb --- /dev/null +++ b/files/es/web/api/element/getboundingclientrect/index.html @@ -0,0 +1,98 @@ +--- +title: element.getBoundingClientRect +slug: Web/API/Element/getBoundingClientRect +tags: + - API + - Boundary + - Bounding + - Bounds + - CSSOM View + - Cliente + - DOM + - Elemento + - Minimo + - Referencia + - metodo +translation_of: Web/API/Element/getBoundingClientRect +--- +<div>{{APIRef("DOM")}}</div> + +<p>El método <code><strong>Element.getBoundingClientRect()</strong></code> devuelve el tamaño de un elemento y su posición relativa respecto a la ventana de visualización (<em>viewport).</em></p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox notranslate"><em>domRect</em> = <em>element</em>.getBoundingClientRect();</pre> + +<h3 id="Valor">Valor</h3> + +<p>El valor devuelto es un objeto {{domxref("DOMRect")}} que es la unión de los rectángulos devueltos por {{domxref("Element.getClientRects", "getClientRects()")}}para el elemento, es decir, las <em>CSS border-boxes</em> asociadas con el elemento. El resultado es el rectángulo más pequeño que contiene al elemento completo, con las propiedades de solo lectura <code>left</code>, <code>top</code>, <code>right</code>, <code>bottom</code>, <code>x</code>, <code>y</code>, <code>width</code>, and <code>height</code> describiendo la <em>border-box</em> total en pixels. Excepto <code>width</code> and <code>height</code> las propiedades son relativas a la esquina superior izquierda (<em>top-left</em>) de la ventana.</p> + +<p style="display: block;"><img alt="Explicación de los valores DOMRect" src="https://mdn.mozillademos.org/files/15087/rect.png" style="float: right; height: 300px; width: 300px;" title="Explicación de los valores DOMRect"></p> + +<p>Las <em>border-boxes</em> vacías son ignoradas. Si todas las <em>border-boxes</em> del elemento estan vacías, entonces se devuelve un rectángulo con <code>width</code> and <code>height</code> iguales a cero donde el <code>top</code> y el <code>left</code> son el top-left de la <em>border-box</em> de la primera <em>CSS box</em> (en onden de contenido) para el elemento.</p> + +<p>La cantidad de <em>scrolling</em> realizado en la ventana (o cualquier otro elemento <em>scrollable</em>) se tiene en cuenta cuando se calcula el rectángulo. Esto implica que los bordes del rectángulo (<code>top</code>, <code>left</code>, <code>bottom</code>, and <code>right</code>) cambián sus valores cada vez que la posición de <em>scrolling</em> cambia (ya que sus valores no son absolutos sino relativos a la ventana). Si se necesita el <em>bounding rectangle</em> relativo a la esquina <em>top-left</em> del documento, hay que añadir la posición de <em>scrolling</em> actual a las propiedades <code>top</code> and <code>left</code> (dicha posición de <em>scrolling</em> puede obtenerse usando {{domxref("window.scrollX")}} y {{domxref("window.scrollY")}}) para obtener el <em>bounding rectangle</em> independiente de la posición de <em>scrolling</em>.</p> + +<h3 id="Fallback_para_todos_los_navegadores">Fallback para todos los navegadores</h3> + +<p>Los scripts que requieran una alta compatibilidad <em>cross-browser</em> pueden usar {{domxref("window.pageXOffset")}} y {{domxref("window.pageYOffset")}} en lugar de <code>window.scrollX</code> y <code>window.scrollY.</code> Si no se tiene acceso a esas propiedades puede usarse el siguiente código:</p> + +<pre class="brush: js notranslate">// Para scrollX +(((t = document.documentElement) || (t = document.body.parentNode)) + && typeof t.scrollLeft == 'number' ? t : document.body).scrollLeft +// Para scrollY +(((t = document.documentElement) || (t = document.body.parentNode)) + && typeof t.scrollTop == 'number' ? t : document.body).scrollTop +</pre> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush:js notranslate">// rect es un objeto DOMRect con ocho propiedades: left, top, right, bottom, x, y, width, height +var rect = obj.getBoundingClientRect(); +</pre> + +<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("CSSOM View", "#dom-element-getboundingclientrect", "Element.getBoundingClientRect()")}}</td> + <td>{{Spec2("CSSOM View")}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h3 id="Notas">Notas</h3> + +<p>El objeto <code>DOMRect</code> devuelto puede modificarse en navegadores modernos. Esto no era así en versiones anteriores que devolvían <code>DOMRectReadOnly</code> de forma efectiva. Con IE y Edge, el hecho de no poder agregar propiedades faltantes a su objeto <code>ClientRect</code> <a href="https://msdn.microsoft.com/en-us/library/hh826029(VS.85).aspx">MSDN: <code>ClientRect</code></a>, devuelto impide rellenar los valores <code>x</code> e <code>y</code>.</p> + +<p>Debido a problemas de compatibilidad (ver a continuación), es más seguro confiar sólo en las propiedades <code>left</code>, <code>top</code>, <code>right</code>, and <code>bottom</code>. </p> + +<p>Las propiedades en el objeto <code>DOMRect</code> devuelto no son suyas. Mientras que el operador <code>in</code> y <code>for...in</code> encontrarán las propiedades devueltas, otras API como <code>Object.keys()</code> fallarán. Además, e inesperadamente, ES2015 y nuevas características como <code>Object.assign()</code> y los operadores rest/spread de los objetos, no podrán copiar las propiedades devueltas.</p> + +<pre class="brush: js notranslate">rect = elt.getBoundingClientRect() +// El resultado en emptyObj es {} +emptyObj = Object.assign({}, rect) +emptyObj = { ...rect } +{width, ...emptyObj} = rect +</pre> + +<h2 id="Compatibilidad_en_navegadores">Compatibilidad en navegadores</h2> + +<p>{{Compat("api.Element.getBoundingClientRect")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("Element.getClientRects", "getClientRects()")}}</li> + <li><a href="https://msdn.microsoft.com/en-us/library/ms536433(VS.85).aspx">MSDN: <code>getBoundingClientRect</code></a></li> + <li><a href="https://msdn.microsoft.com/en-us/library/hh826029(VS.85).aspx">MSDN: <code>ClientRect</code></a>, una versión anterior a <code>DOMRect</code> </li> +</ul> diff --git a/files/es/web/api/element/getclientrects/index.html b/files/es/web/api/element/getclientrects/index.html new file mode 100644 index 0000000000..507cda7bb8 --- /dev/null +++ b/files/es/web/api/element/getclientrects/index.html @@ -0,0 +1,54 @@ +--- +title: element.getClientRects +slug: Web/API/Element/getClientRects +tags: + - NeedsBrowserCompatibility + - NeedsExample + - NeedsLiveSample + - NeedsUpdate + - Referencia_DOM_de_Gecko +translation_of: Web/API/Element/getClientRects +--- +<p> {{ ApiRef("DOM") }}</p> + +<p>El método <code><strong>Element.getClientRects()</strong></code> devuelve una colección de objetos {{domxref("DOMRect")}} que indican los rectángulos que delimitan el rectángulo de cada línea de texto en el navegador.</p> + +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> + +<pre><code>var <em>rectCollection</em> = <var>object</var>.getClientRects();</code></pre> + +<h3 id="Devuelve" name="Devuelve">Devuelve</h3> + +<p>El valor devuelto es una colección de objetos rectangulares {{domxref("DOMRect")}}, uno para cada cuadro borde CSS asociado al elemento. Cada objeto {{domxref("DOMRect")}} contiene las propiedades de sólo lectura: <code>left</code>, <code>top</code>, <code>right</code> y <code>bottom</code>, que describen la caja, en pixeles, con el valor top-left relativo al valor top-left del <em>viewport. </em>En el caso de tablas con subtítulos, el subtítulo es incluido aún cuado esté fuera del cuadro borde de la tabla. En caso de ser ejecutado en algún elemento SVG que no sea el <code><svg> </code>externo, el "viewport" al cual los rectángulos de resultado serán relativos será el "viewport" que establece el <code><svg> </code>externo (y serán transformados por las trasnformaciones del <code><svg> </code>externo, si estas existen).</p> + +<p>{{ fx_minversion_note(3.5, "Firefox 3.5 ha agregado las propiedades <code>width</code> y <code>height</code> al objeto TextRectangle.") }}</p> + +<p>La cantidad de desplazamiento que ha tenido el área del viewport (o cualquier otro elemento desplazable) se tiene en cuenta al calcular los rectángulos.</p> + +<p>Los rectángulos devueltos no incluyen los márgenes de ningún elemento hijo que se haya podido haber desbordado.</p> + +<p>Para los elementos de AREA en HTML, elementos SVG que no renderizen nada por si mismos, los elementos <code>display:none</code>, y generalmente cualquier elemento que no sea renderizado directamente, se devuelve una lista vacia.</p> + +<p>Aún si la caja CSS tiene bordes vacios, se devuelven las coordenadas. Las coordenadas <code>left</code>, <code>top</code>, <code>right</code> y <code>bottom</code> pueden aún tener significado.</p> + +<p>Es posible que los valores de desplazamiento sean fracciones de pixel.</p> + +<h3 id="Ejemplo" name="Ejemplo">Ejemplo</h3> + +<pre class="eval">var rects = obj.getClientRects(); +var numLines = rects.length; +</pre> + +<h3 id="Especificaci.C3.B3n" name="Especificaci.C3.B3n">Especificación</h3> + +<p>No forma parte de ninguna especificación W3C.</p> + +<h3 id="Notas" name="Notas">Notas</h3> + +<p><code>getClientRects()</code> apareció por primera vez en el modelo de objeto de MS IE DHTML.</p> + +<h3 id="Referencias" name="Referencias">Referencias</h3> + +<ul> + <li><a class="external" href="http://msdn2.microsoft.com/en-us/library/ms536435.aspx">MSDN's getClientRects definition</a></li> +</ul> diff --git a/files/es/web/api/element/getelementsbyclassname/index.html b/files/es/web/api/element/getelementsbyclassname/index.html new file mode 100644 index 0000000000..a1e6d7b3e3 --- /dev/null +++ b/files/es/web/api/element/getelementsbyclassname/index.html @@ -0,0 +1,112 @@ +--- +title: Element.getElementsByClassName() +slug: Web/API/Element/getElementsByClassName +translation_of: Web/API/Element/getElementsByClassName +--- +<p>{{APIRef("DOM")}}</p> + +<p>El método <strong><code>Element.getElementsByClassName()</code></strong> retorna una {{domxref("HTMLCollection")}} "viva" conteniendo todos los elementos hijos que tienen todos los nombres de clase dados. Cuando se llama en el objeto document, se realiza la búsqueda en el documento completo, incluyendo el nodo raíz.</p> + +<p>De forma similar, el método {{domxref("Document.getElementsByClassName", "Document.getElementsByClassName()")}} actúa en todo el documento; retornará los elementos que sean descendientes del documento raiz especificado que tengan los nombres de clase dados.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><var>var <em>elements</em></var> = <em>element</em>.getElementsByClassName(<em>names</em>);</pre> + +<ul> + <li><em><var>elements</var></em> es una {{ domxref("HTMLCollection") }} "viva" de los elementos encontrados.</li> + <li><em><var>names</var></em> es una cadena representando la lista de nombres de clase que deben concordar; los nombres de clase está separados por espacios en blanco.</li> + <li><em>element</em> es cualquier {{domxref("Element")}} de un documento.</li> +</ul> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>Obtiene todos los elementos que tienen una clase <code>test</code>:</p> + +<pre class="brush: js">element.getElementsByClassName('test');</pre> + +<p>Obtiene todos los elementos que tienen tanto la clase <code>red</code> como <code>test</code>:</p> + +<pre class="brush: js">element.getElementsByClassName('red test');</pre> + +<p>Obtiene todos los elementos que tienen la clase of <code>test</code>, dentro de un elemento que tiene el <code>id</code> <code>main</code>:</p> + +<pre class="brush: js">document.getElementById('main').getElementsByClassName('test');</pre> + +<p>Podemos también usar métodos de {{jsxref("Array.prototype")}} en cualquier {{ domxref("HTMLCollection") }} pasando <code><var>el HTMLCollection</var></code> como el valor <var>this</var> del método. Aquí encontramos todos los elementos {{HTMLElement("div")}} que tienen una clase <code>test</code>:</p> + +<pre class="brush: js">var testElements = document.getElementsByClassName('test'); +var testDivs = Array.prototype.filter.call(testElements, function(testElement){ + return testElement.nodeName === 'div'; +});</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Observaciones</th> + </tr> + <tr> + <td>{{SpecName('DOM WHATWG', '#dom-element-getelementsbyclassname', 'Element.getElementsByClassName()')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Prestación</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }} [1]</td> + <td>9</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }} [2]</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Prestación</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }} [1]</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Anteriormente a Firefox 19, este método retornaba una {{domxref("NodeList")}}; se cambió para reflejar el cambio en la especificación.</p> + +<p>[2] Safari en iOS 8 y OS X 10.10 retorna una {{domxref("NodeList")}}.</p> diff --git a/files/es/web/api/element/getelementsbytagname/index.html b/files/es/web/api/element/getelementsbytagname/index.html new file mode 100644 index 0000000000..6080c186af --- /dev/null +++ b/files/es/web/api/element/getelementsbytagname/index.html @@ -0,0 +1,50 @@ +--- +title: element.getElementsByTagName +slug: Web/API/Element/getElementsByTagName +tags: + - Referencia_DOM_de_Gecko +translation_of: Web/API/Element/getElementsByTagName +--- +<p>{{ ApiRef("DOM") }}</p> + +<h3 id="Resumen" name="Resumen">Resumen</h3> + +<p>Devuelve una lista de elementos que tienen un <a href="es/DOM/element.tagName">tag name</a> determinado. Se explora el árbol por debajo del elemento dado, excluyendo el propio elemento.</p> + +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> + +<pre class="eval"><em>elements</em> =<em>element</em>.getElementsByTagName(<em>tagName</em>) +</pre> + +<ul> + <li><code>elements</code> es un <code>NodeList</code> del elemento encontrado en el orden en que aparece en el árbol.</li> + <li><code>element</code> es el elemento a partir del cual debe empezar la búsqueda. Recuerda que sólo se buscan los elementos descendentes del elemento dado, sin incluir el propio elemento.</li> + <li><code>tagName</code> es el nombre que se busca. La cadena especial <code>"*"</code> representa todos los elementos.</li> +</ul> + +<div class="note"> +<p>En Firefox 2 (Gecko 1.8.1) y anteriores, este método no funcionaba correctamente si el árbol contenía algún elemento con etiqueta de nombre conteniendo espacios. (Ver {{ Bug(206053) }} para más detalles).</p> + +<p>Es recomendable usar <a href="es/DOM/document.getElementsByTagNameNS">DOM:document.getElementsByTagNameNS</a> cuando se manejan documentos con "multi-namespace".</p> +</div> + +<h3 id="Ejemplo" name="Ejemplo">Ejemplo</h3> + +<pre>// comprueba la alineación de las celdas en una tabla. +var table = document.getElementById("forecast-table"); +var cells = table.getElementsByTagName("td"); +for (var i = 0; i < cells.length; i++) { + status = cells[i].getAttribute("status"); + if ( status == "open") { + // grab the data + } +} +</pre> + +<h3 id="Notas" name="Notas">Notas</h3> + +<p><code>element.getElementsByTagName</code> es similar a <a href="es/DOM/document.getElementsByTagName">document.getElementsByTagName</a>, excepto por que su búsqueda está restringida a los elementos que descienden del elemento especificado.</p> + +<h3 id="Especificaci.C3.B3n" name="Especificaci.C3.B3n">Especificación</h3> + +<p><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-1938918D">DOM Level 2 Core: Element.getElementsByTagName </a></p> diff --git a/files/es/web/api/element/getelementsbytagnamens/index.html b/files/es/web/api/element/getelementsbytagnamens/index.html new file mode 100644 index 0000000000..3f8a92ef90 --- /dev/null +++ b/files/es/web/api/element/getelementsbytagnamens/index.html @@ -0,0 +1,128 @@ +--- +title: Element.getElementsByTagNameNS() +slug: Web/API/Element/getElementsByTagNameNS +translation_of: Web/API/Element/getElementsByTagNameNS +--- +<div>{{APIRef("DOM")}}</div> + +<p>El método <code><strong>Element.getElementsByTagNameNS()</strong></code> devuelve una {{domxref("HTMLCollection")}} viva de elementos con el nombre de etiqueta dado perteneciente al espacio de nombres dado. Es similar a {{Domxref("Document.getElementsByTagNameNS")}}, con la excepción de que su búsqueda está limitada a los descendientes del elemento especificado.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><var>elementos</var> = <var>elemento</var>.getElementsByTagNameNS(<var>espacioNombreURI</var>, <var>nombreLocal</var>)</pre> + +<ul> + <li><code>elementos</code> es una {{domxref("HTMLCollection")}} viva de elementos encontrados en el orden en el que aparecen en el árbol.</li> + <li><code>elemento</code> es el elemento desde el cual la búsqueda debería comenzar. Nótese que sólo los descendientes de este elemento están incluídos en la búsqueda, no el nodo en sí.</li> + <li><code>espacioNombreURI</code> es el URI del espacio de nombres de los elementos a buscar (vea {{domxref("Node.namespaceURI")}}). Por ejemplo, si usted necesita buscar elementos XHTML, use el URI de espacio de nombres de XHTML, <span class="nowiki"><code>http://www.w3.org/1999/xhtml</code></span>.</li> + <li><font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: #eeeeee;">nombreLocal</span></font> puede ser el nombre local de los elementos a buscar o el valor especial <code>"*"</code>, que encuentra todos los elementos (vea {{domxref("Node.localName")}}).</li> +</ul> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush:js">// verifica la alineación en un número de celdas en una tabla en un documento XHTML. +var table = document.getElementById("forecast-table"); +var cells = table.getElementsByTagNameNS("http://www.w3.org/1999/xhtml", "td"); + +for (var i = 0; i < cells.length; i++) { + var axis = cells[i].getAttribute("axis"); + if (axis == "year") { + // obtiene los datos + } +}</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('DOM WHATWG', '#dom-element-getelementsbytagnamens', 'Element.getElementsByTagNameNS()')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Cambió el valor devuelto de {{domxref("NodeList")}} a {{domxref("HTMLCollection")}}.</td> + </tr> + <tr> + <td>{{SpecName('DOM3 Core', 'core.html#ID-A6C90942', 'Element.getElementsByTagNameNS()')}}</td> + <td>{{Spec2('DOM3 Core')}}</td> + <td>Sin cambios desde {{SpecName('DOM2 Core')}}.</td> + </tr> + <tr> + <td>{{SpecName('DOM2 Core', 'core.html#ID-A6C90942', 'Element.getElementsByTagNameNS()')}}</td> + <td>{{Spec2('DOM2 Core')}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_los_navegadores">Compatibilidad con los navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>1.0<sup>[1]</sup></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}<sup>[2]</sup></td> + <td>5.5</td> + <td>{{CompatVersionUnknown}}<sup>[1]</sup></td> + <td>{{CompatVersionUnknown}}<sup>[1]</sup></td> + </tr> + <tr> + <td>getElementsByTagName("*")</td> + <td>1.0</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>6.0</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}<sup>[2]</sup></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Inicialmente, este método devolvía una {{domxref("NodeList")}}; luego fue modificado para reflejar el cambio en la especificación.</p> + +<p>[2] El comportamiento de <code>element.getElementsByTagNameNS</code> cambió entre Firefox 3.5 y Firefox 3.6. En Firefox 3.5 y anteriores, esta función automáticamente convertía mayúsculas o minúsculas en las consultas, de manera que una búsqueda de "foo" encontraría "Foo" o "foo". En Firefox 3.6 y posteriores esta función es sensible a mayúsculas y minúsculas, por lo que una consulta por "foo" sólo encontrará "foo" y no "Foo". Para más información al respecto, por favor vea el <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=542185#c5">comentario de Henri Sivonen sobre este cambio</a>. También puede ver <a href="/en-US/docs/Case_Sensitivity_in_class_and_id_Names">la parte relevante del estándar, que establece qué partes de la API son sensibles a mayúsculas y minúsculas y qué partes no.</a></p> + +<p>Previo a Firefox 19, este método devolvía una {{domxref("NodeList")}}; luego fue modificado para reflejar el cambio en la especificación.</p> diff --git a/files/es/web/api/element/hasattribute/index.html b/files/es/web/api/element/hasattribute/index.html new file mode 100644 index 0000000000..ea7a38ddff --- /dev/null +++ b/files/es/web/api/element/hasattribute/index.html @@ -0,0 +1,123 @@ +--- +title: Element.hasAttribute() +slug: Web/API/Element/hasAttribute +translation_of: Web/API/Element/hasAttribute +--- +<div>{{APIRef("DOM")}}</div> + +<p>El método <strong><code>Elemento.hasAttribute()</code></strong> devuelve un valor <strong>Booleano</strong> indicando si el elemento tiene el atributo especificado o no.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="brush: js"><var>var <em>resultado</em></var> = <em><var>elemento</var></em>.hasAttribute(<em><var>nombre</var></em>); +</pre> + +<dl> + <dt><code>resultado</code></dt> + <dd>contendrá el valor devuelto (<code>true</code> o <code>false)</code>.</dd> + <dt><code>nombre</code></dt> + <dd>consiste en una cadena de caracteres que representa el nombre del atributo a chequear.</dd> +</dl> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush:js">var foo = document.getElementById("foo"); +if (foo.hasAttribute("bar")) { + // hacer algo +} +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<pre class="brush:js">;(function(prototype) { + prototype.hasAttribute = prototype.hasAttribute || function(name) { + return !!(this.attributes[name] && + this.attributes[name].specified); + } +})(Element.prototype); +</pre> + +<h2 id="Notas">Notas</h2> + +<div>{{DOMAttributeMethods}}</div> + +<h2 id="Especificaciones">Especificaciones</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('DOM WHATWG', '#dom-element-hasattribute', 'Element.hasAttribute()')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>From {{SpecName('DOM3 Core')}}, moved from {{domxref("Node")}} to {{domxref("Element")}}</td> + </tr> + <tr> + <td>{{SpecName('DOM3 Core', 'core.html#ID-ElHasAttr', 'Element.hasAttribute()')}}</td> + <td>{{Spec2('DOM3 Core')}}</td> + <td>No change from {{SpecName('DOM2 Core')}}</td> + </tr> + <tr> + <td>{{SpecName('DOM2 Core', 'core.html#ID-ElHasAttr', 'Element.hasAttribute()')}}</td> + <td>{{Spec2('DOM2 Core')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>8.0</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>Edge</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}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> diff --git a/files/es/web/api/element/id/index.html b/files/es/web/api/element/id/index.html new file mode 100644 index 0000000000..b75cd87e77 --- /dev/null +++ b/files/es/web/api/element/id/index.html @@ -0,0 +1,119 @@ +--- +title: Element.id +slug: Web/API/Element/id +tags: + - API + - DOM + - Elemento + - Propiedad + - Referencia +translation_of: Web/API/Element/id +--- +<div>{{ ApiRef("DOM") }}</div> + +<div> </div> + +<p>La propiedad <strong><code>Element.id</code></strong> representa el identificador del elemento, reflejando el atributo global de <strong><a href="/en-US/docs/Web/HTML/Global_attributes/id">id</a></strong>.</p> + +<p>debe ser un único documento, y con frecuencia es utilizado para recuperar el elemento usando {{domxref("document.getElementById", "getElementById")}}. Otros usos comunes de <code>id</code> incluyen la utilización de elementos <a href="/en-US/docs/Web/CSS/ID_selectors" title="Web/CSS/ID_selectors">ID como un selector</a> cuando se está estilando el documento con <a href="/en-US/docs/Web/CSS" title="CSS">CSS</a>.</p> + +<div class="note"> +<p><strong>Nota</strong>: los identificadores distinguen mayúsculas y minúsculas, pero se debe evitar la creación de IDs que difieran solamente en la capitalization (ver <a href="/en-US/docs/Case_Sensitivity_in_class_and_id_Names" title="Case_Sensitivity_in_class_and_id_Names">diferenciación de mayúsculas y minúsculas en nombres y destacados </a>).</p> +</div> + +<h2 id="Syntax" name="Syntax">Síntasix</h2> + +<pre class="syntaxbox">var <em>idStr</em> = <em>elt</em>.id; // Get the id. +<em>elt</em>.id = <em>idStr; // Set the id</em> +</pre> + +<ul> + <li><em><code>idStr</code></em> es el identificador del elemento.</li> +</ul> + +<h2 id="Specification" name="Specification">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('DOM WHATWG', '#dom-element-id', 'id')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>No change from {{SpecName('DOM2 HTML')}}.</td> + </tr> + <tr> + <td>{{SpecName('DOM2 HTML', 'html.html#ID-63534901', 'id')}}</td> + <td>{{Spec2('DOM2 HTML')}}</td> + <td>No change from {{SpecName('DOM1')}}.</td> + </tr> + <tr> + <td>{{SpecName('DOM1', 'level-one-html.html#ID-63534901', 'id')}}</td> + <td>{{Spec2('DOM1')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_los_navegadores">Compatibilidad de los navegadores</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Función</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Función</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>Soporte Básico</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>La <a href="/en-US/docs/Web/HTML/Global_attributes/id"><strong>id </strong></a> del atributo global DOM.</li> +</ul> diff --git a/files/es/web/api/element/index.html b/files/es/web/api/element/index.html new file mode 100644 index 0000000000..a689499051 --- /dev/null +++ b/files/es/web/api/element/index.html @@ -0,0 +1,539 @@ +--- +title: element +slug: Web/API/Element +tags: + - Referencia_DOM_de_Gecko +translation_of: Web/API/Element +--- +<p>{{ ApiRef("DOM") }} Este capítulo proporciona una breve explicación para los métodos generales, las propiedades y los eventos disponibles para los elementos HTML y XML en el DOM de Gecko.</p> + +<p>Varias especificaciones aplicadas a los elementos:</p> + +<ul> + <li><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Core/">Especificaciones esenciales del DOM</a> —describe las interfaces esenciales compartidas por la mayoría de los objetos DOM en los documentos HTML y XML.</li> + <li><a class="external" href="http://www.w3.org/TR/DOM-Level-2-HTML/">Especificaciones HTML del DOM</a> —describe las interfaces para objetos en documentos HTML y XHTML construidos con la especificación base.</li> + <li><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Events/">Especificiones de los eventos DOM</a> —describe los eventos compartidos por la mayoría de objetos DOM, construidos con las especificaciones y base DOM <a class="external" href="http://www.w3.org/TR/DOM-Level-2-Views/">Opiniones</a>.</li> +</ul> + +<p>Los artículos listados aquí amplían lo antedicho e incluyen enlaces a la especificación apropiada del DOM de W3C.</p> + +<p>Mientras que estas interfaces son generalmente compartidas por la mayoría de los elementos HTML y XML, hay muchas más especiales para los objetos particulares listados en la especificación HTML del DOM —por ejemplo las interfaces del <a href="/es/DOM/table" title="es/DOM/table">elemento tabla de HTML</a> y <a href="/es/DOM/form" title="es/DOM/form">elemento formulario de HTML</a>.</p> + +<h3 id="Propiedades" name="Propiedades">Propiedades</h3> + +<table class="fullwidth-table"> + <tbody> + <tr> + <th>Nombre</th> + <th>Descripción</th> + <th>Tipo</th> + <th>Disponibilidad</th> + </tr> + <tr> + <td><code><a href="/es/DOM/element.attributes" title="es/DOM/element.attributes">attributes</a></code></td> + <td>Todos los atributos asociados a un elemento.</td> + <td><code><a href="/es/DOM/NamedNodeMap" title="es/DOM/NamedNodeMap">NamedNodeMap</a></code></td> + <td><small>para <a href="/es/DOM" title="es/DOM">todos</a></small></td> + </tr> + <tr> + <td><code><a href="/es/DOM/element.childNodes" title="es/DOM/element.childNodes">childNodes</a></code></td> + <td>Todos los nodos hijos de un elemento.</td> + <td><code><a href="/es/DOM/NodeList" title="es/DOM/NodeList">Listado de nudo</a></code></td> + <td><small>para <a href="/es/DOM" title="es/DOM">todos</a></small></td> + </tr> + <tr> + <td><code><a href="/es/DOM/element.className" title="es/DOM/element.className">className</a></code></td> + <td>La clase del elemento.</td> + <td><code><a href="/es/Core_JavaScript_1.5_Reference/Global_Objects/String" title="es/Core_JavaScript_1.5_Reference/Global_Objects/String">Secuencia</a></code></td> + <td><small>para <a href="/es/HTML" title="es/HTML">HTML</a>, <a href="/es/XUL" title="es/XUL">XUL</a></small></td> + </tr> + <tr> + <td><code><a href="/es/DOM/element.clientHeight" title="es/DOM/element.clientHeight">clientHeight</a></code></td> + <td>El alto interior del elemento.</td> + <td><code><a href="/es/Core_JavaScript_1.5_Reference/Global_Objects/Number" title="es/Core_JavaScript_1.5_Reference/Global_Objects/Number">Número</a></code></td> + <td><small>para <a href="/es/HTML" title="es/HTML">HTML</a></small></td> + </tr> + <tr> + <td><code><a href="/es/DOM/element.clientWidth" title="es/DOM/element.clientWidth">clientWidth</a></code></td> + <td>El ancho interior del elemento.</td> + <td><code><a href="/es/Core_JavaScript_1.5_Reference/Global_Objects/Number" title="es/Core_JavaScript_1.5_Reference/Global_Objects/Number">Número</a></code></td> + <td><small>para <a href="/es/HTML" title="es/HTML">HTML</a></small></td> + </tr> + <tr> + <td><code><a href="/es/DOM/element.dir" title="es/DOM/element.dir">dir</a></code></td> + <td>La direccionalidad del elemento.</td> + <td><code><a href="/es/Core_JavaScript_1.5_Reference/Global_Objects/String" title="es/Core_JavaScript_1.5_Reference/Global_Objects/String">Secuencia</a></code></td> + <td><small>para <a href="/es/HTML" title="es/HTML">HTML</a>, <a href="/es/XUL" title="es/XUL">XUL</a></small></td> + </tr> + <tr> + <td><code><a href="/es/DOM/element.firstChild" title="es/DOM/element.firstChild">firstChild</a></code></td> + <td>El primer hijo directo del elemento, <code>null</code> si no hay.</td> + <td><code><a href="/es/DOM/Node" title="es/DOM/Node">Nudo</a></code></td> + <td><small>para <a href="/es/DOM" title="es/DOM">todos</a></small></td> + </tr> + <tr> + <td><code><a href="/es/DOM/element.id" title="es/DOM/element.id">id</a></code></td> + <td>La identificación del elemento.</td> + <td><code><a href="/es/Core_JavaScript_1.5_Reference/Global_Objects/String" title="es/Core_JavaScript_1.5_Reference/Global_Objects/String">Secuencia</a></code></td> + <td><small>para <a href="/es/HTML" title="es/HTML">HTML</a>, <a href="/es/XUL" title="es/XUL">XUL</a></small></td> + </tr> + <tr> + <td><code><a href="/es/DOM/element.innerHTML" title="es/DOM/element.innerHTML">innerHTML</a></code></td> + <td>El contenido y el código que hay dentro del elemento.</td> + <td><code><a href="/es/Core_JavaScript_1.5_Reference/Global_Objects/String" title="es/Core_JavaScript_1.5_Reference/Global_Objects/String">Secuencia</a></code></td> + <td><small>para <a href="/es/HTML" title="es/HTML">HTML</a></small></td> + </tr> + <tr> + <td><code><a href="/es/DOM/element.lang" title="es/DOM/element.lang">lang</a></code></td> + <td>El lenguaje de los atributos, texto y contenidos del elemento.</td> + <td><code><a href="/es/Core_JavaScript_1.5_Reference/Global_Objects/String" title="es/Core_JavaScript_1.5_Reference/Global_Objects/String">Secuencia</a></code></td> + <td><small>para <a href="/es/HTML" title="es/HTML">HTML</a></small></td> + </tr> + <tr> + <td><code><a href="/es/DOM/element.lastChild" title="es/DOM/element.lastChild">lastChild</a></code></td> + <td>El último hijo directo del elemento, <code>null</code> si no hay.</td> + <td><code><a href="/es/DOM/Node" title="es/DOM/Node">Node</a></code></td> + <td><small>para <a href="/es/DOM" title="es/DOM">todos</a></small></td> + </tr> + <tr> + <td><code><a href="/es/DOM/element.localName" title="es/DOM/element.localName">localName</a></code></td> + <td>La parte local del nombre cualificado del elemento.</td> + <td><code><a href="/es/Core_JavaScript_1.5_Reference/Global_Objects/String" title="es/Core_JavaScript_1.5_Reference/Global_Objects/String">Secuencia</a></code></td> + <td><small>para <a href="/es/DOM" title="es/DOM">todos</a></small></td> + </tr> + <tr> + <th>Nombre</th> + <th>Descripción</th> + <th>Tipo</th> + <th>Disponibilidad</th> + </tr> + <tr> + <td><code><a href="/es/DOM/element.name" title="es/DOM/element.name">name</a></code></td> + <td>El nombre del elemento.</td> + <td><code><a href="/En/Core_JavaScript_1.5_Reference/Global_Objects/String" title="En/Core_JavaScript_1.5_Reference/Global_Objects/String">Secuencia</a></code></td> + <td><small>para <a href="/es/HTML" title="es/HTML">HTML</a></small></td> + </tr> + <tr> + <td><code><a href="/es/DOM/element.namespaceURI" title="es/DOM/element.namespaceURI">namespaceURI</a></code></td> + <td>El URI del espacio de nombre de ese nodo, <code>null</code> si no está especificado.</td> + <td><code><a href="/En/Core_JavaScript_1.5_Reference/Global_Objects/String" title="En/Core_JavaScript_1.5_Reference/Global_Objects/String">Secuencia</a></code></td> + <td><small>para <a href="/es/DOM" title="es/DOM">todos</a></small></td> + </tr> + <tr> + <td><code><a href="/es/DOM/element.nextSibling" title="es/DOM/element.nextSibling">nextSibling</a></code></td> + <td>El nodo inmediatamente posterior al primero dado en el árbol, <code>null</code> si no hay.</td> + <td><code><a href="/es/DOM/Node" title="es/DOM/Node">Nudo</a></code></td> + <td><small>para <a href="/es/DOM" title="es/DOM">todos</a></small></td> + </tr> + <tr> + <td><code><a href="/es/DOM/element.nodeName" title="es/DOM/element.nodeName">nodeName</a></code></td> + <td>El nombre del nodo de ese elemento.</td> + <td><code><a href="/En/Core_JavaScript_1.5_Reference/Global_Objects/String" title="En/Core_JavaScript_1.5_Reference/Global_Objects/String">Secuencia</a></code></td> + <td><small>para <a href="/es/DOM" title="es/DOM">todos</a></small></td> + </tr> + <tr> + <td><code><a href="/es/DOM/element.nodeType" title="es/DOM/element.nodeType">nodeType</a></code></td> + <td>Un número que representa el tipo del nodo. Lo mismo que <code>1</code> para los elementos DOM.</td> + <td><code><a href="/En/Core_JavaScript_1.5_Reference/Global_Objects/Number" title="En/Core_JavaScript_1.5_Reference/Global_Objects/Number">Número</a></code></td> + <td><small>para <a href="/es/DOM" title="es/DOM">todos</a></small></td> + </tr> + <tr> + <td><code><a href="/es/DOM/element.nodeValue" title="es/DOM/element.nodeValue">nodeValue</a></code></td> + <td>El valor del nodo. Lo mismo que <code>null</code> para los elementos DOM.</td> + <td><code><a href="/En/Core_JavaScript_1.5_Reference/Global_Objects/String" title="En/Core_JavaScript_1.5_Reference/Global_Objects/String">Secuencia</a></code></td> + <td><small>para <a href="/es/DOM" title="es/DOM">todos</a></small></td> + </tr> + <tr> + <td><code><a href="/es/DOM/element.offsetHeight" title="es/DOM/element.offsetHeight">offsetHeight</a></code></td> + <td>El alto de un elemento, tal cual está escrito en la composición.</td> + <td><code><a href="/En/Core_JavaScript_1.5_Reference/Global_Objects/Number" title="En/Core_JavaScript_1.5_Reference/Global_Objects/Number">Número</a></code></td> + <td><small>para <a href="/es/HTML" title="es/HTML">HTML</a></small></td> + </tr> + <tr> + <td><code><a href="/es/DOM/element.offsetLeft" title="es/DOM/element.offsetLeft">offsetLeft</a></code></td> + <td>La distancia que hay desde el borde izquierdo del elemento al de su <code>offsetParent</code>.</td> + <td><code><a href="/En/Core_JavaScript_1.5_Reference/Global_Objects/Number" title="En/Core_JavaScript_1.5_Reference/Global_Objects/Number">Número</a></code></td> + <td><small>para <a href="/es/HTML" title="es/HTML">HTML</a></small></td> + </tr> + <tr> + <td><code><a href="/es/DOM/element.offsetParent" title="es/DOM/element.offsetParent">offsetParent</a></code></td> + <td>El elemento del cual todos los cálculos de distancia son actualmente computados.</td> + <td><code><a href="/es/DOM/element" title="es/DOM/element">Elemento</a></code></td> + <td><small>para <a href="/es/HTML" title="es/HTML">HTML</a></small></td> + </tr> + <tr> + <td><code><a href="/es/DOM/element.offsetTop" title="es/DOM/element.offsetTop">offsetTop</a></code></td> + <td>La distancia desde el borde superior del elemento hasta el de su <code>offsetParent</code>.</td> + <td><code><a href="/En/Core_JavaScript_1.5_Reference/Global_Objects/Number" title="En/Core_JavaScript_1.5_Reference/Global_Objects/Number">Número</a></code></td> + <td><small>para <a href="/es/HTML" title="es/HTML">HTML</a></small></td> + </tr> + <tr> + <td><code><a href="/es/DOM/element.offsetWidth" title="es/DOM/element.offsetWidth">offsetWidth</a></code></td> + <td>El ancho de un elemento, tal cual está escrito en la composición.</td> + <td><code><a href="/En/Core_JavaScript_1.5_Reference/Global_Objects/Number" title="En/Core_JavaScript_1.5_Reference/Global_Objects/Number">Número</a></code></td> + <td><small>para <a href="/es/HTML" title="es/HTML">HTML</a></small></td> + </tr> + <tr> + <td><code><a href="/es/DOM/element.ownerDocument" title="es/DOM/element.ownerDocument">ownerDocument</a></code></td> + <td>El documento en el cual está ese nodo, <code>null</code> si no hay.</td> + <td><code><a href="/es/DOM/document" title="es/DOM/document">Documento</a></code></td> + <td><small>para <a href="/es/DOM" title="es/DOM">todos</a></small></td> + </tr> + <tr> + <th>Nombre</th> + <th>Descripción</th> + <th>Tipo</th> + <th>Disponibilidad</th> + </tr> + <tr> + <td><code><a href="/es/DOM/element.parentNode" title="es/DOM/element.parentNode">parentNode</a></code></td> + <td>El elemento original(padre) de ese nodo, <code>null</code> si no hay dentro del <a href="/es/DOM/document" title="es/DOM/document">documento de DOM</a>.</td> + <td><code><a href="/es/DOM/Node" title="es/DOM/Node">Nudo</a></code></td> + <td><small>para <a href="/es/DOM" title="es/DOM">todos</a></small></td> + </tr> + <tr> + <td><code><a href="/es/DOM/element.prefix" title="es/DOM/element.prefix">prefix</a></code></td> + <td>El prefijo del espacio de nombre del nodo, <code>null</code> si no está especificado.</td> + <td><code><a href="/En/Core_JavaScript_1.5_Reference/Global_Objects/String" title="En/Core_JavaScript_1.5_Reference/Global_Objects/String">Secuencia</a></code></td> + <td><small>para <a href="/es/DOM" title="es/DOM">todos</a></small></td> + </tr> + <tr> + <td><code><a href="/es/DOM/element.previousSibling" title="es/DOM/element.previousSibling">previousSibling</a></code></td> + <td>El nodo inmediatamente anterior al primero dado en el árbol , <code>null</code> si no hay.</td> + <td><code><a href="/es/DOM/Node" title="es/DOM/Node">Nudo</a></code></td> + <td><small>para <a href="/es/DOM" title="es/DOM">todos</a></small></td> + </tr> + <tr> + <td><code><a href="/es/DOM/element.scrollHeight" title="es/DOM/element.scrollHeight">scrollHeight</a></code></td> + <td>Muestra la altura de deslizamiento del elemento.</td> + <td><code><a href="/En/Core_JavaScript_1.5_Reference/Global_Objects/Number" title="En/Core_JavaScript_1.5_Reference/Global_Objects/Number">Número</a></code></td> + <td><small>para <a href="/es/HTML" title="es/HTML">HTML</a></small></td> + </tr> + <tr> + <td><code><a href="/es/DOM/element.scrollLeft" title="es/DOM/element.scrollLeft">scrollLeft</a></code></td> + <td>Obtiene/establece el offset de scroll izquierdo de un elemento.</td> + <td><code><a href="/es/Core_JavaScript_1.5_Reference/Global_Objects/Number" title="es/Core_JavaScript_1.5_Reference/Global_Objects/Number">Número</a></code></td> + <td><small>para <a href="/es/HTML" title="es/HTML">HTML</a></small></td> + </tr> + <tr> + <td><code><a href="/es/DOM/element.scrollTop" title="es/DOM/element.scrollTop">scrollTop</a></code></td> + <td>Obtiene/establece el offset de scroll superior de un elemento.</td> + <td><code><a href="/es/Core_JavaScript_1.5_Reference/Global_Objects/Number" title="es/Core_JavaScript_1.5_Reference/Global_Objects/Number">Número</a></code></td> + <td><small>para <a href="/es/HTML" title="es/HTML">HTML</a></small></td> + </tr> + <tr> + <td><code><a href="/es/DOM/element.scrollWidth" title="es/DOM/element.scrollWidth">scrollWidth</a></code></td> + <td>Muestra el ancho de deslizamiento de un elemento.</td> + <td><code><a href="/es/Core_JavaScript_1.5_Reference/Global_Objects/Number" title="es/Core_JavaScript_1.5_Reference/Global_Objects/Number">Número</a></code></td> + <td><small>para <a href="/es/HTML" title="es/HTML">HTML</a></small></td> + </tr> + <tr> + <td><code><a href="/Es/DOM/Element.style" title="Es/DOM/Element.style">style</a></code></td> + <td>Un objeto representando las declaraciones de los atributos de estilo del elemento.</td> + <td><code><a href="/es/DOM/CSSStyleDeclaration" title="es/DOM/CSSStyleDeclaration">Estilo CSS</a></code></td> + <td><small>para <a href="/es/HTML" title="es/HTML">HTML</a>, <a href="/es/XUL" title="es/XUL">XUL</a></small></td> + </tr> + <tr> + <td><code><a href="/es/DOM/element.tabIndex" title="es/DOM/element.tabIndex">tabIndex</a></code></td> + <td>Obtiene/establece la posición del elemento en el órden de tabulación.</td> + <td><code><a href="/En/Core_JavaScript_1.5_Reference/Global_Objects/Number" title="En/Core_JavaScript_1.5_Reference/Global_Objects/Number">Número</a></code></td> + <td><small>para <a href="/es/HTML" title="es/HTML">HTML</a></small></td> + </tr> + <tr> + <td><code><a href="/es/DOM/element.tagName" title="es/DOM/element.tagName">tagName</a></code></td> + <td>El nombre de la etiqueta para el elemento dado.</td> + <td><code><a href="/En/Core_JavaScript_1.5_Reference/Global_Objects/String" title="En/Core_JavaScript_1.5_Reference/Global_Objects/String">Secuencia</a></code></td> + <td><small>para <a href="/es/DOM" title="es/DOM">todos</a></small></td> + </tr> + <tr> + <td><code><a href="/es/DOM/element.textContent" title="es/DOM/element.textContent">textContent</a></code></td> + <td>Obtiene/establece los contenidos textuales de un elemento y todos sus descendentes.</td> + <td><code><a href="/En/Core_JavaScript_1.5_Reference/Global_Objects/String" title="En/Core_JavaScript_1.5_Reference/Global_Objects/String">Secuencia</a></code></td> + <td><small>para <a href="/es/DOM" title="es/DOM">todos</a></small></td> + </tr> + </tbody> +</table> + +<h3 id="M.C3.A9todos" name="M.C3.A9todos">Métodos</h3> + +<table class="fullwidth-table"> + <tbody> + <tr> + <th>Nombre y Descripción</th> + <th>Devuelve</th> + <th>Disponible</th> + </tr> + <tr> + <td><code><a href="/es/DOM/element.addEventListener" title="es/DOM/element.addEventListener">addEventListener</a>( <a href="/En/Core_JavaScript_1.5_Reference/Global_Objects/String" title="En/Core_JavaScript_1.5_Reference/Global_Objects/String">type</a>, <a href="/en/JavaScript/Reference/Global_Objects/Function" title="en/JavaScript/Reference/Global_Objects/Function">handler</a>, <a href="/en/JavaScript/Reference/Global_Objects/Boolean" title="en/JavaScript/Reference/Global_Objects/Boolean">bubble</a>)</code><br> + Registra un controlador de evento para un tipo de evento específico en un elemento.</td> + <td>-</td> + <td><small><a href="/es/DOM/event" title="es/DOM/event">Todos</a></small></td> + </tr> + <tr> + <td><code><a href="/es/docs/Web/API/Node/appendChild" title="es/DOM/element.appendChild">appendChild</a>( <a href="/es/DOM/Node" title="es/DOM/Node">appendedNode</a> )</code><br> + Inserta un nodo así como el último nodo hijo de este elemento.</td> + <td><a href="/es/DOM/Node" title="es/DOM/Node">Node</a></td> + <td><small><a href="/es/DOM" title="es/DOM">Todos</a></small></td> + </tr> + <tr> + <td><code><a href="/es/DOM/element.blur" title="es/DOM/element.blur">blur</a>()</code><br> + Quita el foco del teclado del elemento actual.</td> + <td>-</td> + <td><small>para <a href="/es/HTML" title="es/HTML">HTML</a>, <a href="/es/XUL" title="es/XUL">XUL</a></small></td> + </tr> + <tr> + <td><code><a href="/es/DOM/element.click" title="es/DOM/element.click">click</a>()</code><br> + Simula un clic sobre el elemento actual.</td> + <td>-</td> + <td><small>para <a href="/es/HTML" title="es/HTML">HTML</a>, <a href="/es/XUL" title="es/XUL">XUL</a></small></td> + </tr> + <tr> + <td><code><a href="/es/docs/Web/API/Node/cloneNode" title="es/DOM/element.cloneNode">cloneNode</a>( <a href="/en/JavaScript/Reference/Global_Objects/Boolean" title="en/JavaScript/Reference/Global_Objects/Boolean">deep</a>)</code><br> + Hace copia de un nudo, y opcionalmente, de todo sus contenidos</td> + <td><a href="/es/DOM/Node" title="es/DOM/Node">Node</a></td> + <td><small>para <a href="/es/DOM" title="es/DOM">Todos</a></small></td> + </tr> + <tr> + <td><code><a href="/es/DOM/element.dispatchEvent" title="es/DOM/element.dispatchEvent">dispatchEvent</a>( <a href="/es/DOM/event" title="es/DOM/event">event</a> )</code><br> + Envía un evento a este nodo en el DOM.</td> + <td><a href="/es/Core_JavaScript_1.5_Reference/Global_Objects/Boolean" title="es/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">Boolean</a></td> + <td><small><a href="/es/DOM" title="es/DOM">Todos</a></small></td> + </tr> + <tr> + <td><code><a href="/es/docs/Web/API/Element/getAttribute" title="es/DOM/element.getAttribute">getAttribute</a>( <a href="/es/Core_JavaScript_1.5_Reference/Global_Objects/String" title="es/Core_JavaScript_1.5_Reference/Global_Objects/String">name</a> )</code><br> + Devuelve el valor de un atributo nombrado desde el nodo actual.</td> + <td><a href="/es/Core_JavaScript_1.5_Reference/Global_Objects/Object" title="es/Core_JavaScript_1.5_Reference/Global_Objects/Object">Object</a></td> + <td><small><a href="/es/DOM" title="es/DOM">Todos</a></small></td> + </tr> + <tr> + <td><code><a href="/es/docs/Web/API/Element/getAttributeNS" title="es/DOM/element.getAttributeNS">getAttributeNS</a>( <a href="/es/Core_JavaScript_1.5_Reference/Global_Objects/String" title="es/Core_JavaScript_1.5_Reference/Global_Objects/String">namespace</a>, <a href="/es/Core_JavaScript_1.5_Reference/Global_Objects/String" title="es/Core_JavaScript_1.5_Reference/Global_Objects/String">name</a> )</code><br> + Devuelve el valor del atributo con el nombre especificado, desde el nodo actual.</td> + <td><a href="/es/Core_JavaScript_1.5_Reference/Global_Objects/Object" title="es/Core_JavaScript_1.5_Reference/Global_Objects/Object">Object</a></td> + <td><small><a href="/es/DOM" title="es/DOM">Todos</a></small></td> + </tr> + <tr> + <td><code><a href="/es/docs/Web/API/Element/getAttributeNode" title="es/DOM/element.getAttributeNode">getAttributeNode</a>( <a href="/es/Core_JavaScript_1.5_Reference/Global_Objects/String" title="es/Core_JavaScript_1.5_Reference/Global_Objects/String">name</a> )</code><br> + Devuelve la representación del nodo del atributo nombrado desde el nodo actual.</td> + <td><a href="/es/DOM/Attr" title="es/DOM/Attr">Attr</a></td> + <td><small><a href="/es/DOM" title="es/DOM">Todos</a></small></td> + </tr> + <tr> + <td><code><a href="/es/docs/Web/API/Element/getAttributeNodeNS" title="es/DOM/element.getAttributeNodeNS">getAttributeNodeNS</a>( <a href="/es/Core_JavaScript_1.5_Reference/Global_Objects/String" title="es/Core_JavaScript_1.5_Reference/Global_Objects/String">namespace</a>, <a href="/es/Core_JavaScript_1.5_Reference/Global_Objects/String" title="es/Core_JavaScript_1.5_Reference/Global_Objects/String">name</a> )</code><br> + Devuelve la representación del nodo del atributo con el nombre especificado, desde el nodo actual.</td> + <td><a href="/es/DOM/Attr" title="es/DOM/Attr">Attr</a></td> + <td><small><a href="/es/DOM" title="es/DOM">Todos</a></small></td> + </tr> + <tr> + <th>Nombre y Descripción</th> + <th>Devuelve</th> + <th>Disponibilidad</th> + </tr> + <tr> + <td><code><a href="/es/docs/Web/API/Element/getElementsByTagName" title="es/DOM/element.getElementsByTagName">getElementsByTagName</a>( <a href="/es/Core_JavaScript_1.5_Reference/Global_Objects/String" title="es/Core_JavaScript_1.5_Reference/Global_Objects/String">name</a> )</code><br> + Devuelve un conjunto de todos los elementos descendentes, de un nombre de etiqueta particular, desde el elemento actual.</td> + <td><a href="/es/DOM/NodeSet" title="es/DOM/NodeSet">NodeSet</a></td> + <td><small><a href="/es/DOM" title="es/DOM">Todos</a></small></td> + </tr> + <tr> + <td><code><a href="/es/docs/Web/API/Element/getElementsByTagNameNS" title="es/DOM/element.getElementsByTagNameNS">getElementsByTagNameNS</a>( <a href="/es/Core_JavaScript_1.5_Reference/Global_Objects/String" title="es/Core_JavaScript_1.5_Reference/Global_Objects/String">namespace</a>, <a href="/es/Core_JavaScript_1.5_Reference/Global_Objects/String" title="es/Core_JavaScript_1.5_Reference/Global_Objects/String">name</a> )</code><br> + Devuelve un conjunto de todos los elementos descendentes, de un nombre de etiqueta y espacio particular, desde el elemento actual.</td> + <td><a href="/es/DOM/NodeSet" title="es/DOM/NodeSet">NodeSet</a></td> + <td><small><a href="/es/DOM" title="es/DOM">Todos</a></small></td> + </tr> + <tr> + <td><code><a href="/es/docs/Web/API/Element/hasAttribute" title="es/DOM/element.hasAttribute">hasAttribute</a>( <a href="/es/Core_JavaScript_1.5_Reference/Global_Objects/String" title="es/Core_JavaScript_1.5_Reference/Global_Objects/String">name</a> )</code><br> + Verifica si el elemento tiene el atributo especificado o no.</td> + <td><a href="/es/Core_JavaScript_1.5_Reference/Global_Objects/Boolean" title="es/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">Boolean</a></td> + <td><small><a href="/es/DOM" title="es/DOM">Todos</a></small></td> + </tr> + <tr> + <td><code><a href="/es/docs/Web/API/Element/hasAttributeNS" title="es/DOM/element.hasAttributeNS">hasAttributeNS</a>( <a href="/es/Core_JavaScript_1.5_Reference/Global_Objects/String" title="es/Core_JavaScript_1.5_Reference/Global_Objects/String">namespace</a>, <a href="/es/Core_JavaScript_1.5_Reference/Global_Objects/String" title="es/Core_JavaScript_1.5_Reference/Global_Objects/String">name</a> )</code><br> + Verifica si el elemento tiene el atributo especificado, en el nombre de espacio especificado o no.</td> + <td><a href="/es/Core_JavaScript_1.5_Reference/Global_Objects/Boolean" title="es/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">Boolean</a></td> + <td><small><a href="/es/DOM" title="es/DOM">Todos</a></small></td> + </tr> + <tr> + <td><code><a href="/es/docs/Web/API/Element/hasAttributes" title="es/DOM/element.hasAttributes">hasAttributes</a>()</code><br> + Verifica si el elemento tiene o no algún atributo.</td> + <td><a href="/es/Core_JavaScript_1.5_Reference/Global_Objects/Boolean" title="es/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">Boolean</a></td> + <td><small><a href="/es/DOM" title="es/DOM">Todos</a></small></td> + </tr> + <tr> + <td><code><a href="/es/docs/Web/API/Node/hasChildNodes" title="es/DOM/element.hasChildNodes">hasChildNodes</a>()</code><br> + Verifica si el elemento tiene nodos hijos o no.</td> + <td><a href="/es/Core_JavaScript_1.5_Reference/Global_Objects/Boolean" title="es/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">Boolean</a></td> + <td><small><a href="/es/DOM" title="es/DOM">Todos</a></small></td> + </tr> + <tr> + <td><code><a href="/es/docs/Web/API/Node/insertarAntes" title="es/DOM/element.insertBefore">insertBefore</a>( <a href="/es/DOM/Node" title="es/DOM/Node">insertedNode</a>, <a href="/es/DOM/Node" title="es/DOM/Node">adjacentNode</a> )</code><br> + Inserta el primer nodo antes que el segundo, Nodo hijo en el DOM.</td> + <td><a href="/es/DOM/Node" title="es/DOM/Node">Node</a></td> + <td><small><a href="/es/DOM" title="es/DOM">Todos</a></small></td> + </tr> + <tr> + <td><code><a href="/es/docs/Web/API/Node/normalize" title="es/DOM/element.normalize">normalize</a>()</code><br> + Limpia todos los nodos de texto debajo de este elemento (une lo adyacente, quita lo vacío).</td> + <td>-</td> + <td><small><a href="/es/DOM" title="es/DOM">Todos</a></small></td> + </tr> + <tr> + <td><code><a href="/es/docs/Web/API/Element/removeAttribute" title="es/DOM/element.removeAttribute">removeAttribute</a>( <a href="/es/Core_JavaScript_1.5_Reference/Global_Objects/String" title="es/Core_JavaScript_1.5_Reference/Global_Objects/String">name</a> )</code><br> + Quita el atributo nombrado desde el nodo actual.</td> + <td>-</td> + <td><small><a href="/es/DOM" title="es/DOM">All</a></small></td> + </tr> + <tr> + <td><code><a href="/es/docs/Web/API/Element/removeAttributeNS" title="es/DOM/element.removeAttributeNS">removeAttributeNS</a>( <a href="/es/Core_JavaScript_1.5_Reference/Global_Objects/String" title="es/Core_JavaScript_1.5_Reference/Global_Objects/String">namespace</a>, <a href="/es/Core_JavaScript_1.5_Reference/Global_Objects/String" title="es/Core_JavaScript_1.5_Reference/Global_Objects/String">name</a> )</code><br> + Quita el atributo con el nombre y nombre de espacio especificado desde el nodo actual.</td> + <td>-</td> + <td><small><a href="/es/DOM" title="es/DOM">Todos</a></small></td> + </tr> + <tr> + <th>Nombre y Descripción</th> + <th>Devuelve</th> + <th>Disponibilidad</th> + </tr> + <tr> + <td><code><a href="/es/docs/Web/API/Element/removeAttributeNode" title="es/DOM/element.removeAttributeNode">removeAttributeNode</a>( <a href="/es/Core_JavaScript_1.5_Reference/Global_Objects/String" title="es/Core_JavaScript_1.5_Reference/Global_Objects/String">name</a> )</code><br> + Quita la representación del nodo del atributo nombrado desde el nodo actual.</td> + <td>-</td> + <td><small><a href="/es/DOM" title="es/DOM">Todos</a></small></td> + </tr> + <tr> + <td><code><a href="/es/docs/Web/API/Node/removeChild" title="es/DOM/element.removeChild">removeChild</a>( <a href="/es/DOM/Node" title="es/DOM/Node">removedNode</a> )</code><br> + Quita el nodo hijo desde el elemento actual.</td> + <td><a href="/es/DOM/Node" title="es/DOM/Node">Node</a></td> + <td><small><a href="/es/DOM" title="es/DOM">Todos</a></small></td> + </tr> + <tr> + <td><code><a href="/es/docs/Web/API/Element/removeEventListener" title="es/DOM/element.removeEventListener">removeEventListener</a>( <a href="/es/Core_JavaScript_1.5_Reference/Global_Objects/String" title="es/Core_JavaScript_1.5_Reference/Global_Objects/String">type</a>, <a href="/es/Core_JavaScript_1.5_Reference/Global_Objects/Function" title="es/Core_JavaScript_1.5_Reference/Global_Objects/Function">handler</a> )</code><br> + Quita un oyente de evento desde el elemento.</td> + <td>-</td> + <td><small><a href="/es/DOM/event" title="es/DOM/event">Todos</a></small></td> + </tr> + <tr> + <td><code><a href="/es/docs/Web/API/Node/replaceChild" title="es/DOM/element.replaceChild">replaceChild</a>( <a href="/es/DOM/Node" title="es/DOM/Node">insertedNode</a>, <a href="/es/DOM/Node" title="es/DOM/Node">replacedNode</a> )</code><br> + Reemplaza un nodo hijo en el elemento actual con otro.</td> + <td><a href="/es/DOM/Node" title="es/DOM/Node">Node</a></td> + <td><small><a href="/es/DOM" title="es/DOM">Todos</a></small></td> + </tr> + <tr> + <td><code><a href="/es/docs/Web/API/Element/scrollIntoView" title="es/DOM/element.scrollIntoView">scrollIntoView</a>( <a href="/es/Core_JavaScript_1.5_Reference/Global_Objects/Boolean" title="es/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">alignWithTop</a> )</code><br> + Recorre la página hasta que el elemento se obtiene en la vista.</td> + <td>-</td> + <td><small><a href="/es/HTML" title="es/HTML">HTML</a></small></td> + </tr> + <tr> + <td><code><a href="/es/docs/Web/API/Element/setAttribute" title="Es/DOM/Element.setAttribute">setAttribute</a>( <a href="/es/Core_JavaScript_1.5_Reference/Global_Objects/String" title="es/Core_JavaScript_1.5_Reference/Global_Objects/String">name</a>, <a href="/es/Core_JavaScript_1.5_Reference/Global_Objects/Object" title="es/Core_JavaScript_1.5_Reference/Global_Objects/Object">value</a> )</code><br> + Establece el valor de un atributo nombrado desde el nodo actual.</td> + <td>-</td> + <td><small><a href="/es/DOM" title="es/DOM">Todos</a></small></td> + </tr> + <tr> + <td><code><a href="/es/docs/Web/API/Element/setAttributeNS" title="es/DOM/element.setAttributeNS">setAttributeNS</a>( <a href="/es/Core_JavaScript_1.5_Reference/Global_Objects/String" title="es/Core_JavaScript_1.5_Reference/Global_Objects/String">namespace</a>, <a href="/es/Core_JavaScript_1.5_Reference/Global_Objects/String" title="es/Core_JavaScript_1.5_Reference/Global_Objects/String">name</a>, <a href="/es/Core_JavaScript_1.5_Reference/Global_Objects/Object" title="es/Core_JavaScript_1.5_Reference/Global_Objects/Object">value</a> )</code><br> + Establece el valor del atributo con el nombre y nombre de espacio especificado desde el nodo actual.</td> + <td>-</td> + <td><small><a href="/es/DOM" title="es/DOM">Todos</a></small></td> + </tr> + <tr> + <td><code><a href="/es/docs/Web/API/Element/setAttributeNode" title="es/DOM/element.setAttributeNode">setAttributeNode</a>( <a href="/es/Core_JavaScript_1.5_Reference/Global_Objects/String" title="es/Core_JavaScript_1.5_Reference/Global_Objects/String">name</a>, <a href="/es/DOM/Attr" title="es/DOM/Attr">attrNode</a> )</code><br> + Establece la representación del nodo del atributo nombrado desde el nodo actual.</td> + <td>-</td> + <td><small><a href="/es/DOM" title="es/DOM">Todos</a></small></td> + </tr> + <tr> + <td><code><a href="/es/docs/Web/API/Element/setAttributeNodeNS" title="es/DOM/element.setAttributeNodeNS">setAttributeNodeNS</a>( <a href="/es/Core_JavaScript_1.5_Reference/Global_Objects/String" title="es/Core_JavaScript_1.5_Reference/Global_Objects/String">namespace</a>, <a href="/es/Core_JavaScript_1.5_Reference/Global_Objects/String" title="es/Core_JavaScript_1.5_Reference/Global_Objects/String">name</a>, <a href="/es/DOM/Attr" title="es/DOM/Attr">attrNode</a> )</code><br> + Establece la representación del nodo del atributo con el nombre y nombre de espacio especificado desde el nodo actual.</td> + <td>-</td> + <td><small><a href="/es/DOM" title="es/DOM">Todos</a></small></td> + </tr> + </tbody> +</table> + +<h3 id="Eventos" name="Eventos">Eventos</h3> + +<p>Son propiedades correspondientes a los atributos del evento "on" en HTML.</p> + +<p>A diferencia de los atributos correspondientes, los valores de esas propiedades son funciones (o cualquier otro objeto trabajando con la interfaz <a class="external" href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventListener">EventListener</a>) más bien que una cadena de carácteres. En efecto, asignar un atributo de evento en HTML crea una función envolvente alrededor del código especificado. Por ejemplo, el siguiente HTML:</p> + +<pre><div onclick="foo();">clic aquí!</div> +</pre> + +<p>Si <code>element</code> es una referencia a esta <code>div</code>, el valor de <code>element.onclick</code> será:</p> + +<pre>function onclick(event) { + foo(); +} +</pre> + +<p>El objeto <a href="/es/DOM/event" title="es/DOM/event">event</a> es pasado al parámetro <code>event</code> de esta función envolvente.</p> + +<dl> + <dt><a href="/es/DOM/element.onblur" title="es/DOM/element.onblur">onblur</a> - (al quitar el foco)</dt> + <dd>Devuelve el código de manejo de evento para el evento <code>blur</code>.</dd> +</dl> + +<dl> + <dt><a href="/es/DOM/element.onchange" title="es/DOM/element.onchange">onchange</a> - (al modificar)</dt> + <dd>Devuelve el código de manejo de evento para el evento <code>change</code>.</dd> +</dl> + +<dl> + <dt><a href="/es/DOM/element.onclick" title="es/DOM/element.onclick">onclick</a> - (al hacer clic)</dt> + <dd>Devuelve el código de manejo de evento para el evento <code>onclick</code>.</dd> +</dl> + +<dl> + <dt><a href="/es/DOM/element.ondblclick" title="es/DOM/element.ondblclick">ondblclick</a> - (al hacer doble clic)</dt> + <dd>Devuelve el código de manejo de evento para el evento <code>ondblclick</code>.</dd> +</dl> + +<dl> + <dt><a href="/es/DOM/element.onfocus" title="es/DOM/element.onfocus">onfocus</a> - (al poner el foco)</dt> + <dd>Devuelve el código de manejo de evento para el evento <code>onfocus</code>.</dd> +</dl> + +<dl> + <dt><a href="/es/DOM/element.onkeydown" title="es/DOM/element.onkeydown">onkeydown</a> - (al tener una tecla apretada)</dt> + <dd>Devuelve el código de manejo de evento para el evento <code>onkeydown</code>.</dd> +</dl> + +<dl> + <dt><a href="/es/DOM/element.onkeypress" title="es/DOM/element.onkeypress">onkeypress</a> - (al apretar una tecla)</dt> + <dd>Devuelve el código de manejo de evento para el evento <code>onkeypress</code>.</dd> +</dl> + +<dl> + <dt><a href="/es/DOM/element.onkeyup" title="es/DOM/element.onkeyup">onkeyup</a> - (al soltar una tecla)</dt> + <dd>Devuelve el código de manejo de evento para el evento <code>onkeyup</code>.</dd> +</dl> + +<dl> + <dt><a href="/es/DOM/element.onmousedown" title="es/DOM/element.onmousedown">onmousedown</a> - (al tener el botón del ratón apretado)</dt> + <dd>Devuelve el código de manejo de evento para el evento <code>onmousedown</code>.</dd> +</dl> + +<dl> + <dt><a href="/es/DOM/element.onmousemove" title="es/DOM/element.onmousemove">onmousemove</a> - (al mover el ratón)</dt> + <dd>Devuelve el código de manejo de evento para el evento <code>onmousemove</code>.</dd> +</dl> + +<dl> + <dt><a href="/es/DOM/element.onmouseout" title="es/DOM/element.onmouseout">onmouseout</a> - (al quitar el puntero del ratón)</dt> + <dd>Devuelve el código de manejo de evento para el evento <code>onmouseout</code>.</dd> +</dl> + +<dl> + <dt><a href="/es/DOM/element.onmouseover" title="es/DOM/element.onmouseover">onmouseover</a> - (al pasar el ratón encima)</dt> + <dd>Devuelve el código de manejo de evento para el evento <code>onmouseover</code>.</dd> +</dl> + +<dl> + <dt><a href="/es/DOM/element.onmouseup" title="es/DOM/element.onmouseup">onmouseup</a> - (al soltar el botón del ratón)</dt> + <dd>Devuelve el código de manejo de evento para el evento <code>onmouseup</code>.</dd> +</dl> + +<dl> + <dt><a href="/es/DOM/element.onresize" title="es/DOM/element.onresize">onresize</a> - (al re-dimensionar la pantalla)</dt> + <dd>Devuelve el código de manejo de evento para el evento <code>onresize</code>.</dd> +</dl> diff --git a/files/es/web/api/element/innerhtml/index.html b/files/es/web/api/element/innerhtml/index.html new file mode 100644 index 0000000000..b0e9552b47 --- /dev/null +++ b/files/es/web/api/element/innerhtml/index.html @@ -0,0 +1,151 @@ +--- +title: element.innerHTML +slug: Web/API/Element/innerHTML +tags: + - API + - DOM + - Gecko + - Propiedad + - Referencia +translation_of: Web/API/Element/innerHTML +--- +<p>{{APIRef("DOM")}}</p> + +<h2 id="Summary" name="Summary">Resumen</h2> + +<p>La propiedad <strong><code>Element.innerHTML</code></strong> devuelve o establece la sintaxis HTML describiendo los descendientes del elemento.</p> + +<p>Al establecerse se reemplaza la sintaxis HTML del elemento por la nueva.</p> + +<div class="note"><strong>Nota: </strong>Si un nodo tiene un texto secundario que incluye los caracteres <code>(&), (<),</code> o <code>(>)</code>, <code>innerHTML</code> devuelve estos caracteres como &amp, &lt y &gt respectivamente. Use {{ domxref("Node.textContent") }} para conseguir una copia correcta del contenido de estos nodos de texto.</div> + +<p>Para <strong>insertar el código HTML</strong> en el documento en lugar de cambiar el contenido de un elemento, use el método <a href="https://developer.mozilla.org/es/docs/Web/API/Element/insertAdjacentHTML">insertAdjacentHTML().</a></p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox"><em>const content</em> = <em>element</em>.innerHTML; + +<em>element</em>.innerHTML = <em>htmlString</em>;</pre> + +<h3 class="brush: js" id="Valor">Valor</h3> + +<p>La variable constante <code>content</code> contiene un <a href="https://developer.mozilla.org/es/docs/Web/API/DOMString">DOMString</a> que contiene el código HTML serializado describiendo todos los descendientes de <code>element</code>. Cuando se establece el valor de innerHTML, <strong>se eliminan todos los descendientes de <code>element</code></strong>, analiza la cadena <code>htmString</code> y asigna los nodos resultantes como descendientes de <code>element</code>.</p> + +<h3 id="Excepciones">Excepciones</h3> + +<dl> + <dt><code>SyntaxError</code></dt> + <dd>Se intentó establecer el valor de <code>innerHTML</code> utilizando una cadena que no está formada correctamente en HTML</dd> + <dt><code>NoModificationAllowedError</code></dt> + <dd>Se intentó insertar el código HTML en un nodo cuyo elemento primario es <a href="https://developer.mozilla.org/es/docs/Web/API/Document">document</a>.</dd> +</dl> + +<h2 id="Notes" name="Notes">Notas de uso</h2> + +<p>La propiedad <code>innerHTML</code> de muchos tipos de elementos—incluyendo {{ HTMLElement("body") }} o {{ HTMLElement("html") }}—puede ser devuelta o establecida. Esta propiedad se puede usar para ver el código HTML de la página actual, incluida la que haya sido modificada dinámicamente:</p> + +<h3 id="Devolver_la_sintaxis_HTML_de_un_elemento">Devolver la sintaxis HTML de un elemento</h3> + +<p>Devolver el valor de <code>innerHTML</code><font><font>hace que el agente de usuario serialice el fragmento HTML compuesto por los descendientes del elemento. </font><font>La cadena resultante es devuelta.</font></font></p> + +<pre><em>const content</em><code> = </code><em>element</em>.innerHTML; +</pre> + +<p>Esto le permite ver la sintaxis HTML de los nodos contenidos en el elemento.</p> + +<h3 id="Reemplazar_el_contenido_de_un_elemento">Reemplazar el contenido de un elemento</h3> + +<p>Esta propiedad proporciona una forma sencilla de cambiar completamente los contenidos de un elemento por contenido nuevo. Por ejemplo, los contenidos completos del cuerpo del documento se pueden borrar así:</p> + +<pre class="brush: js">document.body.innerHTML = ""; // Reemplaza el contenido de <body> con una cadena vacía +</pre> + +<p>El siguiente ejemplo recupera la sintaxis HTML actual del documento y reemplaza los caracteres "<code><</code>" con la entidad HTML "<code>&lt;</code>", convirtiendo esencialmente el HTML en texto plano. Esto luego se envuelve en un elemento <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/pre"><pre></a>. Entonces el valor de innerHTML se cambia a esta nueva cadena. Como resultado, se muestra en pantalla el código fuente completo de la página.</p> + +<pre><code>document.documentElement.innerHTML = "<pre>" + + document.documentElement.innerHTML.replace(/</g,"&lt;") + + "</pre>";</code> +</pre> + +<div class="note"> +<p>Esta propiedad fue inicialmente implementada por navegadores web, y luego especificada por el WHATWG y el W3C en HTML5. Implementaciones antiguas no la implementarán exactamente igual. Por ejemplo, cuando el texto es ingresado en una caja de <strong>texto multilinea (elemento <code>textarea</code>)</strong>, Internet Explorer <font><font>cambiará el valor de la propiedad <code>innerHTML</code> del </font></font><strong>elemento <code>textarea</code></strong><font><font>, mientras que los navegadores Gecko no lo hacen.</font></font></p> +</div> + +<h3 id="Consideración_de_seguridad">Consideración de seguridad</h3> + +<p>No es extraño que <code>innerHTML</code> sea usado para introducir texto en una página web. Esto añade un riesgo de seguridad.</p> + +<pre class="brush: js">//ejemplo 1 +var name = "Juan"; +// asumiendo que 'el' es un elemento de HTML DOM +el.innerHTML = name; // sin peligro + +// ... + +//ejemplo 2 +name = "<script>alert('Soy Juan con una alerta molesta!')</script>"; +el.innerHTML = name; // fíjese que<span id="result_box" lang="es"> <span class="hps">el</span> <span class="hps">texto</span> <span class="hps">es molesto</span> <span class="hps">y no es realmente</span> <span class="hps">lo que se esperaba</span><span>.</span></span> +</pre> + +<p>Aunque esto, el ejemplo 2, puede parecer un ataque <a class="external" href="http://en.wikipedia.org/wiki/Cross-site_scripting">cross-site scripting</a>, <strong>el resultado es inofensivo</strong>, ya que HTML5 especifica que un tag <code><a href="https://developer.mozilla.org/es/docs/Web/HTML/Elemento/script"><script></a> </code>insertado a través innerHTML <a href="https://www.w3.org/TR/2008/WD-html5-20080610/dom.html#innerhtml0">no debe ejecutarse</a>.</p> + +<p>Sin embargo, hay maneras de ejecutar JavaScript sin necesidad de utilizar el elemento <code><script></code>, por lo que todavía hay un riesgo de seguridad cada vez que se utiliza <code>innerHTML</code> para establecer cadenas de texto sobre las que no tiene control. Por ejemplo:</p> + +<pre class="brush: js">const name = "<img src='x' onerror='alert(1)'>"; +el.innerHTML = name; // con peligro, la alerta ahora si es mostrada</pre> + +<p>Por esa razón, cuando solo tratamos con texto, es recomendable no usar <code>innerHTML</code>, sino <a href="/En/DOM/Node.textContent">Node.textContent</a>, que no interpretará la cadena pasada como HTML, sino como texto plano.</p> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre class="brush: html"><!doctype html> +<html> + <head> + <meta charset="utf-8"> + <title>Documento sin título</title> + </head> + <body> + <div id="txt"> + <p>primer parrafo hijo de div id="txt"</p> + <p>segundo parrafo hijo de id="txt" txt</p> + </div> + </body> +</html></pre> + +<pre class="brush: js">txt = document.getElementById("txt"); +console.log(txt.innerHTML); +/* +La siguiente cadena (string) se muestra en la ventana de la consola: +<p>primer parrafo hijo de div id="txt"</p> +<p>segundo parrafo hijo de id="txt" txt</p> +*/</pre> + +<h2 id="Specification" name="Specification">Especificaciones</h2> + +<ul> + <li>W3C's HTML 5 <code>innerHTML</code> para <a class="external" href="http://www.w3.org/TR/2008/WD-html5-20080610/dom.html#innerhtml0" title="http://www.w3.org/TR/2008/WD-html5-20080610/dom.html#innerhtml0">documentos </a><a class="external" href="http://www.w3.org/TR/2008/WD-html5-20080610/dom.html#innerhtml0" title="http://www.w3.org/TR/2008/WD-html5-20080610/dom.html#innerhtml0">HTML</a></li> + <li>W3C's HTML 5 <code>innerHTML</code> para <a class="external" href="http://www.w3.org/TR/2008/WD-html5-20080610/dom.html#innerhtml1" title="http://www.w3.org/TR/2008/WD-html5-20080610/dom.html#innerhtml1">documentos </a><a class="external" href="http://www.w3.org/TR/2008/WD-html5-20080610/dom.html#innerhtml1" title="http://www.w3.org/TR/2008/WD-html5-20080610/dom.html#innerhtml1">XHTML</a></li> +</ul> + +<h2 id="See_also" name="See_also">Ver también</h2> + +<ul> + <li><code><a class="external" href="http://innerdom.sourceforge.net/">innerDOM</a></code> - Para aquellos que desean adherirse a los estándares, aquí hay un conjunto de funciones JavaScript que ofrecen serializar o analizar XML para así establecer contenidos de elementos definidos como cadena(s) via el DOM o para conseguir contenidos de elementos obtenidos del DOM como cadenas.</li> + <li><a class="external" href="http://code.google.com/p/jssaxparser/" title="http://code.google.com/p/jssaxparser/">jssaxparser</a> - Una solución más robusta (aunque más pesada) que innerDOM (soporta análisis con espacios de nombres, atributos entre comillas simples, secciones CDATA, etc) es este analizador SAX2 cuando se utiliza con su manejador de contenido DOM. (Ofrece String to DOM, DOM to string es <a class="external" href="http://code.assembla.com/brettz9/subversion/nodes/DOMToString" title="http://code.assembla.com/brettz9/subversion/nodes/DOMToString">significativamente más fácil</a>)</li> +</ul> + +<div class="s3gt_translate_tooltip_mini_box" id="s3gt_translate_tooltip_mini" style="background: initial !important; border: initial !important; border-radius: initial !important; border-collapse: initial !important; direction: ltr !important; font-weight: initial !important; height: initial !important; letter-spacing: initial !important; max-width: initial !important; min-height: initial !important; margin: auto !important; outline: initial !important; padding: initial !important; position: absolute; text-align: initial !important; text-shadow: initial !important; width: initial !important; display: initial !important; color: inherit !important; font-size: 13px !important; font-family: X-LocaleSpecific, sans-serif, Tahoma, Helvetica !important; line-height: 13px !important; vertical-align: top !important; white-space: inherit !important; left: 163px; top: 957px; opacity: 0.85;"> +<div class="s3gt_translate_tooltip_mini" id="s3gt_translate_tooltip_mini_logo" title="Traducir texto seleccionado"> </div> + +<div class="s3gt_translate_tooltip_mini" id="s3gt_translate_tooltip_mini_sound" title="Escuchar"> </div> + +<div class="s3gt_translate_tooltip_mini" id="s3gt_translate_tooltip_mini_copy" title="Copiar texto al Portapapeles"> </div> +</div> + +<div class="s3gt_translate_tooltip_mini_box" id="s3gt_translate_tooltip_mini" style="background: initial !important; border: initial !important; border-radius: initial !important; border-collapse: initial !important; direction: ltr !important; font-weight: initial !important; height: initial !important; letter-spacing: initial !important; max-width: initial !important; min-height: initial !important; margin: auto !important; outline: initial !important; padding: initial !important; position: absolute; text-align: initial !important; text-shadow: initial !important; width: initial !important; display: initial !important; color: inherit !important; font-size: 13px !important; font-family: X-LocaleSpecific, sans-serif, Tahoma, Helvetica !important; line-height: 13px !important; vertical-align: top !important; white-space: inherit !important; left: 503px; top: 778px; opacity: 0.15;"> +<div class="s3gt_translate_tooltip_mini" id="s3gt_translate_tooltip_mini_logo" title="Traducir texto seleccionado"> </div> + +<div class="s3gt_translate_tooltip_mini" id="s3gt_translate_tooltip_mini_sound" title="Escuchar"> </div> + +<div class="s3gt_translate_tooltip_mini" id="s3gt_translate_tooltip_mini_copy" title="Copiar texto al Portapapeles"> </div> +</div> diff --git a/files/es/web/api/element/insertadjacentelement/index.html b/files/es/web/api/element/insertadjacentelement/index.html new file mode 100644 index 0000000000..4f06780e1e --- /dev/null +++ b/files/es/web/api/element/insertadjacentelement/index.html @@ -0,0 +1,115 @@ +--- +title: Element.insertAdjacentElement() +slug: Web/API/Element/insertAdjacentElement +translation_of: Web/API/Element/insertAdjacentElement +--- +<p>{{APIRef("DOM")}}</p> + +<p>El método <strong><code>insertAdjacentElement()</code></strong> inserta un elemento nodo dado en una posición dada con respecto al elemento sobre el que se invoca.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="notranslate"><em>elementoObjetivo</em>.insertAdjacentElement(<em>posición</em>, <em>elemento</em>);</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>posición</code></dt> + <dd>Un {{domxref("DOMString")}} representando la posición relativa al <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">elementoObjetivo</span></font>; debe ser una de las siguientes cadenas: + <ul> + <li><code style="color: red;">'beforebegin'</code>: Antes del <code>elementoObjetivo</code>.</li> + <li><code style="color: green;">'afterbegin'</code>: Dentro del <code>elementoObjetivo</code>, antes de su primer hijo.</li> + <li><code style="color: blue;">'beforeend'</code>: Dentro del <code>elementoObjetivo</code>, después de su último hijo.</li> + <li><code style="color: magenta;">'afterend'</code>: Después del <code>elementoObjetivo</code>.</li> + </ul> + </dd> + <dt><code>elemento</code></dt> + <dd>El elemento HTML a ser insertado.</dd> +</dl> + +<h3 id="Valor_devuelto">Valor devuelto</h3> + +<p>El elemento insertado o <code>null</code>, si la inserción falla.</p> + +<h3 id="Excepciones">Excepciones</h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Excepción</th> + <th scope="col">Explicación</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>SyntaxError</code></td> + <td>La <code>posición</code> especificada no tiene un valor reconocido.</td> + </tr> + <tr> + <td><code>TypeError</code></td> + <td>El <code>elemento</code> especificado no es un elemento válido.</td> + </tr> + </tbody> +</table> + +<h3 id="Visualización_de_los_nombres_de_posición">Visualización de los nombres de posición</h3> + +<pre class="notranslate"><!-- <strong><code style="color: red;">beforebegin</code></strong> --> +<code style="font-weight: bold;"><p></code> + <!-- <strong><code style="color: green;">afterbegin</code></strong> --> + foo + <!-- <strong><code style="color: blue;">beforeend</code></strong> --> +<code style="font-weight: bold;"></p></code> +<!-- <strong><code style="color: magenta;">afterend</code></strong> --></pre> + +<div class="note"><strong>Nota:</strong> Las posiciones <code>beforebegin</code> y <code>afterend</code> sólo funcionan si el nodo está en un árbol y tiene un padre.</div> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre class="brush: js notranslate">beforeBtn.addEventListener('click', function() { + var tempDiv = document.createElement('div'); + tempDiv.style.backgroundColor = randomColor(); + activeElem.insertAdjacentElement('beforebegin',tempDiv); + setListener(tempDiv); +}); + +afterBtn.addEventListener('click', function() { + var tempDiv = document.createElement('div'); + tempDiv.style.backgroundColor = randomColor(); + activeElem.insertAdjacentElement('afterend',tempDiv); + setListener(tempDiv); +});</pre> + +<p>Mira nuestro <a href="https://mdn.github.io/dom-examples/insert-adjacent/insertAdjacentElement.html">insertAdjacentElement.html</a> demo en Github (mira el<a href="https://github.com/mdn/dom-examples/blob/master/insert-adjacent/insertAdjacentElement.html"> código fuente</a> también.) Aquí tenemos una secuencia de elementos {{htmlelement("div")}} dentro de un contenedor. Cuando uno es clickeado, se torna en seleccionado y tu puedes presionar los botones <em>Insert before</em> e <em>Insert after</em> para insertar nuevos divs antes o despues del elemento seleccionado usando <code>insertAdjacentElement()</code>.</p> + +<h2 id="Specification" name="Specification">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('DOM WHATWG', '#dom-element-insertadjacentelement', 'insertAdjacentElement()')}}</td> + <td>{{ Spec2('DOM WHATWG') }}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_Compatibility" name="Browser_Compatibility">Compatibilidad con Navegadores</h2> + +<p>{{Compat("api.Element.insertAdjacentElement")}}</p> + +<h2 id="Mira_también">Mira también</h2> + +<ul> + <li>{{domxref("Element.insertAdjacentHTML()")}}</li> + <li>{{domxref("Element.insertAdjacentText()")}}</li> + <li>{{domxref("Node.insertBefore()")}} (similar to <code>beforebegin</code>, with different arguments)</li> + <li>{{domxref("Node.appendChild()")}} (mismo efecto que <code>beforeend</code>)</li> +</ul> diff --git a/files/es/web/api/element/insertadjacenthtml/index.html b/files/es/web/api/element/insertadjacenthtml/index.html new file mode 100644 index 0000000000..03be31a430 --- /dev/null +++ b/files/es/web/api/element/insertadjacenthtml/index.html @@ -0,0 +1,99 @@ +--- +title: Element.insertAdjacentHTML() +slug: Web/API/Element/insertAdjacentHTML +tags: + - API + - Cambiando el DOM + - DOM + - HTML + - Insertando Elementos + - Insertando Nodos + - Referencia + - insertAdjacentHTML + - metodo +translation_of: Web/API/Element/insertAdjacentHTML +--- +<div>{{APIRef("DOM")}}</div> + +<p>EL método <strong><code>insertAdjacentHTML()</code></strong> de la interfaz {{domxref("Element")}} analiza la cadena de texto introducida como cadena HTML o XML e inserta al árbol DOM los nodos resultantes de dicho análisis en la posición especificada. Este método no re-analiza el elemento sobre el cual se está invocando y por lo tanto no corrompe los elementos ya existentes dentro de dicho elemento. Esto evita el paso adicional de la serialización, haciéndolo mucho más rápido que la manipulación directa con {{domxref("Element.innerHTML", "innerHTML")}}.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><em>element</em>.insertAdjacentHTML(<em>posición</em>, <em>texto</em>);</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code><strong>posición</strong></code></dt> + <dd>Un {{domxref("DOMString")}} que representa la posición relativa al <code>elemento</code>, y deberá ser una de las siguientes cadenas: + <ul> + <li><code style="color: red;">'beforebegin'</code>: Antes que el propio <code>elemento</code>.</li> + <li><code style="color: green;">'afterbegin'</code>: Justo dentro del <code>elemento</code>, antes de su primer elemento hijo.</li> + <li><code style="color: blue;">'beforeend'</code>: Justo dentro del <code>elemento</code>, después de su último elemento hijo.</li> + <li><code style="color: magenta;">'afterend'</code>: Después del propio <code>elemento</code>.</li> + </ul> + </dd> + <dt><code>texto</code></dt> + <dd>Es la cadena a ser analizada como HTML o XML e insertada en el árbol.</dd> +</dl> + +<h3 id="Visualizacion_de_las_posiciones">Visualizacion de las posiciones</h3> + +<pre><!-- <strong><code style="color: red;">beforebegin</code></strong> --> +<code style="font-weight: bold;"><p></code> + <!-- <strong><code style="color: green;">afterbegin</code></strong> --> + foo + <!-- <strong><code style="color: blue;">beforeend</code></strong> --> +<code style="font-weight: bold;"></p></code> +<!-- <strong><code style="color: magenta;">afterend</code></strong> --></pre> + +<div class="note"><strong>Nota: </strong>Las posiciones <code>beforebegin</code> y <code>afterend</code> funcionan únicamente si el nodo se encuentra en el árbol DOM y tiene un elemento padre.</div> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush: js">// <div id="one">one</div> +var d1 = document.getElementById('one'); +d1.insertAdjacentHTML('afterend', '<div id="two">two</div>'); + +// En este punto, la nueva estructura es: +// <div id="one">one</div><div id="two">two</div></pre> + +<h2 id="Notas">Notas</h2> + +<h3 id="Consideraciones_de_seguridad">Consideraciones de seguridad</h3> + +<p>Cuando se inserte texto HTML en una página usando <code>insertAdjacentHTML()</code> debe tener cuidado de no usar cadenas de texto que no contengan las secuencias de escape pertinentes según sea el caso.</p> + +<p>Se recomienda no usar <code>insertAdjacentHTML()</code> cuando se pretende insertar texto plano; en su lugar, se debe utilizar la propiedad {{domxref("Node.textContent")}} o el método {{domxref("Element.insertAdjacentText()")}}. Este método no interpreta el contenido pasado como HTML, si no que lo inserta como texto plano.</p> + +<h2 id="Especificación">Especificación</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('DOM Parsing', '#widl-Element-insertAdjacentHTML-void-DOMString-position-DOMString-text', 'Element.insertAdjacentHTML()')}}</td> + <td>{{ Spec2('DOM Parsing') }}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<p>{{Compat("api.Element.insertAdjacentHTML")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("Element.insertAdjacentElement()")}}</li> + <li>{{domxref("Element.insertAdjacentText()")}}</li> + <li>{{domxref("XMLSerializer")}}: Contruir una representación del DOM de un texto XML</li> + <li><a class="external" href="https://hacks.mozilla.org/2011/11/insertadjacenthtml-enables-faster-html-snippet-injection/">hacks.mozilla.org guest post</a><span class="external"> por Henri Sivonen incluye puntos de referencia mostrando que insertAdjacentHTML puede ser mucho más rápido en algunos casos.</span></li> +</ul> diff --git a/files/es/web/api/element/localname/index.html b/files/es/web/api/element/localname/index.html new file mode 100644 index 0000000000..0876729853 --- /dev/null +++ b/files/es/web/api/element/localname/index.html @@ -0,0 +1,152 @@ +--- +title: Element.localName +slug: Web/API/Element/localName +tags: + - API + - Compatibilidad de los Navegadores en Móviles + - Compatibilidad de los navegadores + - DOM + - Propiedad + - Referencia +translation_of: Web/API/Element/localName +--- +<div>{{APIRef("DOM")}}</div> + +<p>La propiedad únicamente de lectura <code><strong>Element.localName</strong></code> devuelve la parte local del nombre calificado de un objeto.</p> + +<div class="note"> +<p>Antes de DOM4 esta API fué definida dentro de la interfaz{{domxref("Node")}}.</p> +</div> + +<h2 id="Sintasix">Sintasix</h2> + +<pre class="syntaxbox"><var>name</var> = <var>element</var>.localName +</pre> + +<h3 id="Valor_de_Retorno">Valor de Retorno</h3> + +<p> {{domxref("DOMString")}} <span id="result_box" lang="es"><span>que representa la parte</span> <span>local del</span> <span>nombre cualificado</span> <span>del elemento.</span></span></p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>(debe ser servido con contenido tipo XML , como <code>text/xml</code> o <code>application/xhtml+xml</code>.)</p> + +<pre class="brush:xml"><html xmlns="http://www.w3.org/1999/xhtml" + xmlns:svg="http://www.w3.org/2000/svg"> +<head> + <script type="application/javascript"><![CDATA[ + function test() { + var text = document.getElementById('text'); + var circle = document.getElementById('circle'); + + text.value = "<svg:circle> has:\n" + + "localName = '" + circle.localName + "'\n" + + "namespaceURI = '" + circle.namespaceURI + "'"; + } + ]]></script> +</head> +<body onload="test()"> + <svg:svg version="1.1" + width="100px" height="100px" + viewBox="0 0 100 100"> + <svg:circle cx="50" cy="50" r="30" style="fill:#aaa" id="circle"/> + </svg:svg> + <textarea id="text" rows="4" cols="55"/> +</body> +</html> +</pre> + +<h2 id="Notas">Notas</h2> + +<p><span id="result_box" lang="es"><span>El nombre local</span> <span>de un nodo</span> <span>es la parte del</span> <span>nombre completo</span> <span>del</span> <span>nodo que</span> <span>va situado después de</span> <span>los dos puntos.</span> <span>Nombres calificados</span> <span>se utilizan normalmente en</span> <span>XML</span> <span>como parte</span> <span>del espacio de los nombres</span> <span>(s)</span> <span>de los</span> <span>documentos particulares XML</span> <span>.</span> <span>Por ejemplo</span><span>,</span> <span>en el nombre</span> calificado <span>ecomm</span> <span>:</span> <span>socios</span><span>,</span> <span>socios</span> <span>es el nombre</span> <span>local y</span> <span>ecomm</span> <span>es</span> <span>el prefijo</span><span>:</span></span></p> + +<pre class="brush:xml line-numbers language-xml"><code class="language-xml"><span class="tag token"><span class="tag token"><span class="punctuation token">1 <</span><span class="namespace token">ecomm:</span>business</span> <span class="attr-name token">id</span><span class="attr-value token"><span class="punctuation token">=</span><span class="punctuation token">"</span>soda_shop<span class="punctuation token">"</span></span> <span class="attr-name token">type</span><span class="attr-value token"><span class="punctuation token">=</span><span class="punctuation token">"</span>brick_n_mortar<span class="punctuation token">"</span></span> <span class="attr-name token"><span class="namespace token">xmlns:</span>ecomm</span><span class="attr-value token"><span class="punctuation token">=</span><span class="punctuation token">"</span>http://example.com/ecomm<span class="punctuation token">"</span></span><span class="punctuation token">></span></span> +2 <span class="tag token"><span class="tag token"><span class="punctuation token"><</span><span class="namespace token">ecomm:</span>partners</span><span class="punctuation token">></span></span> +3 <span class="tag token"><span class="tag token"><span class="punctuation token"><</span><span class="namespace token">ecomm:</span>partner</span> <span class="attr-name token">id</span><span class="attr-value token"><span class="punctuation token">=</span><span class="punctuation token">"</span>1001<span class="punctuation token">"</span></span><span class="punctuation token">></span></span>Tony's Syrup Warehouse +4 <span class="tag token"><span class="tag token"><span class="punctuation token"></</span><span class="namespace token">ecomm:</span>partner</span><span class="punctuation token">></span></span> +5 <span class="tag token"><span class="tag token"><span class="punctuation token"></</span><span class="namespace token">ecomm:</span>partner</span><span class="punctuation token">></span></span> +<span class="tag token"><span class="tag token"><span class="punctuation token">6 </</span><span class="namespace token">ecomm:</span>business</span><span class="punctuation token">></span></span></code></pre> + +<div class="note"> +<p><strong>Nota:</strong> En {{Gecko("1.9.2")}} y anteriores,devuelve la versión en mayúsculas del nombre local para elementos HTML en HTML DOMs (en contraposición a elementos XHTML en XML DOMs). En versiones posteriores, en concordancia con HTML5,<span id="result_box" lang="es"><span>la propiedad devuelve</span> <span>en</span> <span>el caso de</span> <span>almacenamiento</span> <span>interno DOM</span></span> , <span id="result_box" lang="es"> <span>minúscula</span> <span>para ambos elementos</span> <span>HTML en</span> <span>HTML</span> <span>DOM</span> <span>y</span> <span>elementos XHTML</span> <span>en</span> <span>DOM</span> <span>XML</span></span>. La propiedad {{domxref("element.tagName","tagName")}} continua devolviéndolo en mayúsculas para elementos HTML en HTML DOMs.</p> +</div> + +<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('DOM4', '#interface-element', 'Element.localName')}}</td> + <td>{{Spec2('DOM4')}}</td> + <td>definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_los_navegadores">Compatibilidad de los navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Función</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>46.0<sup>[1]</sup></td> + <td>{{CompatGeckoDesktop("48.0")}}<sup>[1]</sup></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Función</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("48.0")}}<sup>[1]</sup></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Esta API estaba disponible previamente en la {{domxref("Node")}} API.</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("Element.namespaceURI")}}</li> + <li>{{domxref("Element.prefix")}}</li> + <li>{{domxref("Attr.localName")}}</li> + <li>{{domxref("Node.localName")}}</li> +</ul> diff --git a/files/es/web/api/element/matches/index.html b/files/es/web/api/element/matches/index.html new file mode 100644 index 0000000000..eef4ae271d --- /dev/null +++ b/files/es/web/api/element/matches/index.html @@ -0,0 +1,120 @@ +--- +title: Element.matches() +slug: Web/API/Element/matches +tags: + - API + - DOM + - Elemento + - Referencia + - metodo + - msMatchesSelector + - webkitMatchesSelector +translation_of: Web/API/Element/matches +--- +<div>{{APIRef("DOM")}}</div> + +<p>El método <strong><code>matches()</code></strong> comprueba si el {{domxref("Element")}} sería seleccionable por el selector CSS especificado en la cadena; en caso contrario, retorna <code>false</code>.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox notranslate">var <var>result</var> = <var>element</var>.matches(<var>selectorString</var>); +</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<p><code><var>selectorString</var></code> es una cadena de texto que representa el selector a probar.</p> + +<h3 id="Valor_devuelto">Valor devuelto</h3> + +<p><code><var>result</var></code> es un {{domxref("Boolean")}}.</p> + +<h3 id="Excepciones">Excepciones</h3> + +<dl> + <dt><code>SYNTAX_ERR</code></dt> + <dd>La cadena especificada como selector no es válida.</dd> +</dl> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush: html notranslate"><ul id="aves"> + <li>Loro de alas naranja</li> + <li class="amenazada">Ágila Filipina</li> + <li>Gran Pelícano Blancpo/li> +</ul> + +<script type="text/javascript"> + var aves = document.getElementsByTagName('li'); + + for (var i = 0; i < aves.length; i++) { + if (aves[i].matches('.amenazada')) { + console.log('El ' + aves[i].textContent + ' está amenazada de extinción!'); + } + } +</script> +</pre> + +<p>Esto mostrará "El Águila Filipina está amenazada de extinción!" en el log de la consola, dado que el elemento tiene un atributo <code>class</code> con valor <code>amenazada</code>.</p> + +<h2 id="Polyfill">Polyfill</h2> + +<p>Para navegadores que no soportan <code>Element.matches()</code> o <code>Element.matchesSelector()</code>, pero aun incorporan soporte para <code>document.querySelectorAll()</code>, existe un polyfill:</p> + +<pre class="notranslate">if (!Element.prototype.matches) { + Element.prototype.matches = + Element.prototype.matchesSelector || + Element.prototype.mozMatchesSelector || + Element.prototype.msMatchesSelector || + Element.prototype.oMatchesSelector || + Element.prototype.webkitMatchesSelector || + function(s) { + var matches = (this.document || this.ownerDocument).querySelectorAll(s), + i = matches.length; + while (--i >= 0 && matches.item(i) !== this) {} + return i > -1; + }; +}</pre> + +<p>However, given the practicality of supporting older browsers, the following should suffice for most (if not all) practical cases (ej. soporte IE9+).</p> + +<pre class="brush: js notranslate">if (!Element.prototype.matches) { + Element.prototype.matches = Element.prototype.msMatchesSelector || + Element.prototype.webkitMatchesSelector; +} +</pre> + +<h2 id="Especificación">Especificación</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Observaciones</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('DOM WHATWG', '#dom-element-matches', 'Element.prototype.matches')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Definición Inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + + + +<p>{{Compat("api.Element.matches")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li> + <div class="syntaxbox"><a href="/en-US/docs/Web/Guide/CSS/Getting_started/Selectors">The syntax of Selectors</a></div> + </li> + <li> + <div class="syntaxbox">Otros métodos que usan selectores: {{domxref("element.querySelector()")}} and {{domxref("element.closest()")}}.</div> + </li> +</ul> diff --git a/files/es/web/api/element/mousedown_event/index.html b/files/es/web/api/element/mousedown_event/index.html new file mode 100644 index 0000000000..4a207e28f3 --- /dev/null +++ b/files/es/web/api/element/mousedown_event/index.html @@ -0,0 +1,223 @@ +--- +title: mousedown +slug: Web/API/Element/mousedown_event +tags: + - API + - DOM + - Evento + - Interfaz +translation_of: Web/API/Element/mousedown_event +--- +<p>El evento <code>mousedown</code> se activa cuando el botón de un dispositivo apuntador (usualmente el botón de un ratón) es presionado en un elemento.</p> + +<h2 id="General_info">General info</h2> + +<dl> + <dt style="float: left; text-align: right; width: 120px;">Especificación</dt> + <dd style="margin: 0 0 0 120px;"><a class="external" href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-mousedown">DOM L3</a></dd> + <dt style="float: left; text-align: right; width: 120px;">Interface</dt> + <dd style="margin: 0 0 0 120px;">{{domxref("MouseEvent")}}</dd> + <dt style="float: left; text-align: right; width: 120px;">Bubbles</dt> + <dd style="margin: 0 0 0 120px;">Sí</dd> + <dt style="float: left; text-align: right; width: 120px;">Cancelable</dt> + <dd style="margin: 0 0 0 120px;">Sí</dd> + <dt style="float: left; text-align: right; width: 120px;">Target</dt> + <dd style="margin: 0 0 0 120px;">Elemento</dd> + <dt style="float: left; text-align: right; width: 120px;">Default Action</dt> + <dd style="margin: 0 0 0 120px;">Varios: Comenzar una acción de arrastrar y soltar; comenzar la selección de un texto; comenzar una interacción de desplazamiento (en combinación con el botón medio del mouse, si es soportado)</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><a href="/en-US/docs/Web/API/EventTarget" title="EventTarget is an interface implemented by objects that can receive events and may have listeners for them."><code>EventTarget</code></a></td> + <td>The event target (the topmost target in the DOM tree).</td> + </tr> + <tr> + <td><code>type</code> {{readonlyInline}}</td> + <td><a href="/en-US/docs/Web/API/DOMString" title="DOMString is a UTF-16 String. As JavaScript already uses such strings, DOMString is mapped directly to a String."><code>DOMString</code></a></td> + <td>The type of event.</td> + </tr> + <tr> + <td><code>bubbles</code> {{readonlyInline}}</td> + <td><a href="/en-US/docs/Web/API/Boolean" title="The Boolean object is an object wrapper for a boolean value."><code>Boolean</code></a></td> + <td>Whether the event normally bubbles or not</td> + </tr> + <tr> + <td><code>cancelable</code> {{readonlyInline}}</td> + <td><a href="/en-US/docs/Web/API/Boolean" title="The Boolean object is an object wrapper for a boolean value."><code>Boolean</code></a></td> + <td>Whether the event is cancellable or not?</td> + </tr> + <tr> + <td><code>view</code> {{readonlyInline}}</td> + <td><a class="new" href="/en-US/docs/Web/API/WindowProxy" rel="nofollow" title="The documentation about this has not yet been written; please consider contributing!"><code>WindowProxy</code></a></td> + <td><a href="/en-US/docs/Web/API/Document/defaultView" title="In browsers, document.defaultView returns the window object associated with a document, or null if none is available."><code>document.defaultView</code></a> (<code>window</code> of the document)</td> + </tr> + <tr> + <td><code>detail</code> {{readonlyInline}}</td> + <td><code>long</code> (<code>float</code>)</td> + <td>A count of consecutive clicks that happened in a short amount of time, incremented by one.</td> + </tr> + <tr> + <td><code>currentTarget</code> {{readonlyInline}}</td> + <td>EventTarget</td> + <td>The node that had the event listener attached.</td> + </tr> + <tr> + <td><code>relatedTarget</code> {{readonlyInline}}</td> + <td>EventTarget</td> + <td>For <code>mouseover</code>, <code>mouseout</code>, <code>mouseenter</code> and <code>mouseleave</code> events: the target of the complementary event (the <code>mouseleave</code> target in the case of a <code>mouseenter</code> event). <code>null</code> otherwise.</td> + </tr> + <tr> + <td><code>screenX</code> {{readonlyInline}}</td> + <td>long</td> + <td>The X coordinate of the mouse pointer in global (screen) coordinates.</td> + </tr> + <tr> + <td><code>screenY</code> {{readonlyInline}}</td> + <td>long</td> + <td>The Y coordinate of the mouse pointer in global (screen) coordinates.</td> + </tr> + <tr> + <td><code>clientX</code> {{readonlyInline}}</td> + <td>long</td> + <td>The X coordinate of the mouse pointer in local (DOM content) coordinates.</td> + </tr> + <tr> + <td><code>clientY</code> {{readonlyInline}}</td> + <td>long</td> + <td>The Y coordinate of the mouse pointer in local (DOM content) coordinates.</td> + </tr> + <tr> + <td><code>button</code> {{readonlyInline}}</td> + <td>unsigned short</td> + <td>The button number that was pressed when the mouse event was fired: Left button=0, middle button=1 (if present), right button=2. For mice configured for left handed use in which the button actions are reversed the values are instead read from right to left.</td> + </tr> + <tr> + <td><code>buttons</code> {{readonlyInline}}</td> + <td>unsigned short</td> + <td>The buttons being pressed when the mouse event was fired: Left button=1, Right button=2, Middle (wheel) button=4, 4th button (typically, "Browser Back" button)=8, 5th button (typically, "Browser Forward" button)=16. If two or more buttons are pressed, returns the logical sum of the values. E.g., if Left button and Right button are pressed, returns 3 (=1 | 2). <a href="/en-US/docs/Web/API/MouseEvent">More info</a>.</td> + </tr> + <tr> + <td><code>mozPressure</code> {{readonlyInline}}</td> + <td>float</td> + <td>The amount of pressure applied to a touch or tabdevice when generating the event; this value ranges between 0.0 (minimum pressure) and 1.0 (maximum pressure).</td> + </tr> + <tr> + <td><code>ctrlKey</code> {{readonlyInline}}</td> + <td>boolean</td> + <td><code>true</code> if the control key was down when the event was fired. <code>false</code> otherwise.</td> + </tr> + <tr> + <td><code>shiftKey</code> {{readonlyInline}}</td> + <td>boolean</td> + <td><code>true</code> if the shift key was down when the event was fired. <code>false</code> otherwise.</td> + </tr> + <tr> + <td><code>altKey</code> {{readonlyInline}}</td> + <td>boolean</td> + <td><code>true</code> if the alt key was down when the event was fired. <code>false</code> otherwise.</td> + </tr> + <tr> + <td><code>metaKey</code> {{readonlyInline}}</td> + <td>boolean</td> + <td><code>true</code> if the meta key was down when the event was fired. <code>false</code> otherwise.</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>Edge</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>On disabled form elements</td> + <td>{{CompatVersionUnknown}}<sup>[1]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}<sup>[1]</sup></td> + <td>{{CompatUnknown}}</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>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>On disabled form elements</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Sólo funciona para elementos {{HTMLElement("textarea")}} y algunos elementos tipo {{HTMLElement("input")}}.</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{event("mousedown")}}</li> + <li>{{event("mouseup")}}</li> + <li>{{event("mousemove")}}</li> + <li>{{event("click")}}</li> + <li>{{event("dblclick")}}</li> + <li>{{event("mouseover")}}</li> + <li>{{event("mouseout")}}</li> + <li>{{event("mouseenter")}}</li> + <li>{{event("mouseleave")}}</li> + <li>{{event("contextmenu")}}</li> +</ul> diff --git a/files/es/web/api/element/name/index.html b/files/es/web/api/element/name/index.html new file mode 100644 index 0000000000..717ad9dd3c --- /dev/null +++ b/files/es/web/api/element/name/index.html @@ -0,0 +1,79 @@ +--- +title: Element.name +slug: Web/API/Element/name +tags: + - API + - Compatibilidad de los navegadores + - DOM + - Elemento + - Propiedad + - Referencia + - Web + - actualizacion +translation_of: Web/API +--- +<p>{{ APIRef("DOM") }}</p> + +<h2 id="Summary" name="Summary">Sumario</h2> + +<p><code><strong>name</strong></code> <span id="result_box" lang="es"><span>obtiene o establece</span> <span>la</span> <span>propiedad del nombre</span> <span>de un</span> <span>objeto DOM</span><span>;</span> <span>sólo se aplica a</span> <span>los</span> <span>siguientes elementos</span><span>:</span></span> {{ HTMLelement("a") }}, {{ HTMLelement("applet") }}, {{ HTMLelement("button") }}, {{ HTMLelement("form") }}, {{ HTMLelement("frame") }}, {{ HTMLelement("iframe") }}, {{ HTMLelement("img") }}, {{ HTMLelement("input") }}, {{ HTMLelement("map") }}, {{ HTMLelement("meta") }}, {{ HTMLelement("object") }}, {{ HTMLelement("param") }}, {{ HTMLelement("select") }}, and {{ HTMLelement("textarea") }}.</p> + +<div class="note"> +<p><strong>Nota:</strong> <code>La propiedad name no esixte para otros elementos</code>; a diferencia de <a href="/en/DOM/Element.tagName" title="en/DOM/element.tagName"><code>tagName</code></a> y <a href="/en/DOM/Node.nodeName" title="en/DOM/Node.nodeName"><code>nodeName</code></a>, no es una propiedad de los modos de comunicación (interfaces) {{domxref("Node")}}, {{domxref("Element")}} or {{domxref("HTMLElement")}}.</p> +</div> + +<p><code>name</code> puede ser utilizado en el método{{ domxref("document.getElementsByName()") }} , en una <a href="/en/DOM/HTMLFormElement" title="en/DOM/form">configuración</a> y con la colección de <a href="/en/DOM/form.elements" title="en/DOM/form.elements">elementos</a> de la configuración. cuando utilizamos una configuración o elementos de una colección, puede devolver un solo elemento o una colección.</p> + +<h2 id="Syntax" name="Syntax">Síntasix</h2> + +<pre class="eval"><em>HTMLElement</em>.name = <em>string</em>; +var elName = <em>HTMLElement</em>.name; + +var fControl = <em>HTMLFormElement</em>.<em>elementName</em>; +var controlCollection = <em>HTMLFormElement</em>.elements.<em>elementName</em>; +</pre> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre class="eval"><form action="" name="formA"> + <input type="text" value="foo"> +</form> + +<script type="text/javascript"> + + // Get a reference to the first element in the form + var formElement = document.forms['formA'].elements[0]; + + // Give it a name + formElement.name = 'inputA'; + + // Show the value of the input + alert(document.forms['formA'].elements['inputA'].value); + +</script> +</pre> + +<h2 id="Notes" name="Notes">Notas</h2> + +<p>En Internet Explorer (IE), la propiedad <code>name</code> de los objetos DOM , creada utilizando{{ domxref("document.createElement()") }} no puede ser establecida o modificada</p> + +<h2 id="Specification" name="Specification">Especificaciones</h2> + +<p>W3C DOM 2 HTML Specification:</p> + +<ul> + <li><a class="external" href="http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-32783304">Anchor</a></li> + <li><a class="external" href="http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-39843695">Applet</a></li> + <li><a class="external" href="http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-34812697">Button</a></li> + <li><a class="external" href="http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-22051454">Form</a></li> + <li><a class="external" href="http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-91128709">Frame</a></li> + <li><a class="external" href="http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-96819659">iFrame</a></li> + <li><a class="external" href="http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-47534097">Image</a></li> + <li><a class="external" href="http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-89658498">Input</a></li> + <li><a class="external" href="http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-52696514">Map</a></li> + <li><a class="external" href="http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-31037081">Meta</a></li> + <li><a class="external" href="http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-20110362">Object</a></li> + <li><a class="external" href="http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-59871447">Param</a></li> + <li><a class="external" href="http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-41636323">Select</a></li> + <li><a class="external" href="http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-70715578">Textarea</a></li> +</ul> diff --git a/files/es/web/api/element/namespaceuri/index.html b/files/es/web/api/element/namespaceuri/index.html new file mode 100644 index 0000000000..e2403ce0a5 --- /dev/null +++ b/files/es/web/api/element/namespaceuri/index.html @@ -0,0 +1,125 @@ +--- +title: Element.namespaceURI +slug: Web/API/Element/namespaceURI +tags: + - API + - Compatibilidad de los navegadores + - DOM + - Propiedad + - Referencia +translation_of: Web/API/Element/namespaceURI +--- +<div>{{APIRef("DOM")}}</div> + +<p>La propiedad <code><strong>Element.namespaceURI</strong></code> unicamente de lectura devuelve la URI namespace de el elemento, <code>o la anula si el elemento no está en un</code> namespace.</p> + +<div class="note"> +<p>Antes de DOM4 esta API fué definida dentro de la interfaz {{domxref("Node")}}.</p> +</div> + +<h2 id="Síntasix">Síntasix</h2> + +<pre class="syntaxbox"><var>namespace</var> = <var>element</var>.namespaceURI</pre> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>En este snippet, un elemento está siendo examinado por su {{domxref("localName")}} y su <code>namespaceURI</code>. Si el <code>namespaceURI</code> devuelve el XUL namespace y el <code>localName</code> devuelve "browser", entonces se entiende que el nodo es XUL <code><browser/></code>.</p> + +<pre class="brush:js">if (element.localName == "browser" && + element.namespaceURI == "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul") { + // this is a XUL browser +}</pre> + +<h2 id="Notes" name="Notes">Notas</h2> + +<p><span id="result_box" lang="es"><span>Esto no es un</span> <span>valor calculado</span> <span>resultante</span><span> de</span> <span>una búsqueda de</span> un namespace<span>, basado</span> <span>en un examen de</span> <span>las</span> <span>declaraciones</span> <span>del namespace</span> <span>en el campo de aplicación</span><span>.</span> <span>La</span> <span>URI del namespace</span> <span>de un nodo</span> <span>se congela</span> <span>en el momento</span> <span>de creación</span> <span>del nodo</span><span>.</span></span></p> + +<div id="gt-input-tool"> +<div dir="ltr" style="zoom: 1;">En Firefox 3.5 y versiones anteriores, la URI del namespace para elementos HTML en documentos HTML <code>es nula</code>. En versiones posteriores, de conformidad con HTML5, es <code><a class="external" href="http://www.w3.org/1999/xhtml" rel="freelink">http://www.w3.org/1999/xhtml</a></code> como en XHTML. {{gecko_minversion_inline("1.9.2")}}</div> + +<div dir="ltr" style="zoom: 1;"> </div> +</div> + +<p>Se puede crear un elemento con el <code>namespaceURI</code> especificado utilizando el método DOM Level 2 <a href="/en-US/docs/Web/API/Document/createElementNS" title="Document.createElementNS">document.createElementNS</a>.</p> + +<p>El DOM no maneja o hace valer la validación del namespace por si mismo. Depende de la aplicación DOM para hacer cualquier validación necesaria. Date cuenta también que el prefijo del namespace , una vez que se asocia con un particular elemento, no puede ser cambiado.</p> + +<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("DOM4", "#dom-element-namespaceuri", "Element.namespaceuri")}}</td> + <td>{{Spec2("DOM4")}}</td> + <td>definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_los_navegadores">Compatibilidad en los navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Función</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>46.0<sup>[1]</sup></td> + <td>{{CompatGeckoDesktop("48.0")}}<sup>[1]</sup></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Función</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("48.0")}}<sup>[1]</sup></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Esta API estaba disponible previamente en {{domxref("Node")}} API.</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("Element.localName")}}</li> + <li>{{domxref("Element.prefix")}}</li> + <li>{{domxref("Attr.namespaceURI")}}</li> + <li>{{domxref("Node.namespaceURI")}}</li> +</ul> diff --git a/files/es/web/api/element/ongotpointercapture/index.html b/files/es/web/api/element/ongotpointercapture/index.html new file mode 100644 index 0000000000..156c25f4fb --- /dev/null +++ b/files/es/web/api/element/ongotpointercapture/index.html @@ -0,0 +1,133 @@ +--- +title: Element.ongotpointercapture +slug: Web/API/Element/ongotpointercapture +tags: + - API + - Controlador + - DOM + - Elemento + - Eventos Puntero + - Propiedad + - Referencia +translation_of: Web/API/GlobalEventHandlers/ongotpointercapture +--- +<p>{{ ApiRef("DOM") }}</p> + +<p><code>ongotpointercapture</code> es una propiedad {{domxref("EventHandler")}} de la interfaz {{domxref("Element")}} <span id="result_box" lang="es"><span>que devuelve</span> <span>el controlador de eventos</span> <span>(función</span><span>)</span> <span>para el</span></span> evento tipo {{event("gotpointercapture")}}.</p> + +<h2 id="Syntax" name="Syntax">Síntasix</h2> + +<pre class="eval">var gotCaptureHandler = target.ongotpointercpature; +</pre> + +<h3 id="Return_Value" name="Return_Value">Valor de Retorno</h3> + +<dl> + <dt><code>gotCaptureHandler</code></dt> + <dd><span id="result_box" lang="es"><span>El controlador de eventos</span> <span>gotpointercapture</span> para el <span>elemento target</span><span>.</span></span></dd> +</dl> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush: js"><html> +<script> +function overHandler(ev) { + // Determine the target event's gotpointercapture handler + var gotCaptureHandler = ev.target.ongotpointercapture; +} +function init() { + var el=document.getElementById("target"); + el.onpointerover = overHandler; +} +</script> +<body onload="init();"> +<div id="target"> Touch me ... </div> +</body> +</html> +</pre> + +<h2 id="Specifications" name="Specifications">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('Pointer Events 2','#widl-Element-ongotpointercapture', 'ongotpointercapture')}}</td> + <td>{{Spec2('Pointer Events 2')}}</td> + <td>Versión no estable.</td> + </tr> + <tr> + <td>{{SpecName('Pointer Events', '#widl-Element-ongotpointercapture', 'ongotpointercapture')}}</td> + <td>{{Spec2('Pointer Events')}}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">Compatibilidad en los Navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Función</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}} <sup>[1]</sup></td> + <td>{{CompatIE("10")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Función</th> + <th>Android</th> + <th>Android Webview</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatIE("10")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Implementación retirada. Ver {{Bug("1166347")}}.</p> + +<h2 id="See_also" name="See_also">Ver también</h2> + +<ul> + <li>{{ event("gotpointercapture") }}</li> +</ul> diff --git a/files/es/web/api/element/onlostpointercapture/index.html b/files/es/web/api/element/onlostpointercapture/index.html new file mode 100644 index 0000000000..336c672605 --- /dev/null +++ b/files/es/web/api/element/onlostpointercapture/index.html @@ -0,0 +1,132 @@ +--- +title: Element.onlostpointercapture +slug: Web/API/Element/onlostpointercapture +tags: + - API + - Controlador de Eventos + - DOM + - Eventos Puntero + - Propiedad + - Referencia +translation_of: Web/API/GlobalEventHandlers/onlostpointercapture +--- +<p>{{ ApiRef("DOM") }}</p> + +<p><code>onlostpointercapture</code> es una propiedad {{domxref("EventHandler")}} de la interfaz {{domxref("Element")}} <span id="result_box" lang="es"><span>que devuelve</span> <span>el controlador de eventos</span> <span>(función</span><span>)</span> <span>para el evento tipo </span></span>{{event("lostpointercapture")}} .</p> + +<h2 id="Syntax" name="Syntax">Síntasix</h2> + +<pre class="eval">var lostCaptureHandler = target.onlostpointercpature; +</pre> + +<h3 id="Return_Value" name="Return_Value">Valor de Retorno</h3> + +<dl> + <dt><code>lostCaptureHandler</code></dt> + <dd>El controlador de eventos <em>lostpointercapture</em> para el elemento <code>target</code>.</dd> +</dl> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush: js"><html> +<script> +function overHandler(ev) { + // Determine the target event's lostpointercapture handler + var lostCaptureHandler = ev.target.onlostpointercapture; +} +function init() { + var el=document.getElementById("target"); + el.onpointerover = overHandler; +} +</script> +<body onload="init();"> +<div id="target"> Touch me ... </div> +</body> +</html> +</pre> + +<h2 id="Specifications" name="Specifications">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('Pointer Events 2','#widl-Element-onlostpointercapture', 'onlostpointercapture')}}</td> + <td>{{Spec2('Pointer Events 2')}}</td> + <td>Versión no estable.</td> + </tr> + <tr> + <td>{{SpecName('Pointer Events', '#widl-Element-onlostpointercapture', 'onlostpointercapture')}}</td> + <td>{{Spec2('Pointer Events')}}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">Compatibilidad en los Navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Función</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}} <sup>[1]</sup></td> + <td>{{CompatIE("10")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Función</th> + <th>Android</th> + <th>Android Webview</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatIE("10")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Implementación retirada. Ver {{Bug("1166347")}}.</p> + +<h2 id="See_also" name="See_also">Ver también</h2> + +<ul> + <li>{{ event("lostpointercapture") }}</li> +</ul> diff --git a/files/es/web/api/element/onwheel/index.html b/files/es/web/api/element/onwheel/index.html new file mode 100644 index 0000000000..b8f829969b --- /dev/null +++ b/files/es/web/api/element/onwheel/index.html @@ -0,0 +1,31 @@ +--- +title: Element.onwheel +slug: Web/API/Element/onwheel +tags: + - API + - DOM + - Gecko + - Propiedad + - Referencia +translation_of: Web/API/GlobalEventHandlers/onwheel +--- +<p>{{ ApiRef("DOM") }}</p> + +<p>{{ non-standard_header() }}</p> + +<h3 id="Sumario">Sumario</h3> + +<p>La propiedad <code>onwheel</code> devuelve el código del controlador de eventos <code>onwheel</code> en el elemento actual.</p> + +<h3 id="Syntax">Syntax</h3> + +<pre class="eval">element.onwheel = <em>event handling code</em> +</pre> + +<h3 id="Notas">Notas</h3> + +<p>El evento <code>wheel</code> se genera cuando el usuario desplaza el contenido de un elemento.</p> + +<h3 id="Ver_también">Ver también</h3> + +<p><a href="https://www.w3.org/Bugs/Public/show_bug.cgi?id=18542" title="https://www.w3.org/Bugs/Public/show_bug.cgi?id=18542">Bug 18542 – el atributo onmousewheel debe ser reemplazado con onwheel</a></p> diff --git a/files/es/web/api/element/outerhtml/index.html b/files/es/web/api/element/outerhtml/index.html new file mode 100644 index 0000000000..7e9647f0db --- /dev/null +++ b/files/es/web/api/element/outerhtml/index.html @@ -0,0 +1,143 @@ +--- +title: Element.outerHTML +slug: Web/API/Element/outerHTML +translation_of: Web/API/Element/outerHTML +--- +<p>{{APIRef("DOM")}}</p> + +<h2 id="Summary" name="Summary">Resumen</h2> + +<p>El atributo <code>outerHTML</code> del interfaz DOM {{ domxref("element") }} obtiene el fragmento HTML serializado que describe el elemento incluyendo sus descendientes. Puede ser asignado para reemplazar el elemento por los nodos resultantes de examinar de la cadena proporcionada.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="eval"><em>var content</em> = <em>element</em>.outerHTML; +</pre> + +<p>Al retorno, <code>content</code> contendrá el fragmento de HTML serializado que describe al elemento <code>element</code> y a sus descendientes.</p> + +<pre class="eval"><em>element</em>.outerHTML = content; +</pre> + +<p>Reemplaza el elemento por los nodos generados del análisis de la cadena <code>content</code> con el padre de <code>element</code> como el nodo de contexto para el algoritmo de procesado del fragmento.</p> + +<h2 id="Examples" name="Examples">Ejemplos</h2> + +<p>Ontener el valor de la propiedas <code>outerHTML</code> de un elemento:</p> + +<pre class="brush: js">// HTML: +// <div id="d"><p>Content</p><p>Further Elaborated</p></div> + +d = document.getElementById("d"); +dump(d.outerHTML); + +// La cadena '<div id="d"><p>Content</p><p>Further Elaborated</p></div>' +// es volcada a la ventana de la consola. +</pre> + +<p>Reemplazar un nodo mediante la asignación de la propiedad <code>outerHTML</code>:</p> + +<pre class="brush: js">// HTML: +// <div id="container"><div id="d">This is a div.</div></div> + +container = document.getElementById("container"); +d = document.getElementById("d"); +console.log(container.firstChild.nodeName); // logs "DIV" + +d.outerHTML = "<p>This paragraph replaced the original div.</p>"; +console.log(container.firstChild.nodeName); // logs "P" + +// El div #d no será parte del árbol del documento, +// el nuevo párrafo lo reemplazará. +</pre> + +<h2 id="Notas">Notas</h2> + +<p>Si el elemento no tiene elemento padre, esto es, si es el elemento raíz del documento, la asignación de su propiedad <code>outerHTML</code> lanzará una <code><a href="/en/DOM/DOMException" title="DOMException">DOMException</a></code> con el código de error <code>NO_MODIFICATION_ALLOWED_ERR</code>. Por ejemplo:</p> + +<pre class="brush: js">document.documentElement.outerHTML = "test"; // lanza una DOMException +</pre> + +<p>Además, aunque el elemento es reemplazado en el documento, la variable cuya propiedad <code>outerHTML</code> fue asignada continuará conteniendo una referencia al elemento original:</p> + +<pre class="brush: js">var p = document.getElementsByTagName("p")[0]; +console.log(p.nodeName); // muestra: "P" +p.outerHTML = "<div>This div replaced a paragraph.</div>"; +console.log(p.nodeName); // sigue mostrando: "P"; +</pre> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Observaciones</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('DOM Parsing', '#outerhtml', 'Element.outerHTML')}}</td> + <td>{{ Spec2('DOM Parsing') }}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Prestación</th> + <th>Firefox (Gecko)</th> + <th>Chrome</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{ CompatGeckoDesktop("11") }}</td> + <td>0.2</td> + <td>4.0</td> + <td>7</td> + <td>1.3</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Prestiación</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatGeckoMobile("11") }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("HTMLElement.outerText")}}</li> + <li>MSDN: <a class="external" href="http://msdn.microsoft.com/en-us/library/ms534310%28v=vs.85%29.aspx">Propiedad outerHTML</a></li> +</ul> diff --git a/files/es/web/api/element/prefix/index.html b/files/es/web/api/element/prefix/index.html new file mode 100644 index 0000000000..4fc15aed1a --- /dev/null +++ b/files/es/web/api/element/prefix/index.html @@ -0,0 +1,115 @@ +--- +title: Element.prefix +slug: Web/API/Element/prefix +tags: + - API + - Compatibilidad de los Navegadores en Móviles + - Compatibilidad de los navegadores + - DOM + - Propiedad + - Referencia +translation_of: Web/API/Element/prefix +--- +<div>{{APIRef("DOM")}}</div> + +<p>La propiedad <code><strong>Element.prefix</strong></code> unicamente de lectura devuelve el namespace prefix de el elemento especificado, o<code> null si no hay especificado </code>prefix .</p> + +<div class="note"> +<p>Antes de DOM4 esta API fué definida dentro de la interfaz {{domxref("Node")}}.</p> +</div> + +<h2 id="Síntasix">Síntasix</h2> + +<pre class="syntaxbox"><var>string</var> = <var>element</var>.prefix +</pre> + +<h2 id="Ejemplos">Ejemplos</h2> + +<p><span class="short_text" id="result_box" lang="es"><span>Los siguientes registros</span> <span>"</span><span>x</span><span>"</span> <span>en la consola.</span></span></p> + +<pre class="brush:xml"><x:div onclick="console.log(this.prefix)"/> +</pre> + +<h2 id="Notas">Notas</h2> + +<p> Solo funcionará cuando se utiliza un analizador de namespace, ej. Cuando un documento es servido con un tipo XML MIME . No funcionará para documentos HTML.</p> + +<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("DOM4", "#dom-element-prefix", "Element.prefix")}}</td> + <td>{{Spec2("DOM4")}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_los_Navegadores">Compatibilidad en los Navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Función</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>46.0<sup>[1]</sup></td> + <td>{{CompatGeckoDesktop("48.0")}}<sup>[1]</sup></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Función</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("48.0")}}<sup>[1]</sup></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Esta API estaba previamente disponible en {{domxref("Node")}} API.</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("Element.namespaceURI")}}</li> + <li>{{domxref("Element.localName")}}</li> + <li>{{domxref("Attr.prefix")}}</li> + <li>{{domxref("Node.prefix")}}</li> +</ul> diff --git a/files/es/web/api/element/queryselector/index.html b/files/es/web/api/element/queryselector/index.html new file mode 100644 index 0000000000..8ce9cbe15f --- /dev/null +++ b/files/es/web/api/element/queryselector/index.html @@ -0,0 +1,187 @@ +--- +title: Element.querySelector() +slug: Web/API/Element/querySelector +translation_of: Web/API/Element/querySelector +--- +<div>{{APIRef("DOM")}}</div> + +<p>El método <code><strong>querySelector() </strong></code>de la intrefaz <strong> </strong>{{domxref("Element")}} devuelve el primer descendiente del elemento sobre el cual es invocado que coincida con el o los selectores especificados.</p> + +<h2 id="Syntax" name="Syntax">Sintáxis</h2> + +<pre class="syntaxbox notranslate"><var>elemento</var> = elementoBase.querySelector(<em>selectore</em>s); +</pre> + +<h3 id="Parametros">Parametros</h3> + +<dl> + <dt><code>selectores</code></dt> + <dd>Es el grupo de <a href="/en-US/docs/Web/Guide/CSS/Getting_Started/Selectors">selectores</a> que servirán para filtrar los elementos descendientes del {{domxref("Element")}} <code>elementoBase</code>; debe tener una sintáxis CSS válida o se producirá una excepción <code>SyntaxError</code>. Devuelve el primer elemento que encuentre que coincida con el grupo de selectores.</dd> +</dl> + +<h3 id="Valor_devuelto">Valor devuelto</h3> + +<p>Devolverá el primer descendiente del elemento <code>elementoBase</code> que coincida con el grupo de <code>selectores</code> especificado. Para la comparación se recorrerá la jerarquía completa de elementos, incluyendo a aquellos que no son descendientes del <code>elementoBase</code>; en otras palabras, los <code>selectores</code> se aplican primero al documento completo, no sólo al <code>elementoBase</code>, creando una lista inicial de elementos potencialmente seleccionables. Después se examina dicha lista para comprobar qué elementos son descendientes del <code>elementoBase</code>. El método <code>querySelector()</code> devolverá el primero de dichos elementos descendientes.</p> + +<p>Si no hubiera coincidencias, devolverá el valor <code>null</code>.</p> + +<h3 id="Excepciones">Excepciones</h3> + +<dl> + <dt><code>SyntaxError</code></dt> + <dd>Los <code>selectores</code> especificados no son válidos.</dd> +</dl> + +<h2 id="Ejemplos">Ejemplos</h2> + +<p>Vamos a ver unos cuantos ejemplos.</p> + +<h3 id="Encontrar_un_elemento_a_traves_del_valor_de_sus_atributos">Encontrar un elemento a traves del valor de sus atributos</h3> + +<p>En este primer ejemplo, obtendremos el primer elemento {{HTMLElement("style")}} del body del documento HTML que no tenga atributo "type" o cuyo atributo "type" sea igual a "text/css":</p> + +<pre class="brush:js notranslate">var el = document.body.querySelector("style[type='text/css'], style:not([type])"); +</pre> + +<h3 id="Toda_la_jerarquía_cuenta">Toda la jerarquía cuenta</h3> + +<p>El ejemplo que mostramos a continuación, demuestra que la jerarquía de todo el documento se tiene en cuenta cuando se aplican los <code>selectores</code>, de modo que se tienen en cuenta todos los niveles que se encuentran fuera de la jerarquía del <code>elementoBase</code> para localizar coincidencias.</p> + +<h4 id="HTML">HTML</h4> + +<pre class="brush: html notranslate"><div> + <h5>Original content</h5> + <p> + inside paragraph + <span>inside span</span> + inside paragraph + </p> +</div> +<div> + <h5>Output</h5> + <div id="output"></div> +</div></pre> + +<h4 id="JavaScript">JavaScript</h4> + +<pre class="brush: js notranslate">var baseElement = document.querySelector("p"); +document.getElementById("output").innerHTML = + (baseElement.querySelector("div span").innerHTML);</pre> + +<h4 id="Resultado">Resultado</h4> + +<p>El resultado es el siguiente:</p> + +<p>{{ EmbedLiveSample('The_entire_hierarchy_counts', 600, 160) }}</p> + +<p>Podemos ver que el selector <code>"div span"</code> coincide con el elemento {{HTMLElement("span")}}, aunque <code>baseElement</code> excluye el elemento {{domxref("div")}} al no ser parte de su selector.</p> + +<h3 id="Más_ejemplos">Más ejemplos</h3> + +<p>Puedes ver más ejemplos sobre el formato apropiado para los <code>selectores</code> aquí {{domxref("Document.querySelector()")}}.</p> + +<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">Comentarios</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('DOM4','#dom-parentnode-queryselectorallselectors','querySelectorAll()')}}</td> + <td>{{Spec2('DOM4')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('Selectors API Level 2','#queryselectorall','querySelectorAll()')}}</td> + <td>{{Spec2('Selectors API Level 2')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('Selectors API Level 1','#queryselectorall','querySelectorAll()')}}</td> + <td>{{Spec2('Selectors API Level 1')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_los_Navegadores">Compatibilidad en los Navegadores</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 (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatChrome(1) }}<br> + </td> + <td> + <p>{{ CompatGeckoDesktop(1.9.1) }}</p> + </td> + <td> + <p>9 [1]</p> + </td> + <td> + <p>{{CompatVersionUnknown}}</p> + </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> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] <code>querySelector()</code> funciona en IE8, pero solo para selectores CSS 2.1.</p> + +<h2 id="También_puedes_consultar">También puedes consultar:</h2> + +<ul> + <li><a href="/es/docs/Referencia_DOM_de_Gecko/Localizando_elementos_DOM_usando_selectores">Localizando elementos DOM usando selectores</a></li> + <li><a href="/es/docs/Web/CSS/Selectores_atributo">Selectores de atributo</a> en la guia de CSS</li> + <li><a href="/es/docs/Learn/CSS/Building_blocks/Selectores_CSS/Selectores_de_atributos">Selectores de atributo</a> en MDN Learning</li> + <li>{{domxref("Element.querySelectorAll()")}}</li> + <li>{{domxref("Document.querySelector()")}} y {{domxref("Document.querySelectorAll()")}}</li> + <li>{{domxref("DocumentFragment.querySelector()")}} y {{domxref("DocumentFragment.querySelectorAll()")}}</li> + <li>{{domxref("ParentNode.querySelector()")}} y {{domxref("ParentNode.querySelectorAll()")}}</li> + <li><a href="/en-US/docs/Code_snippets/QuerySelector">Code snippets for querySelector</a></li> + <li>Otros métodos que toman selectores: {{domxref("element.closest()")}} y {{domxref("element.matches()")}}.</li> +</ul> diff --git a/files/es/web/api/element/removeattribute/index.html b/files/es/web/api/element/removeattribute/index.html new file mode 100644 index 0000000000..bc4573b0af --- /dev/null +++ b/files/es/web/api/element/removeattribute/index.html @@ -0,0 +1,41 @@ +--- +title: Element.removeAttribute() +slug: Web/API/Element/removeAttribute +tags: + - API + - DOM + - Elemento + - Referencia +translation_of: Web/API/Element/removeAttribute +--- +<p>{{ APIRef("DOM") }}</p> + +<p><code>removeAttribute</code> elimina un atributo del elemento especificado.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="eval"><em>element</em>.removeAttribute(<em>attrName</em>); +</pre> + +<ul> + <li><code>attrName</code> es una cadena que nombra el atributo a ser eliminado de <em>element</em>.</li> +</ul> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre>// <div id="div1" align="left" width="200px"> +document.getElementById("div1").removeAttribute("align"); +// ahora: <div id="div1" width="200px"> +</pre> + +<h2 id="Notes" name="Notes">Notas</h2> + +<p>Debe usarse preferiblemente <code>removeAttribute</code> en lugar de establecer el valor del atributo a <code>null</code> usando <a href="/en/DOM/element.setAttribute" title="en/DOM/element.setAttribute">setAttribute</a>.</p> + +<p>Intentar eliminar un atributo que no existe en el elemento no disparará una excepción.</p> + +<p>{{ DOMAttributeMethods() }}</p> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<p><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-6D6AC0F9">DOM Level 2 Core: removeAttribute</a> (introducido en <a class="external" href="http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#method-removeAttribute">DOM Level 1 Core</a>)</p> diff --git a/files/es/web/api/element/requestfullscreen/index.html b/files/es/web/api/element/requestfullscreen/index.html new file mode 100644 index 0000000000..823330dbe8 --- /dev/null +++ b/files/es/web/api/element/requestfullscreen/index.html @@ -0,0 +1,104 @@ +--- +title: Element.requestFullscreen() +slug: Web/API/Element/requestFullScreen +tags: + - Pantalla completa +translation_of: Web/API/Element/requestFullScreen +--- +<div>{{APIRef("DOM")}}{{seeCompatTable}}</div> + +<p>Asynchronously requests that the element be made full-screen.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox">element.mozRequestFullScreen(); +</pre> + +<h2 id="Notas">Notas</h2> + +<p>No esta garantizado que el elemento se cambie a modo pantalla completa. Si la autorización para entrar a modo pantalla completa es permitida, el documento obtendrá un evento "mozfullscreenchange" para hacerle saber que esta en modo pantalla completa en ese momento. Si la autorización es denegada, el documento obtiene un evento "mozfullscreenerror".</p> + +<p>Ve a <a href="/en-US/docs/Web/Guide/API/DOM/Using_full_screen_mode">Using full-screen mode</a> para mas detalles y ejemplos.</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("Fullscreen", "#dom-element-requestfullscreen", "Element.requestFullScreen()")}}</td> + <td>{{Spec2("Fullscreen")}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox</th> + <th>Edge<br> + Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}{{property_prefix("webkit")}} (also as webkitRequestFullScreen)</td> + <td>{{CompatGeckoDesktop("9.0")}} (as mozRequestFullScreen)</td> + <td>11 {{property_prefix("ms")}}<a href="https://msdn.microsoft.com/en-us/library/dn254939%28v=vs.85%29.aspx">¹</a><br> + 20<a href="https://msdn.microsoft.com/en-us/library/dn265028%28v=vs.85%29.aspx">¹</a><a href="https://msdn.microsoft.com/en-us/library/dn254939%28v=vs.85%29.aspx">²</a></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</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>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("9.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Mira_también">Mira también</h2> + +<ul> + <li><a href="/en-US/docs/Web/Guide/API/DOM/Using_full_screen_mode">Using full-screen mode</a></li> + <li>{{domxref("document.mozCancelFullScreen()")}}</li> + <li>{{domxref("document.mozFullScreen")}}</li> + <li>{{domxref("document.mozFullScreenElement")}}</li> + <li>{{domxref("document.mozFullScreenEnabled")}}</li> + <li>{{cssxref(":-moz-full-screen")}}</li> + <li>{{HTMLAttrXRef("allowfullscreen", "iframe")}}</li> +</ul> diff --git a/files/es/web/api/element/runtimestyle/index.html b/files/es/web/api/element/runtimestyle/index.html new file mode 100644 index 0000000000..289c3fe13b --- /dev/null +++ b/files/es/web/api/element/runtimestyle/index.html @@ -0,0 +1,82 @@ +--- +title: Element.runtimeStyle +slug: Web/API/Element/runtimeStyle +tags: + - API + - Necesidad de compatibilidad de los navegadores + - Necesidad de compatibilidad de los navegadores móviles + - Necesidad de ejemplo + - Propiedad +translation_of: Web/API/Element/runtimeStyle +--- +<div>{{APIRef("DOM")}}</div> + +<p>{{ Non-standard_header() }}</p> + +<h2 id="Sumario">Sumario</h2> + +<p><span id="result_box" lang="es"><strong><span>Element.runtimeStyle</span></strong> <span>es una</span> <span>propiedad exclusiva</span> <span>similar a</span> <span>{</span><span>{</span><span>domxref</span> <span>(</span><span>"</span><span>HTMLElement.style</span><span>"</span><span>)</span><span>}</span><span>}</span><span>, excepto</span> <span>sus</span> <span>estilos,</span> <span>que tienen</span> <span>mayor precedencia</span> <span>y</span> <span>modificaciön.It</span> <span>no modifica</span> <span>el contenido del atributo</span> </span><code><a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/style">style</a></code> <span lang="es"><span>.</span> <span>Está disponible en</span> <span>las versiones anteriores de</span> <span>Microsoft</span> <span>Internet Explorer</span><span>.</span></span></p> + +<h2 id="especificación">especificación</h2> + +<p>No forma parte de ninguna especificación.</p> + +<p>Microsoft <a href="https://msdn.microsoft.com/en-us/library/ms535889(v=vs.85).aspx">tiene una descripción en MSDN</a>.</p> + +<h2 id="Browser_Compatibility" name="Browser_Compatibility">Compatibilidad de los Navegadores</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Función</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 Básico</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>6</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>Función</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatNo() }}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("Element.currentStyle")}} </li> +</ul> diff --git a/files/es/web/api/element/scrollheight/index.html b/files/es/web/api/element/scrollheight/index.html new file mode 100644 index 0000000000..d281054beb --- /dev/null +++ b/files/es/web/api/element/scrollheight/index.html @@ -0,0 +1,212 @@ +--- +title: Element.scrollHeight +slug: Web/API/Element/scrollHeight +tags: + - API + - Necesidad de Ejemplo de eliminación DHTML + - Propiedad + - Referencia + - Vista CSSOM +translation_of: Web/API/Element/scrollHeight +--- +<p>{{APIRef("DOM")}}</p> + +<p><span id="result_box" lang="es"><span>El elemento </span><strong> <span>Element.scrollHeight</span></strong> <span>atributo unicamente de lectura</span> <span>es una medida de</span> <span>la altura del</span> <span>contenido de un elemento</span><span>,</span> <span>incluyendo el contenido</span> que <span>no es visible</span> <span>en la pantalla</span> <span>debido al desbordamiento</span><span>.</span> <span>El valor</span> </span><code>scrollHeight</code><span lang="es"> <span>es</span> <span>igual a la</span> <span>altura mínima (</span><span>donde la altura</span> <span>incluye el relleno</span> <span>, pero no incluye</span> <span>bordes y márgenes</span><span>)</span> <span>El elemento</span> <span>lo necesita</span> <span>con el fin de</span> <span>adaptarse a</span> <span>todos los contenidos</span> <span>en</span> <span>el punto de vista</span> <span>sin necesidad de utilizar</span> <span>una barra de desplazamiento</span> <span>vertical.</span> <span>Incluye</span> <span>el </span> <span>elemento</span> <span>relleno pero no</span> <span>su margen</span><span>.</span></span></p> + +<div class="note"> +<p><span id="result_box" lang="es"><span>Esta propiedad</span> <span>redondea</span> <span>el valor a</span> <span>un número entero</span><span>.</span> <span>Si se necesita</span> <span>un valor fraccionario</span><span>,</span> <span>utilizar </span></span>{{domxref("Element.getBoundingClientRect()")}}.</p> +</div> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox notranslate">var <em>intElemScrollHeight</em> = <em>element</em>.scrollHeight;</pre> + +<p><em>intElemScrollHeight</em> es una variable que almacena un número entero correspondiente al valor scrollHeight en pixels del elemento. scrollHeight es una propiedad unicamente de lectura.</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<div id="offsetContainer" style="margin: 40px 50px 50px; background-color: rgb(255, 255, 204); border: 4px dashed black; color: black; position: relative; display: inline-block;"> +<div id="idDiv" style="margin: 24px 29px; border: 24px black solid; padding: 0px 28px; width: 199px; height: 102px; overflow: auto; background-color: white; font-size: 13px!important; font-family: Arial, sans-serif;"> +<p id="PaddingTopLabel" style="text-align: center; font-style: italic; font-weight: bold; font-size: 13px!important; font-family: Arial, sans-serif; margin: 0px;">padding-top</p> + +<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p> + +<p>Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> + +<p id="PaddingBottomLabel" style="text-align: center; font-style: italic; font-weight: bold; font-size: 13px!important; font-family: Arial, sans-serif; margin: 0px;">padding-bottom</p> +</div> +<strong>Left</strong> <strong>Top</strong> <strong style="color: blue; font-family: arial,sans-serif; font-size: 13px!important; font-weight: bold; left: 370px; position: absolute; top: 85px;">Right</strong> <strong style="color: blue; font-family: arial,sans-serif; font-size: 13px!important; font-weight: bold; left: 164px; position: absolute; top: 203px;">Bottom</strong> <em>margin-top</em> <em>margin-bottom</em> <em>border-top</em> <em>border-bottom</em></div> + +<p><img alt="Image:scrollHeight.png" class="internal" src="/@api/deki/files/840/=ScrollHeight.png"></p> + +<h2 id="Problemas_y_Soluciones">Problemas y Soluciones</h2> + +<h3 id="Determina_si_un_elemento_ha_sido_totalmente_desplazado"><span id="result_box" lang="es"><span>Determina</span> <span>si un elemento</span> <span>ha sido totalmente</span> <span>desplazado</span></span></h3> + +<p>La siguiente equivalencia devuelve <code>true</code> si un elemento está al final de su desplazamiento, <code>false</code> si no es así.</p> + +<pre class="syntaxbox notranslate">element.scrollHeight - element.scrollTop === element.clientHeight</pre> + +<h2 id="scrollHeight_Demo">scrollHeight Demo</h2> + +<p>As<code>ociada al evento <a href="/en-US/docs/DOM/element.onscroll">onscroll</a></code> , esta equivalencia puede ser útil para determinar si un usuario ha leido un texto o no (ver también las propiedades de <code><a href="/en-US/docs/DOM/element.scrollTop">element.scrollTop</a></code> y <code><a href="/en-US/docs/DOM/element.clientHeight">element.clientHeight</a></code> ). Por ejemplo:</p> + +<h3 id="HTML">HTML</h3> + +<pre class="brush: html notranslate"><form name="registration"> + <p> + <textarea id="rules">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum at laoreet magna. +Aliquam erat volutpat. Praesent molestie, dolor ut eleifend aliquam, mi ligula ultrices sapien, quis cursus +neque dui nec risus. Duis tincidunt lobortis purus eu aliquet. Quisque in dignissim magna. Aenean ac lorem at +velit ultrices consequat. Nulla luctus nisi ut libero cursus ultrices. Pellentesque nec dignissim enim. Phasellus +ut quam lacus, sed ultricies diam. Vestibulum convallis rutrum dolor, sit amet egestas velit scelerisque id. +Proin non dignissim nisl. Sed mi odio, ullamcorper eget mattis id, malesuada vitae libero. Integer dolor lorem, +mattis sed dapibus a, faucibus id metus. Duis iaculis dictum pulvinar. In nisi nibh, dapibus ac blandit at, porta +at arcu. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Praesent +dictum ipsum aliquet erat eleifend sit amet sollicitudin felis tempus. Aliquam congue cursus venenatis. Maecenas +luctus pellentesque placerat. Mauris nisl odio, condimentum sed fringilla a, consectetur id ligula. Praesent sem +sem, aliquet non faucibus vitae, iaculis nec elit. Nullam volutpat, lectus et blandit bibendum, nulla lorem congue +turpis, ac pretium tortor sem ut nibh. Donec vel mi in ligula hendrerit sagittis. Donec faucibus viverra fermentum. +Fusce in arcu arcu. Nullam at dignissim massa. Cras nibh est, pretium sit amet faucibus eget, sollicitudin in +ligula. Vivamus vitae urna mauris, eget euismod nunc. Aenean semper gravida enim non feugiat. In hac habitasse +platea dictumst. Cras eleifend nisl volutpat ante condimentum convallis. Donec varius dolor malesuada erat +consequat congue. Donec eu lacus ut sapien venenatis tincidunt. Quisque sit amet tellus et enim bibendum varius et +a orci. Donec aliquet volutpat scelerisque. Proin et tortor dolor. Ut aliquet, dolor a mattis sodales, odio diam +pulvinar sem, egestas pretium magna eros vitae felis. Nam vitae magna lectus, et ornare elit. Morbi feugiat, ipsum +ac mattis congue, quam neque mollis tortor, nec mollis nisl dolor a tortor. Maecenas varius est sit amet elit +interdum quis placerat metus posuere. Duis malesuada justo a diam vestibulum vel aliquam nisi ornare. Integer +laoreet nisi a odio ornare non congue turpis eleifend. Cum sociis natoque penatibus et magnis dis parturient montes, +nascetur ridiculus mus. Cras vulputate libero sed arcu iaculis nec lobortis orci fermentum. + </textarea> + </p> + <p> + <input type="checkbox" id="agree" name="accept" /> + <label for="agree">I agree</label> + <input type="submit" id="nextstep" value="Next" /> + </p> +</form></pre> + +<h3 id="CSS">CSS</h3> + +<pre class="brush: css notranslate">#notice { + display: inline-block; + margin-bottom: 12px; + border-radius: 5px; + width: 600px; + padding: 5px; + border: 2px #7FDF55 solid; +} + +#rules { + width: 600px; + height: 130px; + padding: 5px; + border: #2A9F00 solid 2px; + border-radius: 5px; +}</pre> + +<h3 id="JavaScript">JavaScript</h3> + +<pre class="brush: js notranslate">function checkReading () { + if (checkReading.read) { + return; + } + checkReading.read = this.scrollHeight - this.scrollTop === this.clientHeight; + document.registration.accept.disabled = document.getElementById("nextstep").disabled = !checkReading.read; + checkReading.noticeBox.innerHTML = checkReading.read ? "Thank you." : "Please, scroll and read the following text."; +} + +onload = function () { + var oToBeRead = document.getElementById("rules"); + checkReading.noticeBox = document.createElement("span"); + document.registration.accept.checked = false; + checkReading.noticeBox.id = "notice"; + oToBeRead.parentNode.insertBefore(checkReading.noticeBox, oToBeRead); + oToBeRead.parentNode.insertBefore(document.createElement("br"), oToBeRead); + oToBeRead.onscroll = checkReading; + checkReading.call(oToBeRead); +}</pre> + +<p>{{EmbedLiveSample('scrollHeight_Demo', '640', '400')}}</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th>Especificación</th> + <th>Estado</th> + <th>Comentario</th> + </tr> + <tr> + <td>{{SpecName("CSSOM View", "#dom-element-scrollheight", "Element.scrollHeight")}}</td> + <td>{{Spec2("CSSOM View")}}</td> + <td>Inicial definición</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_los_Navegadores">Compatibilidad de los Navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Función</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>4.0</td> + <td>3.0<sup>[1]</sup></td> + <td>8.0</td> + <td>{{CompatVersionUnknown}}</td> + <td>4.0</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Función</th> + <th>Android</th> + <th>Android Webview</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] En versiones anteriores a Firefox 21, <span id="result_box" lang="es"><span>cuando el contenido</span> <span>de</span> <span>un elemento</span> <span>no genera una</span> <span>barra de desplazamiento vertical</span><span>,</span></span>su propiedad <code>scrollHeight</code> es igual a su propiedad <code>clientHeight</code> . Esto puede significar que el contenido es demasiado breve para necesitar una barra de desplazamiento vertical, o que el elemento tiene un estilo CSS con un valor <code>overflow</code> <code>que desborda el contenido visible</code> (no desplazable).</p> + +<h2 id="Ver_También">Ver También</h2> + +<ul> + <li><a href="https://docs.microsoft.com/en-us/previous-versions//hh781509(v=vs.85)">MSDN: Measuring Element Dimension and Location with CSSOM in Windows Internet Explorer 9</a></li> + <li>{{domxref("Element.clientHeight")}}</li> + <li>{{domxref("HTMLElement.offsetHeight")}}</li> + <li><a href="/en-US/docs/Determining_the_dimensions_of_elements">Determinación de las dimensiones de los elementos</a></li> +</ul> diff --git a/files/es/web/api/element/scrollintoview/index.html b/files/es/web/api/element/scrollintoview/index.html new file mode 100644 index 0000000000..7c0b23a429 --- /dev/null +++ b/files/es/web/api/element/scrollintoview/index.html @@ -0,0 +1,151 @@ +--- +title: Element.scrollIntoView() +slug: Web/API/Element/scrollIntoView +tags: + - Experimental + - Expérimental(2) + - metodo +translation_of: Web/API/Element/scrollIntoView +--- +<div>{{ APIRef("DOM")}}</div> + +<p>El método <code><strong>scrollIntoView()</strong></code> de la interfaz {{domxref("Element")}} desplaza el contenedor principal del elemento de forma que el elemento sobre el cual se invoca <code>scrollIntoView()</code> sea visible al usuario.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox notranslate">element.scrollIntoView(); // Equivalente a <code>element.scrollIntoView(true) +</code>element.scrollIntoView(<em>alignToTop</em>); // Argumentos booleanos +element.scrollIntoView(<em>scrollIntoViewOptions</em>); // Argumento objeto +</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><em><code>alignToTop</code></em></dt> + <dd>Es un valor {{jsxref("Boolean")}}: + <ul> + <li>Si es <code>true</code>, la parte superior del elemento se alineará con la parte superior del área visible del elemento desplazable antecesor.</li> + <li>Si es <code>false</code>, la parte inferior del elemento se alineará con la parte inferior del área visible del elemento desplazable antecesor.</li> + </ul> + </dd> + <dt><em><code>scrollIntoViewOptions</code></em> {{optional_inline}} {{experimental_inline}}</dt> + <dd>Un booleano o un objeto con las siguientes opciones:</dd> + <dt><code>behavior</code> {{optional_inline}}</dt> + <dd>Establece la transición de la animación.<br> + Puede ser <code>auto</code> o <code>smooth</code>. Por defecto es <code>auto</code>.</dd> + <dt><code>block</code> {{optional_inline}}</dt> + <dd>Establece el alineamiento vertical.<br> + Puede ser <code>start</code>, <code>center</code>, <code>end</code>, o <code>nearest</code>. Por defecto es <code>start</code>.</dd> + <dt><code>inline</code> {{optional_inline}}</dt> + <dd>Establece el alineamiento horizontal<br> + Puede ser <code>start</code>, <code>center</code>, <code>end</code>, o <code>nearest</code>. Por defecto es <code>nearest</code>.</dd> +</dl> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre class="brush: javascript notranslate">var element = document.getElementById("box"); + +element.scrollIntoView(); +element.scrollIntoView(false); +element.scrollIntoView({block: "end"}); +element.scrollIntoView({block: "end", behavior: "smooth"}); +</pre> + +<h2 id="Notas">Notas</h2> + +<p>Puede que el desplazamiento no sea llevado completamente a la parte superior o inferior dependiente de la disposición de otros elementos. </p> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<table> + <thead> + <tr> + <th>Especificación</th> + <th>Estado</th> + <th>Comentario</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("CSSOM View", "#dom-element-scrollintoview", "Element.scrollIntoView()")}}</td> + <td>{{Spec2("CSSOM View")}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<ul> + <li><a class="external" href="http://dev.w3.org/csswg/cssom-view/#dom-element-scrollintoview" title="http://dev.w3.org/csswg/cssom-view/#dom-element-scrollintoview">CSSOM: Scrolling elements into view</a></li> +</ul> + +<h2 id="Browser_compatibility" name="Browser_compatibility">Compatibilidad con navegadores</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Implementación básica</td> + <td>1.0</td> + <td>{{ CompatGeckoDesktop(1.0) }}</td> + <td>6</td> + <td>10.0 and possibly older versions</td> + <td>4 and possibly older versions</td> + </tr> + <tr> + <td> + <p>Implementan<br> + <code>scrollIntoViewOptions</code></p> + </td> + <td>{{CompatNo}}</td> + <td>{{ CompatGeckoDesktop(36) }}</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>Característica</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Implementación básica</td> + <td>?</td> + <td>{{ CompatGeckoMobile(1.0) }}</td> + <td>?</td> + <td>?</td> + <td>?</td> + </tr> + <tr> + <td> + <p>Implementan<br> + <code>scrollIntoViewOptions</code></p> + </td> + <td>{{CompatNo}}</td> + <td>{{ CompatGeckoMobile(36) }}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> diff --git a/files/es/web/api/element/scrollleft/index.html b/files/es/web/api/element/scrollleft/index.html new file mode 100644 index 0000000000..df527ccdc5 --- /dev/null +++ b/files/es/web/api/element/scrollleft/index.html @@ -0,0 +1,153 @@ +--- +title: Element.scrollLeft +slug: Web/API/Element/scrollLeft +tags: + - API + - Necesita Tabla de Compatibilidad + - Necesita Trabajo de Markup + - Necesita tabla de Especificaciones + - Propiedad + - Referencia + - Vista CSSOM +translation_of: Web/API/Element/scrollLeft +--- +<p>{{ APIRef("DOM") }}</p> + +<p>La propiedad <strong><code>Element.scrollLeft</code></strong><span id="result_box" lang="es"><span> obtiene o establece el número de píxeles que desplaza el contenido de un elemento hacia la izquierda.</span></span></p> + +<p><span id="result_box" lang="es"><span>Tenga en cuenta que si el elemento <code>{{cssxref ( "dirección")}} </code>del elemento es <code>rtl </code>(</span></span>derecha-a-izquierda<span lang="es"><span>), entonces<code> scrollLeft</code> es 0 cuando la barra de desplazamiento está en su posición más a la derecha (al inicio del contenido desplazado) y cada vez más</span> <span>Negativo mientras se desplaza hacia el final del contenido.</span></span></p> + +<h2 id="Syntax_and_values" name="Syntax_and_values">Síntasix</h2> + +<pre class="eval">// <span class="short_text" id="result_box" lang="es"><span>Obtener el número de píxeles desplazados</span></span> +var <var>sLeft</var> = <var>element</var>.scrollLeft; +</pre> + +<p><span id="result_box" lang="es"><span><em>SLeft</em> es un número entero que representa el número de píxeles que el elemento ha desplazado hacia la izquierda.</span></span></p> + +<pre class="eval">// <span class="short_text" id="result_box" lang="es"><span>Establecer el número de píxeles desplazados</span></span> +<var>element</var>.scrollLeft = 10; +</pre> + +<p><span id="result_box" lang="es"><span><code>ScrollLeft</code> se puede establecer en cualquier valor entero, sin embargo:</span></span></p> + +<ul> + <li> + <div id="gt-text-top"> + <div class="g-unit" id="gt-src-c"> + <div id="gt-src-p"> + <div id="gt-src-wrap"> + <div dir="ltr" style="zoom: 1;"><span id="result_box" lang="es"><span>Si el elemento no se puede desplazar (por ejemplo, no tiene desbordamiento), <code>scrollLeft </code>se establece en 0.</span></span></div> + </div> + </div> + </div> + </div> + </li> + <li> <span id="result_box" lang="es"><span>Si se establece en un valor menor que 0 (mayor que 0 para elementos de derecha a izquierda), <code>scrollLeft</code> se establece en 0.</span></span></li> + <li><span id="result_box" lang="es"><span>Si se establece en un valor mayor que el máximo que se puede desplazar el contenido,<code> scrollLeft </code>se establece en el valor máximo.</span></span></li> +</ul> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre class="brush: html"><!DOCTYPE html> +<html> +<head> + <meta charset="utf-8"> + <style> + #container { + border: 1px solid #ccc; height: 100px; overflow: scroll; width: 100px; + } + #content { + background-color: #ccc; width: 250px; + } + </style> + <script> + document.addEventListener('DOMContentLoaded', function () { + var button = document.getElementById('slide'); + button.onclick = function () { + document.getElementById('container').scrollLeft += 20; + }; + }, false); + </script> +</head> +<body> + <div id="container"> + <div id="content">Lorem ipsum dolor sit amet.</div> + </div> + <button id="slide" type="button">Slide</button> +</body> +</html> +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('CSSOM View', '#dom-element-scrollleft', 'scrollLeft')}}</td> + <td>{{Spec2("CSSOM View")}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_los_navegadores">Compatibilidad en los navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Función</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Función</th> + <th>Android</th> + <th>Android Webview</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> diff --git a/files/es/web/api/element/scrolltop/index.html b/files/es/web/api/element/scrolltop/index.html new file mode 100644 index 0000000000..5b4fb19139 --- /dev/null +++ b/files/es/web/api/element/scrolltop/index.html @@ -0,0 +1,69 @@ +--- +title: Element.scrollTop +slug: Web/API/Element/scrollTop +translation_of: Web/API/Element/scrollTop +--- +<p>{{ APIRef("DOM") }}</p> + +<p>La propiedad <code><strong>Element.scrollTop</strong></code> obtiene o establece el número de pixels que el contenido de un elemento ha sido desplazado (enrollado) hacia arriba. El <code>scrollTop</code> de un elemento es una medida de la distancia desde el límite superior de un elemento al límite superior de su contenido visible. Cuando un elemento no genera una barra de scroll vertical, el valor de su <code>scrollTop</code> es establecido por defecto a <code>0</code>.</p> + +<h2 id="Syntax_and_values" name="Syntax_and_values">Sintaxis</h2> + +<pre class="brush: js">// Obtiene el número de pixels desplazados +var <var> intElemScrollTop</var> = someElement.scrollTop; +</pre> + +<p><var>Después de ejecutar este código, </var><code><var>intElemScrollTop</var></code> es un entero que corresponde al número de pixesl que el contenido del {{domxref("element")}} ha sido desplazado hacia arriba.</p> + +<pre class="brush: js">// Establece el número de pixels desplazados +<var>element</var>.scrollTop = <var>intValue</var>; +</pre> + +<p><code>scrollTop</code> puede ser establecido a cualquier valor entero, con ciertas salvedades:</p> + +<ul> + <li>Si el elemento no puede ser desplazado (p.e. no tiene desbordamiento (overflow) o si el elemento no es desplazable (<strong>non-scrollable</strong>), <code>scrollTop</code> es establecido a <code>0</code>.</li> + <li>Si se asigna un valor menor que <code>0</code>, <code>scrollTop</code> es establecido a <code>0</code>.</li> + <li>Si se asigna un valor mayor que el máximo al que el contenido puede ser desplazado, <code>scrollTop</code> es establecido al valor máximo.</li> +</ul> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<div id="offsetContainer" style="margin: 40px 50px 50px; background-color: rgb(255, 255, 204); border: 4px dashed black; color: black; position: relative; display: inline-block;"> +<div id="idDiv" style="margin: 24px 29px; border: 24px black solid; padding: 0px 28px; width: 199px; height: 102px; overflow: auto; background-color: white; font-size: 13px!important; font-family: Arial, sans-serif;"> +<p id="PaddingTopLabel" style="text-align: center; font-style: italic; font-weight: bold; font-size: 13px!important; font-family: Arial, sans-serif; margin: 0px;">padding-top</p> + +<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p> + +<p>Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> + +<p id="PaddingBottomLabel" style="text-align: center; font-style: italic; font-weight: bold; font-size: 13px!important; font-family: Arial, sans-serif; margin: 0px;">padding-bottom</p> +</div> +<strong style="color: blue; font-family: arial,sans-serif; font-size: 13px!important; font-weight: bold; left: -32px; position: absolute; top: 85px;">Left</strong> <strong style="color: blue; font-family: arial,sans-serif; font-size: 13px!important; font-weight: bold; left: 170px; position: absolute; top: -24px;">Top</strong> <strong style="color: blue; font-family: arial,sans-serif; font-size: 13px!important; font-weight: bold; left: 370px; position: absolute; top: 85px;">Right</strong> <strong style="color: blue; font-family: arial,sans-serif; font-size: 13px!important; font-weight: bold; left: 164px; position: absolute; top: 203px;">Bottom</strong> <em>margin-top</em> <em>margin-bottom</em> <em>border-top</em> <em>border-bottom</em></div> + +<p><img alt="Image:scrollTop.png" class="internal" src="/@api/deki/files/842/=ScrollTop.png"></p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Observaciones</th> + </tr> + <tr> + <td>{{SpecName('CSSOM View', '#dom-element-scrolltop', 'scrollTop')}}</td> + <td>{{Spec2("CSSOM View")}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Referencias">Referencias</h2> + +<ul> + <li><a class="external" href="http://dev.w3.org/csswg/cssom-view/#dom-element-scrolltop" title="http://dev.w3.org/csswg/cssom-view/#dom-element-scrolltop">Borrador del Módulo Vista del W3C</a></li> + <li><a class="external" href="http://msdn.microsoft.com/en-us/library/ms534618(VS.85).aspx" title="http://msdn.microsoft.com/en-us/library/ms534618(VS.85).aspx">definición de scrollTop en MSDN</a></li> + <li><a href="http://msdn.microsoft.com/en-us/library/hh781509(v=vs.85).aspx" title="http://msdn.microsoft.com/en-us/library/hh781509(v=vs.85).aspx">Medidas de Dimensión y Ubicación de Elementos en MSDN</a></li> +</ul> diff --git a/files/es/web/api/element/scrolltopmax/index.html b/files/es/web/api/element/scrolltopmax/index.html new file mode 100644 index 0000000000..9e5fc20255 --- /dev/null +++ b/files/es/web/api/element/scrolltopmax/index.html @@ -0,0 +1,80 @@ +--- +title: Element.scrollTopMax +slug: Web/API/Element/scrollTopMax +tags: + - API + - CSSOM View + - Elemento + - Propiedad + - Read-only + - Referencia + - Solo lectura +translation_of: Web/API/Element/scrollTopMax +--- +<p>{{APIRef("DOM")}}{{Non-standard_header}}</p> + +<p>La propiedad de solo lectura(read-only) <code><strong>Element.scrollTopMax</strong></code> retorna un {{jsxref("Number")}} que representa el máximo offset posible para el elemento.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre>var <em>pxl</em> = <em>elt</em>.scrollTopMax;</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<p><em>Esta propiedad no es parte de ninguna especificación.</em></p> + +<h2 id="Browser_compatibility" name="Browser_compatibility">Compatibilidad de Navegadores</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() }}</td> + <td>{{ CompatGeckoDesktop(16) }}</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>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>{{ CompatGeckoMobile(16) }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_además">Ver además</h2> + +<ul> + <li>{{domxref("Element.scrollLeftMax")}} dada la misma información para otros ejes.</li> +</ul> diff --git a/files/es/web/api/element/scrollwidth/index.html b/files/es/web/api/element/scrollwidth/index.html new file mode 100644 index 0000000000..aaeb7486a8 --- /dev/null +++ b/files/es/web/api/element/scrollwidth/index.html @@ -0,0 +1,119 @@ +--- +title: Element.scrollWidth +slug: Web/API/Element/scrollWidth +translation_of: Web/API/Element/scrollWidth +--- +<div>{{ APIRef("DOM") }}</div> + +<p>La propiedad de sólo lectura <strong><code>Element.scrollWidth</code></strong> retorna bien la anchura en pixels del contenido de un elemento o bien la anchura del elemento en si, la que sea mayor de ambas. Si el elemento es más ancho que su área contenedora (por ejemplo, si existen barras de desplazamiento para desplazarse a través del contenido), <code>scrollWidth</code> es mayor que <code>clientWidth</code>.</p> + +<div class="note"> +<p>El valor de esta propiedad será red redondedo a un entero. Si necesita un valor fraccional, use {{ domxref("element.getBoundingClientRect()") }}.</p> +</div> + +<h2 id="Syntax_and_values" name="Syntax_and_values">Sintaxis</h2> + +<pre class="syntaxbox">var <var>xScrollWidth</var> = <var>element</var>.scrollWidth;</pre> + +<p><var>xScrollWidth</var> es el ancho del contenido de <var>element</var> en pixels.</p> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre class="brush:html"><!DOCTYPE html> +<html> +<head> + <title>Ejemplo</title> + <style> + div { + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + } + + #aDiv { + width: 100px; + } + + button { + margin-bottom: 2em; + } + </style> +</head> + +<body> + <div id="aDiv"> + FooBar-FooBar-FooBar-FooBar + </div> + <button id="aButton"> + Check for overflow + </button> + + <div id="anotherDiv"> + FooBar-FooBar-FooBar-FooBar + </div> + <button id="anotherButton"> + Check for overflow + </button> +</body> +<script> + var buttonOne = document.getElementById('aButton'), + buttonTwo = document.getElementById('anotherButton'), + divOne = document.getElementById('aDiv'), + divTwo = document.getElementById('anotherDiv'); + + //comprueba si un desbordamiento está ocurriendo + function isOverflowing(element) { + return (element.scrollWidth > element.offsetWidth); + } + + function alertOverflow(element) { + if (isOverflowing(element)) { + alert('El contenido desborda el contenedor.'); + } else { + alert('Sin desobordamiento!'); + } + } + + buttonOne.addEventListener('click', function() { + alertOverflow(divOne); + }); + + buttonTwo.addEventListener('click', function() { + alertOverflow(divTwo); + }); +</script> +</html> + +</pre> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th>Especificación</th> + <th>Estado</th> + <th>Observaciones</th> + </tr> + <tr> + <td>{{SpecName("CSSOM View", "#dom-element-scrollwidth", "Element.scrollWidth")}}</td> + <td>{{Spec2("CSSOM View")}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("api.Element.scrollWidth")}}</p> + + <h2 id="See_also" name="See_also">Ver también</h2> + + +<ul> + <li>{{domxref("Element.clientWidth")}}</li> + <li>{{domxref("HTMLElement.offsetWidth")}}</li> + <li><a href="/en-US/docs/Determining_the_dimensions_of_elements">Determinando las dimensiones de elementos</a></li> +</ul> diff --git a/files/es/web/api/element/setattribute/index.html b/files/es/web/api/element/setattribute/index.html new file mode 100644 index 0000000000..725efd11fc --- /dev/null +++ b/files/es/web/api/element/setattribute/index.html @@ -0,0 +1,88 @@ +--- +title: Element.setAttribute +slug: Web/API/Element/setAttribute +tags: + - API + - DOM + - Elemento + - NeedsBrowserCompatibility + - NeedsSpecTable + - Referencia + - metodo + - setAttribute +translation_of: Web/API/Element/setAttribute +--- +<p>{{APIRef("DOM")}}</p> + +<p>Establece el valor de un atributo en el elemento indicado. Si el atributo ya existe, el valor es actualizado, en caso contrario, el nuevo atributo es añadido con el nombre y valor indicado.</p> + +<p>Para obtener el valor actual de un atributo, se utiliza {{domxref("Element.getAttribute", "getAttribute()")}}; para eliminar un atributo, se llama a {{domxref("Element.removeAttribute", "removeAttribute()")}}.</p> + +<h2 id="Sintaxis" name="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><em>Element</em>.setAttribute(<em>name</em>, <em>value</em>); +</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code>name</code></dt> + <dd>Un {{domxref("DOMString")}} indicando el nombre del atributo cuyo valor se va a cambiar. El nombre del atributo se convierte automáticamente en minúsculas cuando <code>setAttribute()</code> se llama sobre un elemento HTML en un documento HTML.</dd> + <dt><code>value</code></dt> + <dd>Un {{domxref("DOMString")}} que contenga el valor que asignar al atributo. Cualquier valor indicado que no sea una cadena de texto se convierte automáticamente en una cadena de texto.</dd> +</dl> + +<p>Los atributos booleanos se consideran <code>true</code> si al menos están presentes en el elemento, independientemente de su <code>value</code> actual; como regla, se debería especificar una cadena de texto vacía (<code>""</code>) en <code>value</code> (algunas personas utilizan el nombre del atributo; esto funciona pero no es un standard). Vea un {{anch("Ejemplo", "ejemplo")}} posterior para una demostración práctica.</p> + +<p>Dado que <code>value</code> se convierte en una cadena de texto, indicando <code>null</code> no necesariamente hace lo que se espera. En lugar de eliminar el atributo o establecer su valor para ser {{jsxref("null")}}, establece el valor del atributo a la cadena de texto <code>"null"</code>. Si se desea eliminar un atributo, se debe llamar a {{domxref("Element.removeAttribute", "removeAttribute()")}}.</p> + +<h3 id="Valor_devuelto">Valor devuelto</h3> + +<p>{{jsxref("undefined")}}.</p> + +<h3 id="Excepciones">Excepciones</h3> + +<dl> + <dt><code>InvalidCharacterError</code></dt> + <dd>El atributo especificado <code>name</code> contiene uno o más caracteres que no son válidos en el nombre del atributo.</dd> +</dl> + +<h2 id="Ejemplo" name="Ejemplo">Ejemplo</h2> + +<p>En el siguiente ejemplo, <code>setAttribute()</code> se utiliza para establecer atributos en un {{HTMLElement("button")}}.</p> + +<h3 id="HTML">HTML</h3> + +<pre class="brush: html"><button>Hola Mundo</button></pre> + +<h3 id="JavaScript">JavaScript</h3> + +<pre class="brush:js">var b = document.querySelector("button"); + +b.setAttribute("name", "helloButton"); +b.setAttribute("disabled", ""); +</pre> + +<p>Esto demuestra dos cosas:</p> + +<ul> + <li>La primera llamada a <code>setAttribute()</code> muestra cómo se cambia el valor del atributo <code>name</code> a "helloButton". Puede ver esto utilizando el inspector de página de su navegador (<a href="https://developers.google.com/web/tools/chrome-devtools/inspect-styles/?hl=es">Chrome</a>, <a href="https://docs.microsoft.com/en-us/microsoft-edge/devtools-guide">Edge</a>, <a href="/es/docs/Tools/Page_Inspector">Firefox</a>, <a href="https://developer.apple.com/library/content/documentation/AppleApplications/Conceptual/Safari_Developer_Guide/Introduction/Introduction.html">Safari</a>).</li> + <li>Para establecer el valor de un atributo booleano, como <code>disabled</code>, se puede especificar cualquier valor. Una cadena de texto vacía o el nombre de un atributo son valores recomendados. Todo lo que importa es que si el atributo está presente, <em>independientemente de su valor actual</em>, su valor se considera como <code>true</code>. La ausencia del atributo significa que su valor es <code>false</code>. Estableciendo una cadena vacía (<code>""</code>) como el valor del atributo <code>disabled</code>, se estaría cambiando <code>disabled</code> a <code>true</code>, lo que provoca que el botón sea deshabilitado.</li> +</ul> + +<p>{{ EmbedLiveSample('Example', '300', '50') }}</p> + +<p>{{DOMAttributeMethods}}</p> + +<h2 id="Especificación" name="Especificación">Especificación</h2> + +<ul> + <li><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-F68F082">DOM Level 2 Core: setAttribute</a> (introducido en <a class="external" href="http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#method-setAttribute">DOM Level 1 Core</a>)</li> + <li><a class="external" href="http://www.whatwg.org/specs/web-apps/current-work/#apis-in-html-documents" title="http://www.whatwg.org/specs/web-apps/current-work/#apis-in-html-documents">HTML5: APIs en documentos HTML</a></li> +</ul> + +<h2 id="Compatibilidad con navegadores" name="Compatibilidad con navegadores">Compatibilidad con navegadores</h2> + +<h3 id="Notas" name="Notas">Notas Gecko</h3> + +<p>Utilizando <code>setAttribute()</code> para modificar ciertos atributos, el más notable es <code>value</code> en XUL, funciona de forma inconsistente, ya que el atributo especifica el valor determinado. Para acceder o modificar los valores actuales, se deben utilizar las propiedades. Por ejemplo, utilizar <code>Element.value</code> en lugar de <code>Element.setAttribute()</code>.</p> diff --git a/files/es/web/api/element/setattributens/index.html b/files/es/web/api/element/setattributens/index.html new file mode 100644 index 0000000000..59a4d9809e --- /dev/null +++ b/files/es/web/api/element/setattributens/index.html @@ -0,0 +1,33 @@ +--- +title: Element.setAttributeNS() +slug: Web/API/Element/setAttributeNS +translation_of: Web/API/Element/setAttributeNS +--- +<p>{{ APIRef("DOM") }}</p> + +<p><code>setAttributeNS añade un nuevo atributo o cambia el valor de un atributo con el namespace dado y el nombre.</code></p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="eval"><em>elemento</em>.setAttributeNS(<em>namespace</em>,<em>nombre</em>,<em>valor</em>) +</pre> + +<ul> + <li><code>namespace</code> es un string especificando el namespace del atributo.</li> + <li><code>name es un string identificando el atributo a ser puesto.</code></li> + <li><code>value es el string del valor deseado del nuevo atributo.</code></li> +</ul> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre class="eval">var d = document.getElementById("d1"); +d.setAttributeNS("<span class="nowiki">http://www.mozilla.org/ns/specialspace</span>", "align", "center"); +</pre> + +<h2 id="Notes" name="Notes">Notas</h2> + +<p>{{ DOMAttributeMethods() }}</p> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<p><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-ElSetAttrNS">DOM Level 2 Core: setAttributeNS</a></p> diff --git a/files/es/web/api/element/setcapture/index.html b/files/es/web/api/element/setcapture/index.html new file mode 100644 index 0000000000..b0c3ef52ab --- /dev/null +++ b/files/es/web/api/element/setcapture/index.html @@ -0,0 +1,86 @@ +--- +title: Element.setCapture() +slug: Web/API/Element/setCapture +tags: + - API + - DOM + - Element + - Método(2) + - Referencia +translation_of: Web/API/Element/setCapture +--- +<p>{{ APIRef("DOM") }}{{ gecko_minversion_header("2.0") }}</p> + +<p><span id="result_box" lang="es"><span>Llame a este método durante el manejo de un evento mousedown para redirigir todos los eventos de mouse a este elemento hasta que se suelte el botón del mouse o se llame {{domxref ( "document.releaseCapture ()")}}.</span></span></p> + +<h2 id="Syntax" name="Syntax">Sintasix</h2> + +<pre class="eval">element.setCapture(<em>retargetToElement</em>); +</pre> + +<dl> + <dt><code>retargetToElement</code></dt> + <dd><span id="result_box" lang="es"> <span>Si es verdadero, todos los eventos se dirigen directamente a este elemento;</span> <span>Si es falso, los eventos también pueden descargar a los descendientes de este elemento.</span></span></dd> +</dl> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<p><span id="result_box" lang="es"><span>En este ejemplo, las coordenadas actuales del mouse se dibujan mientras situas el mouse alrededor después de hacer clic y mantener pulsado un elemento.</span></span></p> + +<pre class="brush: html"><html> +<head> + <title>Mouse Capture Example</title> + <style type="text/css"> + #myButton { + border: solid black 1px; + color: black; + padding: 2px; + -moz-box-shadow:black 2px 2px; + } + </style> + + <script type="text/javascript"> + function init() { + var btn = document.getElementById("myButton"); + btn.addEventListener("mousedown", mouseDown, false); + btn.addEventListener("mouseup", mouseUp, false); + } + + function mouseDown(e) { + e.target.setCapture(); + e.target.addEventListener("mousemove", mouseMoved, false); + } + + function mouseUp(e) { + e.target.removeEventListener("mousemove", mouseMoved, false); + } + + function mouseMoved(e) { + var output = document.getElementById("output"); + output.innerHTML = "Position: " + e.clientX + ", " + e.clientY; + } + </script> +</head> +<body onload="init()"> + <p>This is an example of how to use mouse capture on elements in Gecko 2.0.</p> + <p><a id="myButton" href="#">Test Me</a></p> + <div id="output">No events yet</div> +</body> +</html> +</pre> + +<p><a href="/samples/domref/mousecapture.html">Ver ejemplo en vivo</a></p> + +<h2 id="Notes" name="Notes">Notas</h2> + +<p><span id="result_box" lang="es"><span>El elemento no puede desplazarse completamente hacia arriba o hacia abajo dependiendo del diseño de otros elementos.</span></span></p> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<p>Ninguna.</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{ domxref("document.releaseCapture()") }}</li> +</ul> diff --git a/files/es/web/api/element/shadowroot/index.html b/files/es/web/api/element/shadowroot/index.html new file mode 100644 index 0000000000..17af57bb3c --- /dev/null +++ b/files/es/web/api/element/shadowroot/index.html @@ -0,0 +1,83 @@ +--- +title: Element.shadowRoot +slug: Web/API/Element/shadowRoot +translation_of: Web/API/Element/shadowRoot +--- +<div>{{APIRef("Shadow DOM")}}</div> + + + +<p>La propiedad de solo lectura 'Element.shadowRoot' representa el shadow root alojado por el elemento. Use {{DOMxRef("Element.attachShadow()")}} para agregar un shadow root a un elemento existente.</p> + +<h2 id="Syntax" name="Syntax">Syntax</h2> + +<pre class="syntaxbox">var <em>shadowroot =</em><em> element</em>.shadowRoot; +</pre> + +<h3 id="Value">Value</h3> + +<p>A {{DOMxRef("ShadowRoot")}} object instance, or <code>null</code> if the associated shadow root was attached with its {{DOMxRef("ShadowRoot.mode", "mode")}} set to <code>closed</code>. (See {{DOMxRef("Element.attachShadow()")}} for further details).</p> + +<h2 id="Examples">Examples</h2> + +<p>The following snippets are taken from our <a href="https://github.com/mdn/web-components-examples/tree/master/life-cycle-callbacks">life-cycle-callbacks</a> example (<a href="https://mdn.github.io/web-components-examples/life-cycle-callbacks">see it live also</a>), which creates an element that displays a square of a size and color specified in the element's attributes.</p> + +<p>Inside the <code><custom-square></code> element's class definition we include some life cycle callbacks that make a call to an external function, <code>updateStyle()</code>, which actually applies the size and color to the element. You'll see that we are passing it <code>this</code> (the custom element itself) as a parameter.</p> + +<pre class="brush: js">connectedCallback() { + console.log('Custom square element added to page.'); + updateStyle(this); +} + +attributeChangedCallback(name, oldValue, newValue) { + console.log('Custom square element attributes changed.'); + updateStyle(this); +}</pre> + +<p>In the <code>updateStyle()</code> function itself, we get a reference to the shadow DOM using {{domxref("Element.shadowRoot")}}. From here we use standard DOM traversal techniques to find the {{htmlelement("style")}} element inside the shadow DOM and then update the CSS found inside it:</p> + +<pre class="brush: js">function updateStyle(elem) { + const shadow = elem.shadowRoot; + const childNodes = Array.from(shadow.childNodes); + + childNodes.forEach(childNode => { + if (childNode.nodeName === 'STYLE') { + childNode.textContent = ` + div { + width: ${elem.getAttribute('l')}px; + height: ${elem.getAttribute('l')}px; + background-color: ${elem.getAttribute('c')}; + } + `; + } + }); +}</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('DOM WHATWG', '#dom-element-shadowroot', 'shadowRoot')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("api.Element.shadowRoot")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{DOMxRef("Element.openOrClosedShadowRoot")}} {{non-standard_inline}}</li> +</ul> diff --git a/files/es/web/api/element/tagname/index.html b/files/es/web/api/element/tagname/index.html new file mode 100644 index 0000000000..5f522efc3e --- /dev/null +++ b/files/es/web/api/element/tagname/index.html @@ -0,0 +1,44 @@ +--- +title: element.tagName +slug: Web/API/Element/tagName +tags: + - Referencia_DOM_de_Gecko +translation_of: Web/API/Element/tagName +--- +<p>{{ ApiRef("DOM") }}</p> + +<h3 id="Resumen" name="Resumen">Resumen</h3> + +<p>Devuelve el nombre del elemento.</p> + +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> + +<pre class="eval"><em>elementName</em> = element.tagName +</pre> + +<ul> + <li><code>elementName</code> es una cadena que contiene el nombre del elemento actual.</li> +</ul> + +<h3 id="Notas" name="Notas">Notas</h3> + +<p>En XML (y los lenguajes basados en XML tales como XHTML) el código <code>tagName</code> es sensible a las mayúsculas. En HTML, <code>tagName</code> devuelve el nombre del elemento en forma canonica, es decir con todas sus letras en mayúscula. El valor del código of <code>tagName</code> es el mismo que el de la instrucción <a href="es/DOM/element.nodeName">nodeName</a>.</p> + +<h3 id="Ejemplo" name="Ejemplo">Ejemplo</h3> + +<p>Si tenemos la siguiente línea de código:</p> + +<pre class="eval"><span id="born">Cuando yo nací...</span> +</pre> + +<p>y el siguiente script</p> + +<pre class="eval">var span = document.getElementById("born"); +alert(span.tagName); +</pre> + +<p>en XHTML (o alguna otra forma de XML) el resultado de la alerta será el contenido de "span". En HTML, el contenido será el de "SPAN".</p> + +<h3 id="Especificaci.C3.B3n" name="Especificaci.C3.B3n">Especificación</h3> + +<p><a class="external" href="http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-104682815">DOM Level 2 Core: tagName</a></p> diff --git a/files/es/web/api/element/wheel_event/index.html b/files/es/web/api/element/wheel_event/index.html new file mode 100644 index 0000000000..6b4e69d173 --- /dev/null +++ b/files/es/web/api/element/wheel_event/index.html @@ -0,0 +1,320 @@ +--- +title: wheel +slug: Web/API/Element/wheel_event +tags: + - eventos +translation_of: Web/API/Element/wheel_event +--- +<p>El evento "wheel" se dispara cuando la ruleta de un dispositivo (usualmente un ratón) gira. Este evento reemplaza al ahora obsoleto evento {{event("mousewheel")}}.</p> + +<h2 id="Información_general">Información general</h2> + +<dl> + <dt style="float: left; text-align: right; width: 120px;">Interfaz</dt> + <dd style="margin: 0 0 0 120px;">{{domxref("WheelEvent")}}</dd> + <dt style="float: left; text-align: right; width: 120px;">Sincronía</dt> + <dd style="margin: 0 0 0 120px;">asíncrono</dd> + <dt style="float: left; text-align: right; width: 120px;">Bubble</dt> + <dd style="margin: 0 0 0 120px;">Si</dd> + <dt style="float: left; text-align: right; width: 120px;">Cancelable</dt> + <dd style="margin: 0 0 0 120px;">Si</dd> + <dt style="float: left; text-align: right; width: 120px;">Target</dt> + <dd style="margin: 0 0 0 120px;">defaultView, Document, Element</dd> + <dt style="float: left; text-align: right; width: 120px;">Acción predet.</dt> + <dd style="margin: 0 0 0 120px;">Scroll, atras/adelante (historial), o zoom.</dd> +</dl> + +<h2 id="Propiedades">Propiedades</h2> + +<p><em>Este evento implementa las propiedades de: {{domxref("WheelEvent")}}, {{domxref("MouseEvent")}}, {{domxref("UIEvent")}} y {{domxref("Event")}}.</em></p> + +<h3 id="Propiedades_de_WheelEvent">Propiedades de <code>WheelEvent</code></h3> + +<p>{{page("/en-US/docs/Web/API/WheelEvent", "Properties")}}</p> + +<h3 id="Propiedades_de_MouseEvent">Propiedades de <code>MouseEvent</code></h3> + +<p>{{page("/en-US/docs/Web/API/MouseEvent", "Properties")}}</p> + +<h3 id="Propiedades_UIEvent">Propiedades <code>UIEvent</code></h3> + +<p>{{page("/en-US/docs/Web/API/UIEvent", "Properties")}}</p> + +<h3 id="Propiedades_Event">Propiedades <code>Event</code></h3> + +<p>{{page("/en-US/docs/Web/API/Event", "Properties")}}</p> + +<h2 id="Métodos">Métodos</h2> + +<p><em>Este evento implementa los métodos de: {{domxref("WheelEvent")}}, {{domxref("MouseEvent")}}, {{domxref("UIEvent")}} y {{domxref("Event")}}.</em></p> + +<h3 id="Métodos_de_WheelEvent">Métodos de <code>WheelEvent</code></h3> + +<p>{{page("/en-US/docs/Web/API/WheelEvent", "Methods")}}</p> + +<h3 id="Métodos_de_MouseEvent">Métodos de <code>MouseEvent</code></h3> + +<p>{{page("/en-US/docs/Web/API/MouseEvent", "Methods")}}</p> + +<h3 id="Métodos_de_UIEvent">Métodos de <code>UIEvent</code></h3> + +<p>{{page("/en-US/docs/Web/API/UIEvent", "Methods")}}</p> + +<h3 id="Métodos_de_Event">Métodos de <code>Event</code></h3> + +<p>{{page("/en-US/docs/Web/API/Event", "Methods")}}</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('DOM3 Events','DOM3-Events.html#event-type-wheel','wheel')}}</td> + <td>{{Spec2('DOM3 Events')}}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad">Compatibilidad</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>31</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("17.0")}}</td> + <td>{{CompatIE("9.0")}}<sup>[1]</sup></td> + <td>18</td> + <td>7.0</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("17.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Internet Explorer solo toma el evento "wheel" mediante <code>addEventListener</code>, no se permite el atributo <code>onwheel</code> en objetos del DOM. <a href="https://connect.microsoft.com/IE/feedback/details/782835/missing-onwheel-attribute-for-the-wheel-event-although-its-supported-via-addeventlistener">Bug report.</a><br> + </p> + +<h3 id="Escuchar_al_evento_en_distintos_navegadores">Escuchar al evento en distintos navegadores</h3> + +<p>En el siguiente script se crea el método multi-navegador <code>addWheelListener </code>que permite escuchar el evento wheel en diferentes navegadores a la vez que se previene el funcionamiento por defecto.</p> + +<pre class="brush:js;">// crea el metodo "addWheelListener" global +// ejemplo: addWheelListener( elem, function( e ) { console.log( e.deltaY ); e.preventDefault(); } ); +(function(window,document) { + + var prefix = "", _addEventListener, support; + + // detecta el tipo de evento permitido por el navegador + if ( window.addEventListener ) { + _addEventListener = "addEventListener"; + } else { + _addEventListener = "attachEvent"; + prefix = "on"; + } + + // detecta el tipo de evento wheel manejado por el navegador + support = "onwheel" in document.createElement("div") ? "wheel" : // Los navegadores modernos permiten "wheel" + document.onmousewheel !== undefined ? "mousewheel" : // Webkit e IE soportan al menos "mousewheel" + "DOMMouseScroll"; // Asumiremos que el resto de navegadores son Firefox antiguos + + window.addWheelListener = function( elem, callback, useCapture ) { + _addWheelListener( elem, support, callback, useCapture ); + + // controlaremos MozMousePixelScroll en Firefox antiguos + if( support == "DOMMouseScroll" ) { + _addWheelListener( elem, "MozMousePixelScroll", callback, useCapture ); + } + }; + + function _addWheelListener( elem, eventName, callback, useCapture ) { + elem[ _addEventListener ]( prefix + eventName, support == "wheel" ? callback : function( originalEvent ) { + !originalEvent && ( originalEvent = window.event ); + + // Creamos un objeto de evento + var event = { + // tomamos como referencia el objeto original + originalEvent: originalEvent, + target: originalEvent.target || originalEvent.srcElement, + type: "wheel", + deltaMode: originalEvent.type == "MozMousePixelScroll" ? 0 : 1, + deltaX: 0, + deltaZ: 0, + preventDefault: function() { + originalEvent.preventDefault ? + originalEvent.preventDefault() : + originalEvent.returnValue = false; + } + }; + + // calculamos deltaY (y deltaX) dependiendo del evento + if ( support == "mousewheel" ) { + event.deltaY = - 1/40 * originalEvent.wheelDelta; + // Webkit tambien soporta wheelDeltaX + originalEvent.wheelDeltaX && ( event.deltaX = - 1/40 * originalEvent.wheelDeltaX ); + } else { + event.deltaY = originalEvent.detail; + } + + // Disparamos el callback + return callback( event ); + + }, useCapture || false ); + } + +})(window,document);</pre> + +<h2 id="Notas_para_Gecko">Notas para Gecko</h2> + +<h3 id="Orden_de_los_eventos_en_eventos_antiguos">Orden de los eventos en eventos antiguos</h3> + +<p>Si el evento wheel no ha sido implementado, los eventos <code>DOMMouseScroll</code> y <code>MozMousePixelScroll</code> se usarán para dar retrocompativilidad. Sus atributos se calculan dependiendo del delta del evento wheel y el padre más cercano. Si el evento wheel o alguno de los anteriores invoca<span style="line-height: 1.5;"> {{ domxref("event.preventDefault()") }}, no ocurrirá nada.</span></p> + +<p>El orden de ejecución del evento es:</p> + +<ol> + <li>Eventos wheel en grupo de eventos por defecto (aplicaciones web y add-ons pueden manejar los eventos de este grupo)</li> + <li><code>Un evento DOMMouseScroll</code> vertical en caso de que el deltaY, en consecutivas llamadas del evento se vuelva mayor que 1.0 o menor que -1.0</li> + <li><code>Un evento MozMousePixelScroll</code> vertical en caso de que el <code>deltaY</code> del último evento <code>wheel</code> no sea igual a cero</li> + <li><code>Un evento DOMMouseScroll</code> horizontal en caso de que el <code>deltaX</code> acumule un valor mayor que 1.0 o menor que -1.0</li> + <li><code>Un evento MozMousePixelScroll</code> horizontal en caso de que el <code>deltaX</code> del último evento no sea igual que cero</li> + <li>Un evento <code>wheel</code> en el grupo de sistema (Solamente add-ons pueden gestionar este grupo de eventos)</li> +</ol> + +<p><br> + <span style="font-style: inherit; line-height: 1.5;">¿Qué ocurre si</span><strong style="font-style: inherit; font-weight: 700; line-height: 1.5;"> </strong><code style="font-weight: 700; line-height: 1.5;">preventDefault()</code><strong style="font-style: inherit; font-weight: 700; line-height: 1.5;"> es llamado?</strong></p> + +<table> + <thead> + </thead> + <tbody> + <tr> + <th scope="row"><code>wheel</code> (grupo por defecto de evetos)</th> + <td><code>Se llama preventDefault()</code></td> + <td> </td> + <td> </td> + <td> </td> + <td> </td> + </tr> + <tr> + <th scope="row"><code>DOMMouseScroll</code> (Vertical)</th> + <td>No se llama</td> + <td><code>Se llama preventDefault()</code></td> + <td> </td> + <td> </td> + <td> </td> + </tr> + <tr> + <th scope="row"><code>MozMousePixelScroll</code> (Vertical)</th> + <td>No se llama</td> + <td><code>defaultPrevented</code> devuelve true</td> + <td><code>Se llama preventDefault()</code></td> + <td> </td> + <td> </td> + </tr> + <tr> + <th scope="row"><code>DOMMouseScroll</code> (Horizontal)</th> + <td>No se llama</td> + <td>No se ve afectado</td> + <td>No se ve afectado</td> + <td><code>Se llama preventDefault()</code></td> + <td> </td> + </tr> + <tr> + <th scope="row"><code>MozMousePixelScroll</code> (Horizontal)</th> + <td>No se llama</td> + <td>No se ve afectado</td> + <td>No se ve afectado</td> + <td><code>defaultPrevented</code> devuelve true</td> + <td><code>Se llama preventDefault()</code></td> + </tr> + <tr> + <th scope="row"><code>wheel</code> (grupo de eventos de sistema)</th> + <td><code>defaultPrevented</code> devuelve true</td> + <td><code>defaultPrevented</code> devuelve true</td> + <td><code>defaultPrevented</code> devuelve true</td> + <td><code>defaultPrevented</code> devuelve true</td> + <td><code>defaultPrevented</code> devuelve true</td> + </tr> + </tbody> +</table> + +<p>En caso de que un Add-on necesite conocer si uno de los eventos legacy es usado por contenidos del DOM puede usar el evento wheel de #6. Lee la documentación de <a href="/en-US/docs/XPCOM_Interface_Reference/nsIEventListenerService" title="/en-US/docs/XPCOM_Interface_Reference/nsIEventListenerService"><code>nsIEventListenerService</code></a> para mayor detalle acerca del grupo de eventos de sistema.</p> + +<p>Los valores delta y las acciones por defecto de eventos predefinidos pueden ser personalizados en las preferencias de usuario (<a href="https://wiki.mozilla.org/Gecko:Mouse_Wheel_Scrolling#Preferences_for_customizing_delta_values_and_default_action" title="/en-US/docs/HTML/Element/details">details</a>). Por lo tanto, no se debe presuponer que alguna acción en concreto va a ocurrir tras recibir este evento.</p> + +<h3 id="Valores_delta">Valores delta</h3> + +<p>Los valores delta no indican la cantidad de scroll actual de manera predeterminada. Si el usuario presiona alguna tecla mdificadora mientras mueve la rueda de scroll, dicha acción puede causar otra totalmente diferente a la esperada, como ir adelante o atras por el historial o hacer zoom. Además, incluso cuando la acción sea la esperada, el elemento que la recibe puede ser distinto al deseado.<br> + El objetivo del evento wheel solo está definido por la posición del cursor en el momento que se dispara este.</p> + +<h3 id="El_valor_de_deltaMode">El valor de deltaMode</h3> + +<p>En Windows, los siguientes 3 eventos nativos del DOM causan eventos <code>wheel</code>.</p> + +<dl> + <dt>WM_MOUSEWHEEL (Evento wheel vertical del ratón)</dt> + <dd>El <code>deltaMode</code> puede ser <code>DOM_DELTA_LINE</code> o <code>DOM_DELTA_PAGE</code>. Depende de las preferencias de usuario en Windows (Para configuraciones por defecto, debería ser <code>DOM_DELTA_LINE</code>).</dd> + <dt>WM_MOUSEHWHEEL (Evento wheel horizontal del ratón)</dt> + <dd><code>EldeltaMode</code> puede ser <code>DOM_DELTA_LINE</code> o <code>DOM_DELTA_PAGE</code>. Sin embargo, ni la configuración de velocidad de rueda de ratón de Windows ni ningún UI similar de drivers permite modificar el scroll de páginas. De modo que, normalmente este valor es <code>DOM_DELTA_LINE</code>.</dd> + <dt>WM_GESTURE (Solo utilizado en navegación gestual)</dt> + <dd>El <code>deltaMode</code> es siempre <code>DOM_DELTA_PIXEL</code>. Pero la mayoría de dispositivos táctiles de portatiles emulan la rueda de ratón en lugar de usar este evento. Este evento es usado típicamente en Tablet PC.</dd> +</dl> + +<p>En Mac, el valor de <code>deltaMode</code> depende del dispositivo. Si el dispositivo permite alta resolución, el scroll se hará en pixels, de manera que el valor del <code>deltaMode</code> será <code>DOM_DELTA_PIXEL</code>. De todos modos, el usuario puede cambiarlo a <code>DOM_DELTA_LINE</code> con la preferencia <code>"mousewheel.enable_pixel_scrolling"</code>. Si el dispositivo no soporta alta resolución, es siembre <code>DOM_DELTA_LINE</code>.</p> + +<p>En otras plataformas, el valor de <code>deltaMode</code> es siempre <code>DOM_DELTA_LINE</code>.</p> + +<h3 id="Eventos_no_confiables">Eventos no confiables</h3> + +<p>Los eventos <code>wheel</code> no nativos nunca causarán acción por defecto.</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{ domxref("WheelEvent") }}</li> + <li>Gecko's legacy events: <code>DOMMouseScroll</code> and <code>MozMousePixelScroll</code></li> + <li>Non-Gecko browsers' legacy event: <code>mousewheel</code></li> + <li>WebKit bug: <a href="https://bugs.webkit.org/show_bug.cgi?id=94081" title="https://bugs.webkit.org/show_bug.cgi?id=94081">https://bugs.webkit.org/show_bug.cgi?id=94081</a></li> +</ul> diff --git a/files/es/web/api/elementoshtmlparavideo/index.html b/files/es/web/api/elementoshtmlparavideo/index.html new file mode 100644 index 0000000000..4b36d9cba2 --- /dev/null +++ b/files/es/web/api/elementoshtmlparavideo/index.html @@ -0,0 +1,202 @@ +--- +title: Elementos HTML para Video +slug: Web/API/ElementosHTMLparaVideo +translation_of: Web/API/HTMLVideoElement +--- +<div> +<div>{{APIRef("HTML DOM")}}</div> +</div> + +<p>El interfaz de <strong><code>HTMLVideoElement</code></strong> provee propiedades especiales y metodos para manipular objectos de videos. Tambien, este interfaz hereda propiedades y métodos de {{domxref("HTMLMediaElement")}} y {{domxref("HTMLElement")}}.</p> + +<p>La lista de <a href="/en-US/docs/HTML/Supported_media_formats">supported media formats</a> (formatos de medios compatibles) varía de un navegador a otro. Debe proveer su video en un formato sencillo que sea compatible con todos los navegadores o proveer varias fuentes de videos in varios formatos, para que así todo navegador que necesite este cubierto.</p> + +<p>{{InheritanceDiagram(600, 140)}}</p> + +<h2 id="Propiedades">Propiedades</h2> + +<p><em>Hereda las propiedades de los interfaces anteriores, {{domxref("HTMLMediaElement")}}, y </em><em>{{domxref("HTMLElement")}}.</em></p> + +<dl> + <dt>{{domxref("HTMLVideoElement.height")}}</dt> + <dd>Es un {{domxref("DOMString")}} que refleja el atributo HTML {{htmlattrxref("height", "video")}}, el cual especifica la altura del area mostrada, en pixeles CSS.</dd> + <dt>{{domxref("HTMLVideoElement.poster")}}</dt> + <dd>Es un {{domxref("DOMString")}} que refleja el atributo HTML {{htmlattrxref("poster", "video")}}, el cual especifica que imagen sera mostrada en la ausencia de data de video.</dd> + <dt>{{domxref("HTMLVideoElement.videoHeight")}} {{readonlyInline}}</dt> + <dd>Devuelve un <code>unsigned long</code> que contiene la altura intrinsica del recurso en pixeles CSS, tomando en consideracion las dimensiones, aspecto proporcional, apertura limpia, resolucion, etc., ya definidas por el formato usado por el recurso. Si el estado disponible del elemento es <code>HAVE_NOTHING</code>, su valor es <code>0</code>.</dd> + <dt>{{domxref("HTMLVideoElement.videoWidth")}} {{readonlyInline}}</dt> + <dd>Devuelve un <code>unsigned long</code> que contiene la anchura intrinsica del recurso en pixeles CSS, tomando en consideracion las dimensiones, aspecto proporcional, apertura limpia, resolucion, etc., ya definidas por el formato usado por el recurso. Si el estado disponible del elemento es <code>HAVE_NOTHING</code>, su valor es <code>0</code>.</dd> + <dt>{{domxref("HTMLVideoElement.width")}}</dt> + <dd>Es un {{domxref("DOMString")}} que refleja el atributo HTML {{htmlattrxref("width", "video")}}, el cual especifica la anchura del area mostrada, en pixeles CSS.</dd> +</dl> + +<h3 id="Propiedades_especificas_para_Gecko">Propiedades especificas para Gecko</h3> + +<dl> + <dt>{{domxref("HTMLVideoElement.mozParsedFrames")}} {{readonlyInline}}{{non-standard_inline}}</dt> + <dd><code>Devuelve un unsigned long</code> con el conteo de marcos de video que han sido analizados del recurso de multimedia.</dd> + <dt>{{domxref("HTMLVideoElement.mozDecodedFrames")}} {{readonlyInline}}{{non-standard_inline}}</dt> + <dd>Devuelve un <code>unsigned long</code> con el conteo de marcos de video que han sido decifrados como imágines.</dd> + <dt>{{domxref("HTMLVideoElement.mozPresentedFrames")}} {{readonlyInline}}{{non-standard_inline}}</dt> + <dd>Devuelve un <code>unsigned long</code> con el conteo de marcos decodificados que han sido presentados a la canalización de render para pintar.</dd> + <dt>{{domxref("HTMLVideoElement.mozPaintedFrames")}} {{readonlyInline}}{{non-standard_inline}}</dt> + <dd>Devuelve un <code>unsigned long</code> con el conteo de marcos presentados que han sido pintados en la pantalla.</dd> + <dt>{{domxref("HTMLVideoElement.mozFrameDelay")}} {{readonlyInline}}{{non-standard_inline}}</dt> + <dd>Devuelve un <code>double</code> con el tiempo, en segundos, que el último marco de video fue pintado por retrazo.</dd> + <dt>{{domxref("HTMLVideoElement.mozHasAudio")}} {{readonlyInline}}{{non-standard_inline}}</dt> + <dd>Devuelve un {{domxref("Boolean")}} indicando si existe algún audio asociado con el video.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<p><em>Hereda los métodos anteriores de </em><em>{{domxref("HTMLMediaElement")}} y </em><em>{{domxref("HTMLElement")}}.</em></p> + +<dl> + <dt>{{domxref("HTMLVideoElement.getVideoPlaybackQuality()")}} {{experimental_inline}}</dt> + <dd>Devuelve un {{domxref("VideoPlaybackQuality")}} para objetos que contienen las medidas de reproducciones actuales.</dd> +</dl> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificacion</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('Media Source Extensions', '#idl-def-HTMLVideoElement', 'Extensions to HTMLVideoElement')}}</td> + <td>{{Spec2("Media Source Extensions")}}</td> + <td>Anadio el metodo <code>getVideoPlaybackQuality()</code> .</td> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', "the-video-element.html#the-video-element", "HTMLAreaElement")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>Sin cambios del {{SpecName('HTML5 W3C')}}.</td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', "embedded-content-0.html#the-video-element", "HTMLAreaElement")}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>Definicion incial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_Navegador">Compatibilidad con Navegador</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Caracteristicas</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Apoyo basico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("2.0")}}</td> + <td>9.0</td> + <td>10.50</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>mozParsedFrames mozDecodedFrames mozPresentedFrames mozPaintedFrames mozFrameDelay</code> {{non-standard_inline}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop("5.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>mozHasAudio</code> {{non-standard_inline}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{ CompatGeckoDesktop("15.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>getVideoPlaybackQuality()</code>{{experimental_inline}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{ CompatGeckoDesktop("25.0")}}<sup>[1]</sup></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Características</th> + <th>Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Apoyo básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("2.0")}}</td> + <td>9.0</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>mozParsedFrames mozDecodedFrames mozPresentedFrames mozPaintedFrames mozFrameDelay</code> {{non-standard_inline}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoMobile("5.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>mozHasAudio</code> {{non-standard_inline}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{ CompatGeckoMobile("15.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>getVideoPlaybackQuality()</code>{{experimental_inline}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{ CompatGeckoMobile("25.0")}}<sup>[1]</sup></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Gecko implementa esto detras de la preferencia <code>media.mediasource.enabled</code>, predispuesto a <code>false</code>.</p> + +<h2 id="Lea_Tambien">Lea Tambien</h2> + +<ul> + <li>Elemento HTML implementando este interfaz: {{HTMLElement("video")}}.</li> + <li><a class="external" href="http://people.mozilla.org/~cpearce/paint-stats-demo.html">Demonstracion de estadisticas de pintura de video</a></li> + <li><a href="/en-US/docs/HTML/Supported_media_formats">Formatos de medios compatibles </a></li> +</ul> diff --git a/files/es/web/api/event/bubbles/index.html b/files/es/web/api/event/bubbles/index.html new file mode 100644 index 0000000000..a940b1e4a7 --- /dev/null +++ b/files/es/web/api/event/bubbles/index.html @@ -0,0 +1,47 @@ +--- +title: event.bubbles +slug: Web/API/Event/bubbles +tags: + - Anidado + - DOM + - Propagación + - Referencia + - Referência(2) + - eventos +translation_of: Web/API/Event/bubbles +--- +<p>{{ ApiRef("DOM") }}</p> + +<h3 id="Resumen" name="Resumen">Resumen</h3> + +<p>Indica si el evento determinado <em>se propaga</em> (burbujea) a través del DOM o no. Esta propagación se refiere a si el evento viaja desde el elemento donde se originó hasta los elementos padres<font face="Consolas, Monaco, Andale Mono, monospace"> </font>en orden de anidamiento.</p> + +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> + +<pre class="eval"><em>e</em>vent.bubbles +</pre> + +<p>Retorna un valor Booleano que es <code>true</code> si el evento se propaga en el DOM.</p> + +<h3 id="Ejemplo_2">Ejemplo</h3> + +<pre>var bool = event.bubbles;</pre> + +<p><code>bool</code> tiene el valor <code>true</code> o <code>false</code>, dependiendo de si el evento puede ser burbuja o no.</p> + +<h3 id="Notas" name="Notas">Notas</h3> + +<p>Sólo ciertos eventos pueden ser burbuja. Los eventos que pueden ser burbuja tienen esta propiedad con el valor <code>true</code>. Podemos usar esta propiedad para comprobar si un elemento puede ser burbuja o no.</p> + +<h3 id="Ejemplo" name="Ejemplo">Ejemplo</h3> + +<pre> function goInput(e) { + // comprueba si es burbuja y + if (!e.bubbles) { + // entrega el evento si no lo es + passItOn(e); + } + // está siendo propagado + doOutput(e) +} +</pre> diff --git a/files/es/web/api/event/cancelable/index.html b/files/es/web/api/event/cancelable/index.html new file mode 100644 index 0000000000..efb6eb04f6 --- /dev/null +++ b/files/es/web/api/event/cancelable/index.html @@ -0,0 +1,38 @@ +--- +title: event.cancelable +slug: Web/API/Event/cancelable +tags: + - Referencia_DOM_de_Gecko +translation_of: Web/API/Event/cancelable +--- +<div>{{ ApiRef("DOM") }}</div> + +<h3 id="Resumen" name="Resumen">Resumen</h3> + +<p>Indica si el elemento puede ser cancelado o no.</p> + +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> + +<pre class="eval"><i>bool</i> = +<i>event</i>.cancelable; +</pre> + +<p><code>bool</code> tiene valor <code>true</code> o <code>false</code>, dependiendo de si el evento puede ser desactivado.</p> + +<h3 id="Notas" name="Notas">Notas</h3> + +<p>Si un evento puede ser cancelado o no, es algo que se determina en el momento en que el evento es inicializado.</p> + +<p>Para cancelar un evento, llama al método <a href="es/DOM/event.preventDefault">preventDefault</a> en el evento. Esto evita que la tarea de implementación ejecute la acción por defecto asociada con el evento.</p> + +<h3 id="Especificaci.C3.B3n" name="Especificaci.C3.B3n">Especificación</h3> + +<p><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-Event-canCancel">DOM Level 2 Events: cancelable</a></p> + +<p> </p> + +<p> </p> + +<div class="noinclude"> </div> + +<p>{{ languages( { "en": "en/DOM/event.cancelable", "ja": "ja/DOM/event.cancelable", "pl": "pl/DOM/event.cancelable" } ) }}</p> diff --git a/files/es/web/api/event/createevent/index.html b/files/es/web/api/event/createevent/index.html new file mode 100644 index 0000000000..0d04851789 --- /dev/null +++ b/files/es/web/api/event/createevent/index.html @@ -0,0 +1,34 @@ +--- +title: Event.createEvent() +slug: Web/API/Event/createEvent +tags: + - API + - DOM + - Evento + - metodo +translation_of: Web/API/Document/createEvent +--- +<p>{{APIRef("DOM")}}</p> + +<p>Crea un nuevo evento, que debe ser inicializado llamando a su método <code>init()</code>.</p> + +<h3 id="Sintaxis">Sintaxis</h3> + +<pre><code>document.createEvent(tipo);</code></pre> + +<dl> + <dt><code>tipo</code></dt> + <dd>Una string indicando el tipo de evento a crear.</dd> +</dl> + +<p>Este método devuelve un nuevo objeto {{ domxref("Event") }} del DOM del tipo indicado, que debe ser inicializado antes de su uso.</p> + +<h3 id="Ejemplo">Ejemplo</h3> + +<pre>var nuevoEvento = document.createEvent("UIEvents");</pre> + +<h3 id="Especificación">Especificación</h3> + +<ul> + <li><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-document" title="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-document">DOM Level 2 Events</a></li> +</ul> diff --git a/files/es/web/api/event/currenttarget/index.html b/files/es/web/api/event/currenttarget/index.html new file mode 100644 index 0000000000..0c9d9a2a9e --- /dev/null +++ b/files/es/web/api/event/currenttarget/index.html @@ -0,0 +1,75 @@ +--- +title: Event.currentTarget +slug: Web/API/Event/currentTarget +tags: + - API + - DOM + - Gecko + - Property +translation_of: Web/API/Event/currentTarget +--- +<p>{{APIRef("DOM")}}</p> + +<p>Identifica el target (objetivo) actual del evento, ya que el evento atraviesa el DOM. Siempre hace referencia al elmento al cual el controlador del evento fue asociado, a diferencia de <code>event.target</code>, que identifica el elemento el el que se produjo el evento.</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>Es interesante utilizar <code>event.currentTarget</code> cuando se asocia un mismo controlador de eventos a varios elementos.</p> + +<pre class="brush: js">function hide(e){ + e.currentTarget.style.visibility = "hidden"; + console.log(e.currentTarget); + // Cuando esta función es usada como un controlador de evento: this === e.currentTarget +} + +var ps = document.getElementsByTagName('p'); + +for(var i = 0; i < ps.length; i++){ + // console: imprime el elemento pulsado <p> + ps[i].addEventListener('click', hide, false); +} +// console: imprime <body> +document.body.addEventListener('click', hide, false); + +// hace desaparecer párrafos al hacer click alrededor +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th>Especificación</th> + <th>Estado</th> + <th>Comentario</th> + </tr> + <tr> + <td>{{SpecName("DOM WHATWG", "#dom-event-currenttarget", "Event.currentTarget")}}</td> + <td>{{Spec2("DOM WHATWG")}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName("DOM4", "#dom-event-currenttarget", "Event.currentTarget")}}</td> + <td>{{Spec2("DOM4")}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName("DOM3 Events", "#dfn-current-event-target", "current event target")}}</td> + <td>{{Spec2("DOM3 Events")}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName("DOM2 Events", "#Events-Event-currentTarget", "Event.currentTarget")}}</td> + <td>{{Spec2("DOM2 Events")}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<p>{{Compat("api.Event.currentTarget")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<p><a href="/en-US/docs/Web/API/Event/Comparison_of_Event_Targets">Comparativa de Event Targets</a></p> diff --git a/files/es/web/api/event/defaultprevented/index.html b/files/es/web/api/event/defaultprevented/index.html new file mode 100644 index 0000000000..ff1f9fba79 --- /dev/null +++ b/files/es/web/api/event/defaultprevented/index.html @@ -0,0 +1,81 @@ +--- +title: event.defaultPrevented +slug: Web/API/Event/defaultPrevented +translation_of: Web/API/Event/defaultPrevented +--- +<p>{{ ApiRef() }}</p> + +<h3 id="Resumen">Resumen</h3> + +<p>Retorna un boleano indicando si {{ domxref("event.preventDefault()") }} fue llamado en el evento o no.</p> + +<div class="note"><strong>Nota:</strong> Deberías usar este en lugar del que no es estándar, el método obsoleto <code>getPreventDefault()</code> (ver {{ bug(691151) }}).</div> + +<h3 id="Sintaxis">Sintaxis</h3> + +<pre class="eval">bool = event.defaultPrevented </pre> + +<h3 id="Ejemplo">Ejemplo</h3> + +<pre> if (e.defaultPrevented) { + /* El evento por defecto fue prevenido */ + } +</pre> + +<h3 id="Compatibilidad_del_Navegador">Compatibilidad del Navegador</h3> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{ CompatChrome(18) }}</td> + <td>{{ CompatGeckoDesktop("6.0") }}</td> + <td>{{ CompatIE(9.0) }}</td> + <td>{{ CompatOpera(11.0) }}</td> + <td>{{ CompatSafari("5.0") }}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatGeckoMobile("6.0") }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatSafari(5.0) }}</td> + </tr> + </tbody> +</table> +</div> + +<h3 id="Especificación">Especificación</h3> + +<ul> + <li><a class="external" href="http://www.w3.org/TR/2006/WD-DOM-Level-3-Events-20060413/events.html#Events-Event-defaultPrevented" title="http://www.w3.org/TR/2006/WD-DOM-Level-3-Events-20060413/events.html#Events-Event-defaultPrevented">DOM 3 Events</a></li> +</ul> + +<p>{{ languages( {"zh-cn": "zh-cn/DOM/event.defaultPrevented" } ) }}</p> diff --git a/files/es/web/api/event/event/index.html b/files/es/web/api/event/event/index.html new file mode 100644 index 0000000000..b1410daf7b --- /dev/null +++ b/files/es/web/api/event/event/index.html @@ -0,0 +1,80 @@ +--- +title: Event() +slug: Web/API/Event/Event +translation_of: Web/API/Event/Event +--- +<p>{{APIRef("DOM")}}</p> + +<p>El constructor <code><strong>Event()</strong></code> crea un nuevo {{domxref("Event")}}.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"> <em>event</em> = new Event(<em>typeArg</em>, <em>eventInit</em>);</pre> + +<h3 id="Valores">Valores</h3> + +<dl> + <dt><em>typeArg</em></dt> + <dd>Es un {{domxref("DOMString")}} que representa el nombre del evento.</dd> + <dt><em>eventInit </em>{{optional_inline}}</dt> +</dl> + +<dl> + <dd>Es un <code>EventInit</code> dictionary, con los siguientes campos: + + <ul> + <li><code>"bubbles"</code>: (Opcional) {{jsxref("Boolean")}} indica si el evento se propaga. Por defecto es <code>false</code>.</li> + <li><code>"cancelable"</code>: (Opcional) A {{jsxref("Boolean")}} indica si el evento puede ser cancelado. Por defecto es <code>false</code>.</li> + <li><code>"scoped"</code>: (Opcional) {{jsxref("Boolean")}} indica el ámbito de propagación. Si el valor es <code>true</code>, <code>deepPath</code> contendrá el nodo de destino.</li> + <li><code>"composed"</code>: (Opcional) {{jsxref("Boolean")}} que indica si el evento disparará listeners fuera de un shadow root. Por defecto es <code>false</code>.<span style="display: none;"> </span></li> + </ul> + </dd> +</dl> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush: js">// crea un evento look que se propaga y no puede cancelarse + +var ev = new Event("look", {"bubbles":true, "cancelable":false}); +document.dispatchEvent(ev); +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table" style="height: 49px; width: 1000px;"> + <thead> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('DOM WHATWG','#interface-event','Event()')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Definición inicial.</td> + </tr> + <tr> + <td>{{SpecName('Shadow DOM','#widl-EventInit-scoped', 'scoped')}}</td> + <td>{{Spec2('Shadow DOM')}}</td> + <td>Añade ámbito a <code>EventInit</code> dictionary.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<p> </p> + + + +<p>{{Compat("api.Event.Event")}}</p> + +<p> </p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("Event")}}</li> +</ul> diff --git a/files/es/web/api/event/index.html b/files/es/web/api/event/index.html new file mode 100644 index 0000000000..67cc05b076 --- /dev/null +++ b/files/es/web/api/event/index.html @@ -0,0 +1,185 @@ +--- +title: evento +slug: Web/API/Event +tags: + - para_revisar +translation_of: Web/API/Event +--- +<p>{{APIRef("DOM")}}</p> + +<p>« <a href="/es/Referencia_DOM_de_Gecko" title="es/Referencia_DOM_de_Gecko">Referencia DOM de Gecko</a></p> + +<h3 id="Introducci.C3.B3n" name="Introducci.C3.B3n">Introducción</h3> + +<p>Éste capítulo describe el Modelo De Evento DOM de nivel 2 como es implementado por <a href="/es/Gecko" title="es/Gecko">Gecko</a>. La propia interfaz de <a class="external" href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-Event">Evento</a> es descrita, así como las interfaces para el registro de evento sobre los nodos en el DOM, manipuladores y "oyentes" (<code>listeners</code>) de eventos, y varios ejemplos mas extensos que muestran como las varias interfaces de evento se relacionan unas con las otras.</p> + +<p>Hay un diagrama excelente que explica claramente las tres fases del flujo de eventos a través del DOM en el <a class="external" href="http://www.w3.org/TR/DOM-Level-3-Events/events.html#Events-flow">DOM Level 3 Events draft</a>.</p> + +<h4 id="La_interfaz_evento_.28Event.29_de_DOM" name="La_interfaz_evento_.28Event.29_de_DOM">La interfaz evento (<code>Event</code>) de DOM</h4> + +<p>Los gestores de eventos pueden estar atados a varios elementos en el DOM. Cuando un evento ocurre, un objeto de evento es dinámicamente creado y pasado secuencialmente a las "escuchas" (<small>listeners</small>) autorizadas para la gestión del evento. La interfaz <code>Event</code> del DOM es entonces accesible por la función de manejo, vía el objeto de evento puesto como el primer (y único) argumento.</p> + +<p><span class="comment">Given that we don't list the three ways right here, the sentence is unclear, and is not perfectly right either IMO. -Nickolay There are three ways to attach an event listener to an element. With 2 of those techniques, the event object is passed to the handler function implicitly. The remaining technique requires you to specify the <code>event</code> object as a parameter, which is passed explicitly to the event handler function.</span> El ejemplo siguiente muestra como un objeto de evento es pasado a una función de gestión de evento, y puede llamarse desde otra parecida.</p> + +<p>El parámetro "evt" no es pasado en el código de abajo, el objeto de evento es cambiado automáticamente a <em>foo</em>. Todo lo necesario es definir un parámetro en el gestor de evento para recibir el objeto de evento.</p> + +<pre>function foo(evt) { + // Las funciones de gestión como esta + // dan una referencia implícita del + // evento que toca manejar + // (en este caso se llama "evt"). + alert(evt); +} +table_el.onclick = foo; +</pre> + +<p>Este ejemplo es muy simple pero muestra una característica importante de los eventos en el DOM de Gecko, la cual es que en el DOM se accede a los objetos de eventos a través de las funciones de manejo. Entonces al tener una referencia al objeto de evento, se puede llegar a todas las propiedades y métodos descritos en este capítulo.</p> + +<p>Para más detalles de como los eventos se mueven dentro del DOM, ver: <a href="/es/Referencia_DOM_de_Gecko/Ejemplos#Ejemplo_5:_Propagaci.C3.B3n_de_evento" title="es/Referencia_DOM_de_Gecko/Ejemplos#Ejemplo_5:_Propagaci.C3.B3n_de_evento">Ejemplo 5: Propagación de evento</a></p> + +<h4 id="Lista_de_los_gestores_de_evento_del_DOM" name="Lista_de_los_gestores_de_evento_del_DOM">Lista de los gestores de evento del DOM</h4> + +<p>Además del objeto <code>event</code> descrito aquí, el Gecko DOM también proporciona métodos para registrar oyentes de eventos en nodos en el DOM, quitando aquellos oyentes de eventos, y enviando eventos desde el DOM.</p> + +<p>Estos y los varios <a href="/es/DOM/element#Manejo_de_los_eventos" title="es/DOM/element#Manejo_de_los_eventos">manejos de eventos</a> de elementos HTML o XML son los puntos de entrada principales para los eventos en el DOM. Estos tres métodos se describen en la lista de <a href="/es/DOM/element" title="es/DOM/element">referencia al elemento</a>.</p> + +<p>Puede también pasar la referencia del objeto del evento como un parámetro predefinido, llamado <code>event</code>, a la función que maneja el evento. Esto es muy parecido a la forma en que trabaja <code>this</code>, pero para objetos de eventos, más bien que las referencias del objeto del elemento.</p> + +<pre><html> +<head> +<title>Ejemplo de parámetro de objeto de evento</title> + +<script type="text/javascript"> + +function showCoords(event){ + alert( + "clientX value: " + event.clientX + "\n" + + "clientY value: " + event.clientY + "\n" + ); +} + +</script> +</head> + +<body onmousedown="showCoords(event)"> +<p>Para ver las coordinadas del ratón +haga clic en cualquier lugar de esta página.</p> +</body> +</html> +</pre> + +<p>El parámetro predefinido del objeto <code>event</code> permite pasar tantos parámetros de gestión de evento como sea necesario:</p> + +<pre><html> +<head> +<title>Ejemplo de objeto con varios parámetros</title> + +<script type="text/javascript"> + +var par2 = 'hello'; +var par3 = 'world!'; + +function muestraCoords(evt, p2, p3){ + alert( + "clienteX value: " + evt.clientX + "\n" + + "clientY value: " + evt.clientY + "\n" + + "p2: " + p2 + "\n" + + "p3: " + p3 + "\n" + ); +} + +</script> +</head> + +<body onmousedown="muestraCoords(event, par2, par3)"> +<p>Para ver las coordinadas del ratón +haga clic en cualquier lugar de esta página.</p> +</body> +</html> +</pre> + +<h3 id="Propiedades" name="Propiedades">Propiedades</h3> + +<dl> + <dt><a href="/es/DOM/event.altKey" title="es/DOM/event.altKey">event.altKey</a> </dt> + <dd>Devuelve un valor indicando si la tecla <code><alt></code> fue pulsada durante el evento.</dd> + <dt><a href="/es/DOM/event.bubbles" title="es/DOM/event.bubbles">event.bubbles</a> </dt> + <dd>Devuelve un valor que indica si el evento se propaga hacia arriba a través del DOM o no.</dd> + <dt><a href="/es/DOM/event.button" title="es/DOM/event.button">event.button</a> </dt> + <dd>Devuelve el botón del ratón.</dd> + <dt><a href="/es/DOM/event.cancelBubble" title="es/DOM/event.cancelBubble">event.cancelBubble</a> {{deprecated_inline}} </dt> + <dd>Devuelve un valor que indica si la propagación hacia arriba fue cancelada o no.</dd> + <dt><a href="/es/DOM/event.cancelable" title="es/DOM/event.cancelable">event.cancelable</a> </dt> + <dd>Devuelve un valor que indica si el evento se puede cancelar.</dd> + <dt><a href="/es/DOM/event.charCode" title="es/DOM/event.charCode">event.charCode</a> </dt> + <dd>Devuelve el valor Unicode de una tecla de carácter que fue apretada como parte de un evento <a href="/es/DOM/event/keypress" title="es/DOM/event/keypress">keypress</a>.</dd> + <dt><a href="/es/DOM/event.clientX" title="es/DOM/event.clientX">event.clientX</a> </dt> + <dd>Devuelve la posición horizontal del evento.</dd> + <dt><a href="/es/DOM/event.clientY" title="es/DOM/event.clientY">event.clientY</a> </dt> + <dd>Devuelve la posición vertical del evento.</dd> + <dt><a href="/es/DOM/event.ctrlKey" title="es/DOM/event.ctrlKey">event.ctrlKey</a> </dt> + <dd>Devuelve un valor que indica si la tecla <code><Ctrl></code> fue apretada durante el evento.</dd> + <dt><a href="/es/DOM/event.currentTarget" title="es/DOM/event.currentTarget">event.currentTarget</a> </dt> + <dd>Devuelve una referencia al objetivo actual registrado para el evento.</dd> + <dt><a href="/es/DOM/event.detail" title="es/DOM/event.detail">event.detail</a> </dt> + <dd>Devuelve detalles sobre el evento, dependiendo del tipo de evento.</dd> + <dt><a href="/es/DOM/event.eventPhase" title="es/DOM/event.eventPhase">event.eventPhase</a> </dt> + <dd>Utilizado para indicar qué fase del flujo del evento es actualmente en proceso de evaluación.</dd> + <dt><a href="/es/DOM/event.explicitOriginalTarget" title="es/DOM/event.explicitOriginalTarget">event.explicitOriginalTarget</a> </dt> + <dd>El objetivo del evento (específico a Mozilla).</dd> + <dt><a href="/es/DOM/event.isChar" title="es/DOM/event.isChar">event.isChar</a> </dt> + <dd>Devuelve un valor que indica si el evento produce o no una tecla de carácter.</dd> + <dt><a href="/es/DOM/event.keyCode" title="es/DOM/event.keyCode">event.keyCode</a> </dt> + <dd>Devuelve el valor Unicode de una tecla que no es caracter en un evento <a href="/es/DOM/event/keypress" title="es/DOM/event/keypress">keypress</a> o cualquier tecla en cualquier otro tipo de evento de teclado.</dd> + <dt><a href="/es/DOM/event.layerX" title="es/DOM/event.layerX">event.layerX</a> </dt> + <dd>Devuelve la coordenada horizontal del evento relativo a la capa actual.</dd> + <dt><a href="/es/DOM/event.layerY" title="es/DOM/event.layerY">event.layerY</a> </dt> + <dd>Devuelve la coordenada vertical del evento relativo a la capa actual.</dd> + <dt><a href="/es/DOM/event.metaKey" title="es/DOM/event.metaKey">event.metaKey</a> </dt> + <dd>Devuelve un valor booleano indicando si la <code>meta</code> tecla fue presionada durante un evento.</dd> + <dt><a href="/es/DOM/event.originalTarget" title="es/DOM/event.originalTarget">event.originalTarget</a> </dt> + <dd>El objetivo principal de un evento, antes de cualquier reapunte (Especifiación Mozilla).</dd> + <dt><a href="/es/DOM/event.pageX" title="es/DOM/event.pageX">event.pageX</a> </dt> + <dd>Devuelve la coordenada horizontal del evento, relativo al documento completo.</dd> + <dt><a href="/es/DOM/event.pageY" title="es/DOM/event.pageY">event.pageY</a> </dt> + <dd>Devuelve la coordenada vertical del evento, relativo al documento completo.</dd> + <dt><a href="/es/DOM/event.relatedTarget" title="es/DOM/event.relatedTarget">event.relatedTarget</a> </dt> + <dd>Identifica un objetivo secundario para el evento.</dd> + <dt><a href="/es/DOM/event.screenX" title="es/DOM/event.screenX">event.screenX</a> </dt> + <dd>Devuelve la coordenada horizontal del evento en la pantalla.</dd> + <dt><a href="/es/DOM/event.screenY" title="es/DOM/event.screenY">event.screenY</a> </dt> + <dd>Devuelve la coordenada vertical del evento en la pantalla.</dd> + <dt><a href="/es/DOM/event.shiftKey" title="es/DOM/event.shiftKey">event.shiftKey</a> </dt> + <dd>Devuelve un valor booleano indicando si la tecla <code><shift></code> fue presionada cuando el evento fue disparado.</dd> + <dt><a href="/es/DOM/event.target" title="es/DOM/event.target">event.target</a> </dt> + <dd>Devuelve una referencia al objetivo en la cual el evento fue originalmente enviado.</dd> + <dt><a href="/es/DOM/event.timeStamp" title="es/DOM/event.timeStamp">event.timeStamp</a> </dt> + <dd>Devuelve el momento de creación del evento.</dd> + <dt><a href="/es/DOM/event.type" title="es/DOM/event.type">event.type</a> </dt> + <dd>Devuelve el nombre del evento (distingue mayúsculas y minúsculas).</dd> + <dt><a href="/es/DOM/event.view" title="es/DOM/event.view">event.view</a> </dt> + <dd>El atributo vista identifica la <code>AbstractView</code> del cual el evento fue generado.</dd> + <dt><a href="/es/DOM/event.which" title="es/DOM/event.which">event.which</a> </dt> + <dd>Devuelve el valor Unicode de la tecla en un evento del teclado, sin importar el tipo de tecla que se presionó.</dd> +</dl> + +<h3 id="M.C3.A9todos" name="M.C3.A9todos">Métodos</h3> + +<dl> + <dt><a href="/es/DOM/event.initEvent" title="es/DOM/event.initEvent">event.initEvent</a> </dt> + <dd>Inicia el valor de un evento que se ha creado vía la interfaz <code>DocumentEvent</code>.</dd> + <dt><a href="/es/DOM/event.initKeyEvent" title="es/DOM/event.initKeyEvent">event.initKeyEvent</a> </dt> + <dd>Inicia un evento del teclado. (Específico de Gecko).</dd> + <dt><a href="/es/DOM/event.initMouseEvent" title="es/DOM/event.initMouseEvent">event.initMouseEvent</a> </dt> + <dd>Inicia un evento del ratón una vez que se ha creado.</dd> + <dt><a href="/es/DOM/event.initUIEvent" title="es/DOM/event.initUIEvent">event.initUIEvent</a> </dt> + <dd>Inicia un evento de la interfaz de usuario (<em>UI</em>) una vez que se ha creado.</dd> + <dt><a href="/es/DOM/event.preventBubble" title="es/DOM/event.preventBubble">event.preventBubble</a> {{obsolete_inline}} </dt> + <dd>Previene la expansión del evento. Este método es desaconsejado en favor del estándar <a href="/es/DOM/event.stopPropagation" title="es/DOM/event.stopPropagation">stopPropagation</a> y ha sido <a href="/es/Los_cambios_en_Gecko_1.9_afectando_a_los_sitios_web" title="es/Los_cambios_en_Gecko_1.9_afectando_a_los_sitios_web">retirado en Gecko 1.9</a>.</dd> + <dt><a href="/es/DOM/event.preventCapture" title="es/DOM/event.preventCapture">event.preventCapture</a> {{obsolete_inline}}</dt> + <dd>Este método es desaconsejado en favor del estándar <a href="/es/DOM/event.stopPropagation" title="es/DOM/event.stopPropagation">stopPropagation</a> y ha sido <a href="/es/Los_cambios_en_Gecko_1.9_afectando_a_los_sitios_web" title="es/Los_cambios_en_Gecko_1.9_afectando_a_los_sitios_web">retirado en Gecko 1.9</a>.</dd> + <dt><a href="/es/DOM/event.preventDefault" title="es/DOM/event.preventDefault">event.preventDefault</a> </dt> + <dd>Cancela el evento (si éste es anulable).</dd> + <dt><a href="/es/DOM/event.stopPropagation" title="es/DOM/event.stopPropagation">event.stopPropagation</a> </dt> + <dd>Para la propagación de los eventos más allá en el DOM.</dd> +</dl> diff --git a/files/es/web/api/event/initevent/index.html b/files/es/web/api/event/initevent/index.html new file mode 100644 index 0000000000..360effb8ef --- /dev/null +++ b/files/es/web/api/event/initevent/index.html @@ -0,0 +1,42 @@ +--- +title: event.initEvent +slug: Web/API/Event/initEvent +tags: + - Referencia_DOM_de_Gecko +translation_of: Web/API/Event/initEvent +--- +<div>{{ ApiRef("DOM") }}{{deprecated_header}}</div> +<h3 id="Resumen" name="Resumen">Resumen</h3> + +<p>El método <code>initEvent</code> se usa para dar valor inicial a un <a href="es/DOM/event">evento</a> creado mediante <a href="es/DOM/document.createEvent">document.createEvent</a>.</p> + +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> + +<pre class="eval"><em>event</em>.initEvent(<em>type</em>,<em>bubbles</em>,<em>cancelable</em>) +</pre> + +<dl> + <dt><code>type</code></dt> + <dd>El tipo de evento.</dd> + <dt><code>bubbles</code></dt> + <dd>Un valor binario indicando si el evento debe ser recurrente en la cadena de eventos, o no (ver <a href="/es/docs/DOM/event.bubbles">bubbles</a>).</dd> + <dt><code>cancelable</code></dt> + <dd>Un valor binario indicando si el evento puede ser cancelado o no (ver <a href="/es/docs/DOM/event.cancelable">cancelable</a>).</dd> +</dl> + +<p>Nota: Un valor binario puede tener sólo valores 1 y 0. En lógica de Boole, cierto (<em>true</em> ) y falso (<em>false</em> ).</p> + +<h3 id="Ejemplo" name="Ejemplo">Ejemplo</h3> + +<pre class="eval">// crea un evento "click" que puede ser recurrente y +// NO puede ser cancelado. +event.initEvent("click", true, false); +</pre> + +<h3 id="Notas" name="Notas">Notas</h3> + +<p>Los eventos inicializados de esta forma, deben haber sido creados por el método <a href="es/DOM/document.createEvent">document.createEvent</a>. Debemos llamar a <code>initEvent</code> para inicializar el evento antes de que pueda ser lanzado con <a href="es/DOM/element.dispatchEvent">dispatched</a>.</p> + +<h3 id="Especificaci.C3.B3n" name="Especificaci.C3.B3n">Especificación</h3> + +<p><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-Event-initEvent">DOM Level 2 Events: Event.initEvent</a></p> diff --git a/files/es/web/api/event/preventdefault/index.html b/files/es/web/api/event/preventdefault/index.html new file mode 100644 index 0000000000..e0e6ba18b1 --- /dev/null +++ b/files/es/web/api/event/preventdefault/index.html @@ -0,0 +1,95 @@ +--- +title: event.preventDefault +slug: Web/API/Event/preventDefault +tags: + - Referencia_DOM_de_Gecko +translation_of: Web/API/Event/preventDefault +--- +<p>{{ApiRef("DOM")}}</p> + +<h3 id="Resumen" name="Resumen">Resumen</h3> + +<p>Cancela el evento si este es cancelable, sin detener el resto del funcionamiento del evento, es decir, puede ser llamado de nuevo.</p> + +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> + +<pre class="eval"><em>event</em>.preventDefault() +</pre> + +<h3 id="Ejemplo" name="Ejemplo">Ejemplo</h3> + +<p>Cambiar el estado de una caja de selección es la función por defecto de la acción de hacer clic sobre la caja. Este ejemplo ilustra como hacer que esto no ocurra:</p> + +<pre><html> +<head> +<title>ejemplo de preventDefault</title> + +<script type="text/javascript"> + +function stopDefAction(evt) { + evt.preventDefault(); +} +</script> +</head> + +<body> + +<p>Por favor, haz clic sobre la caja de selección.</p> + +<form> +<input type="checkbox" onclick="stopDefAction(event);"/> +<label for="checkbox">Selección</label> +</form> + +</body> +</html> +</pre> + +<p>Puedes ver <code>preventDefault</code> en acción <a class="external" href="http://developer.mozilla.org/samples/domref/dispatchEvent.html">aquí</a>.</p> + +<p>El siguiente ejemplo demuestra cómo puede evitarse que un texto invalido entre en un campo de formulario mediante preventDefault().</p> + +<pre><html> +<head> +<title>preventDefault example</title> + +<script type="text/javascript"> + +function checkName(evt) { +var charCode = evt.charCode; + + if (charCode != 0) { + if (charCode < 97 || charCode > 122) { + evt.preventDefault(); + alert("Por favor usa sólo letras minúsculas." + "\n" + + "charCode: " + charCode + "\n" + ); + } + } +} + +</script> +</head> + +<body> + +<p>Por favor entra tu nombre en letras minúsculas solamente.</p> +<form> +<input type="text" onkeypress="checkName(event);"/> +</form> + +</body> +</html> +</pre> + +<h3 id="Notas" name="Notas">Notas</h3> + +<p>Llamar a <code>preventDefault</code> en cualquier momento durante la ejecución, cancela el evento, lo que significa que cualquier acción por defecto que deba producirse como resultado de este evento, no ocurrirá.</p> + +<p>Puedes usar <a href="es/DOM/event.cancelable">event.cancelable</a> para comprobar si el evento es cancelable o no. Llamar a <code>preventDefault</code> para un evento no cancelable, no tiene ningún efecto.</p> + +<p><code>preventDefault</code> no detiene las siguientes llamadas al evento producidas en el DOM. En su lugar debería usarse <a href="es/DOM/event.stopPropagation">event.stopPropagation</a> para ese propósito.</p> + +<h3 id="Especificaci.C3.B3n" name="Especificaci.C3.B3n">Especificación</h3> + +<p><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-Event-preventDefault">DOM Level 2 Events: preventDefault</a></p> diff --git a/files/es/web/api/event/stoppropagation/index.html b/files/es/web/api/event/stoppropagation/index.html new file mode 100644 index 0000000000..c92c594950 --- /dev/null +++ b/files/es/web/api/event/stoppropagation/index.html @@ -0,0 +1,103 @@ +--- +title: Event.stopPropagation() +slug: Web/API/Event/stopPropagation +translation_of: Web/API/Event/stopPropagation +--- +<div>{{APIRef("DOM")}}</div> + +<p>El método <code>stopPropagation()</code> de la interfaz {{domxref("Event")}} evita la propagación adicional del evento actual en las fases de captura y <em>bubbling</em>.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><em>event</em>.stopPropagation();</pre> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>Ver ejemplo 5: <a href="https://developer.mozilla.org/en-US/docs/DOM/DOM_Reference/Examples#Example_5:_Event_Propagation">Propagación del evento</a> en el capítulo de Ejemplos para un ejemplo mas detallado de este método y la propagación del evento en el DOM.</p> + +<h2 id="Notas">Notas</h2> + +<p>Ver las <a class="external" href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-flow-capture">Especificaciones del DOM</a> para la explicación del flujo del eventos. (El <a class="external" href="http://www.w3.org/TR/DOM-Level-3-Events/#event-flow">Borrador de eventos del DOM nivel 3</a> tiene una ilustración.)</p> + +<p><a href="/en-US/docs/Web/API/event.preventDefault">preventDefault</a> es un método complementario que puede ser usado para prevenir la acción default del evento cuando este ocurre.</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th>Especificación</th> + <th>Estado</th> + <th>Comentario</th> + </tr> + <tr> + <td>{{SpecName("DOM WHATWG", "#dom-event-stoppropagation", "Event.stopPropagation()")}}</td> + <td>{{Spec2("DOM WHATWG")}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName("DOM4", "#dom-event-stoppropagation", "Event.stopPropagation()")}}</td> + <td>{{Spec2("DOM4")}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName("DOM2 Events", "#Events-Event-stopPropagation", "Event.stopPropagation()")}}</td> + <td>{{Spec2("DOM2 Events")}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_navegadores">Compatibilidad en navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>9</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> diff --git a/files/es/web/api/event/target/index.html b/files/es/web/api/event/target/index.html new file mode 100644 index 0000000000..1e28aef0b3 --- /dev/null +++ b/files/es/web/api/event/target/index.html @@ -0,0 +1,138 @@ +--- +title: Event.target +slug: Web/API/Event/target +tags: + - Evento + - Propiedad + - Referencia +translation_of: Web/API/Event/target +--- +<p>{{ApiRef("DOM")}}</p> + +<p>La propiedad <code><strong>target</strong></code> de la interfaz del {{domxref("event.currentTarget")}} es una referencia al objeto en el cual se lanzo el evento. Es diferente de {{domxref("event.currentTarget")}} donde el controlador de eventos (event handler) es llamado durante la fase de bubbling or capturing del evento.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox notranslate">const theTarget = algunEvento.target</pre> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>La propiedad <code>event.target</code> puede ser usada para implementar una <strong>delegación del evento</strong>.</p> + +<pre class="brush: js notranslate">// Crear una lista +const ul = document.createElement('ul'); +document.body.appendChild(ul); + +const li1 = document.createElement('li'); +const li2 = document.createElement('li'); +ul.appendChild(li1); +ul.appendChild(li2); + +function hide(e){ + // e.target se refiere elemento clickado <li> + // Esto es diferente de e.currentTarget, que se referiría al padre <ul> en este contexto + e.target.style.visibility = 'hidden'; +} + +// Incluir el 'listener' a la lista +// Se ejecutará cuando se haga click en cada <li> +ul.addEventListener('click', hide, false); +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th>Especificación</th> + <th>Estado</th> + <th>Comentario</th> + </tr> + <tr> + <td>{{SpecName("DOM WHATWG", "#dom-event-target", "Event.target")}}</td> + <td>{{Spec2("DOM WHATWG")}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName("DOM4", "#dom-event-target", "Event.target")}}</td> + <td>{{Spec2("DOM4")}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName("DOM2 Events", "#Events-Event-target", "Event.target")}}</td> + <td>{{Spec2("DOM2 Events")}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_del_navegador"><strong>Compatibilidad del navegador</strong></h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Notas_de_compatibilidad">Notas de compatibilidad</h2> + +<p>En IE 6-8 el evento 'model' es diferente. Los eventos 'listeners' son are incluidos con el método no estándar {{domxref('EventTarget.attachEvent')}}. En este modelo, el evento 'object' tiene una propiedad {{domxref('Event.srcElement')}}, en vez de la propiedad <code>target</code>, y tiene la misma semántica que <code>event.target</code>.</p> + +<pre class="brush: js notranslate">function hide(e) { + // Soporte en IE6-8 + var target = e.target || e.srcElement; + target.style.visibility = 'hidden'; +} +</pre> + +<h2 id="También_ver">También ver</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Event/Comparison_of_Event_Targets"> Comparación de los Eventos</a></li> +</ul> diff --git a/files/es/web/api/event/type/index.html b/files/es/web/api/event/type/index.html new file mode 100644 index 0000000000..7f9f02f6e9 --- /dev/null +++ b/files/es/web/api/event/type/index.html @@ -0,0 +1,103 @@ +--- +title: event.type +slug: Web/API/Event/type +tags: + - API + - DOM + - Evento + - Propiedad + - Referencia +translation_of: Web/API/Event/type +--- +<div>{{APIRef}}</div> + +<p>La propiedad de sólo-lectura <code><strong>Event.type</strong></code> devuelve una cadena de texto que contiene el tipo de evento. Se establece cuando se contruye el evento y es el nombre que se utiliza normalmente para referirse al evento en cuestión, como <code>click</code>, <code>load</code> o <code>error</code>.</p> + +<p>El argumento <code>event</code> de {{ domxref("EventTarget.addEventListener()") }} y {{ domxref("EventTarget.removeEventListener()") }} no es sensible a mayúsculas.</p> + +<p>Para una lista de tipos de evento displonibles, vea la <a href="/es/docs/Web/Reference/Events">referencia de eventos</a></p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">event.type +</pre> + +<h2 id="Ejemplos">Ejemplos</h2> + +<pre class="brush: html"><!DOCTYPE html> +<html lang="en"> +<head> + <meta charset="utf-8"> + + <title>Event.type Example</title> + + <script> + var currEvent; + function getEvtType(evt) { + console.group(); + + currEvent = evt.type; + console.log(currEvent); + + document.getElementById("Etype").innerHTML = currEvent; + + console.groupEnd(); + } + + // Eventos de teclado + document.addEventListener("keypress", getEvtType, false); //[second] + + document.addEventListener("keydown", getEvtType, false); //first + document.addEventListener("keyup", getEvtType, false); //third + + // Eventos de ratón + document.addEventListener("click", getEvtType, false); // third + + document.addEventListener("mousedown", getEvtType, false); //first + document.addEventListener("mouseup", getEvtType, false); //second + + </script> +</head> + +<body> + +<p>Press any key or click the mouse to get the event type.</p> +<p>Event type: <span id="Etype" style="color:red">-</span></p> + +</body> +</html> +</pre> + +<h3 id="Resultado">Resultado</h3> + +<p>{{EmbedLiveSample('Example')}}</p> + +<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('DOM WHATWG', '#dom-event-type', 'Event.type')}}</td> + <td>{{ Spec2('DOM WHATWG') }}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('DOM2 Events', '#Events-Event-type', 'Event.type')}}</td> + <td>{{ Spec2('DOM2 Events') }}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_navegadores">Compatibilidad en navegadores</h2> + + + +<p>{{Compat("api.Event.type")}}</p> diff --git a/files/es/web/api/eventlistener/index.html b/files/es/web/api/eventlistener/index.html new file mode 100644 index 0000000000..e0a11040cc --- /dev/null +++ b/files/es/web/api/eventlistener/index.html @@ -0,0 +1,44 @@ +--- +title: EventListener +slug: Web/API/EventListener +translation_of: Web/API/EventListener +--- +<p>{{APIRef("DOM Events")}}</p> + +<h2 id="Method_overview" name="Method_overview">Información General del Método</h2> + +<table class="standard-table"> + <tbody> + <tr> + <td><code>void <a href="#handleEvent()">handleEvent</a>(in Event event);</code></td> + </tr> + </tbody> +</table> + +<h2 id="Methods" name="Methods">Metodos</h2> + +<h3 id="handleEvent()" name="handleEvent()">handleEvent()</h3> + +<p>Este metodo es llamado cuando un evento ocurre del tipo para el cual la interfaz <code>EventListener</code> fue registrada.</p> + +<pre class="eval">void handleEvent( + in Event event +); +</pre> + +<h5 id="Parameters" name="Parameters">Parametros</h5> + +<dl> + <dt><code>event</code></dt> + <dd>El DOM {{ domxref("Event") }} a registrar.</dd> +</dl> + +<h3 id="Remarks" name="Remarks">Observaciones</h3> + +<p>Como la interfaz es marcada con la bandera <code><span class="nowiki">[function],todas los objetos </span></code><a href="/en/JavaScript/Reference/Global_Objects/Function" title="en/Core_JavaScript_1.5_Reference/Global_Objects/Function">Function</a> de javascript automaticamente implementan esta interfaz. Llamando el método {{manch("handleEvent") }} en tales implementaciones automaticamente invocan la funcion.</p> + +<h2 id="See_also" name="See_also">Mira también</h2> + +<ul> + <li>{{ spec("http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventListener","Document Object Model Events: EventListener","REC") }}</li> +</ul> diff --git a/files/es/web/api/eventsource/index.html b/files/es/web/api/eventsource/index.html new file mode 100644 index 0000000000..db259edd2a --- /dev/null +++ b/files/es/web/api/eventsource/index.html @@ -0,0 +1,168 @@ +--- +title: EventSource +slug: Web/API/EventSource +tags: + - API + - Eventos Server-sent + - Interfaz +translation_of: Web/API/EventSource +--- +<div>{{APIRef("Websockets API")}}</div> + +<p>La interfaz <strong><code>EventSource</code></strong> se utiliza para recibir eventos server-side. Se realiza la conexión a un servidor sobre HTTP y se reciben eventos en formato <code>text/event-stream</code> sin tener que cerrar la conexión.</p> + +<dl> +</dl> + +<h2 id="Constructor">Constructor</h2> + +<dl> + <dt>{{domxref("EventSource.EventSource", "EventSource()")}}</dt> + <dd>Crea un nuevo <code>EventSource</code> a partiendo de un valor {{domxref("USVString")}}.</dd> +</dl> + +<h2 id="Propiedades">Propiedades</h2> + +<p><em>Esta interfaz también heredará propiedades de su antecesor, {{domxref("EventTarget")}}.</em></p> + +<dl> + <dt>{{domxref("EventSource.readyState")}} {{readonlyinline}}</dt> + <dd>Un número representando el estado de la conexión. Los valores posibles son CONECTANDO (<code>0</code>), ABIERTO (<code>1</code>), o CERRADO (<code>2</code>).</dd> + <dt>{{domxref("EventSource.url")}} {{readonlyinline}}</dt> + <dd>Un valor {{domxref("DOMString")}} representando la URL de la fuente.</dd> + <dt>{{domxref("EventSource.withCredentials")}} {{readonlyinline}}</dt> + <dd>Un valor {{domxref("Boolean")}} indicando si el objecto <code>EventSource</code> ha sido instanciado con credeciales CORS disponibles (true) o no (false, valor por defecto).</dd> +</dl> + +<h3 id="Manejadores_de_Eventos">Manejadores de Eventos</h3> + +<dl> + <dt>{{domxref("EventSource.onerror")}}</dt> + <dd>En un {{domxref("EventHandler")}} que se invoca cuando ocurre un error y se envía el evento {{event("error")}} a través del objeto <code>EventSource</code>.</dd> + <dt>{{domxref("EventSource.onmessage")}}</dt> + <dd>Es un {{domxref("EventHandler")}} que se invoca cuando se recibe un evento {{event("message")}}, que indica que se ha enviado un mensaje desde la fuente.</dd> + <dt>{{domxref("EventSource.onopen")}}</dt> + <dd>Es un {{domxref("EventHandler")}} que se invoca cuando se recibe un evento {{event("open")}}, que sucede en el momento que la conexión se abre.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<p><em>Esta interfaz también heredará métodos de su antecesor, {{domxref("EventTarget")}}.</em></p> + +<dl> + <dt>{{domxref("EventSource.close()")}}</dt> + <dd>Cierra la conexión, si ésta existe, y asigna el valor CLOSED al atributo <code>readyState</code>. Si la conexión ya estaba cerrada, este método no hace nada.</dd> +</dl> + +<h2 id="Ejemplos">Ejemplos</h2> + +<pre class="brush: js">var evtSource = new EventSource('sse.php'); +var eventList = document.querySelector('ul'); + +evtSource.onmessage = function(e) { + var newElement = document.createElement("li"); + + newElement.textContent = "message: " + e.data; + eventList.appendChild(newElement); +}</pre> + +<div class="note"> +<p><strong>Nota</strong>: Está disponible un ejemplo completo en GitHub — ver <a href="https://github.com/mdn/dom-examples/tree/master/server-sent-events">Simple SSE demo using PHP.</a></p> +</div> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', "comms.html#the-eventsource-interface", "EventSource")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<ul> +</ul> + +<h2 id="Compatibilidad_de_navegadoresEdit">Compatibilidad de navegadores<a class="button section-edit only-icon" href="https://developer.mozilla.org/es/docs/Web/API/Blob$edit#Browser_compatibility" rel="nofollow, noindex"><span>Edit</span></a></h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte EventSource</td> + <td>6</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop("6.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>5</td> + </tr> + <tr> + <td>Disponible en workers compartidos y dedicados<sup>[1]</sup></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop("53.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Características</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte EventSource</td> + <td>4.4</td> + <td>45</td> + <td>{{CompatNo}}</td> + <td>12</td> + <td>4.1</td> + </tr> + <tr> + <td>Disponible en workers compartidos y dedicados<sup>[1]</sup></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("53.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Pero <a href="https://github.com/w3c/ServiceWorker/issues/947">todavía no disponible en service workers</a>.</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events" title="en/Server-sent events/Using server-sent events">Using server-sent events</a></li> +</ul> diff --git a/files/es/web/api/eventsource/onopen/index.html b/files/es/web/api/eventsource/onopen/index.html new file mode 100644 index 0000000000..109962298c --- /dev/null +++ b/files/es/web/api/eventsource/onopen/index.html @@ -0,0 +1,127 @@ +--- +title: EventSource.onopen +slug: Web/API/EventSource/onopen +translation_of: Web/API/EventSource/onopen +--- +<div>{{APIRef('WebSockets API')}}</div> + +<p>La propiedad <code><strong>onopen</strong></code> de la interfaz {{domxref("EventSource")}} es un {{domxref("EventHandler")}} llamado cuando un evento {{event("open")}} es recibido, esto pasa cuando la conexión fue solo abierta.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox">eventSource.onopen = function</pre> + +<h2 id="Ejemplos">Ejemplos</h2> + +<pre class="brush: js">evtSource.onopen = function() { + console.log("Connection to server opened."); +};</pre> + +<div class="note"> +<p><strong>Nota</strong>: Tu puedes encontrar un ejemplo completo en GitHub — ve <a href="https://github.com/mdn/dom-examples/tree/master/server-sent-events">Simple SSE demo using PHP.</a></p> +</div> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', "comms.html#handler-eventsource-onopen", "onopen")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<ul> +</ul> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Caracteristica</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>EventSource support</td> + <td>6</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop("6.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>5</td> + </tr> + <tr> + <td>Available in shared and dedicated workers<sup>[1]</sup></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop("53.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th> + <table class="compat-table"> + <tbody> + <tr> + <th>Caracteristica</th> + </tr> + </tbody> + </table> + </th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>EventSource support</td> + <td>4.4</td> + <td>45</td> + <td>{{CompatNo}}</td> + <td>12</td> + <td>4.1</td> + </tr> + <tr> + <td>Available in shared and dedicated workers<sup>[1]</sup></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("53.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] But <a href="https://github.com/w3c/ServiceWorker/issues/947">not service workers as yet</a>.</p> + +<h2 id="Mira_también">Mira también</h2> + +<ul> + <li>{{domxref("EventSource")}}</li> +</ul> diff --git a/files/es/web/api/eventtarget/addeventlistener/index.html b/files/es/web/api/eventtarget/addeventlistener/index.html new file mode 100644 index 0000000000..d5b3aa4aef --- /dev/null +++ b/files/es/web/api/eventtarget/addeventlistener/index.html @@ -0,0 +1,335 @@ +--- +title: element.addEventListener +slug: Web/API/EventTarget/addEventListener +translation_of: Web/API/EventTarget/addEventListener +--- +<p>{{apiref("DOM Events")}}</p> + +<h2 id="Summary" name="Summary">Resumen</h2> + +<p><code>addEventListener()</code> Registra un evento a un objeto en específico. El <a href="/en-US/docs/DOM/EventTarget" title="DOM/EventTarget">Objeto especifico</a> puede ser un simple <a href="/en-US/docs/DOM/element" title="DOM/element">elemento</a> en un archivo, el mismo <code><a href="/en-US/docs/DOM/document" title="DOM/document">documento</a></code> , una <code><a href="/en-US/docs/DOM/window" title="DOM/window">ventana</a></code> o un <code><a href="/en-US/docs/DOM/XMLHttpRequest" title="XMLHttpRequest">XMLHttpRequest</a></code>.</p> + +<p>Para registrar más de un eventListener, puedes llamar <code>addEventListener()</code> para el mismo elemento pero con diferentes tipos de eventos o parámetros de captura.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox notranslate"><code><em>target</em>.addEventListener(tipo, <em>listener</em>[, <em>useCapture</em>]); +<em>target</em>.addEventListener(tipo, <em>listener</em>[, <em>useCapture</em>, <em>wantsUntrusted </em>{{ Non-standard_inline() }}]); // Gecko/Mozilla only</code></pre> + +<dl> + <dt><code>tipo</code></dt> + <dd>Una cadena representando el <a class="internal" href="/en-US/docs/DOM/event.type" title="DOM/Event.type">tipo de evento</a> a escuchar.</dd> + <dt><code>listener</code></dt> + <dd>El objeto que recibe una notificación cuando un evento de el tipo especificado ocurre. Debe ser un objeto implementando la interfaz <a class="external" href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventListener"><code>EventListener</code></a> o solo una <a href="/en-US/docs/JavaScript/Guide/Functions" title="JavaScript/Guide/Functions">function</a> en JavaScript.</dd> + <dt><code>useCapture</code> {{ optional_inline() }}</dt> + <dd>Si es <code>true</code>, <code>useCapture</code> indica que el usuario desea iniciar la captura. Después de iniciar la captura, todos los eventos del tipo especificado serán lanzados al <code>listener</code> registrado antes de comenzar a ser controlados por algún <code>EventTarget</code> que esté por debajo en el arbol DOM del documento. + <div class="note"><strong>Note:</strong> For event listeners attached to the event target; the event is in the target phase, rather than capturing and bubbling phases. Events in the target phase will trigger all listeners on an element regardless of the <code>useCapture</code> parameter.</div> + + <div class="note"><strong>Note:</strong> <code>useCapture</code> became optional only in more recent versions of the major browsers; for example, it was not optional prior to Firefox 6. You should provide that parameter for broadest compatibility.</div> + </dd> +</dl> + +<dl> + <dt>wantsUntrusted {{Non-standard_inline}}</dt> + <dd>If <code>true</code>, the listener receives synthetic events dispatched by web content (the default is <code>false</code> for chrome and <code>true</code> for regular web pages). This parameter is only available in Gecko and is mainly useful for the code in add-ons and the browser itself. See <a href="https://developer.mozilla.org/en-US/docs/Code_snippets/Interaction_between_privileged_and_non-privileged_pages">Interaction between privileged and non-privileged pages</a> for an example.</dd> +</dl> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre class="brush: html notranslate"><!DOCTYPE html> +<html> +<head> +<title>DOM Event Example</title> + +<style> +#t { border: 1px solid red } +#t1 { background-color: pink; } +</style> + +<script> +// Function to change the content of t2 +function modifyText() { + var t2 = document.getElementById("t2"); + t2.firstChild.nodeValue = "three"; +} + +// Function to add event listener to t +function load() { + var el = document.getElementById("t"); + el.addEventListener("click", modifyText, false); +} + +document.addEventListener("DOMContentLoaded", load, false); +</script> + +</head> +<body> + +<table id="t"> + <tr><td id="t1">one</td></tr> + <tr><td id="t2">two</td></tr> +</table> + +</body> +</html> +</pre> + +<p><a href="https://jsfiddle.net/madBYK/UumUP">Ver en el JSFiddle</a></p> + +<p>En el ejemplo anterior , <code>modifyText()</code> es una listener para los eventos <code style="font-style: normal; line-height: 1.5;">click</code><span style="line-height: 1.5;"> registrados utilzando</span><span style="line-height: 1.5;"> </span><code style="font-style: normal; line-height: 1.5;">addEventListener()</code><span style="line-height: 1.5;">. Un click en cualquier parte de la tabla notificara al handler y ejecutara la función </span><code style="font-style: normal; line-height: 1.5;">modifyText()</code><span style="line-height: 1.5;">.</span></p> + +<p>Si quieres pasar parámetros a la función del listener, debes utilizar funciones anónimas.</p> + +<pre class="brush: html notranslate"><!DOCTYPE html> +<html> +<head> +<title>DOM Event Example</title> + +<style> +#t { border: 1px solid red } +#t1 { background-color: pink; } +</style> + +<script> + +// Function to change the content of t2 +function modifyText(new_text) { + var t2 = document.getElementById("t2"); + t2.firstChild.nodeValue = new_text; +} + +// Function to add event listener to t +function load() { + var el = document.getElementById("t"); + el.addEventListener("click", function(){modifyText("four")}, false); +} +</script> + +</head> +<body onload="load();"> + +<table id="t"> + <tr><td id="t1">one</td></tr> + <tr><td id="t2">two</td></tr> +</table> + +</body> +</html> +</pre> + +<h2 id="Notas">Notas</h2> + +<h3 id="Why_use_addEventListener.3F" name="Why_use_addEventListener.3F">¿Porqué utilizar <code>addEventListener</code>?</h3> + +<p><code>addEventListener</code> es la forma de registrar un listener de eventos, como se especifica en W3C DOM. Sus beneficios son los siguientes:</p> + +<ul> + <li>Permite agregar mas de un listener a un solo evento. Esto es particularmente útil para las librerias <a href="/en-US/docs/DHTML" title="DHTML">DHTML</a> o las <a href="/en-US/docs/Extensions" title="Extensions">Extensiones de Mozilla</a> que deben funcionar bien, incluso si se utilizan otras librerias/extensiones.</li> + <li>Da un control mas detallado de la fase en la que el listener se activa (capturing vs. bubbling)</li> + <li>Funciona en cualquier elemento del DOM, no únicamente con elementos de HTML.</li> +</ul> + +<p>La alternativa, <a href="#Older_way_to_register_event_listeners">Antigua forma de registrar event listeners</a> es descrita a continuación.</p> + +<h3 id="Adding_a_listener_during_event_dispatch" name="Adding_a_listener_during_event_dispatch">Adding a listener during event dispatch</h3> + +<p>If an <code>EventListener</code> is added to an <code>EventTarget</code> while it is processing an event, it will not be triggered by the current actions but may be triggered during a later stage of event flow, such as the bubbling phase.</p> + +<h3 id="Multiple_identical_event_listeners" name="Multiple_identical_event_listeners">Multiple identical event listeners</h3> + +<p>If multiple identical <code>EventListener</code>s are registered on the same <code>EventTarget</code> with the same parameters, the duplicate instances are discarded. They do not cause the <code>EventListener</code> to be called twice, and since the duplicates are discarded, they do not need to be removed manually with the <a href="/en-US/docs/Web/API/EventTarget/removeEventListener" title="DOM/element.removeEventListener">removeEventListener</a> method.</p> + +<h3 id="The_value_of_this_within_the_handler" name="The_value_of_this_within_the_handler">The value of <code>this</code> within the handler</h3> + +<p>It is often desirable to reference the element from which the event handler was fired, such as when using a generic handler for a series of similar elements. When attaching a function using <code>addEventListener()</code> the value of <code>this</code> is changed—note that the value of <code>this</code> is passed to a function from the caller.</p> + +<p>In the example above, the value of <code>this</code> within <code>modifyText()</code> when called from the click event is a reference to the table 't'. This is in contrast to the behavior that occurs if the handler is added in the HTML source:</p> + +<pre class="brush: html notranslate"><table id="t" onclick="modifyText();"> + . . . +</pre> + +<p>The value of <code>this</code> within <code>modifyText()</code> when called from the onclick event will be a reference to the global (window) object.</p> + +<div class="note"><strong>Note:</strong> JavaScript 1.8.5 introduces the <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind" title="JavaScript/Reference/Global Objects/Function/bind">Function.prototype.bind()</a></code> method, which lets you specify the value that should be used as <code>this</code> for all calls to a given function. This lets you easily bypass problems where it's unclear what this will be, depending on the context from which your function was called. Note, however, that you'll need to keep a reference to the listener around so you can later remove it.</div> + +<p>This is an example with and without <code>bind</code>:</p> + +<pre class="brush: js notranslate">var Something = function(element) +{ + this.name = 'Something Good'; + this.onclick1 = function(event) { + console.log(this.name); // undefined, as this is the element + }; + this.onclick2 = function(event) { + console.log(this.name); // 'Something Good', as this is the binded Something object + }; + element.addEventListener('click', this.onclick1, false); + element.addEventListener('click', this.onclick2.bind(this), false); // Trick +} +</pre> + +<p>A problem in the example above is that you cannot remove the listener with <code>bind</code>. Another solution is using a special function called <code>handleEvent</code> to catch any events:</p> + +<pre class="brush: js notranslate">var Something = function(element) +{ + this.name = 'Something Good'; + this.handleEvent = function(event) { + console.log(this.name); // 'Something Good', as this is the Something object + switch(event.type) { + case 'click': + // some code here... + break; + case 'dblclick': + // some code here... + break; + } + }; + + // Note that the listeners in this case are this, not this.handleEvent + element.addEventListener('click', this, false); + element.addEventListener('dblclick', this, false); + + // You can properly remove the listners + element.removeEventListener('click', this, false); + element.removeEventListener('dblclick', this, false); +} +</pre> + +<h3 id="Compatibility" name="Compatibility">Legacy Internet Explorer and attachEvent</h3> + +<p>In Internet Explorer versions prior to IE 9, you have to use <code><a class="external" href="http://msdn.microsoft.com/en-us/library/ms536343(VS.85).aspx">attachEvent</a></code> rather than the standard <code>addEventListener</code>. To support IE, the example above can be modified to:</p> + +<pre class="brush: js notranslate">if (el.addEventListener) { + el.addEventListener('click', modifyText, false); +} else if (el.attachEvent) { + el.attachEvent('onclick', modifyText); +} +</pre> + +<p>There is a drawback to <code>attachEvent</code>, the value of <code>this</code> will be a reference to the <code>window</code> object instead of the element on which it was fired.</p> + +<h3 id="Older_way_to_register_event_listeners" name="Older_way_to_register_event_listeners">Older way to register event listeners</h3> + +<p><code>addEventListener()</code> was introduced with the DOM 2 <a class="external" href="http://www.w3.org/TR/DOM-Level-2-Events">Events</a> specification. Before then, event listeners were registered as follows:</p> + +<pre class="brush: js notranslate">// Pass a function reference — do not add '()' after it, which would call the function! +el.onclick = modifyText; + +// Using a function expression +element.onclick = function() { + // ... function logic ... +}; +</pre> + +<p>This method replaces the existing <code>click</code> event listener(s) on the element if there are any. Similarly for other events and associated event handlers such as <code>blur</code> (<code>onblur</code>), <code>keypress</code> (<code>onkeypress</code>), and so on.</p> + +<p>Because it was essentially part of DOM 0, this method is very widely supported and requires no special cross–browser code; hence it is normally used to register event listeners dynamically unless the extra features of <code>addEventListener()</code> are needed.</p> + +<h3 id="Memory_issues" name="Memory_issues">Memory issues</h3> + +<pre class="brush: js notranslate">var i; +var els = document.getElementsByTagName('*'); + +// Case 1 +for(i=0 ; i<els.length ; i++){ + els[i].addEventListener("click", function(e){/*do something*/}, false}); +} + +// Case 2 +function processEvent(e){ + /*do something*/ +} + +for(i=0 ; i<els.length ; i++){ + els[i].addEventListener("click", processEvent, false}); +} + +</pre> + +<p>In the first case, a new (anonymous) function is created at each loop turn. In the second case, the same previously declared function is used as an event handler. This results in smaller memory consumption. Moreover, in the first case, since no reference to the anonymous functions is kept, it is not possible to call <code><a href="/en-US/docs/Web/API/EventTarget/removeEventListener" title="DOM/element.removeEventListener">element.removeEventListener</a></code> because we do not have a reference to the handler, while in the second case, it's possible to do <code>myElement.removeEventListener("click", processEvent, false)</code>.</p> + +<h2 id="Browser_Compatibility" name="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 (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>1.0</td> + <td>{{ CompatGeckoDesktop(1.0) }}</td> + <td>9.0</td> + <td>7</td> + <td>1.0</td> + </tr> + <tr> + <td><code>useCapture</code> made optional</td> + <td>1.0</td> + <td>6.0</td> + <td>9.0</td> + <td>11.60</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>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>1.0</td> + <td>{{ CompatGeckoMobile(1.0) }}</td> + <td>9.0</td> + <td>6.0</td> + <td>1.0</td> + </tr> + </tbody> +</table> +</div> + +<h4 id="Gecko_notes">Gecko notes</h4> + +<ul> + <li>Prior to Firefox 6, the browser would throw if the <code>useCapture</code> parameter was not explicitly <code>false</code>. Prior to Gecko 9.0 {{ geckoRelease("9.0") }}, <code>addEventListener()</code> would throw an exception if the <code>listener</code> parameter was <code>null</code>; now the method returns without error, but without doing anything.</li> +</ul> + +<h4 id="WebKit_notes">WebKit notes</h4> + +<ul> + <li>Although WebKit has explicitly added <code>[optional]</code> to the <code>useCapture</code> parameter <a class="external" href="http://trac.webkit.org/changeset/89781">as recently as June 2011</a>, it had been working before the change. The new change landed in Safari 5.1 and Chrome 13.</li> +</ul> + +<h2 id="Specification" name="Specification">See Also</h2> + +<ul> + <li><a href="/en-US/docs/DOM/element.removeEventListener" title="DOM/element.removeEventListener">element.removeEventListener()</a></li> + <li><a href="/en-US/docs/DOM/Creating_and_triggering_events" title="DOM/Creating_and_triggering_custom_events">Creating and triggering custom events</a></li> + <li><a class="external" href="http://www.quirksmode.org/js/this.html" title="http://www.quirksmode.org/js/this.html">More details on the use of <code>this</code> in event handlers</a></li> +</ul> + +<h2 id="Specification" name="Specification">Specification</h2> + +<ul> + <li><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventTarget-addEventListener" title="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventTarget-addEventListener">DOM Level 2 Events: EventTarget.addEventListener</a></li> + <li><a class="external" href="http://dev.w3.org/2006/webapi/DOM-Level-3-Events/html/DOM3-Events.html#events-EventTarget-addEventListener" title="http://dev.w3.org/2006/webapi/DOM-Level-3-Events/html/DOM3-Events.html#events-EventTarget-addEventListener">DOM Level 3 Events: EventTarget.addEventListener</a></li> +</ul> diff --git a/files/es/web/api/eventtarget/dispatchevent/index.html b/files/es/web/api/eventtarget/dispatchevent/index.html new file mode 100644 index 0000000000..22a15ca8b5 --- /dev/null +++ b/files/es/web/api/eventtarget/dispatchevent/index.html @@ -0,0 +1,35 @@ +--- +title: element.dispatchEvent +slug: Web/API/EventTarget/dispatchEvent +tags: + - Referencia_DOM_de_Gecko +translation_of: Web/API/EventTarget/dispatchEvent +--- +<p>{{ ApiRef("DOM Events")}}</p> + +<h3 id="Resumen" name="Resumen">Resumen</h3> + +<p>Lanza un evento en el sistema de eventos. El evento está sujeto al mismo comportamiento y capacidades que si fuera un evento de lanzamiento directo.</p> + +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> + +<pre class="eval"><em>bool</em> = <em>element</em>.dispatchEvent(<em>event</em>) +</pre> + +<ul> + <li><code>element</code> es el objetivo (<code>target</code> en Inglés) del evento.</li> + <li><code>event</code> es un objeto de tipo <a href="es/DOM/event">event</a> que será lanzado.</li> + <li>El valor devuelto es <code>false</code>, si al menos uno de los negociadores (en Inglés:<em>handler</em> ) que manejan el evento es <a href="es/DOM/event.preventDefault">preventDefault</a>. En caso contrario, devuelve <code>true</code>.</li> +</ul> + +<h3 id="Notas" name="Notas">Notas</h3> + +<p>Como se ve en el ejemplo anterior, <code>dispatchEvent</code> es el último paso en el proceso crear-inicializar-lanzar, que se usa para el lanzamiento manual de eventos en el modelo de implementación de eventos.</p> + +<p>El evento puede ser creado mediante el método <a href="es/DOM/document.createEvent">document.createEvent</a> e inicializado usando <a href="es/DOM/event.initEvent">initEvent</a> u otro método, más específicamente, métodos de inicialización como <a href="es/DOM/event.initMouseEvent">initMouseEvent</a> o <a href="es/DOM/event.initUIEvent">initUIEvent</a>.</p> + +<p>Ver también <a href="es/DOM/event">Event object reference</a>.</p> + +<h3 id="Especificaci.C3.B3n" name="Especificaci.C3.B3n">Especificación</h3> + +<p><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventTarget-dispatchEvent">DOM Level 2 Events: dispatchEvent</a></p> diff --git a/files/es/web/api/eventtarget/index.html b/files/es/web/api/eventtarget/index.html new file mode 100644 index 0000000000..f263590861 --- /dev/null +++ b/files/es/web/api/eventtarget/index.html @@ -0,0 +1,119 @@ +--- +title: EventTarget +slug: Web/API/EventTarget +tags: + - API +translation_of: Web/API/EventTarget +--- +<p>{{ ApiRef("DOM Events") }}</p> + +<p><code>EventTarget</code> es una interfaz implementada por los objetos que pueden administrar eventos y sus escuchadores.</p> + +<p>{{domxref("Element")}}, {{domxref("document")}}, y {{domxref("window")}} son los objetivos más comunes de un evento, pero otros objetos pueden serlo también, por ejemplo {{domxref("XMLHttpRequest")}}, {{domxref("AudioNode")}}, {{domxref("AudioContext")}}, entre otros.</p> + +<p>Muchos objetivos de eventos tales como: elementos, documentos y ventanas, también admiten la configuración de controladores de eventos a través de propiedades y atributos.</p> + +<h2 id="Methods" name="Methods">Métodos</h2> + +<dl> + <dt>{{domxref("EventTarget.addEventListener()")}}</dt> + <dd>Registre un controlador de eventos de un tipo de evento específico en EventTarget.</dd> + <dt>{{domxref("EventTarget.removeEventListener()")}}</dt> + <dd>Elimina un detector de eventos del EventTarget.</dd> + <dt>{{domxref("EventTarget.dispatchEvent()")}}</dt> + <dd>Enviar un evento a este EventTarget.</dd> +</dl> + +<h2 id="Specification" name="Specification">Especificaciones</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('DOM WHATWG', '#interface-eventtarget', 'EventTarget')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>No change.</td> + </tr> + <tr> + <td>{{SpecName('DOM3 Events', 'DOM3-Events.html#interface-EventTarget', 'EventTarget')}}</td> + <td>{{Spec2('DOM3 Events')}}</td> + <td>A few parameters are now optional (<code>listener</code>), or accepts the <code>null</code> value (<code>useCapture</code>).</td> + </tr> + <tr> + <td>{{SpecName('DOM2 Events', 'events.html#Events-EventTarget', 'EventTarget')}}</td> + <td>{{Spec2('DOM2 Events')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_Compatibility" name="Browser_Compatibility">Compatibilidad</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 (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>1.0</td> + <td>{{ CompatGeckoDesktop("1") }}</td> + <td>9.0</td> + <td>7</td> + <td>1.0</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>1.0</td> + <td>{{ CompatGeckoMobile("1") }}</td> + <td>9.0</td> + <td>6.0</td> + <td>1.0</td> + </tr> + </tbody> +</table> +</div> + +<h3 id="Additional_methods_for_Mozilla_chrome_code">Additional methods for Mozilla chrome code</h3> + +<p>Mozilla extensions for use by JS-implemented event targets to implement on* properties. See also <a href="/en-US/docs/Mozilla/WebIDL_bindings" title="/en-US/docs/Mozilla/WebIDL_bindings">WebIDL bindings</a>.</p> + +<ul> + <li>void <strong>setEventHandler</strong>(DOMString type, EventHandler handler) {{ non-standard_inline() }}</li> + <li>EventHandler <strong>getEventHandler</strong>(DOMString type) {{ non-standard_inline() }}</li> +</ul> + +<h2 id="Vea_también">Vea también</h2> + +<ul> + <li><a href="/en-US/docs/Web/Reference/Events" title="/en-US/docs/Web/Reference/Events">Event reference</a> - Los eventos disponibles en la plataforma</li> + <li><a href="/en-US/docs/Web/Guide/DOM/Events" title="/en-US/docs/Web/Guide/DOM/Events">Event developer guide</a> - Guía sobre eventos para desarrolladores</li> + <li>{{domxref("Event")}} - Interface</li> +</ul> diff --git a/files/es/web/api/eventtarget/removeeventlistener/index.html b/files/es/web/api/eventtarget/removeeventlistener/index.html new file mode 100644 index 0000000000..1b022bbe50 --- /dev/null +++ b/files/es/web/api/eventtarget/removeeventlistener/index.html @@ -0,0 +1,217 @@ +--- +title: EventTarget.removeEventListener() +slug: Web/API/EventTarget/removeEventListener +tags: + - API + - DOM + - Event +translation_of: Web/API/EventTarget/removeEventListener +--- +<p>{{APIRef("DOM Events")}}</p> + +<p>El método <strong><code>EventTarget.removeEventListener()</code></strong> remueve del {{domxref("EventTarget")}} un detector de evento previamente registrado con {{domxref("EventTarget.addEventListener")}}. El detector de evento a ser removido es identificado usando una combinación de de tipos de eventos, la misma funcion del detector de eventos, y muchas opciones adicionales que pueden afectar</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox"><var>target</var>.removeEventListener(<var>type</var>, <var>listener</var>[, <var>options</var>]); +<em>target</em>.removeEventListener(<em>tipo</em>, <em>listener</em>[, <em>useCapture</em>])</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><var>tipo</var></dt> + <dd>Un string representando el tipo de evento del que se está removiendo un detector de evento.</dd> + <dt><var>detector (listener)</var></dt> + <dd>La función {{domxref("EventListener")}} del manejador de evento a eliminar del objetivo del evento.</dd> + <dt><var>options</var> {{optional_inline}}</dt> + <dd>Un objeto que especifíca diversas características acerca del detector de eventos. Las opciones disponibles son: + <ul> + <li><code>capture</code>: Un {{jsxref("Boolean")}} que indica que eventos de este tipo serán enviados al <code>listener</code> antes de ser enviado a cualquier <code>EventTarget</code> debado de éste en el DOM.</li> + <li>{{non-standard_inline}}<code> mozSystemGroup</code>: Sólo disponible ejecutando XBL o Firefox' chrome, es un {{jsxref("Boolean")}} que define si el detector es añadido al grupo del sistema.</li> + </ul> + </dd> + <dt><code>useCapture</code> {{optional_inline}}</dt> + <dd>Especifíca si el {{domxref("EventListener")}} que se está eliminando fue registrado como un detector de captura o no. Si no se indica, por defecto <code>useCapture</code> asumirá el valor <code>false</code>.</dd> + <dd>Si un detector se registro dos veces, uno con captura y otro sin, cada uno debe ser eliminado por separado. La eliminación de un detector de captura no afecta a una versión de "no-captura" del mismo detector, y viceversa.</dd> +</dl> + +<h3 id="Valor_de_retorno">Valor de retorno</h3> + +<p><code>undefined</code>.</p> + +<h3 id="Coincidiendo_disparadores_de_evento_para_su_eliminación">Coincidiendo disparadores de evento para su eliminación</h3> + +<p>Habiendose añadido detector de evento llamando {{domxref("EventTarget.addEventListener", "addEventListener()")}}, puede llegar un punto donde se requiera eliminar. Obviamente, se necesita especificar los mismos parámetros de <code>tipo</code> y <code>listener</code> a <code>removeEventListener()</code>, pero que hay acerca de los parámetros de <code>options</code> o de <code>useCapture</code>?</p> + +<p>Mientras <code>addEventListener()</code> permite añadir el mismo detector más de una vez para el mismo tipo, si la opción es diferente, la única opción que <code>removeEventListener()</code> revisará es la bandera de <code>capture</code>/<code>useCapture</code>. Su valor debe coincidir con <code>removeEventListener()</code> para coincidir, pero otros valores no necesitan corresponder.</p> + +<p>Por ejemplo, considerar la siguiente llamada a <code>addEventListener()</code>:</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js">element<span class="punctuation token">.</span><span class="function token">addEventListener</span><span class="punctuation token">(</span><span class="string token">"mousedown"</span><span class="punctuation token">,</span> handleMouseDown<span class="punctuation token">,</span> <span class="boolean token">true</span><span class="punctuation token">)</span><span class="punctuation token">;</span></code></pre> + +<p>Ahora, considera <code>removeEventListener()</code>:</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js">element<span class="punctuation token">.</span><span class="function token">removeEventListener</span><span class="punctuation token">(</span><span class="string token">"mousedown"</span><span class="punctuation token">,</span> handleMouseDown<span class="punctuation token">,</span> <span class="boolean token">false</span><span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// Fallo</span> +element<span class="punctuation token">.</span><span class="function token">removeEventListener</span><span class="punctuation token">(</span><span class="string token">"mousedown"</span><span class="punctuation token">,</span> handleMouseDown<span class="punctuation token">,</span> <span class="boolean token">true</span><span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// Éxito</span></code></pre> + +<p>La primera llamada falla porque el valor de <code>useCapture</code> no coincide. El segundo valor funciona, puesto que <code>useCapture</code> es igual a su valor cuando se añadió el detector.</p> + +<p>Ahora considera lo siguiente:</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js">element<span class="punctuation token">.</span><span class="function token">addEventListener</span><span class="punctuation token">(</span><span class="string token">"mousedown"</span><span class="punctuation token">,</span> handleMouseDown<span class="punctuation token">,</span> <span class="punctuation token">{</span> passive<span class="punctuation token">:</span> <span class="boolean token">true</span> <span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span></code></pre> + +<p>Aqui, especificamos un objeto <code>options</code> en el cual <code>passive</code> esta definido como <code>true</code>, mientras que otras opciones son dejados con su valor por defecto de <code>false</code>.</p> + +<p>Vea consecutivamente, cada una de las siguientes llamadas a <code>removeEventListener()</code>. Cualquiera de éstas donde <code>capture</code> o <code>useCapture</code> es <code>true</code> falla; en todas las demás funciona. Solo la configuración <code>capture</code> importa a <code>removeEventListener()</code>.</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js">element<span class="punctuation token">.</span><span class="function token">removeEventListener</span><span class="punctuation token">(</span><span class="string token">"mousedown"</span><span class="punctuation token">,</span> handleMouseDown<span class="punctuation token">,</span> <span class="punctuation token">{</span> passive<span class="punctuation token">:</span> <span class="boolean token">true</span> <span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// Funciona</span> +element<span class="punctuation token">.</span><span class="function token">removeEventListener</span><span class="punctuation token">(</span><span class="string token">"mousedown"</span><span class="punctuation token">,</span> handleMouseDown<span class="punctuation token">,</span> <span class="punctuation token">{</span> capture<span class="punctuation token">:</span> <span class="boolean token">false</span> <span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// Funciona</span> +element<span class="punctuation token">.</span><span class="function token">removeEventListener</span><span class="punctuation token">(</span><span class="string token">"mousedown"</span><span class="punctuation token">,</span> handleMouseDown<span class="punctuation token">,</span> <span class="punctuation token">{</span> capture<span class="punctuation token">:</span> <span class="boolean token">true</span> <span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// Falla</span> +element<span class="punctuation token">.</span><span class="function token">removeEventListener</span><span class="punctuation token">(</span><span class="string token">"mousedown"</span><span class="punctuation token">,</span> handleMouseDown<span class="punctuation token">,</span> <span class="punctuation token">{</span> passive<span class="punctuation token">:</span> <span class="boolean token">false</span> <span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// Funciona</span> +element<span class="punctuation token">.</span><span class="function token">removeEventListener</span><span class="punctuation token">(</span><span class="string token">"mousedown"</span><span class="punctuation token">,</span> handleMouseDown<span class="punctuation token">,</span> <span class="boolean token">false</span><span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// Funciona</span> +element<span class="punctuation token">.</span><span class="function token">removeEventListener</span><span class="punctuation token">(</span><span class="string token">"mousedown"</span><span class="punctuation token">,</span> handleMouseDown<span class="punctuation token">,</span> <span class="boolean token">true</span><span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// Falla</span></code></pre> + +<p>Vale la pena mencionar que algunos navegadores tienen un comportamiento inconsistente, y a menos que se tengan razones específicas, es probablemente una buena idea usar los mismos valores usados por la llamada a <code>addEventListener()</code> al momento de utilizar <code>removeEventListener()</code>.</p> + +<h2 id="Notas">Notas</h2> + +<p>Si un {{ domxref("EventListener") }} es removido de un {{ domxref("EventTarget") }} cuando aún se está procesando el evento, no será ejecutado. Después de ser removido, un {{ domxref("EventListener") }} no será invocado por el evento al cual se registró, sin embargo se podrá adjuntar de nuevo a dicho evento.</p> + +<p>Llamar {{ domxref("<code>removeEventListener</code>") }} en algún {{ domxref("EventTarget") }} que no contenga el {{ domxref("EventListener") }} especificado será un acción sin efecto, es decir, se podrá llamar {{ domxref("<code>removeEventListener</code>") }} sin efectos negativos en los scripts.</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>Este es un ejemplo en donde se agrega y después se elimina un {{ domxref("EventListener") }} </p> + +<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="keyword token">var</span> body <span class="operator token">=</span> document<span class="punctuation token">.</span><span class="function token">querySelector</span><span class="punctuation token">(</span><span class="string token">'body'</span><span class="punctuation token">)</span><span class="punctuation token">,</span> + clickTarget <span class="operator token">=</span> document<span class="punctuation token">.</span><span class="function token">getElementById</span><span class="punctuation token">(</span><span class="string token">'click-target'</span><span class="punctuation token">)</span><span class="punctuation token">,</span> + mouseOverTarget <span class="operator token">=</span> document<span class="punctuation token">.</span><span class="function token">getElementById</span><span class="punctuation token">(</span><span class="string token">'mouse-over-target'</span><span class="punctuation token">)</span><span class="punctuation token">,</span> + toggle <span class="operator token">=</span> <span class="boolean token">false</span><span class="punctuation token">;</span> + +<span class="keyword token">function</span> <span class="function token">makeBackgroundYellow</span><span class="punctuation token">(</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="string token">'use strict'</span><span class="punctuation token">;</span> + + <span class="keyword token">if</span> <span class="punctuation token">(</span>toggle<span class="punctuation token">)</span> <span class="punctuation token">{</span> + body<span class="punctuation token">.</span>style<span class="punctuation token">.</span>backgroundColor <span class="operator token">=</span> <span class="string token">'white'</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span> <span class="keyword token">else</span> <span class="punctuation token">{</span> + body<span class="punctuation token">.</span>style<span class="punctuation token">.</span>backgroundColor <span class="operator token">=</span> <span class="string token">'yellow'</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span> + + toggle <span class="operator token">=</span> <span class="operator token">!</span>toggle<span class="punctuation token">;</span> +<span class="punctuation token">}</span> + +clickTarget<span class="punctuation token">.</span><span class="function token">addEventListener</span><span class="punctuation token">(</span><span class="string token">'click'</span><span class="punctuation token">,</span> + makeBackgroundYellow<span class="punctuation token">,</span> + <span class="boolean token">false</span> +<span class="punctuation token">)</span><span class="punctuation token">;</span> + +mouseOverTarget<span class="punctuation token">.</span><span class="function token">addEventListener</span><span class="punctuation token">(</span><span class="string token">'mouseover'</span><span class="punctuation token">,</span> <span class="keyword token">function</span> <span class="punctuation token">(</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="string token">'use strict'</span><span class="punctuation token">;</span> + + clickTarget<span class="punctuation token">.</span><span class="function token">removeEventListener</span><span class="punctuation token">(</span><span class="string token">'click'</span><span class="punctuation token">,</span> + makeBackgroundYellow<span class="punctuation token">,</span> + <span class="boolean token">false</span> + <span class="punctuation token">)</span><span class="punctuation token">;</span> +<span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span></code></pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <thead> + <tr> + <th>Especificación</th> + <th>Estado</th> + <th>Comentario</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("DOM WHATWG", "#dom-eventtarget-removeeventlistener", "EventTarget.removeEventListener()")}}</td> + <td>{{Spec2("DOM WHATWG")}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName("DOM4", "#dom-eventtarget-removeeventlistener", "EventTarget.removeEventListener()")}}</td> + <td>{{Spec2("DOM4")}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName("DOM2 Events", "#Events-EventTarget-removeEventListener", "EventTarget.removeEventListener()")}}</td> + <td>{{Spec2("DOM2 Events")}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_Compatibility" name="Browser_Compatibility">Compatibilidad de los navegadores</h2> + + + +<p>{{Compat("api.EventTarget.removeEventListener", 3)}}</p> + +<ul> +</ul> + +<h2 id="Polyfill_to_support_older_browsers">Polyfill to support older browsers</h2> + +<p><code>addEventListener()</code> and <code>removeEventListener()</code> are not present in older browsers. You can work around this by inserting the following code at the beginning of your scripts, allowing use of <code>addEventListener()</code> and <code>removeEventListener()</code> in implementations which do not natively support it. However, this method will not work on Internet Explorer 7 or earlier, since extending the Element.prototype was not supported until Internet Explorer 8.</p> + +<pre class="brush: js">if (!Element.prototype.addEventListener) { + var oListeners = {}; + function runListeners(oEvent) { + if (!oEvent) { oEvent = window.event; } + for (var iLstId = 0, iElId = 0, oEvtListeners = oListeners[oEvent.type]; iElId < oEvtListeners.aEls.length; iElId++) { + if (oEvtListeners.aEls[iElId] === this) { + for (iLstId; iLstId < oEvtListeners.aEvts[iElId].length; iLstId++) { oEvtListeners.aEvts[iElId][iLstId].call(this, oEvent); } + break; + } + } + } + Element.prototype.addEventListener = function (sEventType, fListener /*, useCapture (will be ignored!) */) { + if (oListeners.hasOwnProperty(sEventType)) { + var oEvtListeners = oListeners[sEventType]; + for (var nElIdx = -1, iElId = 0; iElId < oEvtListeners.aEls.length; iElId++) { + if (oEvtListeners.aEls[iElId] === this) { nElIdx = iElId; break; } + } + if (nElIdx === -1) { + oEvtListeners.aEls.push(this); + oEvtListeners.aEvts.push([fListener]); + this["on" + sEventType] = runListeners; + } else { + var aElListeners = oEvtListeners.aEvts[nElIdx]; + if (this["on" + sEventType] !== runListeners) { + aElListeners.splice(0); + this["on" + sEventType] = runListeners; + } + for (var iLstId = 0; iLstId < aElListeners.length; iLstId++) { + if (aElListeners[iLstId] === fListener) { return; } + } + aElListeners.push(fListener); + } + } else { + oListeners[sEventType] = { aEls: [this], aEvts: [ [fListener] ] }; + this["on" + sEventType] = runListeners; + } + }; + Element.prototype.removeEventListener = function (sEventType, fListener /*, useCapture (will be ignored!) */) { + if (!oListeners.hasOwnProperty(sEventType)) { return; } + var oEvtListeners = oListeners[sEventType]; + for (var nElIdx = -1, iElId = 0; iElId < oEvtListeners.aEls.length; iElId++) { + if (oEvtListeners.aEls[iElId] === this) { nElIdx = iElId; break; } + } + if (nElIdx === -1) { return; } + for (var iLstId = 0, aElListeners = oEvtListeners.aEvts[nElIdx]; iLstId < aElListeners.length; iLstId++) { + if (aElListeners[iLstId] === fListener) { aElListeners.splice(iLstId, 1); } + } + }; +} +</pre> + +<h3 id="Example" name="Example"></h3> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{ domxref("EventTarget.addEventListener()") }}.</li> + <li>{{non-standard_inline}}{{domxref("EventTarget.detachEvent()")}}.</li> +</ul> diff --git a/files/es/web/api/fetch_api/conceptos_basicos/index.html b/files/es/web/api/fetch_api/conceptos_basicos/index.html new file mode 100644 index 0000000000..8c02021de6 --- /dev/null +++ b/files/es/web/api/fetch_api/conceptos_basicos/index.html @@ -0,0 +1,73 @@ +--- +title: Conceptos básicos de Fetch +slug: Web/API/Fetch_API/Conceptos_basicos +tags: + - API + - API Fetch + - Fetch + - conceptos + - guard + - request +translation_of: Web/API/Fetch_API/Basic_concepts +--- +<p>{{DefaultAPISidebar("Fetch API")}}{{draft}}</p> + +<div class="summary"> +<p>La <a href="/en-US/docs/Web/API/Fetch_API">API Fetch</a> proporciona una interfaz para obtener recursos (incluso a traves de la red). Parecera familiar a quien sea que haya usado {{domxref("XMLHttpRequest")}}, pero proporciona un conjunto de características más potentes y flexibles. Este artículo explica algunos de los conceptos básicos de la API Fetch.</p> +</div> + +<div class="note"> +<p>Este artículo será añadido en un futuro. Si encuenta un concepto de Fetch que siente necesita una mejor explicación, hagalo saber a alguien en el <a href="https://discourse.mozilla-community.org/c/mdn">foro de discusión de </a><a href="https://discourse.mozilla-community.org/c/mdn">MDN</a>, o <a href="https://wiki.mozilla.org/IRC">Mozilla IRC</a> (#mdn room.)</p> +</div> + +<h2 id="En_pocas_palabras">En pocas palabras</h2> + +<p>En el corazón de Fetch estan las abstracciones de interfaz de cargas de HTTP {{domxref("Request")}}s, {{domxref("Response")}}s, {{domxref("Headers")}}, y {{domxref("Body")}}, junto a un método {{domxref("GlobalFetch.fetch","global fetch")}} para inicializar peticiones de recurso asíncronos. Porque los prinipales componentes de HTTP son abstraídos como objetos Javascript, es sencillo para otras APIs el hacer uso de dicha funcionalidad.</p> + +<p><a href="/en-US/docs/Web/API/ServiceWorker_API">Service Workers</a> es un ejemplo de una API que hace un fuerte uso de Fetch.</p> + +<p>Fetch toma la naturaleza asíncrona de dichas peticiones un paso adelante. La API esta completamente basada en {{jsxref("Promise")}}.</p> + +<h2 id="Guard">Guard</h2> + +<p>Guard es una característica de objetos {{domxref("Headers")}}, con los valores posibles <code>immutable</code>, <code>request</code>, <code>request-no-cors</code>, <code>response</code>, o <code>none</code>, dependiendo de donde el encabezado es usado.</p> + +<p>Cuando un nuevo objeto {{domxref("Headers")}} es creado usando el {{domxref("Headers.Headers","Headers()")}} {{glossary("constructor")}}, su guarda (guard) se establece a <code>none</code> (por defecto). Cuando un objeto {{domxref("Request")}} o {{domxref("Response")}} es creado, tiene un objeto {{domxref("Headers")}} asociado cuyo guarda (guard) se establece como se resume a continuación:</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="row">nuevo tipo de objeto</th> + <th scope="col">creando el constructor</th> + <th scope="col">configuraciones de guarda (guard) del objeto {{domxref("Headers")}} asociado</th> + </tr> + </thead> + <tbody> + <tr> + <td rowspan="2">{{domxref("Request")}}</td> + <td>{{domxref("Request.Request","Request()")}}</td> + <td><code>request</code></td> + </tr> + <tr> + <td>{{domxref("Request.Request","Request()")}} con {{domxref("Request.mode","mode")}} de <code>no-cors</code></td> + <td><code>request-no-cors</code></td> + </tr> + <tr> + <td rowspan="2">{{domxref("Response")}}</td> + <td>{{domxref("Response.Response","Response()")}}</td> + <td><code>response</code></td> + </tr> + <tr> + <td>Métodos {{domxref("Response.error","error()")}} o {{domxref("Response.redirect","redirect()")}}</td> + <td><code>immutable</code></td> + </tr> + </tbody> +</table> + +<p>Un guarda (guard) de encabezado afecta los métodos {{domxref("Headers.set","set()")}}, {{domxref("Headers.delete","delete()")}}, y {{domxref("Headers.append","append()")}} que cambían los contenidos del encabezado. Un <code>TypeError</code> es arrojado si se trata modificar un objeto {{domxref("Headers")}} cuyo guarda (guard) es <code>immutable</code>. Sin embargo, la operación funcionará si</p> + +<ul> + <li>guard es <code title="">request</code> y el nombre del encabezado no es un {{Glossary("forbidden header name")}} .</li> + <li>guard es <code title="">request-no-cors</code> y el encabezado <var>nombre/valor</var> es un {{Glossary("simple header")}} .</li> + <li>guard es <code title="">response</code> y el <var>nombre </var>del encabezado no es {{Glossary("forbidden response header name")}}.</li> +</ul> diff --git a/files/es/web/api/fetch_api/index.html b/files/es/web/api/fetch_api/index.html new file mode 100644 index 0000000000..13c733a799 --- /dev/null +++ b/files/es/web/api/fetch_api/index.html @@ -0,0 +1,81 @@ +--- +title: Fetch API +slug: Web/API/Fetch_API +translation_of: Web/API/Fetch_API +--- +<p>{{DefaultAPISidebar("Fetch API")}}<br> + La API Fetch proporciona una interfaz para recuperar recursos (incluso a través de la red). Resultará familiar a cualquiera que haya usado {{domxref("XMLHttpRequest")}}, pero la nueva API ofrece un conjunto de características más potente y flexible.</p> + +<h2 id="Conceptos_y_uso">Conceptos y uso</h2> + +<p>Fetch ofrece una definición genérica de los objetos {{domxref("Request")}} y {{domxref("Response")}} (y otras cosas relacionadas con las solicitudes de red). Esto permitirá su uso donde sea necesario en un futuro, ya sea para operadores de servicios, API caché y otras cosas similares que manipulen o modifiquen las solicitudes y respuestas, o cualquier otro tipo de caso de uso que pudiera requerirle la generación de sus propias respuestas mediante programación.</p> + +<p>También proporciona una definición para conceptos relacionados, como CORS y la semántica de encabezado HTTP origen, suplantando sus definiciones separadas en otros lugares.</p> + +<p>Para hacer una solicitud y recuperar un recurso, utilice el método {{domxref("GlobalFetch.fetch")}}. Se implementa en múltiples interfaces, específicamente {{domxref("Window")}} y {{domxref("WorkerGlobalScope")}}. Esto hace que esté disponible en casi cualquier contexto donde quiera buscar recursos.</p> + +<p>El método <code>fetch()</code> toma un argumento obligatorio, la ruta de acceso al recurso que desea recuperar. Devuelve una {{domxref("Promise")}} que resuelve en {{domxref("Response")}} a esa petición, sea o no correcta. También puede pasar opcionalmente un objeto de opciones init como segundo argumento (ver {{domxref("Request")}}).</p> + +<p>Una vez que {{domxref("Response")}} es recuperada, hay varios métodos disponibles para definir cuál es el contenido del cuerpo y como se debe manejar (ver {{domxref("Body")}}).</p> + +<p>Puede crear una solicitud y respuesta directamente a con los constructores {{domxref("Request.Request","Request()")}} y {{domxref("Response.Response","Response()")}}, pero no es recomendable hacerlo directamente. En su lugar, es preferible que sean creados como resultado de otras acciones de la API (por ejemplo, {{domxref("FetchEvent.respondWith")}} desde los operadores de servicios).</p> + +<div class="note"> +<p><strong>Nota</strong>: Puede encontrar mas información sobre las características de la API Fetch en <a href="/en-US/docs/Web/API/Fetch_API/Using_Fetch">Usando Fetch</a>, y aprender los conceptos en <a href="/en-US/docs/Web/API/Fetch_API/Basic_concepts">Fetch: conceptos básicos</a>.</p> +</div> + +<h3 id="Abortar_una_petición">Abortar una petición</h3> + +<p>Los navegadores han empezado a añadir soporte experimental para las interfaces {{domxref("AbortController")}} y {{domxref("AbortSignal")}} (Conocidas también como La API Abort), las cuales permiten que operaciones como Fetch y XHR puedan ser abortadas si no han terminado todavía. Visita las páginas de las interfaces para más detalles.</p> + +<h2 id="Fetch_Interfaces_o_Métodos">Fetch Interfaces o Métodos</h2> + +<dl> + <dt>{{domxref("GlobalFetch")}}</dt> + <dd>Contiene el método <code>fetch()</code> utilizado para obtener o inicializar un recurso.</dd> + <dt>{{domxref("Headers")}}</dt> + <dd>Representa los encabezados de la respuesta/solicitud, lo que le permite consultar y tomar diferentes acciones en función de los resultados.</dd> + <dt>{{domxref("Request")}}</dt> + <dd>Representa una solicitud de recursos.</dd> + <dt>{{domxref("Response")}}</dt> + <dd>Representa la respuesta a una solicitud.</dd> +</dl> + +<h2 id="Fetch_mixin">Fetch mixin</h2> + +<dl> + <dt>{{domxref("Body")}}</dt> + <dd>Proporciona métodos relacionados con el contenido de la respuesta/solicitud, lo que le permite declarar cuál es su tipo y cómo debe manejarse.</dd> +</dl> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('Fetch')}}</td> + <td>{{Spec2('Fetch')}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2> + +<p>{{Compat("api.WindowOrWorkerGlobalScope.fetch")}}</p> + +<h2 id="Ver_también">Ver también</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> + <li><a href="https://github.com/github/fetch">Fetch polyfill</a></li> + <li><a href="/en-US/docs/Web/API/Fetch_API/Basic_concepts">Fetch basic concepts</a></li> + <li><a href="http://davidwalsh.name/fetch">Fetch API Examples</a></li> +</ul> diff --git a/files/es/web/api/fetch_api/utilizando_fetch/index.html b/files/es/web/api/fetch_api/utilizando_fetch/index.html new file mode 100644 index 0000000000..0f647a7e61 --- /dev/null +++ b/files/es/web/api/fetch_api/utilizando_fetch/index.html @@ -0,0 +1,377 @@ +--- +title: Uso de Fetch +slug: Web/API/Fetch_API/Utilizando_Fetch +tags: + - API + - BODY + - Experimental + - Fetch + - Guía + - HTTP + - Petición + - Promesa + - Promise + - Respuesta +translation_of: Web/API/Fetch_API/Using_Fetch +--- +<p>{{DefaultAPISidebar("Fetch API")}}{{ SeeCompatTable }}</p> + +<div class="summary"> +<p>La <a href="/en-US/docs/Web/API/Fetch_API">API Fetch</a> proporciona una interfaz JavaScript para acceder y manipular partes del canal HTTP, tales como peticiones y respuestas. También provee un método global {{domxref("GlobalFetch.fetch","fetch()")}} que proporciona una forma fácil y lógica de obtener recursos de forma asíncrona por la red.</p> +</div> + +<p>Este tipo de funcionalidad se conseguía previamente haciendo uso de {{domxref("XMLHttpRequest")}}. Fetch proporciona una alternativa mejor que puede ser empleada fácilmente por otras tecnologías como {{domxref("ServiceWorker_API", "Service Workers")}}. Fetch también aporta un único lugar lógico en el que definir otros conceptos relacionados con HTTP como CORS y extensiones para HTTP.</p> + +<p>La especificación fetch difiere de <code>JQuery.ajax()</code> en dos formas principales:</p> + +<ul> + <li> + <p>El objeto Promise devuelto desde <code>fetch()</code> <strong>no será rechazado con un estado de error HTTP</strong> incluso si la respuesta es un error HTTP 404 o 500. En cambio, este se resolverá normalmente (con un estado <code>ok</code> configurado a false), y este solo sera rechazado ante un fallo de red o si algo impidió completar la solicitud.</p> + </li> + <li>Por defecto, <code>fetch</code> no enviará ni recibirá cookies del servidor, resultando en peticiones no autenticadas si el sitio permite mantentener una sesión de usuario (para mandar cookies, <em>credentials</em> de la opción <a href="https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters">init</a> deberan ser configuradas). Desde <a href="https://github.com/whatwg/fetch/pull/585">el 25 de agosto de 2017</a>. La especificación cambió la politica por defecto de las credenciales a <code>same-origin</code>. Firefox cambió desde la versión 61.0b13.</li> +</ul> + +<p>Una petición básica de <code>fetch</code> es realmente simple de realizar. Eche un vistazo al siguente código:</p> + +<pre class="notranslate">fetch('http://example.com/movies.json') + .then(response => response.json()) + .then(data => console.log(data));</pre> + +<p>Aquí estamos recuperando un archivo JSON a través de red e impriminedo en la consola. El uso de <code>fetch()</code> más simple toma un argumento (la ruta del recurso que quieres buscas) y devuelve un objeto Promise conteniendo la respuesta, un objeto {{domxref("Response")}}.</p> + +<p>Esto es, por supuesto, una respuesta HTTP no el archivo JSON. Para extraer el contenido en el cuerpo del JSON desde la respuesta, usamos el método {{domxref("Body.json","json()")}} (definido en el <a href="https://es.wikipedia.org/wiki/Mixin">mixin</a> de {{domxref("Body")}}, el cual está implementado por los objetos {{domxref("Request")}} y {{domxref("Response")}}).</p> + +<div class="note"> +<p><strong>Nota</strong>: El mixin de <code>Body</code> tambien tiene metodos parecidos para extraer otros tipos de contenido del cuerpo. Vease {{anch("Body")}} para más información.</p> +</div> + +<p>Las peticiones de Fetch son controladas por la directiva de <code>connect-src</code> de <a href="https://developer.mozilla.org/en-US/docs/Security/CSP/CSP_policy_directives">Content Security Policy</a> en vez de la directiva de los recursos que se han devuelto.</p> + +<h3 id="Suministrando_opciones_de_petición">Suministrando opciones de petición</h3> + +<p>El método <code>fetch()</code> puede aceptar opcionalmente un segundo parámetro, un objeto <code>init</code> que permite controlar un numero de diferentes ajustes:</p> + +<p>Vea {{domxref("GlobalFetch.fetch","fetch()")}}, para ver todas las opciones disponibles y más detalles.</p> + +<pre class="notranslate">// Ejemplo implementando el metodo POST: +async function postData(url = '', data = {}) { + // Opciones por defecto estan marcadas con un * + const response = await fetch(url, { + method: 'POST', // *GET, POST, PUT, DELETE, etc. + mode: 'cors', // no-cors, *cors, same-origin + cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached + credentials: 'same-origin', // include, *same-origin, omit + headers: { + 'Content-Type': 'application/json' + // 'Content-Type': 'application/x-www-form-urlencoded', + }, + redirect: 'follow', // manual, *follow, error + referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url + body: JSON.stringify(data) // body data type must match "Content-Type" header + }); + return response.json(); // parses JSON response into native JavaScript objects +} + +postData('https://example.com/answer', { answer: 42 }) + .then(data => { + console.log(data); // JSON data parsed by `data.json()` call + });</pre> + +<p>Tenga en cuenta que <code>mode: "no-cors"</code> solo permite un conjunto limitado de encabezados en la solicitud:</p> + +<ul> + <li><code>Accept</code></li> + <li><code>Accept-Language</code></li> + <li><code>Content-Language</code></li> + <li><code>Content-Type</code> with a value of <code>application/x-www-form-urlencoded</code>, <code>multipart/form-data</code>, or <code>text/plain</code></li> +</ul> + +<h3 id="Comprobando_que_la_petición_es_satisfactoria">Comprobando que la petición es satisfactoria</h3> + +<p>Una petición promise {{domxref("GlobalFetch.fetch","fetch()")}} será rechazada con {{jsxref("TypeError")}} cuando se encuentre un error de red, aunque esto normalmente significa problemas de permisos o similares — por ejemplo, un 404 no constituye un error de red. Una forma precisa de comprobar que la petición <code>fetch()</code> es satisfactoria pasa por comprobar si la promesa ha sido resuelta, además de comprobar que la propiedad {{domxref("Response.ok")}} tiene el valor <code>true</code> que indica que el estado de la petición HTTP es OK (código 200-299). El código sería algo así:</p> + +<pre class="brush: js notranslate">fetch('flores.jpg').then(function(response) { + if(response.ok) { + response.blob().then(function(miBlob) { + var objectURL = URL.createObjectURL(miBlob); + miImagen.src = objectURL; + }); + } else { + console.log('Respuesta de red OK pero respuesta HTTP no OK'); + } +}) +.catch(function(error) { + console.log('Hubo un problema con la petición Fetch:' + error.message); +});</pre> + +<h3 id="Proporcionando_tu_propio_objeto_Request">Proporcionando tu propio objeto Request</h3> + +<p>En lugar de pasar la ruta al recurso que deseas solicitar a la llamada del método <code>fetch()</code>, puedes crear un objeto de petición utilizando el constructor {{domxref("Request.Request","Request()")}}, y pasarlo como un argumento del método <code>fetch()</code>:</p> + +<pre class="brush: js notranslate">var myHeaders = new Headers(); + +var myInit = { method: 'GET', + headers: myHeaders, + mode: 'cors', + cache: 'default' }; + +var myRequest = new Request('flowers.jpg', myInit); + +fetch(myRequest) +.then(function(response) { + return response.blob(); +}) +.then(function(myBlob) { + var objectURL = URL.createObjectURL(myBlob); + myImage.src = objectURL; +});</pre> + +<p><code>Request()</code> acepta exactamente los mismos parámetros que el método <code>fetch()</code>. Puedes incluso pasar un objeto de petición existente para crear una copia del mismo:</p> + +<pre class="brush: js notranslate">var anotherRequest = new Request(myRequest, myInit);</pre> + +<p>Esto es muy útil ya que el cuerpo de las solicitudes y respuestas son de un sólo uso. Haciendo una copia como esta te permite utilizar la petición/respuesta de nuevo, y al mismo tiempo, si lo deseas, modificar las opciones de <code>init</code>. La copia debe estar hecha antes de la lectura del <body>, y leyendo el <body> en la copia, se marcará como leido en la petición original.</p> + +<div class="note"> +<p><strong>Nota</strong>: Existe también un método {{domxref("Request.clone","clone()")}} que crea una copia. Este tiene una semántica ligeramente distinta al otro método de copia — el primero fallará si el cuerpo de la petición anterior ya ha sido leído (lo mismo para copiar una respuesta), mientras que <code>clone()</code> no.</p> +</div> + +<h3 id="Enviar_una_petición_con_credenciales_incluido">Enviar una petición con credenciales incluido</h3> + +<p>Para producir que los navegadores envien una petición con las credenciales incluidas, incluso para una llamada de origen cruzado, añadimos<code> credentials: 'include'</code> en el el objeto <code>init</code> que se pasa al método <code>fetch()</code>.</p> + +<pre class="brush: js line-numbers language-js notranslate"><code class="language-js"><span class="function token">fetch</span><span class="punctuation token">(</span><span class="string token">'https://example.com'</span><span class="punctuation token">,</span> <span class="punctuation token">{</span> + credentials<span class="punctuation token">:</span> <span class="string token">'include'</span> +<span class="punctuation token">}</span><span class="punctuation token">)</span></code></pre> + +<p>Si solo quieres enviar la credenciales si la URL de la petición está en el mismo origen desde donde se llamada el script, añade <code>credentials: 'same-origin'</code>.</p> + +<pre class="brush: js line-numbers language-js notranslate"><code class="language-js"><span class="comment token">// El script fué llamado desde el origen 'https://example.com'</span> + +<span class="function token">fetch</span><span class="punctuation token">(</span><span class="string token">'https://example.com'</span><span class="punctuation token">,</span> <span class="punctuation token">{</span> + credentials<span class="punctuation token">:</span> <span class="string token">'same-origin'</span> +<span class="punctuation token">}</span><span class="punctuation token">)</span></code></pre> + +<p>Sin embargo para asegurarte que el navegador no incluye las credenciales en la petición, usa <code>credentials: 'omit'</code>.</p> + +<pre class="brush: js line-numbers language-js notranslate"><code class="language-js"><span class="function token">fetch</span><span class="punctuation token">(</span><span class="string token">'https://example.com'</span><span class="punctuation token">,</span> <span class="punctuation token">{</span> + credentials<span class="punctuation token">:</span> <span class="string token">'omit'</span> +<span class="punctuation token">}</span><span class="punctuation token">)</span></code></pre> + +<h3 id="Enviando_datos_JSON">Enviando datos JSON</h3> + +<p>Usa {{domxref("GlobalFetch.fetch","fetch()")}} para enviar una petición POST con datos codificados en JSON .</p> + +<pre class="brush: js line-numbers language-js notranslate"><code class="language-js"><span class="keyword token">var</span> url <span class="operator token">=</span> <span class="string token">'https://example.com/profile'</span><span class="punctuation token">;</span> +<span class="keyword token">var</span> data <span class="operator token">=</span> <span class="punctuation token">{</span>username<span class="punctuation token">:</span> <span class="string token">'example'</span><span class="punctuation token">}</span><span class="punctuation token">;</span> + +<span class="function token">fetch</span><span class="punctuation token">(</span>url<span class="punctuation token">,</span> <span class="punctuation token">{</span> + method<span class="punctuation token">:</span> <span class="string token">'POST'</span><span class="punctuation token">,</span> <span class="comment token">// or 'PUT'</span> + body<span class="punctuation token">:</span> JSON<span class="punctuation token">.</span><span class="function token">stringify</span><span class="punctuation token">(</span>data<span class="punctuation token">)</span><span class="punctuation token">,</span> <span class="comment token">// data can be `string` or {object}!</span> + headers<span class="punctuation token">:</span><span class="punctuation token">{</span> + <span class="string token">'Content-Type'</span><span class="punctuation token">:</span> <span class="string token">'application/json'</span> + <span class="punctuation token">}</span> +<span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">.</span><span class="function token">then</span><span class="punctuation token">(</span>res <span class="operator token">=</span><span class="operator token">></span> res<span class="punctuation token">.</span><span class="function token">json</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">)</span> +<span class="punctuation token">.</span><span class="keyword token">catch</span><span class="punctuation token">(</span>error <span class="operator token">=</span><span class="operator token">></span> console<span class="punctuation token">.</span><span class="function token">error</span><span class="punctuation token">(</span><span class="string token">'Error:'</span><span class="punctuation token">,</span> error<span class="punctuation token">)</span><span class="punctuation token">)</span> +<span class="punctuation token">.</span><span class="function token">then</span><span class="punctuation token">(</span>response <span class="operator token">=</span><span class="operator token">></span> console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span><span class="string token">'Success:'</span><span class="punctuation token">,</span> response<span class="punctuation token">)</span><span class="punctuation token">)</span><span class="punctuation token">;</span></code></pre> + +<h3 id="Enviando_un_archivo">Enviando un archivo</h3> + +<p>Los archivos pueden ser subido mediante el HTML de un elemento input <code><input type="file" /></code>, {{domxref("FormData.FormData","FormData()")}} y {{domxref("GlobalFetch.fetch","fetch()")}}.</p> + +<pre class="brush: js line-numbers language-js notranslate"><code class="language-js"><span class="keyword token">var</span> formData <span class="operator token">=</span> <span class="keyword token">new</span> <span class="class-name token">FormData</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">;</span> +<span class="keyword token">var</span> fileField <span class="operator token">=</span> document<span class="punctuation token">.</span><span class="function token">querySelector</span><span class="punctuation token">(</span><span class="string token">"input[type='file']"</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + +formData<span class="punctuation token">.</span><span class="function token">append</span><span class="punctuation token">(</span><span class="string token">'username'</span><span class="punctuation token">,</span> <span class="string token">'abc123'</span><span class="punctuation token">)</span><span class="punctuation token">;</span> +formData<span class="punctuation token">.</span><span class="function token">append</span><span class="punctuation token">(</span><span class="string token">'avatar'</span><span class="punctuation token">,</span> fileField<span class="punctuation token">.</span>files<span class="punctuation token">[</span><span class="number token">0</span><span class="punctuation token">]</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + +<span class="function token">fetch</span><span class="punctuation token">(</span><span class="string token">'https://example.com/profile/avatar'</span><span class="punctuation token">,</span> <span class="punctuation token">{</span> + method<span class="punctuation token">:</span> <span class="string token">'PUT'</span><span class="punctuation token">,</span> + body<span class="punctuation token">:</span> formData +<span class="punctuation token">}</span><span class="punctuation token">)</span> +<span class="punctuation token">.</span><span class="function token">then</span><span class="punctuation token">(</span>response <span class="operator token">=</span><span class="operator token">></span> response<span class="punctuation token">.</span><span class="function token">json</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">)</span> +<span class="punctuation token">.</span><span class="keyword token">catch</span><span class="punctuation token">(</span>error <span class="operator token">=</span><span class="operator token">></span> console<span class="punctuation token">.</span><span class="function token">error</span><span class="punctuation token">(</span><span class="string token">'Error:'</span><span class="punctuation token">,</span> error<span class="punctuation token">)</span><span class="punctuation token">)</span> +<span class="punctuation token">.</span><span class="function token">then</span><span class="punctuation token">(</span>response <span class="operator token">=</span><span class="operator token">></span> console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span><span class="string token">'Success:'</span><span class="punctuation token">,</span> response<span class="punctuation token">)</span><span class="punctuation token">)</span><span class="punctuation token">;</span></code></pre> + +<h2 id="Cabeceras">Cabeceras</h2> + +<p>La interfaz {{domxref("Headers")}} te permite crear tus propios objetos de headers mediante el constructor {{domxref("Headers.Headers","Headers()")}}. Un objeto headers es un simple multi-mapa de nombres y valores:</p> + +<pre class="brush: js notranslate">var content = "Hello World"; +var myHeaders = new Headers(); +myHeaders.append("Content-Type", "text/plain"); +myHeaders.append("Content-Length", content.length.toString()); +myHeaders.append("X-Custom-Header", "ProcessThisImmediately");</pre> + +<p>Lo mismo se puede lograr pasando un "array de arrays" o un objeto literal al constructor:</p> + +<pre class="brush: js notranslate">myHeaders = new Headers({ + "Content-Type": "text/plain", + "Content-Length": content.length.toString(), + "X-Custom-Header": "ProcessThisImmediately", +});</pre> + +<p>Los contenidos pueden ser consultados o recuperados:</p> + +<pre class="brush: js notranslate">console.log(myHeaders.has("Content-Type")); // true +console.log(myHeaders.has("Set-Cookie")); // false +myHeaders.set("Content-Type", "text/html"); +myHeaders.append("X-Custom-Header", "AnotherValue"); + +console.log(myHeaders.get("Content-Length")); // 11 +console.log(myHeaders.getAll("X-Custom-Header")); // ["ProcessThisImmediately", "AnotherValue"] + +myHeaders.delete("X-Custom-Header"); +console.log(myHeaders.getAll("X-Custom-Header")); // [ ]</pre> + +<p>Algunas de estas operaciones solo serán utiles en {{domxref("ServiceWorker_API","ServiceWorkers")}}, pero estas disponen de una mejor API para manipular <code>headers</code>.</p> + +<p>Todos los métodosde de <code>headers</code> lanzan un <code>TypeError</code> si un nombre de cabecera no es un nombre de cabecera HTTP válido. Las operaciones de mutación lanzarán un <code>TypeError</code> si hay un guarda inmutable (ver más abajo). Si no, fallan silenciosamente. Por ejemplo:</p> + +<pre class="brush: js notranslate">var myResponse = Response.error(); +try { + myResponse.headers.set("Origin", "http://mybank.com"); +} catch(e) { + console.log("Cannot pretend to be a bank!"); +}</pre> + +<p>Un buen caso de uso para <code>headers</code> es comprobar cuando el tipo de contenido es correcto antes de que se procese:</p> + +<pre class="brush: js notranslate">fetch(myRequest).then(function(response) { + var contentType = response.headers.get("content-type"); + if(contentType && contentType.indexOf("application/json") !== -1) { + return response.json().then(function(json) { + // process your JSON further + }); + } else { + console.log("Oops, we haven't got JSON!"); + } +});</pre> + +<h3 id="Guarda_Guard">Guarda (Guard)</h3> + +<p>Desde que las cabeceras pueden ser enviadas en peticiones y recibidas en respuestas, y tienen limitaciones sobre que información puede y debería ser mutable, los objeto headers tienen una propierdad de guarda. Este no está expuesto a la Web, pero puede afectar a que operaciones de mutación son permitidas sobre el objeto headers.</p> + +<p>Los valores posibles de guarda (guard) son:</p> + +<ul> + <li><code>none</code>: valor por defecto.</li> + <li><code>request</code>: Guarda para el objeto headers obtenido de la petición ({{domxref("Request.headers")}}).</li> + <li><code>request-no-cors</code>: Guarda para un objeto headers obtenido desde una petición creada con {{domxref("Request.mode")}} a <code>no-cors</code>.</li> + <li><code>response</code>: Guarda para una cabecera obetenida desde un respuesta ({{domxref("Response.headers")}}).</li> + <li><code>immutable</code>: Mayormente utilizado para ServiceWorkers, produce un objeto headers de solo lectura.</li> +</ul> + +<div class="note"> +<p><strong>Nota</strong>: No se debería añadir o establecer una petición a un objeto headers <em>guardado</em> con la cabecera <code>Content-Length</code>. De igual manera, insertar <code>Set-Cookie</code> en la respuesta de la cabecera no esta permitido: ServiceWorkers no estan autorizados a establecer cookies a través de respuestas sintéticas.</p> +</div> + +<h2 id="Objetos_Response">Objetos Response</h2> + +<p>Cómo has visto anteriormente, las instancias de {{domxref("Response")}} son devueltas cuando <code>fetch()</code> es resuelto.</p> + +<p>Las propiedades de response que usarás son:</p> + +<ul> + <li>{{domxref("Response.status")}} — Entero (por defecto con valor 200) que contiene el código de estado de las respuesta.</li> + <li>{{domxref("Response.statusText")}} — Cadena (con valor por defecto "OK"), el cual corresponde al mensaje del estado de código HTTP.</li> + <li>{{domxref("Response.ok")}} — Visto en uso anteriormente, es una clave para comprobar que el estado está dentro del rango 200-299 (ambos incluidos). Este devuelve un valor {{domxref("Boolean")}}, siendo <code>true</code> si lo anterior se cumple y <code>false</code> en otro caso.</li> +</ul> + +<p>Estos pueden también creados programáticamente a través de JavaScript, pero esto solamente es realmete útil en {{domxref("ServiceWorker_API", "ServiceWorkers")}}, cuando pones un objeto response personalizado a una respuesta recibida usando un método {{domxref("FetchEvent.respondWith","respondWith()")}}:</p> + +<pre class="brush: js notranslate">var myBody = new Blob(); + +addEventListener('fetch', function(event) { + event.respondWith( + new Response(myBody, { + headers: { "Content-Type" : "text/plain" } + }) + ); +});</pre> + +<p>El constructor {{domxref("Response.Response","Response()")}} toma dos argurmentos opcionales, un cuerpo para la respuesta y un objeto init (similar al que acepta {{domxref("Request.Request","Request()")}}).</p> + +<div class="note"> +<p><strong>Nota</strong>: El método estático {{domxref("Response.error","error()")}} simplemente devuelve un error en la respuesta. De igual manera que {{domxref("Response.redirect","redirect()")}} devuelve una respuesta que resulta en un redirección a una URL especificada. Estos son solo relevantes tambien a ServiceWorkers.</p> +</div> + +<h2 id="Body">Body</h2> + +<p>Tanto las peticiones como las respuestas pueden contener datos body. Body es una instancia de cualquiera de los siguientes tipos:</p> + +<ul> + <li>{{domxref("ArrayBuffer")}}</li> + <li>{{domxref("ArrayBufferView")}} (Uint8Array y amigos)</li> + <li>{{domxref("Blob")}}/File</li> + <li>string</li> + <li>{{domxref("URLSearchParams")}}</li> + <li>{{domxref("FormData")}}</li> +</ul> + +<p>El mixin de {{domxref("Body")}} define los siguientes metodos para extraer un body (implementado por {{domxref("Request")}} and {{domxref("Response")}}). Todas ellas devuelven una promesa que es eventualmente resuelta con el contenido actual.</p> + +<ul> + <li>{{domxref("Body.arrayBuffer","arrayBuffer()")}}</li> + <li>{{domxref("Body.blob","blob()")}}</li> + <li>{{domxref("Body.json","json()")}}</li> + <li>{{domxref("Body.text","text()")}}</li> + <li>{{domxref("Body.formData","formData()")}}</li> +</ul> + +<p>Este hace uso de los datos no texttuales mucho mas facil que si fuera con XHR.</p> + +<p>Las peticiones body pueden ser establecidas pasando el parametro body:</p> + +<pre class="brush: js notranslate">var form = new FormData(document.getElementById('login-form')); +fetch("/login", { + method: "POST", + body: form +});</pre> + +<p>Tanto peticiones y respuestas (y por extensión la function <code>fetch()</code>), intentaran inteligentemente determinar el tipo de contenido. Una petición tambien establecerá automáticamente la propiedad <code>Context-Type</code> de la cabecera si no es ha establecido una.</p> + +<h2 id="Detectar_característica">Detectar característica</h2> + +<p>Puedes comprobar si el navegador soporta la API de Fetch comprobando la existencia de {{domxref("Headers")}}, {{domxref("Request")}}, {{domxref("Response")}} o {{domxref("GlobalFetch.fetch","fetch()")}} sobre el ámbito de {{domxref("Window")}} o {{domxref("Worker")}}. Por ejemplo:</p> + +<pre class="brush: js line-numbers language-js notranslate"><code class="language-js"><span class="keyword token">if</span> <span class="punctuation token">(</span>self<span class="punctuation token">.</span>fetch<span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="comment token">// run my fetch request here</span> +<span class="punctuation token">}</span> <span class="keyword token">else</span> <span class="punctuation token">{</span> + <span class="comment token">// do something with XMLHttpRequest?</span> +<span class="punctuation token">}</span></code></pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>Para utilizar <code>fetch()</code> en un explorador no soportado, hay disponible un <a href="https://github.com/github/fetch">Fetch Polyfill</a> que recrea la funcionalidad para navegadores no soportados.</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('Fetch')}}</td> + <td>{{Spec2('Fetch')}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_navegadores">Compatibilidad en navegadores</h2> + +<p>{{Compat("api.WindowOrWorkerGlobalScope.fetch")}}</p> + +<h2 id="Vea_también">Vea también</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> + <li><a href="https://github.com/github/fetch">Fetch polyfill</a></li> + <li><a href="https://github.com/mdn/fetch-examples/">Fetch examples on Github</a></li> +</ul> diff --git a/files/es/web/api/fetchevent/index.html b/files/es/web/api/fetchevent/index.html new file mode 100644 index 0000000000..c2f8e4d693 --- /dev/null +++ b/files/es/web/api/fetchevent/index.html @@ -0,0 +1,176 @@ +--- +title: FetchEvent +slug: Web/API/FetchEvent +tags: + - API + - FetchEvent + - Interfaz + - Offline + - Referencia + - Service Workers + - Workers +translation_of: Web/API/FetchEvent +--- +<p>{{APIRef("Service Workers API")}}{{ SeeCompatTable() }}</p> + +<p>Este es el tipo de evento para eventos "<code>fetch</code>" despachados en el {{domxref("ServiceWorkerGlobalScope", "scope global del service worker", "", 1)}}. Contiene información sobre la búsqueda (fetch), incluyendo la petición (request) y cómo el receptor tratará la respuesta (response).</p> + +<p>Provee el método {{domxref("FetchEvent.respondWith", "event.respondWith()")}}, el cúal nos permite proporcionar una respuesta a esta búsqueda (fetch).</p> + +<h2 id="Constructor">Constructor</h2> + +<dl> + <dt>{{domxref("FetchEvent.FetchEvent()", "new FetchEvent()")}}</dt> + <dd>Crea un nuevo objecto <code>FetchEvent</code>. Este constructor no se usa normalmente. El propio navegador crea estos objetos y los proporciona a los callbacks de eventos "<code>fetch</code>".</dd> +</dl> + +<h2 id="Propiedades">Propiedades</h2> + +<p><em>Hereda propiedades del ancestro, {{domxref("Event")}}</em>.</p> + +<dl> + <dt>{{domxref("fetchEvent.clientId")}} {{readonlyInline}}</dt> + <dd>El {{domxref("Client.id", "id")}} del mismo origen {{domxref("Client", "client")}} que inició el "fetch".</dd> + <dt>{{domxref("fetchEvent.preloadResponse")}} {{readonlyinline}}</dt> + <dd>Un {{jsxref("Promise")}} para un {{domxref("Response")}}, o vacío si este no es una navegación, o {{domxref("NavigationPreloadManager", "navigation preload", "", 1)}} no esta habilitado.</dd> + <dt>{{domxref("fetchEvent.request")}} {{readonlyInline}}</dt> + <dd>La {{domxref("Request")}} que el navegador intenta crear.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<p><em>Herada métodos del padre, </em><em>{{domxref("ExtendableEvent")}}</em>.</p> + +<dl> + <dt>{{domxref("fetchEvent.respondWith()")}}</dt> + <dd>Evita el manejo de búsqueda predeterminado del navegador y proporciona (una promesa) una respuesta usted mismo.</dd> + <dt>{{domxref("extendableEvent.waitUntil()")}}</dt> + <dd> + <p>Extiende el tiempo de vida del evento. Se usa para notificar al navegador las tareas que van más allá de la devolución de una respuesta, como la transmisión y el almacenamiento en caché.</p> + </dd> +</dl> + +<h2 id="Ejemplos">Ejemplos</h2> + +<p>Este evento fetch, permite al navegador hacer esta acción por defecto para peticiones non-GET. Para peticiones GET esto intenta retornar una coincidencia en el cache, y vuelve de nuevo a la red. Si busca una concidencia en el cache, actualiza asincronicamente el cache para la próxima vez.</p> + +<pre class="brush: js notranslate">addEventListener('fetch', event => { + // Permite al navegador hacer este asunto por defecto + // para peticiones non-GET. + if (event.request.method != 'GET') return; + + // Evita el valor predeterminado, y manejar solicitud nosostros mismos. + event.respondWith(async function() { + // Intenta obtener la respuesta de el cache. + const cache = await caches.open('dynamic-v1'); + const cachedResponse = await cache.match(event.request); + + if (cachedResponse) { + // Si encontramos una coincidencia en el cache, lo devuelve, pero también + // actualizar la entrada en el cache en segundo plano. + event.waitUntil(cache.add(event.request)); + return cachedResponse; + } + + // Si no encontramos una coincidencia en el cache, usa la red. + return fetch(event.request); + }()); +});</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('Service Workers', '#fetch-event-section', 'FetchEvent')}}</td> + <td>{{Spec2('Service Workers')}}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_Navegadores">Compatibilidad de Navegadores</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>{{CompatChrome(40)}}</td> + <td>{{ CompatGeckoDesktop("44.0") }}[<sup>1]</sup></td> + <td>{{CompatNo}}</td> + <td>24</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>Propiedad preloadResponse</code> </td> + <td>{{CompatChrome(59)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatOpera(46)}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android Webview</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>{{CompatChrome(40)}}</td> + <td>{{CompatChrome(40)}}</td> + <td>{{ CompatGeckoMobile("44.0") }}</td> + <td>{{ CompatVersionUnknown }}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>Propiedad preloadResponse</code> </td> + <td>{{CompatChrome(59)}}</td> + <td>{{CompatChrome(59)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatOperaMobile(46)}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Service workers (and <a href="/en-US/docs/Web/API/Push_API">Push</a>) have been disabled in the <a href="https://www.mozilla.org/en-US/firefox/organizations/">Firefox 45 and 52 Extended Support Releases</a> (ESR.)</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{jsxref("Promise")}}</li> + <li><a href="/en-US/docs/Web/API/Fetch_API">Fetch API</a></li> +</ul> diff --git a/files/es/web/api/file/filename/index.html b/files/es/web/api/file/filename/index.html new file mode 100644 index 0000000000..2179e85756 --- /dev/null +++ b/files/es/web/api/file/filename/index.html @@ -0,0 +1,35 @@ +--- +title: File.fileName +slug: Web/API/File/fileName +tags: + - API + - Archivos + - DOM + - File API + - Propiedad + - Referencia +translation_of: Web/API/File/fileName +--- +<p>{{APIRef("File API")}}{{non-standard_header}} {{obsolete_header(7.0)}}</p> + +<p>Devuelve el nombre del archivo. Por razones de seguridad la ruta es excluída de esta propiedad.</p> + +<div class="note">Propiedad deprecada. Utilice {{domxref("File.name")}} en su lugar.</div> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var <em>name</em> = <em>instanceOfFile</em>.fileName;</pre> + +<h3 id="Valor">Valor</h3> + +<p>Una cadena</p> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<p>No es parte de una especificación.</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("File.name")}}</li> +</ul> diff --git a/files/es/web/api/file/index.html b/files/es/web/api/file/index.html new file mode 100644 index 0000000000..006125622e --- /dev/null +++ b/files/es/web/api/file/index.html @@ -0,0 +1,112 @@ +--- +title: File +slug: Web/API/File +tags: + - API + - File API + - Interfaz + - Referencia + - Web +translation_of: Web/API/File +--- +<div>{{APIRef }}</div> + +<p>La interfaz <strong><code>File</code></strong> provee información acerca de los archivos y permite que el código JavaScript en una página web tenga acceso a su contenido.</p> + +<p>Los objetos <code>File</code> son generalmente recuperados a través de un objeto {{domxref("FileList")}} retornado como resultado de un usuario seleccionado archivos por medio de un elemento {{ HTMLElement("input") }} , desde las operaciones drag y drop de un objeto {{domxref("DataTransfer")}} ,<span style="line-height: 1.5;"> o desde la API </span><code style="font-size: 14px;">mozGetAsFile()</code><span style="line-height: 1.5;"> en un {{ domxref("HTMLCanvasElement") }}. En Gecko, desde código con privilegios es posible crear objetos <code>File</code> representando cualquier archivo local sin esperar la interacción del usuario </span> (ver {{anch("Implementation notes")}} para más información.)</p> + +<p>Un objeto <code>File</code> es una especie específica de {{DOMxRef("Blob")}}, y puede ser utilizada en cualquier contexto que un Blob puede ser usado. En particular, {{DOMxRef("FileReader")}}, {{DOMxRef("URL.createObjectURL()")}}, {{DOMxRef("ImageBitmapFactories.createImageBitmap()", "createImageBitmap()")}}, y {{DOMxRef("XMLHttpRequest", "", "send()")}} aceptan tanto <code>Blob</code>s y <code>File</code>s.</p> + +<p>Ver <a href="https://wiki.developer.mozilla.org/en-US/docs/Using_files_from_web_applications">Utilizando archivos desde aplicaciones web (Using files from web applications)</a> para más información y ejemplos.</p> + +<p>{{InheritanceDiagram}}</p> + +<h2 id="Constructor">Constructor</h2> + +<dl> + <dt>{{domxref("File.File", "File()")}}</dt> + <dd>Retorna un nuevo objeto de tipo <code>File</code>.</dd> +</dl> + +<h2 id="Propiedades">Propiedades</h2> + +<dl> + <dt>{{DOMxRef("File.lastModified")}}{{ReadOnlyInline}}</dt> + <dd>Retorna el último tiempo que el archivo se modifico, en milisegundos desde la época de UNIX (1 de enero de 1970 a medianoche).</dd> + <dt>{{DOMxRef("File.lastModifiedDate")}} {{Deprecated_Inline}}{{ReadOnlyInline}} {{Gecko_MinVersion_Inline("15.0")}}</dt> + <dd>Retorna la última fecha (en un objeto {{JSxRef("Date")}}<code><a href="https://wiki.developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date">Date</a></code>) de modificación del archivo referenciada por el objeto <code>File</code>.</dd> + <dt>{{DOMxRef("File.name")}}{{ReadOnlyInline}}</dt> + <dd>Retorna el nombre del archivo referenciada por el objeto <code>File</code>.</dd> + <dt>{{DOMxRef("File.webkitRelativePath")}} {{Non-standard_Inline}}{{ReadOnlyInline}}</dt> + <dd>Retorna la ruta relativa de la URL del {{DOMxRef("File")}}.</dd> + <dd> + <p><code>File</code> implementa {{DOMxRef("Blob")}}, así que también cuenta con las siguientes propiedades:</p> + </dd> + <dt>{{DOMxRef("File.size")}}{{ReadOnlyInline}}</dt> + <dd>Retorna el tamaño del archivo en bytes.</dd> + <dt>{{DOMxRef("File.type")}}{{ReadOnlyInline}}</dt> + <dd>Retorna el tipo <a href="https://wiki.developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types">MIME </a>del archivo.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<p><em>La interfaz <code>File</code> no define algún método, pero los hereda de la interfaz {{domxref("Blob")}}:</em></p> + +<dl> + <dt>{{DOMxRef("Blob.slice()", "Blob.slice([start[, end[, contentType]]])")}}</dt> + <dd>Retorna un nuevo objeto <code>Blob</code> conteniendo la información en el rango especificado de bytes de la fuente <code>Blob</code>.</dd> + <dt>{{DOMxRef("Blob.stream()")}}</dt> + <dd>Transforma el archivo <code>File</code> en un {{DOMxRef("ReadableStream")}} que puede ser usado para leer el contenido de <code>File</code>.</dd> + <dt>{{DOMxRef("Blob.text()")}}</dt> + <dd>Transforma el archivo <code>File</code> en una corriente (<em>stream</em>) para leerse hasta completarse. Retorna una promesa que se resuelve con un {{DOMxRef("USVString")}} (texto).</dd> + <dt>{{DOMxRef("Blob.arrayBuffer()")}}</dt> + <dd>Transforma el archivo <code>File</code> en una corriente y leerlo hasta completarse. Devuelve una promesa que resuelve con un {{DOMxRef("ArrayBuffer")}}.</dd> +</dl> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('File API')}}</td> + <td>{{Spec2('File API')}}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_Navegadores">Compatibilidad en Navegadores</h2> + +<div> + + +<p>{{Compat("api.File")}}</p> +</div> + +<h3 id="Notas_de_Implementación">Notas de Implementación</h3> + +<ul> + <li>En Gecko, puedes hacer uso de esta API desde código chrome. Vea <a href="/en-US/docs/Extensions/Using_the_DOM_File_API_in_chrome_code" title="Using the DOM File API in chrome code">Utilizando la API DOM File en código chrome (Using the DOM File API in chrome code)</a> para más detalles.</li> + <li>Empezando desde Gecko 6.0 {{geckoRelease("6.0")}}, código privilegiado (como las extensiones por ejemplo) puede pasar un objeto {{interface("nsIFile")}} al constructor DOM <code>File</code> para especificar el archivo a referenciar.</li> + <li>Empezando desde Gecko 8.0 {{geckoRelease("8.0")}}, usted puede usar <code>new File</code> para la creación de objetos <code>File</code> a partir de código de componentes XPCOM en lugar de tener que instanciar el objeto {{interface("nsIDOMFile")}} directamente. El constructor toma, en contraste a Blob, un segundo argumento como nombre de archivo. El nombre de archivo puede ser cualquier String. + <pre class="syntaxbox">File File( + Array parts, + String filename, + BlobPropertyBag properties +);</pre> + </li> + <li> Las siguientes propiedades y métodos no estándar fueron removidos en Gecko 7 {{GeckoRelease("7.0")}}: {{DOMxRef("File.fileName")}}, {{DOMxRef("File.fileSize")}}, {{DOMxRef("File.getAsBinary()")}}, {{DOMxRef("File.getAsDataURL()")}}, {{DOMxRef("File.getAsText()","File.getAsText(string encoding)")}} ({{bug("661876")}}). Propiedades estándar {{DOMxRef("File.name")}}, {{DOMxRef("Blob.size")}}, y métodos en {{DOMxRef("FileReader")}} deberían ser usados en su lugar.</li> +</ul> + +<h2 id="See_also" name="See_also">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/Using_files_from_web_applications" title="Using files from web applications">Usando archivos desde aplicaciones web</a></li> + <li><a href="/en-US/docs/Extensions/Using_the_DOM_File_API_in_chrome_code" title="Extensions/Using the DOM File API in chrome code">Usando la API DOM File en código chrome</a></li> + <li>{{domxref("FileReader")}}</li> +</ul> diff --git a/files/es/web/api/file/lastmodifieddate/index.html b/files/es/web/api/file/lastmodifieddate/index.html new file mode 100644 index 0000000000..8e322a2eec --- /dev/null +++ b/files/es/web/api/file/lastmodifieddate/index.html @@ -0,0 +1,101 @@ +--- +title: File.lastModifiedDate +slug: Web/API/File/lastModifiedDate +tags: + - API + - Archivo + - Archivos + - Deprecado + - File API + - Propiedad + - Referencia + - Solo lectura +translation_of: Web/API/File/lastModifiedDate +--- +<div>{{APIRef("File API") }} {{deprecated_header}}</div> + +<p>La propiedad de solo lectura <code><strong>File.lastModifiedDate</strong></code><strong> </strong>retorna la fecha de ultima modificacion del archivo. Archivos sin una ultima fecha de modificacion conocida retornan la fecha actual.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="brush: js">var time = <em>instanceOfFile</em>.lastModifiedDate</pre> + +<h2 id="Valor">Valor</h2> + +<p>Un objeto <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date">Date</a></code>.</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush:js">// fileInput es un HTMLInputElement: <input type="file" multiple id="myfileinput"> +var fileInput = document.getElementById("myfileinput"); + +// files es un objeto FileList (similar a NodeList) +var files = fileInput.files; + +for (var i = 0; i < files.length; i++) { + alert(files[i].name + " tiene una fecha de ultima modificacion el " + files[i].lastModifiedDate); +}</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<p><em>Aunque estaba presente en las primeras versiones de la especificacion de File API, esta propiedad ha sido eliminada de esta y ahora es no-estandar. Usar {{domxref("File.lastModified")}} como reemplazo.</em></p> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Caracteristica</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>File.lastModified</td> + <td>13.0</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("15.0")}}</td> + <td>10.0</td> + <td>16.0</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Caracteristica</th> + <th>Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>File.lastModified</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Vea_también">Vea también</h2> + +<ul> + <li>{{domxref("File")}}</li> +</ul> diff --git a/files/es/web/api/file/name/index.html b/files/es/web/api/file/name/index.html new file mode 100644 index 0000000000..c03fefb77e --- /dev/null +++ b/files/es/web/api/file/name/index.html @@ -0,0 +1,70 @@ +--- +title: File.name +slug: Web/API/File/name +tags: + - API + - Archivo + - Archivos + - Propiedad + - Referencia +translation_of: Web/API/File/name +--- +<p>{{APIRef("File API")}}</p> + +<p>Retorna el nombre del archivo representado por el objeto {{domxref("File")}}. Por razones de seguridad, la ruta de directorios es excluida de esta propiedad.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="brush: js">var nombre = <em>file</em>.name;</pre> + +<h2 id="Valor">Valor</h2> + +<p>Una cadena, conteniendo el nombre del archivo sin la ruta de directorios, por ejemplo: "Mi resumen.rtf".</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush: html"><input type="file" multiple onchange="processSelectedFiles(this)"> +</pre> + +<pre class="brush: js">function processSelectedFiles(fileInput) { + var files = fileInput.files; + + for (var i = 0; i < files.length; i++) { + alert("Filename " + files[i].name); + } +}</pre> + +<p>Prueba el resultado:</p> + +<p>{{ EmbedLiveSample('Example', 300, 50) }}</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificacion</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('File API', '#file-attrs', 'name')}}</td> + <td>{{Spec2('File API')}}</td> + <td>Definicion inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<div> + + +<p>{{Compat("api.File.name")}}</p> +</div> + +<h2 id="Specification" name="Specification">Vea también</h2> + +<ul> + <li><a href="/en-US/docs/Using_files_from_web_applications">Usando archivos desde aplicaciones web</a></li> +</ul> diff --git a/files/es/web/api/file/type/index.html b/files/es/web/api/file/type/index.html new file mode 100644 index 0000000000..b433446aa4 --- /dev/null +++ b/files/es/web/api/file/type/index.html @@ -0,0 +1,72 @@ +--- +title: File.type +slug: Web/API/File/type +tags: + - API + - Archivos + - File API + - Propiedad + - Referencia + - Tipo de archivo +translation_of: Web/API/File/type +--- +<div>{{APIRef("File API")}}</div> + +<p>Retorna el tipo de media (<a href="/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types">MIME</a>) del archivo representado por un objeto {{domxref("File")}}.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="brush: js">var tipo = <var>file</var>.type;</pre> + +<h2 id="Valor">Valor</h2> + +<p>Una cadena (<em>string</em>), conteniendo el tipo de media (MIME) indicando el tipo del archivo, por ejemplo "image/png" para imágenes PNG.</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush: html"><input type="file" multiple onchange="mostrarTipo(this)"> +</pre> + +<pre class="brush: js">function mostrarTipo(fileInput) { + const archivos = fileInput.files; + + for (let i = 0; i < archivos.length; i++) { + const nombre = archivos[i].name; + const tipo = archivos[i].type; + alert("Nombre del archivo: " + nombre + " , Tipo: " + tipo); + } +}</pre> + +<p><strong>Note:</strong> Based on the current implementation, browsers won't actually read the bytestream of a file to determine its media type. It is assumed based on the file extension; a PNG image file renamed to .txt would give "<em>text/plain</em>" and not "<em>image/png</em>". Moreover, <code>file.type</code> is generally reliable only for common file types like images, HTML documents, audio and video. Uncommon file extensions would return an empty string. Client configuration (for instance, the Windows Registry) may result in unexpected values even for common types. <strong>Developers are advised not to rely on this property as a sole validation scheme.</strong></p> + +<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 API', '#dfn-type', 'type')}}</td> + <td>{{Spec2('File API')}}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_los_navegadores">Compatibilidad de los navegadores</h2> + + + +<p>{{Compat("api.File.type")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/File/Using_files_from_web_applications">Usando archivos desde aplicaciones web (Using files from web applications)</a></li> + <li>Blog Post: <a href="https://textslashplain.com/2018/07/26/be-skeptical-of-client-reported-mime-content-types/">Se excéptico de tipos MIME reportados por el cliente (Be skeptical of client-reported MIME types)</a></li> +</ul> diff --git a/files/es/web/api/file/using_files_from_web_applications/index.html b/files/es/web/api/file/using_files_from_web_applications/index.html new file mode 100644 index 0000000000..5aceed9d6a --- /dev/null +++ b/files/es/web/api/file/using_files_from_web_applications/index.html @@ -0,0 +1,372 @@ +--- +title: Utilizar ficheros desde aplicaciones web +slug: Web/API/File/Using_files_from_web_applications +tags: + - Basura + - Ficheros + - HTML5 + - HacerNavegadorAgnóstico + - Intermedio + - NecesitaActualizar + - Subir + - ajax actualización +translation_of: Web/API/File/Using_files_from_web_applications +--- +<p>{{ gecko_minversion_header("1.9.2") }}</p> + +<p> </p> + +<p>El uso de la API File añadida al DOM en HTML5, ahora hace posible que la página web solicite al usuario que seleccione archivos locales y, a continuación, leer el contenido de esos archivos. Esta selección se puede hacer, ya sea usando un elemento {{HTMLElement ( "input")}} de HTML o mediante arrastrar y soltar.</p> + +<h2 id="Selección_de_ficheros_utilizando_HTML">Selección de ficheros utilizando HTML</h2> + +<p>Seleccionar solo un fichero usando la API File es sencillo:</p> + +<pre><code><input type="file" id="input" onchange="handleFiles(this.files)"></code> +</pre> + +<p>Cuando el usuario elige el fichero, la función <code>handleFiles()</code> es llamada con un objeto <a href="/en/DOM/FileList" title="en/DOM/FileList"><code>FileList </code></a>el cual a su vez contiene un objeto <a href="/en/DOM/File" title="en/DOM/File"><code>File</code></a> que representa el fichero elegido por el usuario.</p> + +<p>Si se prefiere permitir al usuario elegir varios ficheros, entonces se pone el atributo <code>multiple </code>en el elemento <code>input:</code></p> + +<pre><code><input type="file" id="input" multiple="true" onchange="handleFiles(this.files)"></code> +</pre> + +<p>En este caso, la lista de ficheros pasada a la función <code>handleFiles() </code>contiene un objeto <a href="/en/DOM/File" title="en/DOM/File"><code>File </code></a>por cada fichero seleccionado por el usuario. </p> + +<p>{{ h2_gecko_minversion("Using hidden file input elements using the click() method", "2.0") }}</p> + +<p>Comenzando en Gecko 2.0 {{ geckoRelease("2.0") }}, se puede ocultar el realmente feo {{ HTMLElement("input") }} y representar tu propio interfaz para abrir el picker de ficheros y pintar que fichero o ficheros ha seleccionado el usuario. Esto se puede hacer añadiendo al elemento input la característica "display:none" en su css, o estilo y llamando al método <code>click() </code>del elemento {{ HTMLElement("input") }}.</p> + +<p>Como aparece en este HTML:</p> + +<pre class="deki-transform"><form> + <input type="file" id="fileElem" multiple accept="image/*" style="display:none" onchange="handleFiles(this.files)"> +</form> + +<a href="javascript:doClick()">Select some files</a> +</pre> + +<p>Tu método <code>doClick()</code> puede parecerse al siguiente:</p> + +<pre class="deki-transform">function doClick() { + var el = document.getElementById("fileElem"); + if (el) { + el.click(); + } +} +</pre> + +<p>Obviamente puedes cambiar como quieras, el estilo del botón para abrir el picker de ficheros.</p> + +<h3 id="Añadir_dinámicamente_un_listener_tipo_change">Añadir dinámicamente un listener tipo change</h3> + +<p>Si tu campo input ha sido creado usando una libreria JavaScript como <a class="external" href="http://www.jquery.com/" title="http://www.jquery.com/">jQuery</a>, se necesitará usar {{ domxref("element.addEventListener()") }} para añadir el manejador de eventos tipo change, como en el ejemplo siguiente:</p> + +<pre class="deki-transform">var inputElement = document.getElementById("inputField"); +inputElement.addEventListener("change", handleFiles, false); + +function handleFiles() { + var fileList = this.files; + + /* now you can work with the file list */ +} +</pre> + +<p>Nota: en este caso, la función <code>handleFiles() </code>mira la lista de ficheros con la finalidad de aceptar un parametro, mientras los eventos listeners sean añadidos de esta manera no pueden aceptar un parametro del input.</p> + +<p>{{ h1_gecko_minversion("Using blob URLs", "2.0") }}</p> + +<p>Gecko 2.0 {{ geckoRelease("2.0") }} introduce soporte para los métodos de DOM {{ domxref("window.createBlobURL()") }} y {{ domxref("window.revokeBlobURL()") }}. El cual te permite crear un simple string con la URL que referenciar cualquier dato que pueda referenciar usando un objeto <a href="/en/DOM/File" title="en/DOM/File"><code>File</code></a> DOM, esto incluye los ficheros locales del usuario del dispositivo.</p> + +<p>Cuando tienes un objeto<a href="/en/DOM/File" title="en/DOM/File"><code> File</code></a> te gusta poder referenciarlo con una URL desde el HTML, la manera de crear tu propio blob URL para poder hacer esto es la siguiente:</p> + +<pre>var blobURL = window.createBlobURL(fileObj); +</pre> + +<p>El blob URL es un string que identifica el objeto<a href="/en/DOM/File" title="en/DOM/File"><code> File</code></a>. Cada vez que se llama a {{ domxref("window.createBlobURL()") }}, un único blob URL se crea. Cada vez que esto pasa debe de ser liberado. Cuando el documento se cierra, se libera automáticamente, pero si tu página lo usa dinámicamente deberás liberarlos explicitamente llamando a {{ domxref("window.revokeBlobURL()") }}:</p> + +<pre>window.revokeBlobURL(blobURL); +</pre> + +<h2 id="Selección_de_ficheros_usando_drag_and_drop">Selección de ficheros usando drag and drop</h2> + +<p>También se puede dejar al usuario arrastrar los ficheros en tu aplicación web.</p> + +<p>El primer paso para establecer la zona de arrastre, el lugar en donde dejar los ficheros arrastrados. La parte exacta en donde se coloque esta zona de arrastre dentro de tu aplicación, dependerá del diseño de la aplicación, pero crear el elemento es sencillo:</p> + +<pre class="deki-transform">var dropbox; + +dropbox = document.getElementById("dropbox"); +dropbox.addEventListener("dragenter", dragenter, false); +dropbox.addEventListener("dragover", dragover, false); +dropbox.addEventListener("drop", drop, false); +</pre> + +<p>En este ejemplo se transforma el elemento de ID "dropbox" en la zona de arrastre. Esto se hace añadiendo listeners para lo eventos de <code>dragenter</code>, <code>dragover</code>, y <code>drop</code>.</p> + +<p>Realmente en este caso no se necesita hacer nada con los eventos <code>dragenter</code> y <code>dragover</code>, por lo que ambas funciones seran muy sencillas. Sólo pararán la propagacion de eventos y prevendran las acciones por defecto:</p> + +<pre class="deki-transform">function dragenter(e) { + e.stopPropagation(); + e.preventDefault(); +} + +function dragover(e) { + e.stopPropagation(); + e.preventDefault(); +} +</pre> + +<p>La verdadera magia ocurre en la función <code>drop()</code>:</p> + +<pre class="deki-transform">function drop(e) { + e.stopPropagation(); + e.preventDefault(); + + var dt = e.dataTransfer; + var files = dt.files; + + handleFiles(files); +} +</pre> + +<p>Aquí se recupera el campo <code>dataTransfer</code> del evento, a partir de ahi se extraen la lista de ficheros, y se pasan a <code>handleFiles()</code>. A partir de este punto se manejan los ficheros de igual manera tanto si se han obtenido usado el elemento <code>input</code> o drag and drop.</p> + +<h2 id="Recuperando_la_información_de_los_ficheros_selecionados">Recuperando la información de los ficheros selecionados</h2> + +<p>El objeto <a href="/en/DOM/FileList" title="en/DOM/FileList"><code>FileList</code></a> es dado por el DOM y lista todos los ficheros selecionados por el usuario, cada uno es un objeto <a href="/en/DOM/File" title="en/DOM/File"><code>File</code></a>. Para determinar el número de ficheros que han sido seleccionados se comprueba la longitud de la lista con el atributo <code>length</code>:</p> + +<pre>var numFiles = files.length; +</pre> + +<p>Al objeto <a href="/en/DOM/File" title="en/DOM/File"><code>File</code></a> se accede de manera sencilla, accediendo a la lista como si fuera un array:</p> + +<pre class="deki-transform">for (var i = 0; i < files.length; i++) { + var file = files[i]; + .. +} +</pre> + +<p>El bucle itera por todos los ficheros de la lista.</p> + +<p>Cada objeto <a href="/en/DOM/File" title="en/DOM/File"><code>File</code></a> tiene tres atributos que contienen información util sobre el fichero.</p> + +<dl> + <dt><code>name</code></dt> + <dd>Es de solo lectura y es el nombre del fichero sin ninguna información sobre el path.</dd> + <dt><code>size</code></dt> + <dd>Es de solo lectura y es el tamaño del fichero en bytes como un entero de 64-bit.</dd> + <dt><code>type</code></dt> + <dd>Es de solo lectura y contiene MIME type del fichero, o "" si el tipo no puede ser determinado.</dd> +</dl> + +<h2 id="Ejemplo_Mostrando_miniaturas_de_una_selección_de_imágenes_del_usuario">Ejemplo: Mostrando miniaturas de una selección de imágenes del usuario</h2> + +<p>Digamos que usted esta desarrollando el próximo gran sitio web para compartir fotos, y quiere usar HTML5 para mostrar previsualizaciones de miniaturas de imágenes antes de que el usuario actual las suba. Basta con establecer su elemento input o zona de arrastre como se indicó anteriormente, y hacer una llamada a una función <code>handleFiles()</code> como la siguiente.</p> + +<pre class="deki-transform">function handleFiles(files) { + for (var i = 0; i < files.length; i++) { + var file = files[i]; + var imageType = /image.*/; + + if (!file.type.match(imageType)) { + continue; + } + + var img = document.createElement("img"); + img.classList.add("obj"); + img.file = file; + preview.appendChild(img); + + var reader = new FileReader(); + reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img); + reader.readAsDataURL(file); + } +} +</pre> + +<p>Aquí nuestro bucle recorre los archivos seleccionados por el usuario y mira el atributo <code>type</code> de cada archivo para ver si es una imagen (haciendo que una expresión regular coincida con la cadena de texto "image.*"). Para cada archivo que sea una imagen, creamos un nuevo elemento <code>img</code>. Se puede usar CSS para establecer bordes bonitos, sombras, y especificar el tamaño de la imagen, el de manera que ni siquiera necesita hacerse aquí.</p> + +<p>Cada imagen tiene la clase CSS "obj" añadida, para hacerla mas fácil buscarla en el árbol del DOM. Además añadimos un atributo<code> file</code> a cada imagen especificando el <a href="/en/DOM/File" title="en/DOM/File"><code>Fichero</code></a> para la imagen; esto nos permitira traer el hecho de subir las imágenes más tarde. Finalmente, usamos {{ domxref("Node.appendChild()") }} para añadir la nueva miniatura en el área de la previsualización de nuestro documento.</p> + +<p>A continuación establecemos el <a href="/en/DOM/FileReader" title="en/DOM/FileReader"><code>FileReader</code></a> para controlar la carga de la imagen de forma asíncrona y enlazarla con el elemento <code>img</code>. Después de crear el nuevo objeto <code>FileReader</code>, configuramos su función <code>onload</code>, luego llamamos a <code>readAsDataURL()</code> para comenzar la operación de lectura en segundo plano. Cuando el contenido completo de la imagen ha sido cargado, se convierte a <code>data:</code> URL, el cuál es pasado al callback <code>onload</code>. Nuestra implementación de esta rutina simplemente establece el atributo <code>src</code> del elemento <code>img</code> cargado, cuyo resultado es la imagen apareciendo en la miniatura en la pantalla del usuario.</p> + +<p>{{ h1_gecko_minversion("Example: Using blob URLs to display images", "2.0") }}</p> + +<p>Este ejemplo el objeto blob URLs para mostrar las miniaturas de las imágenes. Además, se muestra otra información del archivo incluyendo sus nombres y tamaños. Tú puedes <a href="/samples/domref/file-click-demo.html" title="https://developer.mozilla.org/samples/domref/file-click-demo.html">ver el ejemplo</a> (tenga en cuenta que se requiere una versión <a class="external" href="http://nightly.mozilla.org/" title="http://nightly.mozilla.org/">Nghtly</a> de Firefox del 23 de september 23 o mas reciente, o Firefox 4.0 beta 7).</p> + +<p>El HTML que representa la interfaz es::</p> + +<pre class="deki-transform"><form> + <input type="file" id="fileElem" multiple accept="image/*" style="display:none" onchange="handleFiles(this.files)"> +</form> +<a href="javascript:doClick()">Seleccione algunos archivos</a> +<div id="fileList"> + <p>¡No se han seleccionado archivos!</p> +</div> +</pre> + +<p>Esto establece nuestro elemento {{ HTMLElement("input") }} de nuestro, así como un enlace que invoca el selector de archivos, ya que mantenmos el input file oculto para prevenir mostrar un UI menos atractivo. Esto se explica anteriormente en al la sección {{ anch("Using hidden file input elements using the click() method") }}, así como el método <code>doClick()</code> que invoca el el selector de archivos.</p> + +<p>El método <code>handleFiles()</code> es el siguiente:</p> + +<pre class="deki-transform">function handleFiles(files) { + var d = document.getElementById("fileList"); + if (!files.length) { + d.innerHTML = "<p>¡No se han seleccionado archivos!</p>"; + } else { + var list = document.createElement("ul"); + d.appendChild(list); + for (var i=0; i < files.length; i++) { + var li = document.createElement("li"); + list.appendChild(li); + + var img = document.createElement("img"); + img.src = window.createBlobURL(files[i]);; + img.height = 60; + img.onload = function() { + window.revokeBlobURL(this.src); + } + li.appendChild(img); + + var info = document.createElement("span"); + info.innerHTML = files[i].name + ": " + files[i].size + " bytes"; + li.appendChild(info); + } + } +} +</pre> + +<p>Esto comienza buscando la URL del {{ HTMLElement("div") }} con la ID "fileList". Este es el bloque donde vamos a insertar la lista de archivos incluyendo las miniaturas.</p> + +<p>Si el objeto {{ domxref("FileList") }} pasado a <code>handleFiles()</code> es <code>null</code>, simplemente establecemos el bloque inner HTML para mostrar "¡No se han seleccionado archivos!". En caso contrario, comenzamos a construir nuestra lista de archivos como sigue:</p> + +<ol> + <li>Un nuevo elemento de lista desordenada ({{ HTMLElement("ul") }} es creado.</li> + <li>El nuevo elemento de la lista es insertado en el bloque {{ HTMLElement("div") }} llamando a si método {{ domxref("element.appendChild()") }}.</li> + <li>Para cada {{ domxref("File") }} en el {{ domxref("FileList") }} representado <code>files</code>: + <ol> + <li>Se crea un nuevo elemento de lista ({{ HTMLElement("li") }}) y lo inserta en la lista.</li> + <li>Se crea un nuevo elemento imagen ({{ HTMLElement("img") }}).</li> + <li>Establece en la fuente de la imagen un nuevo blob URL representandoel archivo, usando {{ domxref("window.createBlobURL()") }} para crear el blob URL.</li> + <li>Se establece el alto de la imagen en 60 pixels.</li> + <li>Se configura el controlador para el evento load para liberar el blob URL, puesto que ya no es necesario una vez que la imagen ha sido cargada. Esto se hace llamando al método {{ domxref("window.revokeBlobURL()") }}, pasando la cadena en el blob URL como se ha especificado para <code>img.src</code>.</li> + <li>Se añade el nuevo elemento de la lista a la lista.</li> + </ol> + </li> +</ol> + +<h2 id="Ejemplo_Subiendo_un_archivo_seleccionado_por_el_usuario">Ejemplo: Subiendo un archivo seleccionado por el usuario</h2> + +<p>Otra cosa que podrías querer hacer es dejar que el usuario suba el archivo o los archivos seleccionados (como las imagenes seleccionadas usando el ejemplo anterior) al servidor. Esto se puede hacer de forma asíncrona muy facilmente.</p> + +<h3 id="Creando_las_tareas_de_subida">Creando las tareas de subida</h3> + +<p>Continuando con el código que contruye las miniaturas en el ejemplo anterior, hay que recordar que cada imagen en miniatura se encuentra en la clase CSS "obj", con el correspondiente <a href="/en/DOM/File" title="en/DOM/File"><code>File</code></a> adjunto en un attributo <code>file</code>. Vamos a seleccionar todas las imágenes que el usuario ha seleccionado facilmente para subirlas usando {{ domxref("Document.querySelectorAll()") }}, como sigue:</p> + +<pre class="deki-transform">function sendFiles() { + var imgs = document.querySelectorAll(".obj"); + + for (var i = 0; i < imgs.length; i++) { + new FileUpload(imgs[i], imgs[i].file); + } +} +</pre> + +<p>La segunda línea crea un array, llamado<code> imgs</code>, de todos los elementos en el documento con la clase CSS "obj". En nuestro caso, estos serán todas las miniaturas de las imágenes. Una vez que tenemos esa lista, of all the elements in the document with the CSS class "obj". In our case, these will be all the image thumbnails. Once we have that list, es trivial pasar por la lista, creando una nueva instancia de <code>FileUpload</code> por cada una. Subiendo el correspondiente archivo por cada uno de ellos.</p> + +<h3 id="Manipulando_el_proceso_de_carga_de_un_archivo">Manipulando el proceso de carga de un archivo</h3> + +<p>La función <code>FileUpload</code> acepta dos entradas: un elemento de imagen y un archivo desde el que leer los datos de la imagen.</p> + +<pre class="deki-transform">function FileUpload(img, file) { + this.ctrl = createThrobber(img); + var xhr = new XMLHttpRequest(); + this.xhr = xhr; + + var self = this; + this.xhr.upload.addEventListener("progress", function(e) { + if (e.lengthComputable) { + var percentage = Math.round((e.loaded * 100) / e.total); + self.ctrl.update(percentage); + } + }, false); + + xhr.upload.addEventListener("load", function(e){ + self.ctrl.update(100); + var canvas = self.ctrl.ctx.canvas; + canvas.parentNode.removeChild(canvas); + }, false); + + xhr.open("POST", "http://demos.hacks.mozilla.org/paul/demos/resources/webservices/devnull.php"); + xhr.overrideMimeType('text/plain; charset=x-user-defined-binary'); + xhr.sendAsBinary(file.getAsBinary()); +} +</pre> + +<p>La función <code>FileUpload()</code> mostrada arriba crea un throbber, el cual es usado para mostrar la información del progreso, a continuación se crea un <a href="/en/XMLHttpRequest" title="en/XMLHttpRequest"><code>XMLHttpRequest</code></a> para manejar la subida de los datos.</p> + +<p>Antes de subir los datos de hecho, se toman varias medidas preparatorias:</p> + +<ol> + <li>El listener del progreso de la carga del <code>XMLHttpRequest</code>'s se configura para actualizar el throbber con una nueva información de porcentaje, por lo que a medida que progresa la carga, el throbber será actualizado en base a la última información.</li> + <li>El evento "load" de la carga del <code>XMLHttpRequest</code>'s se configura para actualizar el throbber con el 100% como la información de progreso (para asegurar que el indicador de progreso realmente alcanza el 100%, en caso de las <span class="short_text" id="result_box" lang="es"><span class="hps">peculiaridades</span> <span class="hps">de granularidad durante el proceso</span></span>). Entoces se elimina el throbber, puesto que ya no es necesario. Esto causa que el throbber desaparezca una vez la carga está completa.</li> + <li>La petición para cargar la imagen se inicia llamando al método <code>XMLHttpRequest</code>'s <code>open()</code> para comenzar a generar una petición de tipo POST.</li> + <li>El MIME type para la carga se establece llamando a la función <code>deXMLHttpRequest</code> <code>overrideMimeType()</code>. En este caso, estamos usando un MIME type genérico; usted puede o no puede necesitar establecer MIME type en absoluto, dependiendo de su necesidad.</li> + <li>Finalmente, se llama a la función <code>sendAsBinary()</code> del <code>XMLHttpRequest</code> es llamada para subir el contenido del archivo. <em>TEsto es necesario ser revisado, actualmete se está usando la rutina sincronizada en desuso getAsBinary() para extraer los datos del archivo..</em></li> +</ol> + +<h3 id="Manipulación_del_proceso_de_carga_para_un_archivo_de_forma_asíncrona">Manipulación del proceso de carga para un archivo, de forma asíncrona</h3> + +<pre class="deki-transform">function fileUpload(file) { + // Please report improvements to: marco.buratto at tiscali.it + + var fileName = file.name; + var fileSize = file.size; + var fileData = file.getAsBinary(); // works on TEXT data ONLY. + + var boundary = "xxxxxxxxx"; + var uri = "serverLogic.php"; + + var xhr = new XMLHttpRequest(); + + xhr.open("POST", uri, true); + xhr.setRequestHeader("Content-Type", "multipart/form-data, boundary="+boundary); // simulate a file MIME POST request. + xhr.setRequestHeader("Content-Length", fileSize); + + xhr.onreadystatechange = function() { + if (xhr.readyState == 4) { + if ((xhr.status >= 200 && xhr.status <= 200) || xhr.status == 304) { + + if (xhr.responseText != "") { + alert(xhr.responseText); // display response. + } + } + } + } + + var body = "--" + boundary + "\r\n"; + body += "Content-Disposition: form-data; name='fileId'; filename='" + fileName + "'\r\n"; + body += "Content-Type: application/octet-stream\r\n\r\n"; + body += fileData + "\r\n"; + body += "--" + boundary + "--"; + + xhr.send(body); + return true; +} +</pre> + +<p><em>Esto necesita ser modificado para funcionar con datos binarios también.</em></p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><code><a href="/en/DOM/File" title="en/DOM/File">File</a></code></li> + <li><code><a href="/en/DOM/FileList" title="en/DOM/FileList">FileList</a></code></li> + <li><a href="/en/DOM/FileReader" title="en/DOM/FileReader"><code>FileReader</code></a></li> + <li><a href="/En/XMLHttpRequest/Using_XMLHttpRequest" title="En/Using XMLHttpRequest">Usando XMLHttpRequest</a></li> + <li><a href="/en/XMLHttpRequest" title="en/XMLHttpRequest"><code>XMLHttpRequest</code></a></li> +</ul> + +<p>{{ HTML5ArticleTOC() }}</p> diff --git a/files/es/web/api/file/webkitrelativepath/index.html b/files/es/web/api/file/webkitrelativepath/index.html new file mode 100644 index 0000000000..749914e234 --- /dev/null +++ b/files/es/web/api/file/webkitrelativepath/index.html @@ -0,0 +1,132 @@ +--- +title: File.webkitRelativePath +slug: Web/API/File/webkitRelativePath +tags: + - Archivo + - Entidades Archivo y Directorio de la API + - File API + - Propiedad + - Referencia + - Solo lectura + - Web +translation_of: Web/API/File/webkitRelativePath +--- +<p>{{APIRef("File API")}}{{non-standard_header}}</p> + +<p>La propiedad <code><strong>File.webkitRelativePath</strong></code> de solo lectura contiene un {{domxref("USVString")}} el cual especifica la ruta relativa del archivo al directorio seleccionado por el usuario en un elemento {{HTMLElement("input")}} con su {{htmlattrxref("webkitdirectory", "input")}} atributo definido.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="brush: js"><em>var rulaRelativa = File</em>.webkitRelativePath</pre> + +<h3 id="Valor">Valor</h3> + +<p>Un {{domxref("USVString")}} conteniendo la ruta del archivo relativa al directorio padre seleccionado por el usuario.</p> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<p>En este ejemplo,un seleccionador de directorios es mostrado al usuario para permitirle seleccionar uno o mas directorios. Cuando el evento {{event("change")}} ocurre, una lista de todos los archivos contenidos dentro de la gerarquia de directorio seleccionado es generado y mostrado.</p> + +<h3 id="HTML">HTML</h3> + +<pre class="brush: html"><input type="file" id="filepicker" name="fileList" webkitdirectory multiple /> +<ul id="listing"></ul></pre> + +<h3 id="JavaScript">JavaScript</h3> + +<pre class="brush: js">document.getElementById("filepicker").addEventListener("change", function(event) { + let output = document.getElementById("listing"); + let files = event.target.files; + + for (let i=0; i<files.length; i++) { + let item = document.createElement("li"); + item.innerHTML = files[i].webkitRelativePath; + output.appendChild(item); + }; +}, false); +</pre> + +<h3 id="Resultado">Resultado</h3> + +<p>{{ EmbedLiveSample('Example') }}</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificacion</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('File System API', '#dom-file-webkitrelativepath', 'webkitRelativePath') }}</td> + <td>{{ Spec2('File System API') }}</td> + <td>Especificacion inicial.</td> + </tr> + </tbody> +</table> + +<p>Esta API no tiene especificacion W3C o WHATWG.</p> + +<h2 id="Browser_compatibility" name="Browser_compatibility">Compatibilidad con 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>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Soporte basico</td> + <td>13 {{ property_prefix("webkit") }}</td> + <td>{{ CompatGeckoDesktop(49) }}</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>Caracteristica</th> + <th>Android</th> + <th>Chrome para Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte basico</td> + <td>{{ CompatNo }}</td> + <td>0.16 {{ property_prefix("webkit") }}</td> + <td>{{ CompatGeckoMobile(49) }}</td> + <td>{{ CompatNo }}</td> + <td>{{ CompatNo }}</td> + <td>{{ CompatNo }}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Vea_también">Vea también</h2> + +<ul> + <li><a href="/es/docs/Web/API/File_and_Directory_Entries_API">Entidades "Archivo" y "Directorio" en la API</a></li> + <li>{{domxref("HTMLInputElement.webkitEntries")}}</li> + <li>{{domxref("HTMLInputElement.webkitdirectory")}}</li> +</ul> diff --git a/files/es/web/api/fileerror/index.html b/files/es/web/api/fileerror/index.html new file mode 100644 index 0000000000..c748ea51af --- /dev/null +++ b/files/es/web/api/fileerror/index.html @@ -0,0 +1,193 @@ +--- +title: FileError +slug: Web/API/FileError +translation_of: Web/API/FileError +--- +<p>{{APIRef("File System API")}}{{obsolete_header()}}</p> + +<p>Se ha presentado un error al utilizar la interfaz {{ domxref("FileReader") }}.</p> + +<div class="note"> +<p><strong>Nota:</strong> Esta interfaz es obsoleta de acuerdo a la última especificación. Use la nueva DOM4 {{ domxref("DOMError") }} en su lugar.</p> +</div> + +<p>La <a href="/en/DOM/File_API/File_System_API" title="en/DOM/File_API/File_System_APIB">File System API</a>, a <code>FileError Representa un error que puede surgir al acceder al sistema de archivos utilizando la API asíncrona. Se extiende la interfaz FileERror descrita en la escritura del archivo y añadiendo así códigos de error nuevos.</code></p> + +<p>FileError Objects son pasados una vez se haya lanzado un error. Los objetos tiene un código que muestra el tipo de error que haya ocurrido.</p> + +<h2 id="practices" name="practices">Mejores prácticas</h2> + +<p>La mayoría de la gente no lee la página de errores y excepciones a menos que estén perpletos. Así que los siguientes tips, son algúnos consejos que podrían ayudar a evitar algunos problemas.</p> + +<h3 id="Errores_de_retrollamada.">Errores de retrollamada.</h3> + +<p>Aunque las devoluciones de llamada de error son opcionales, usted debe incluirlos en los argumentos de los métodos. Una aplicación web puede fallar por diversas razones, por lo que no requiere pasar el resto de su día adivinando lo que está pasando y/o realizando el sistema.</p> + +<h3 id="No_haga_funcionar_su_aplicación_desde_ruta_(file)">No haga funcionar su aplicación desde ruta:// (file://)</h3> + +<p>Por razones de seguridad, los navegadores no le permiten ejecutar su aplicación desde file://. De hecho, muchas de las API de almacenamiento de gran alcance(como sistema de archivos, BlobBuilder y FileReader) lanzan errores si ejecuta la aplicación a nivel local de file://. Cuando estás haciendo una prueba de su aplicación y no deseas configurar un servidor web, puede pasarse por alto la restricción de seguridad en Chrome. Simplemente comienza a Chrome con la restricción de seguridad en Chrome con la bandera --allow-file- access-from-files Utilice la bandera sólo para propósitos de prueba.</p> + +<p><strong><em>Tradución a español en proceso...</em></strong></p> + +<p>Hasta el momento se ha traducido hasta este punto, las tablas que verás a continuación contienen pequeñas descripciones báscicas de la implementación y el análisis del tema que se está observando.</p> + +<h2 id="Atributo">Atributo</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Attribute</th> + <th scope="col">Type</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><a name="attr_code"><code>code</code></a></td> + <td><code>unsigned short</code></td> + <td>The most appropriate error code for the condition. See {{anch("Error codes")}} for possible values.</td> + </tr> + </tbody> +</table> + +<h2 id="Error_codes">Error codes</h2> + +<p>{{ Note("Do not rely on the numeric values of the constants, which might change as the specifications continue to change. Use the constant names instead.") }}</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + <tr> + <td><code><a name="NON_TRANSIENT_ERR">ENCODING_ERR</a></code></td> + <td>5</td> + <td>The URL is malformed. Make sure that the URL is complete and valid.</td> + </tr> + <tr> + <td><code><a name="NON_TRANSIENT_ERR">INVALID_MODIFICATION_ERR</a></code></td> + <td>9</td> + <td>The modification requested is not allowed. For example, the app might be trying to move a directory into its own child or moving a file into its parent directory without changing its name.</td> + </tr> + <tr> + <td><code><a name="CONSTRAINT_ERR">INVALID_STATE_ERR</a></code></td> + <td>7</td> + <td>The operation cannot be performed on the current state of the interface object. For example, the state that was cached in an interface object has changed since it was last read from disk.</td> + </tr> + <tr> + <td><code><a name="VER_ERR">NO_MODIFICATION_ALLOWED_ERR</a></code></td> + <td>6</td> + <td>The state of the underlying file system prevents any writing to a file or a directory.</td> + </tr> + <tr> + <td><code><a name="NOT_FOUND_ERR">NOT_FOUND_ERR</a></code></td> + <td>1</td> + <td>A required file or directory could not be found at the time an operation was processed. For example, a file did not exist but was being opened.</td> + </tr> + </thead> + <tbody> + <tr> + <td><code><a name="NON_TRANSIENT_ERR">NOT_READABLE_ERR</a></code></td> + <td>4</td> + <td>The file or directory cannot be read, typically due to permission problems that occur after a reference to a file has been acquired (for example, the file or directory is concurrently locked by another application).</td> + </tr> + <tr> + <td><code><a name="TIMEOUT_ERR">PATH_EXISTS_ERR</a></code></td> + <td>12</td> + <td>The file or directory with the same path already exists.</td> + </tr> + <tr> + <td><code><a name="QUOTA_ERR">QUOTA_EXCEEDED_ERR</a></code></td> + <td>10</td> + <td>Either there's not enough remaining storage space or the storage quota was reached and the user declined to give more space to the database. To ask for more storage, see <a class="external" href="http://code.google.com/chrome/whitepapers/storage.html">Managing HTML5 Offline Storage</a>.</td> + </tr> + <tr> + <td><code><a name="SECURITY_ERR">SECURITY_ERR</a></code></td> + <td>2</td> + <td> + <p>Access to the files were denied for one of the following reasons:</p> + + <ul> + <li>The files might be unsafe for access within a Web application.</li> + <li>Too many calls are being made on file resources.</li> + <li>Other unspecified security error code or situations.</li> + </ul> + </td> + </tr> + <tr> + <td><code><a name="READ_ONLY_ERR">TYPE_MISMATCH_ERR</a></code></td> + <td>11</td> + <td>The app looked up an entry, but the entry found is of the wrong type. For example, the app is asking for a directory, when the entry is really a file.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_Compatibility" name="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 (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>13{{ property_prefix("webkit") }}</td> + <td>{{ CompatNo() }}</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 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>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + </tr> + </tbody> +</table> +</div> + +<h3 id="Gecko_notes">Gecko notes</h3> + +<ul> + <li>The <code>FileError</code> interface has been removed starting with Gecko 13 {{ geckoRelease("13.0") }}. Instead the more general {{ domxref("DOMError") }} interface is used and returned by {{ domxref("FileReader", "FileReader.error") }}.</li> +</ul> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en/DOM/File_APIs/Filesystem/Basic_Concepts_About_the_Filesystem_API" title="en/DOM/File_APIs/Filesystem/Basic_Concepts_About_the_Filesystem_API">Basic Concepts About the File System API</a></li> + <li>{{ domxref("FileReader") }}</li> + <li>{{ domxref("File") }}</li> + <li>{{ domxref("Blob") }}</li> + <li>{{ spec("http://www.w3.org/TR/file-system-api/#errors-and-exceptions", "Specification: FileAPI Errors and exceptions", "WD") }}</li> +</ul> diff --git a/files/es/web/api/filereader/index.html b/files/es/web/api/filereader/index.html new file mode 100644 index 0000000000..d5d0f5e349 --- /dev/null +++ b/files/es/web/api/filereader/index.html @@ -0,0 +1,182 @@ +--- +title: FileReader +slug: Web/API/FileReader +translation_of: Web/API/FileReader +--- +<p>{{ APIRef("File API") }}</p> + +<h2 id="Sumario">Sumario</h2> + +<p> </p> + +<p>El objeto FileReader permite que las aplicaciones web lean ficheros (o información en buffer) almacenados en el cliente de forma asíncrona, usando los objetos {{domxref("File")}} o {{domxref("Blob")}} dependiendo de los datos que se pretenden leer.</p> + +<p> </p> + +<p>El objeto File puede ser obtenido desde un objeto {{domxref("FileList")}} devuelto como resultado de la selección de archivos por parte del usuario en un elemento {{HTMLElement("input")}}, desde el objeto <a href="https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer"><code>DataTransfer </code></a><code>producido por una operación de arrastre (<em>drag and drop</em>) o </code>desde la API mozGetAsFile () en un {{domxref("HTMLCanvasElement")}}.</p> + +<h2 id="Constructor">Constructor</h2> + +<pre class="syntaxbox">FileReader FileReader();</pre> + +<p>Mira el artículo <em><a href="https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications">Using files from web applications</a></em> para más detalles y ejemplos.</p> + +<h2 id="Propiedades">Propiedades</h2> + +<dl> + <dt>{{domxref("FileReader.error")}} {{readonlyinline}}</dt> + <dd>Un {{domxref("DOMError")}} que representa el error que ocurrió al momento de leer el archivo.</dd> + <dt>{{domxref("FileReader.readyState")}} {{readonlyinline}}</dt> + <dd>Devuelve un entero que indica el estado de FileReader. Puede ser uno de los siguientes: + <table class="standard-table"> + <tbody> + <tr> + <td><code>EMPTY</code></td> + <td><code>0</code></td> + <td>No ha sido leido ningún dato aún.</td> + </tr> + <tr> + <td><code>LOADING</code></td> + <td><code>1</code></td> + <td>La información está siendo leída.</td> + </tr> + <tr> + <td><code>DONE</code></td> + <td><code>2</code></td> + <td>Se ha completado la solicitud de lectura.</td> + </tr> + </tbody> + </table> + </dd> + <dt>{{domxref("FileReader.result")}} {{readonlyinline}}</dt> + <dd>El contenido del fichero. Esta propieda es válida solo cuando la propiedad FileReader.readyState es 2, es decir, cuando la lectura ha finalizado. El formato de la información depende de los métodos usados al iniciar la operación de lectura.</dd> +</dl> + +<h3 id="Controladores_de_eventos">Controladores de eventos</h3> + +<dl> + <dt>{{domxref("FileReader.onabort")}}</dt> + <dd>Un controlador para el evento {{event("abort")}}. Este evento se activa cada vez que se interrumpe la operación de lectura.</dd> + <dt>{{domxref("FileReader.onerror")}}</dt> + <dd>Un controlador para el evento {{event("error")}}. Este evento se activa cada vez que la operación de lectura encuentra un error.</dd> + <dt>{{domxref("FileReader.onload")}}</dt> + <dd>Un controlador para el evento {{event("load")}}. Este evento se activa cada vez que la operación de lectura se ha completado satisfactoriamente.</dd> + <dt>{{domxref("FileReader.onloadstart")}}</dt> + <dd>Un controlador para el evento {{event("loadstart")}}. Este evento se activa cada vez que comienza la lectura.</dd> + <dt>{{domxref("FileReader.onloadend")}}</dt> + <dd>Un controlador para el evento {{event("loadend")}}. Este evento se activa cada vez que la operación de lecura se ha completado (ya sea con éxito o fallo).</dd> + <dt>{{domxref("FileReader.onprogress")}}</dt> + <dd>Un controlador para el evento {{event("progress")}}. Este evento se activa mientras se está leyendo el contenido del objeto {{domxref("Blob")}}.</dd> +</dl> + +<div class="note"> +<p>Nota: Como <code>FileReader</code> hereda de {{domxref("EventTarget")}}, todos esos eventos también pueden ser escuchados usando el método {{domxref("EventTarget.addEventListener()","addEventListener")}}.</p> +</div> + +<p> </p> + +<h2 id="Methods" name="Methods">Métodos</h2> + +<p> </p> + +<dl> + <dt>{{domxref("FileReader.abort()")}}</dt> + <dd>Interrumpe la operación de lectura. A su regreso <code>readyState</code> será <code>DONE</code>.</dd> + <dt>{{domxref("FileReader.readAsArrayBuffer()")}} {{ gecko_minversion_inline("7.0") }}</dt> + <dd>Comienza la lectura del contenido del objeto {{ domxref("Blob") }} especificado, una vez terminada, el atributo <code>result </code>contiene un {{domxref("ArrayBuffer")}} representando los datos del fichero.</dd> + <dt>{{domxref("FileReader.readAsBinaryString()")}}</dt> + <dd>Comienza la lectura del contenido del objeto {{ domxref("Blob") }}, una vez terminada, el atributo <code>result</code> contiene los datos binarios en bruto del archivo como una cadena.</dd> + <dt>{{domxref("FileReader.readAsDataURL()")}}</dt> + <dd>Comienza la lectura del contenido del objeto {{ domxref("Blob") }}, una vez terminada, el atributo <code>result</code> contiene un <code>data:</code> URL que representa los datos del fichero.</dd> + <dt>{{domxref("FileReader.readAsText()")}}</dt> + <dd>Comienza la lectura del contenido del objeto {{ domxref("Blob") }}, una vez terminada, el atributo <code>result</code> contiene el contenido del fichero como una cadena de texto.</dd> +</dl> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('File API','#FileReader-interface','FileReader')}}</td> + <td>{{Spec2('File API')}}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">Soporte en los navegadores</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Firefox (Gecko)</th> + <th>Chrome</th> + <th>Internet Explorer*</th> + <th>Opera*</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{ CompatGeckoDesktop("1.9.2") }}</td> + <td>7</td> + <td>10</td> + <td>12.02</td> + <td>6.0.2</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Firefox Mobile (Gecko)</th> + <th>Android</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>32</td> + <td>3</td> + <td>10</td> + <td>11.5</td> + <td>6.1</td> + </tr> + </tbody> +</table> +</div> + +<h3 id="Notas_de_implementación">Notas de implementación</h3> + +<ul> + <li>IE9 tiene una <a href="http://html5labs.interoperabilitybridges.com/prototypes/fileapi/fileapi/info" title="http://html5labs.interoperabilitybridges.com/prototypes/fileapi/fileapi/info">File API Lab</a>.</li> + <li>Opera tiene un <a href="http://www.opera.com/docs/specs/presto28/file/" title="http://my.opera.com/desktopteam/blog/2011/04/05/stability-gmail-socks">soporte parcial</a> in 11.1.</li> +</ul> + +<h4 id="Notas_específicas_para_Gecko">Notas específicas para Gecko</h4> + +<ul> + <li>Antes de Gecko 2.0 beta 7 (Firefox 4.0 beta 7), todos los parámetros {{ domxref("Blob") }} de a continuación eran parámetros {{ domxref("File") }}; esto ya se ha actualizado para que coincida con la especificación correcta.</li> + <li>Antes de Gecko 13.0 {{ geckoRelease("13.0") }} la propiedad<code> FileReader.error</code> devolvía un objeto {{ domxref("FileError") }}. Esta interface ha sido eliminada y <code>FileReader.error</code> ahora devielve el objeto {{ domxref("DOMError") }} tal y como se define en el último borrador de FileAPI.</li> +</ul> + +<h2 id="See_also" name="See_also">See also</h2> + +<ul> + <li><a href="/en/Using_files_from_web_applications" title="en/Using files from web applications">Usando archivos desde aplicaciónes web</a></li> + <li>{{ domxref("File") }}</li> + <li>{{ domxref("Blob") }}</li> +</ul> diff --git a/files/es/web/api/filereader/onload/index.html b/files/es/web/api/filereader/onload/index.html new file mode 100644 index 0000000000..d3172638fd --- /dev/null +++ b/files/es/web/api/filereader/onload/index.html @@ -0,0 +1,29 @@ +--- +title: FileReader.onload +slug: Web/API/FileReader/onload +tags: + - Archivo + - Controlador de Eventos + - Lector de Archivos + - Propiedad + - Referencia +translation_of: Web/API/FileReader/onload +--- +<p>{{APIRef}}</p> + +<p>La propiedad <strong><code>FileReader.onload </code></strong><code>contiene un controlador de evento ejecutado cuando </code>{{event('load')}} es ejecutado, cuando el contenido es leído con <a href="/en-US/docs/Web/API/FileReader/readAsArrayBuffer">readAsArrayBuffer</a>, <a href="/en-US/docs/Web/API/FileReader/readAsBinaryString">readAsBinaryString</a>, <a href="/en-US/docs/Web/API/FileReader/readAsDataURL">readAsDataURL</a> o <a href="/en-US/docs/Web/API/FileReader/readAsText">readAsText</a> está habilitado.</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush:js; line-numbers language-js"><code class="language-js">// Respuest desde un <input type="file" onchange="onChange(event)"> +function onChange(event) { + var file = event.target.files[0]; + var reader = new FileReader(); + reader.onload = function(event) { + // El texto del archivo se mostrará por consola aquí + console.log(event.target.result) + }; + + reader.readAsText(file); +} +</code></pre> diff --git a/files/es/web/api/filereader/readasarraybuffer/index.html b/files/es/web/api/filereader/readasarraybuffer/index.html new file mode 100644 index 0000000000..c8ebd96ae7 --- /dev/null +++ b/files/es/web/api/filereader/readasarraybuffer/index.html @@ -0,0 +1,37 @@ +--- +title: FileReader.readAsArrayBuffer() +slug: Web/API/FileReader/readAsArrayBuffer +tags: + - File + - FileReader + - Leer archivo +translation_of: Web/API/FileReader/readAsArrayBuffer +--- +<p>{{APIRef("File API")}}</p> + +<p>El método <strong><code>readAsArrayBuffer</code></strong> es usado para iniciar la lectura del contenido especificado en {{domxref("Blob")}} o {{domxref("File")}}. Cuando finaliza la operación de lectura, el método {{domxref("FileReader.readyState","readyState")}} devuelve <code>DONE</code>, y el evento {{event("loadend")}} es lanzado. Al mismo tiempo, el atributo {{domxref("FileReader.result","result")}} contiene {{domxref("ArrayBuffer")}} que representa los datos del archivo.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre><em>instanceOfFileReader</em>.readAsArrayBuffer(blob);</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code>blob</code></dt> + <dd>El {{domxref("Blob")}} o {{domxref("File")}} (archivo) que se va a leer.</dd> +</dl> + +<h2 id="Browser_Compatibility" name="Browser_Compatibility">Especificaciones</h2> + +<p>{{page("/es-ES/docs/Web/API/FileReader","Specifications")}}</p> + +<h2 id="Browser_compatibility" name="Browser_compatibility">Compatibilidad del navegador</h2> + +<p>{{page("/es-ES/docs/Web/API/FileReader","Browser compatibility")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("FileReader")}} </li> +</ul> diff --git a/files/es/web/api/filereader/readasdataurl/index.html b/files/es/web/api/filereader/readasdataurl/index.html new file mode 100644 index 0000000000..a4f7155a70 --- /dev/null +++ b/files/es/web/api/filereader/readasdataurl/index.html @@ -0,0 +1,68 @@ +--- +title: FileReader.readAsDataURL() +slug: Web/API/FileReader/readAsDataURL +tags: + - Archivos + - Referencia + - metodo +translation_of: Web/API/FileReader/readAsDataURL +--- +<p>{{APIRef("File API")}}</p> + +<p>El método <code>readAsDataURL</code> es usado para leer el contenido del especificado {{domxref("Blob")}} o {{domxref("File")}}. Cuando la operación de lectura es terminada, el {{domxref("FileReader.readyState","readyState")}} se convierte en <code>DONE</code>, y el {{event("loadend")}} es lanzado. En ese momento, el atributo {{domxref("FileReader.result","result")}} contiene la<code> información como una </code>URL representando la información del archivo como una cadena de caracteres codificados en base64.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><em>instanceOfFileReader</em>.readAsDataURL(blob);</pre> + +<h3 id="Parametros">Parametros</h3> + +<dl> + <dt><code>blob</code></dt> + <dd>El {{domxref("Blob")}} o {{domxref("File")}} desde el cual leer.</dd> +</dl> + +<h2 id="Ejemplo">Ejemplo</h2> + +<h3 id="HTML">HTML</h3> + +<pre class="brush: html"><input type="file" onchange="previewFile()"><br> +<img src="" height="200" alt="Image preview..."></pre> + +<h3 id="JavaScript">JavaScript</h3> + +<pre class="brush: js">function previewFile() { + var preview = document.querySelector('img'); + var file = document.querySelector('input[type=file]').files[0]; + var reader = new FileReader(); + + reader.onloadend = function () { + preview.src = reader.result; + } + + if (file) { + reader.readAsDataURL(file); + } else { + preview.src = ""; + } +}</pre> + +<h3 id="Resultado_en_vivo">Resultado en vivo</h3> + +<p>{{EmbedLiveSample("Ejemplo", "100%", 240)}}</p> + +<div class="note"><strong>Nota:</strong> el constructor <a href="/en-US/docs/Web/API/FileReader"><code>FileReader()</code></a> no es soportado por Internet Explorer version anterior a la 10. Para una completa compatibilidad de codigo puedes ver nuestra <a class="internal" href="https://mdn.mozillademos.org/files/3699/crossbrowser_image_preview.html" title="crossbrowser_image_preview.html">Posibler solución de compatibilidad para vista previa de imagenes entre navegadores</a>. Ve también <a href="https://mdn.mozillademos.org/files/3698/image_upload_preview.html">este ejemplo más poderoso</a>.</div> + +<h2 id="Browser_Compatibility" name="Browser_Compatibility">Especificaciones</h2> + +<p>{{page("/en-US/docs/Web/API/FileReader","Specifications")}}</p> + +<h2 id="Browser_compatibility" name="Browser_compatibility">Compatibilidad de navegadores</h2> + +<p>{{page("/en-US/docs/Web/API/FileReader","Browser compatibility")}}</p> + +<h2 id="Tambien_ver">Tambien ver</h2> + +<ul> + <li>{{domxref("FileReader")}}</li> +</ul> diff --git a/files/es/web/api/filereader/readastext/index.html b/files/es/web/api/filereader/readastext/index.html new file mode 100644 index 0000000000..0eaa0e636b --- /dev/null +++ b/files/es/web/api/filereader/readastext/index.html @@ -0,0 +1,109 @@ +--- +title: FileReader.readAsText() +slug: Web/API/FileReader/readAsText +tags: + - API + - File API + - api de lectura de archivos + - leer archivos +translation_of: Web/API/FileReader/readAsText +--- +<div>{{APIRef("File API")}}</div> + +<p>El método <code>readAsText</code> se usa para leer el contenido de un tipo {{domxref("Blob")}} o {{domxref("File")}}. Cuando la operación de lectura se completa, el atributo {{domxref("FileReader.readyState","readyState")}} cambia a <code>DONE</code>, el evento {{event("loadend")}} se dispara y el atributo {{domxref("FileReader.result","result")}} contiene el contenido del archivo como una cadena de texto.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><em>instanceOfFileReader</em>.readAsText(blob[, encoding]);</pre> + +<h3 id="Parametros">Parametros</h3> + +<dl> + <dt><code>blob</code></dt> + <dd>Una variable de tipo {{domxref("Blob")}} o {{domxref("File")}} de la cual se leerán los datos.</dd> + <dt>encoding {{optional_inline}}</dt> + <dd>Una cadena de texto especificando la codificación de caracteres que se usará en los datos leidos. Por defecto, se utiliza UTF-8 si el parametro no se especifica</dd> +</dl> + +<h2 id="Especificaciones">Especificaciones</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("File API", "#FileReader-interface", "FileReader")}}</td> + <td>{{Spec2("File API")}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_los_navegadores">Compatibilidad en los navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Firefox (Gecko)</th> + <th>Chrome</th> + <th>Edge</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatGeckoDesktop("1.9.2")}}<sup>[1]</sup></td> + <td>7</td> + <td>{{CompatVersionUnknown}}</td> + <td>10<sup>[2]</sup></td> + <td>12.02<sup>[3]</sup></td> + <td>6.0.2</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Firefox Mobile (Gecko)</th> + <th>Android</th> + <th>Edge</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>32</td> + <td>3</td> + <td>{{CompatVersionUnknown}}</td> + <td>10</td> + <td>11.5</td> + <td>6.1</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Anterior a Gecko 2.0 beta 7 (Firefox 4.0 beta 7), todos los parámetros de tipo {{domxref("Blob")}} eran de tipo {{domxref("File")}} ; esto ha sido actualizado para emparejarse a la especificacion de manera correcta. Anterior a Gecko 13.0 {{geckoRelease("13.0")}} la propiedad <code>FileReader.error</code> devolvía un objeto de tipo {{domxref("FileError")}}. Esta interfaz ha sido eliminada y ahora la propiedad <code>FileReader.error</code> devuelve el objeto {{domxref("DOMError")}} como está definido en el borrador de FileAPI.</p> + +<p>[2] IE9 tiene una <a href="http://html5labs.interoperabilitybridges.com/prototypes/fileapi/fileapi/info">File API Lab</a>.</p> + +<p>[3] Opera tiene <a href="http://www.opera.com/docs/specs/presto28/file/">soporte parcial</a> in 11.1.</p> + +<h2 id="Vea_también">Vea también</h2> + +<ul> + <li>{{domxref("FileReader")}}</li> +</ul> diff --git a/files/es/web/api/filereader/result/index.html b/files/es/web/api/filereader/result/index.html new file mode 100644 index 0000000000..83104c8e28 --- /dev/null +++ b/files/es/web/api/filereader/result/index.html @@ -0,0 +1,107 @@ +--- +title: FileReader.result +slug: Web/API/FileReader/result +tags: + - API + - Archivos + - Ficheros +translation_of: Web/API/FileReader/result +--- +<div>{{APIRef("File API")}}</div> + +<div> </div> + +<div>La propiedad <code><strong>result</strong></code> de {{domxref("FileReader")}} retorna el contenido del archivo. Esta propiedad es válida únicamente después de que la operación de lectura del archivo es completada. El formato de la infomación devuelta depende de cuál de los métodos de lectura fue usado.</div> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var <em>file</em> = <em>instanceOfFileReader</em>.result +</pre> + +<h3 id="Valor">Valor</h3> + +<p>Una cadena de texto apropiada o un {{domxref("ArrayBuffer")}} dependiendo de cuál método de lectura haya provocado la operación de lectura. El valor es <code>null</code> si la lectura no se ha completado aún o no fue exitosa.</p> + +<p>Los tipos de resultados son descritos a continuación.</p> + +<p> </p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Método</th> + <th scope="col">Descripción</th> + </tr> + </thead> + <tbody> + <tr> + <td><code><a href="/en-US/docs/Web/API/FileReader/readAsArrayBuffer">readAsArrayBuffer()</a></code></td> + <td><code>result</code> es un <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer">ArrayBuffer</a></code> de JavaScript que contiene la información binaria.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/API/FileReader/readAsBinaryString">readAsBinaryString()</a></code></td> + <td> + <p><code>result</code> contiene la información binaria del archivo en una cadena de texto.</p> + </td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/API/FileReader/readAsDataURL">readAsDataURL()</a></code></td> + <td> + <p><code>result</code> es una cadena de texto que representa una URL con la propiedad <code>data:</code> que contiene la información leída del archivo.</p> + </td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/API/FileReader/readAsText">readAsText()</a></code></td> + <td><code>result</code> es una cadena de texto con el contenido del archivo.</td> + </tr> + </tbody> +</table> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>Este ejemplo representa una función <code>read()</code>, que lee un archivo de un <a href="/en-US/docs/Web/HTML/Element/input/file">file input</a>. Funciona creando un objeto de {{domxref("FileReader")}} y creando un listener para los eventos <a href="/en-US/docs/Web/Events/load">load</a> de tal manera que cuando el archivo es leído, la propiedad <code>result</code> es obtenida y pasada a la función callback proporcionada a <code>read()</code>.</p> + +<p>El contenido es manejado como texto.</p> + +<pre class="brush: js">var fileInput = document.querySelector('input[type="file"]'); + +function read(callback) { + var file = fileInput.files.item(0); + var reader = new FileReader(); + + reader.onload = function() { + callback(reader.result); + } + + reader.readAsText(file); +} +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estatus</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName("File API", "#FileReader-interface", "FileReader")}}</td> + <td>{{Spec2("File API")}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + + + +<p>{{Compat("api.FileReader.result")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("FileReader")}}</li> +</ul> diff --git a/files/es/web/api/filesystem/index.html b/files/es/web/api/filesystem/index.html new file mode 100644 index 0000000000..62f5e91b4b --- /dev/null +++ b/files/es/web/api/filesystem/index.html @@ -0,0 +1,118 @@ +--- +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/fullscreen_api/index.html b/files/es/web/api/fullscreen_api/index.html new file mode 100644 index 0000000000..0914c6d627 --- /dev/null +++ b/files/es/web/api/fullscreen_api/index.html @@ -0,0 +1,297 @@ +--- +title: Fullscreen API +slug: Web/API/Fullscreen_API +translation_of: Web/API/Fullscreen_API +--- +<p>{{DefaultAPISidebar("Fullscreen API")}}</p> + +<p class="summary">La <strong><code>API Fullscreen</code></strong> provee una manera fácil de presentar contenido web usando la pantalla completa del usuario. La API permite indicar al navegador que un elemento y sus hijos, si los tiene, ocupar la pantalla completa, ocultando toda la interfaz del usuario y otras aplicaciones de la pantalla mientras se esté en pantalla completa.</p> + +<div class="note"> +<p>De momento, no todos los navegadores usan la versión sin prefijo de la API. Consulta la <a href="#Prefijado">tabla que resume las diferencias de prefijos y nombres</a>.</p> +</div> + +<h2 id="Specification" name="Specification">Activando modo de pantalla completa</h2> + +<p>Para cualquier elemento que quieras presentar en pantalla completa (como por ejemplo, un elemento {{ HTMLElement("video") }}), puedes presentarlo en pantalla completa, simplemente invocando a su método <code>requestFullscreen()</code>.</p> + +<p>Consideremos este elemento {{ HTMLElement("video") }}:</p> + +<pre class="brush: html"><video controls id="myvideo"> + <source src="somevideo.webm"></source> + <source src="somevideo.mp4"></source> +</video> +</pre> + +<p>Podemos poner este video en pantalla completa con un script como éste:</p> + +<pre class="brush: js">var elem = document.getElementById("myvideo"); +if (elem.requestFullscreen) { + elem.requestFullscreen(); +} +</pre> + +<h3 id="Diferencias_de_presentación">Diferencias de presentación</h3> + +<p>Cabe aclarar una diferencia clave entre las implementaciones de Gecko y WebKit: Gecko automáticamente añade reglas CSS al elemento para ajustarlo a las dimensiones de la pantalla: "<code>width: 100%; height: 100%</code>". WebKit no hace esto; en su lugar, centra el elemento con su mismo tamaño original en un fondo negro. Para obtener el mismo comportamiento en WebKit, necesitas añadir manualmente las reglas CSS "<code>width: 100%; height: 100%;</code>" al elemento:</p> + +<pre class="brush: css">#myvideo:-webkit-full-screen { + width: 100%; + height: 100%; +} +</pre> + +<p>Por otro lado, si quieres emular el comportamiento de WebKit en Gecko, necesitarías colocar el elemento a presentar dentro de otro elemento, con las reglas CSS necesarias para ajustarlo a la apariencia requerida, y será dicho elemento contenedor el que se establecerá para aparecer en pantalla completa.</p> + +<h3 id="Notificación">Notificación</h3> + +<p>Cuando el modo de pantalla completa sea invocado exitosamente, el documento que contiene al elemento recibe un evento {{ event("fullscreenchange") }}. Cuando se sale del modo de pantalla completa, el documento recibe de nuevo un evento {{ event("fullscreenchange") }}. Nótese que el evento {{ event("fullscreenchange") }} no provee información alguna sobre si el documento está entrando o saliendo a modo de pantalla completa, pero puedes saber si está en dicho modo si la propiedad {{ domxref("document.fullscreenElement", "fullscreenElement") }} del documento no es nula.</p> + +<h3 id="Cuando_la_solicitud_de_pantalla_completa_falla">Cuando la solicitud de pantalla completa falla</h3> + +<p>No es garantía que se pueda cambiar a modo de pantalla completa. Por ejemplo, los elementos {{ HTMLElement("iframe") }} tienen un atributo {{ HTMLAttrXRef("allowfullscreen", "iframe") }} para decidir si se permitirá que el contenido se muestre en pantalla completa. Además, ciertos tipos de contenido, como plug-ins en ventana, no pueden ser presentados en modo de pantalla completa. Intentar hacerlo con elementos que no lo permitan (o el padre o descendente de un elemento así), no funcionará. En su lugar, el elemento que solicitó la pantalla completa recibirá un evento <code>fullscreenerror</code>. En Firefox, cuando falla una solicitud de pantalla completa, el navegador registrará un mensaje de error en la consola, explicando la falla de la solicitud. En Chrome y versiones recientes de Opera, sin embargo, no se genera ninguna advertencia.</p> + +<div class="note"> +<p><strong>Nota:</strong> Las solicitudes de pantalla completa necesitan ser invocadas dentro de un manejador de eventos, o de otro modo, serán denegadas.</p> +</div> + +<h2 id="Saliendo_del_modo_de_pantalla_completa">Saliendo del modo de pantalla completa</h2> + +<p>El usuario siempre tendrá la habilidad de salir del modo de pantalla completa por su propia cuenta; véase {{ anch("Things_your_users_want_to_know", "Cosas que los usuarios querrán saber") }}. Incluso se puede hacer programáticamente, llamando al método {{domxref("exitFullscreen()")}}.</p> + +<h2 id="Otra_información">Otra información</h2> + +<p>El objeto {{ domxref("document") }} provee información adiciional que puede ser útil al desarrollar aplicaciones de pantalla completa:</p> + +<dl> + <dt>{{ domxref("document.fullscreenElement", "fullscreenElement") }}</dt> + <dd>El atributo <code>fullscreenElement</code> apunta al {{ domxref("element", "elemento") }} actualmente en modo pantalla. Si no es nulo, el documento está en pantalla completa, y si es nulo, no lo está.</dd> + <dt>{{ domxref("document.fullscreenEnabled", "fullscreenEnabled") }}</dt> + <dd>El atributo <code>fullscreenEnabled</code> indica si el documento está actualmente en un estado que permitiría solicitudes al modo de pantalla completa.</dd> +</dl> + +<h2 id="Things_your_users_want_to_know" name="Things_your_users_want_to_know">Cosas que los usuarios querrán saber</h2> + +<p>Puedes asegurarte de hacer saber a los usuarios que pueden presionar la tecla <kbd>ESC</kbd> (o <kbd>F11</kbd>) para salir del modo de pantalla completa.</p> + +<p>Adicionalmente, navegando a otra página, cambiando de pestaña, o cambiando a otra aplicación(usando, por ejemplo, <kbd>Alt</kbd>-<kbd>Tab</kbd>) mientras se está en pantalla completa, también se saldrá de dicho modo.</p> + +<h2 id="Specification" name="Specification">Ejemplo</h2> + +<p>En este ejemplo, se presenta un video en una página web. Presionando la tecla <kbd>Return</kbd> o <kbd>Enter</kbd> el usuario podrá moverse entre modo de ventana o de pantalla completa para la presentación del video.</p> + +<p><a href="/samples/domref/fullscreen.html">Ver ejemplo en vivo</a></p> + +<h3 id="Observando_la_tecla_Enter">Observando la tecla <kbd>Enter</kbd></h3> + +<p>Cuando la página se carga, este código se ejecuta para establecer un evento para cuando se presione la tecla <kbd>Enter</kbd>.</p> + +<pre class="brush: js">document.addEventListener("keydown", function(e) { + if (e.keyCode == 13) { + toggleFullScreen(); + } +}, false); +</pre> + +<h3 id="Cambiando_entre_modo_de_pantalla_completa_y_modo_de_ventana">Cambiando entre modo de pantalla completa y modo de ventana</h3> + +<p>Este código es llamado cuando el usuario presiona la tecla <kbd>Enter</kbd>, como se ve arriba.</p> + +<pre class="brush: js">function toggleFullScreen() { + if (!document.fullscreenElement) { + document.documentElement.requestFullscreen(); + } else { + if (document.exitFullscreen) { + document.exitFullscreen(); + } + } +} +</pre> + +<p>En este código, primero se observa si el atributo <code>fullscreenElement</code> de {{ domxref("document") }} (comprobando si tiene prefijo <code>moz</code>,<code> ms</code>, o <code>webkit</code>). Si es <code>null</code>, el documento está en modo de ventana actualmente, así que necesitamos cambiarlo a modo de pantalla completa. Esto se hace llamando a la función {{ domxref("element.requestFullscreen()") }}.</p> + +<p>Si el modo de pantalla completa está activado (<code>fullscreenElement</code> no es <code>null</code>), llamamos a la función {{ domxref("document.exitFullscreen()") }}.</p> + +<h2 id="Prefijado">Prefijado</h2> + +<p>De momento, no todos los navegadores están implementando la versión sin prefijo de la API. Aquí está la tabla que resume los prefijos y diferencias de nombres entre ellos:</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Estándar</th> + <th scope="col">Blink (Chrome y Opera)</th> + <th scope="col">Gecko (Firefox)</th> + <th scope="col">Internet Explorer 11</th> + <th scope="col">Edge</th> + <th scope="col">Safari (WebKit)</th> + </tr> + <tr> + <td>{{domxref("Document.fullscreen")}}</td> + <td><code>webkitIsFullScreen</code></td> + <td><code>mozFullScreen</code></td> + <td><em>-</em></td> + <td><code>webkitIsFullScreen</code></td> + <td><code>webkitIsFullScreen</code></td> + </tr> + <tr> + <td>{{domxref("Document.fullscreenEnabled")}}</td> + <td><code>webkitFullscreenEnabled</code></td> + <td><code>mozFullScreenEnabled</code></td> + <td><code>msFullscreenEnabled</code></td> + <td><code>webkitFullscreenEnabled</code></td> + <td><code>webkitFullscreenEnabled</code></td> + </tr> + <tr> + <td>{{domxref("Document.fullscreenElement")}}</td> + <td><code>webkitFullscreenElement</code></td> + <td><code>mozFullScreenElement</code></td> + <td><code>msFullscreenElement</code></td> + <td><code>webkitFullscreenElement</code></td> + <td><code>webkitFullscreenElement</code></td> + </tr> + <tr> + <td>{{domxref("Document.onfullscreenchange")}}</td> + <td><code>onwebkitfullscreenchange</code></td> + <td><code>onmozfullscreenchange</code></td> + <td><code>onmsfullscreenchange</code></td> + <td><code>onwebkitfullscreenchange</code></td> + <td><code>onwebkitfullscreenchange</code></td> + </tr> + <tr> + <td>{{domxref("Document.onfullscreenerror")}}</td> + <td><code>onwebkitfullscreenerror</code></td> + <td><code>onmozfullscreenerror</code></td> + <td><code>onmsfullscreenerror</code></td> + <td><code>onwebkitfullscreenerror</code></td> + <td><code>onwebkitfullscreenerror</code></td> + </tr> + <tr> + <td>{{domxref("Document.exitFullscreen()")}}</td> + <td><code>webkitExitFullscreen()</code></td> + <td><code>mozCancelFullScreen()</code></td> + <td><code>msExitFullscreen()</code></td> + <td><code>webkitExitFullscreen()</code></td> + <td><code>webkitExitFullscreen()</code></td> + </tr> + <tr> + <td>{{domxref("Element.requestFullscreen()")}}</td> + <td><code>webkitRequestFullscreen()</code></td> + <td><code>mozRequestFullScreen()</code></td> + <td><code>msRequestFullscreen()</code></td> + <td><code>webkitRequestFullscreen()</code></td> + <td><code>webkitRequestFullscreen()</code></td> + </tr> + </thead> +</table> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estatus</th> + <th scope="col">Comentarios</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("Fullscreen")}}</td> + <td>{{Spec2("Fullscreen")}}</td> + <td>Versión inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">Browser compatibility</h2> + +<p>All browsers implement this APIs. Nevertheless some implement it with prefixed names we slightly different spelling: e.g. instead of <code>requestFullscreen()</code>, there is a <code>MozRequestFullScreen()</code>.</p> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>15 {{ property_prefix("-webkit") }}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{ CompatGeckoDesktop("9.0") }} {{ property_prefix("-moz") }}<br> + {{CompatGeckoDesktop("47")}} (behind <code>full-screen-api.unprefix.enabled</code>)</td> + <td>11 {{ property_prefix("-ms") }}</td> + <td>12.10</td> + <td>5.0 {{ property_prefix("-webkit") }}</td> + </tr> + <tr> + <td><code>fullscreenEnabled</code></td> + <td>20 {{ property_prefix("-webkit") }}</td> + <td>{{CompatUnknown}}</td> + <td>{{ CompatGeckoDesktop("10.0") }} {{ property_prefix("-moz") }}<br> + {{CompatGeckoDesktop("47")}} (behind <code>full-screen-api.unprefix.enabled</code>)</td> + <td>11 {{ property_prefix("-ms") }}</td> + <td>12.10</td> + <td>5.1 {{ property_prefix("-webkit") }}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{ CompatUnknown() }}</td> + <td>28 {{ property_prefix("-webkit") }}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{ CompatGeckoMobile("9.0") }}{{ property_prefix("-moz") }}<br> + {{CompatGeckoMobile("47")}} (behind <code>full-screen-api.unprefix.enabled</code>)</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + </tr> + <tr> + <td><code>fullscreenEnabled</code></td> + <td>{{ CompatUnknown() }}</td> + <td>28 {{ property_prefix("-webkit") }}</td> + <td>{{CompatUnknown}}</td> + <td>{{ CompatGeckoMobile("10.0") }} {{ property_prefix("moz") }}<br> + {{CompatGeckoMobile("47")}} (behind <code>full-screen-api.unprefix.enabled</code>)</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Véase_también">Véase también</h2> + +<ul> + <li>{{ domxref("Element.requestFullscreen()") }}</li> + <li>{{ domxref("Document.exitFullscreen()") }}</li> + <li>{{ domxref("Document.fullscreen") }}</li> + <li>{{ domxref("Document.fullscreenElement") }}</li> + <li>{{ cssxref(":fullscreen") }}, {{cssxref("::backdrop")}}</li> + <li>{{ HTMLAttrXRef("allowfullscreen", "iframe") }}</li> +</ul> diff --git a/files/es/web/api/gamepad_api/index.html b/files/es/web/api/gamepad_api/index.html new file mode 100644 index 0000000000..ea16ef2b62 --- /dev/null +++ b/files/es/web/api/gamepad_api/index.html @@ -0,0 +1,95 @@ +--- +title: Gamepad API +slug: Web/API/Gamepad_API +tags: + - API + - Experimental + - Gamepad API + - juegos +translation_of: Web/API/Gamepad_API +--- +<div>{{DefaultAPISidebar("Gamepad API")}}</div> + +<p><strong>Gamepad API</strong> es la manera de los desarrolladores de acceder y responder a las señales de los gamepads y otros controles para juegos de una manera simple y consistente. Éste contiene tres interfaces, dos eventos y una función especializada, para responder a los gamepads siendo conectados y desconectados, y acceder a otra información sobre los mismos gamepads, y que botones y otros controles están siendo presionados.</p> + +<h2 id="Interfaces">Interfaces</h2> + +<dl> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/API/Gamepad" title="The Gamepad interface of the Gamepad API defines an individual gamepad or other controller, allowing access to information such as button presses, axis positions, and id."><code>Gamepad</code></a></dt> + <dd>Representa un gamepad/control conectado a la computadora.</dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/API/GamepadButton" title="The GamepadButton interface defines an individual button of a gamepad or other controller, allowing access to the current state of different types of buttons available on the control device."><code>GamepadButton</code></a></dt> + <dd>Representa un botón en uno de los gamepads conectados.</dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/API/GamepadEvent" title="The GamepadEvent interface of the Gamepad API contains references to gamepads connected to the system, which is what the gamepad events Window.gamepadconnected and Window.gamepaddisconnected are fired in response to."><code>GamepadEvent</code></a></dt> + <dd>El evento objeto representa eventos que son enviados a los gamepads.</dd> +</dl> + +<h3 id="Extensiones_experimentales_de_los_gamepads">Extensiones experimentales de los gamepads</h3> + +<dl> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/API/GamepadHapticActuator" title="The GamepadHapticActuator interface of the Gamepad API represents hardware in the controller designed to provide haptic feedback to the user (if available), most commonly vibration hardware."><code>GamepadHapticActuator</code></a></dt> + <dd>Representa el hardware en el control designado para proveer retroalimentación háptica al usuario (si está disponible), más comunmente hardware de vibración.</dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/API/GamepadPose" title="The GamepadPose interface of the Gamepad API represents the pose of a WebVR controller at a given timestamp (which includes orientation, position, velocity, and acceleration information.)"><code>GamepadPose</code></a></dt> + <dd>Representa la posición de un control (ej. posición y orientación el espacio 3D) en el caso de un controllador <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebVR_API">WebVR</a>. Éste no es usado por el nuevo estándar <a href="/en-US/docs/Web/API/WebXR_Device_API">WebXR</a>.</dd> +</dl> + +<p>Ver también las <a href="https://developer.mozilla.org/en-US/docs/Web/API/Gamepad#Experimental_extensions_to_Gamepad">extensiones para la interfaz del navegador</a>, para caracteristicas que le permitan acceder a la información mencionada.</p> + +<h3 id="Extensiones_y_otras_interfaces">Extensiones y otras interfaces</h3> + +<h4 id="Navigator">Navigator</h4> + +<dl> + <dt>{{domxref("Navigator.getGamepads()")}}</dt> + <dd>Una extensión a el objeto {{domxref("Navigator")}} que devuelve un arreglo de objetos {{domxref("Gamepad")}}, uno para cada gamepad conectado.</dd> +</dl> + +<h4 id="Eventos_del_Window">Eventos del Window</h4> + +<dl> + <dt>{{domxref("Window.ongamepadconnected")}}</dt> + <dd>Representa un manejador de evento que se ejecutará cuando un gamepad es conectado (cuando se dispara el evento {{event('gamepadconnected')}}).</dd> + <dt>{{domxref("Window.ongamepaddisconnected")}}</dt> + <dd>Representa un manejador de evento que se ejecutará cuando un gamepad es desconectado (cuando se dispara el evento {{event('gamepaddisconnected')}}).</dd> +</dl> + +<h2 id="Guías_y_tutoriales">Guías y tutoriales</h2> + +<ul> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Gamepad_API/Using_the_Gamepad_API">Usando la gamepad API</a></li> + <li><a href="/en-US/docs/Games/Techniques/Controls_Gamepad_API">Implementación de controles usando la gamepad API</a></li> +</ul> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estatus</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName("GamepadExtensions")}}</td> + <td>{{Spec2("GamepadExtensions")}}</td> + <td>Defines the {{anch("Experimental Gamepad extensions")}}.</td> + </tr> + <tr> + <td>{{SpecName("Gamepad", "", "The Gamepad API specification")}}</td> + <td>{{Spec2("Gamepad")}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_del_navegador">Compatibilidad del navegador</h2> + +<div class="hidden">La tabla de compatibilidad es generada de datos estructurados. Si desea contribuir a los datos, por favor, echa un vistazo <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> y envienos una pull request.</div> + +<p>{{Compat("api.Gamepad")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a class="external text" href="https://hacks.mozilla.org/2013/12/the-gamepad-api/" rel="nofollow">La gamepad API</a> por Ted Mielczarek y Robert Nyman</li> + <li><a href="http://luser.github.io/gamepadtest/">Página de demostración simple de la API</a> (<a href="https://github.com/luser/gamepadtest">código fuente</a>)</li> +</ul> diff --git a/files/es/web/api/gamepadbutton/index.html b/files/es/web/api/gamepadbutton/index.html new file mode 100644 index 0000000000..666d75b9a9 --- /dev/null +++ b/files/es/web/api/gamepadbutton/index.html @@ -0,0 +1,90 @@ +--- +title: GamepadButton +slug: Web/API/GamepadButton +tags: + - API + - API Gamepad + - Referencia + - juegos +translation_of: Web/API/GamepadButton +--- +<div>{{APIRef("Gamepad API")}}</div> + +<p>La interfaz <strong><code>GamepadButton</code></strong> define un botón individual de un gamepad u otro control, dando acceso al estado actual de diferentes tipos de botones disponibles en el dispositivo de control.</p> + +<p>Un objeto <code>GamepadButton</code> se devuelve al solicitar cualquier valor del array devuelto por la propiedad <code>buttons</code> de la interfaz {{domxref("Gamepad")}}.</p> + +<div class="note"> +<p><strong>Nota</strong>: Este es el caso en Firefox Gecko 28 en adelante; Chrome y versiones anteriores de Firefox continúan devolviendo un array de valores dobles cuando se accede a esta propiedad.</p> +</div> + +<h2 id="Propiedades">Propiedades</h2> + +<dl> + <dt>{{domxref("GamepadButton.value")}} {{readonlyInline}}</dt> + <dd>Un valor doble usado para representar el estado actual de botones análogos, así como los gatillos de muchos gamepads modernos. Los valores se normalizan al rango 0.0 —1.0, donde 0.0 representa un botón que no está presionado, y 1.0 representa un botón que está completamente presionado.</dd> + <dt>{{domxref("GamepadButton.pressed")}} {{readonlyInline}}</dt> + <dd>Un valor {{domxref("Boolean")}} que indica el estado el botón, ya sea que actualmente se encuentre presionado (<code>true</code>) o sin presionar (<code>false</code>).</dd> +</dl> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>El siguiente código se toma de mi demostración del botón del API de Gamepad (puedes <a href="http://chrisdavidmills.github.io/gamepad-buttons/">ver el demo en vivo</a>, y <a href="https://github.com/chrisdavidmills/gamepad-buttons/tree/master">encontrar el código fuente</a> en Github.) Nota que el código — en Chrome {{domxref("Navigator.getGamepads")}} necesita un prefijo <code>webkit</code> y los valores del botón serán guardados como un array de valores dobles, mientras qe en Firefox {{domxref("Navigator.getGamepads")}} no se necesita un prefijo, y los valores de los botones se guardan como un array de objetos {{domxref("GamepadButton")}}; estas son las propiedades {{domxref("GamepadButton.value")}} o {{domxref("GamepadButton.pressed")}} a las que necesitamos acceder, dependiendo de qué tipo de botones haya. En este simple ejemplo yo solo he permitido estos.</p> + +<pre class="brush: js notranslate">function gameLoop() { + if(navigator.webkitGetGamepads) { + var gp = navigator.webkitGetGamepads()[0]; + + if(gp.buttons[0] == 1) { + b--; + } else if(gp.buttons[1] == 1) { + a++; + } else if(gp.buttons[2] == 1) { + b++; + } else if(gp.buttons[3] == 1) { + a--; + } + } else { + var gp = navigator.getGamepads()[0]; + + if(gp.buttons[0].value > 0 || gp.buttons[0].pressed == true) { + b--; + } else if(gp.buttons[1].value > 0 || gp.buttons[1].pressed == true) { + a++; + } else if(gp.buttons[2].value > 0 || gp.buttons[2].pressed == true) { + b++; + } else if(gp.buttons[3].value > 0 || gp.buttons[3].pressed == true) { + a--; + } + } + + ball.style.left = a*2 + "px"; + ball.style.top = b*2 + "px"; + + var start = rAF(gameLoop); +};</pre> + +<h2 id="Especificaciones">Especificaciones</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("Gamepad", "#gamepadbutton-interface", "GamepadButton")}}</td> + <td>{{Spec2("Gamepad")}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_Navegadores">Compatibilidad de Navegadores</h2> + +<p>{{Compat("api.GamepadButton")}}</p> + +<h2 id="Recomendado">Recomendado</h2> + +<p><a href="/en-US/docs/Web/Guide/API/Gamepad">Usando la API de Gamepad</a></p> diff --git a/files/es/web/api/geolocation/clearwatch/index.html b/files/es/web/api/geolocation/clearwatch/index.html new file mode 100644 index 0000000000..ceb2cec832 --- /dev/null +++ b/files/es/web/api/geolocation/clearwatch/index.html @@ -0,0 +1,134 @@ +--- +title: Geolocation.clearWatch() +slug: Web/API/Geolocation/clearWatch +translation_of: Web/API/Geolocation/clearWatch +--- +<div class="almost_half_cell" id="gt-res-content"> +<div dir="ltr" style="zoom: 1;">{{ APIref("Geolocation API") }}</div> + +<div dir="ltr" style="zoom: 1;"><span id="result_box" lang="es"><span class="hps">El método</span> <span class="hps"><strong><code>Geolocation.clearWatch()</code></strong></span> <span class="hps">se utiliza para</span> <span class="hps">eliminar el registro de</span> <span class="hps">controladores de</span> <span class="hps">monitoreo</span> <span class="hps">lugar/</span><span class="hps">error</span> <span class="hps">previamente instalados</span> <span class="hps">usando</span> <a href="/es/docs/Web/API/Geolocation.watchPosition"><span class="hps">Geolocation.watchPosition()</span></a><span>.</span></span></div> +</div> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">navigator.geolocation.clearWatch(<em>id</em>);</pre> + +<h3 id="Parametros">Parametros</h3> + +<dl> + <dt><em>id</em></dt> + <dd><span id="result_box" lang="es"><span class="hps">El número de identificación</span> <span class="hps">que devuelve el método</span> <a href="/es/docs/Web/API/Geolocation.watchPosition"><span class="hps">Geolocation.watchPosition()</span></a> <span class="hps">al instalar</span> <span class="hps">el controlador</span> <span class="hps">que desea eliminar</span><span>.</span></span></dd> +</dl> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush: js">var id, target, option; + +function success(pos) { + var crd = pos.coords; + + if (target.latitude === crd.latitude && target.longitude === crd.longitude) { + console.log('Congratulation, you reach the target'); + navigator.geolocation.clearWatch(id); + } +}; + +function error(err) { + console.warn('ERROR(' + err.code + '): ' + err.message); +}; + +target = { + latitude : 0, + longitude: 0, +} + +options = { + enableHighAccuracy: false, + timeout: 5000, + maximumAge: 0 +}; + +id = navigator.geolocation.watchPosition(success, error, options); +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estatus</th> + <th scope="col">Comentario</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('Geolocation')}}</td> + <td>{{Spec2('Geolocation')}}</td> + <td>Especificación inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegador">Compatibilidad de navegador</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>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>5</td> + <td>{{CompatGeckoDesktop("1.9.1")}}</td> + <td>9</td> + <td>10.60<br> + Removido en 15.0<br> + Reintroducido en 16.0</td> + <td>5</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Caracteristica</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobil (Gecko)</th> + <th>IE Mobil</th> + <th>Opera Mobil</th> + <th>Safari Mobil</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatUnknown()}}</td> + <td>{{CompatUnknown()}}</td> + <td>{{CompatGeckoMobile("4")}}</td> + <td>{{CompatUnknown()}}</td> + <td>10.60</td> + <td>{{CompatUnknown()}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="/es/docs/Usar_la_Geolocalizaci%C3%B3n">Usar la Geolocalización</a></li> + <li><a href="/es/docs/Web/API/Geolocalizaci%C3%B3n">Geolocalización</a></li> + <li><a href="/es/docs/Web/API/Geolocation.watchPosition">Geolocation.watchPosition()</a></li> + <li><a href="/es/docs/Web/API/Geolocation.getCurrentPosition">Geolocation.getCurrentPosition()</a></li> +</ul> diff --git a/files/es/web/api/geolocation/getcurrentposition/index.html b/files/es/web/api/geolocation/getcurrentposition/index.html new file mode 100644 index 0000000000..436a002971 --- /dev/null +++ b/files/es/web/api/geolocation/getcurrentposition/index.html @@ -0,0 +1,130 @@ +--- +title: Geolocation.getCurrentPosition() +slug: Web/API/Geolocation/getCurrentPosition +translation_of: Web/API/Geolocation/getCurrentPosition +--- +<p>{{ APIref("Geolocation API") }}</p> + +<h2 id="Resumen">Resumen</h2> + +<p>El método <strong><code>Geolocation.getCurrentPosition()</code></strong> se utiliza para obtener la posición de un dispositivo.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">navigator.geolocation.getCurrentPosition(<em>success</em>, <em>error</em>, <em>options</em>)</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><em>success</em></dt> + <dd><span id="result_box" lang="es"><span class="hps">Una función de</span> <span class="hps">devolución de llamada que</span> <span class="hps">toma un objeto</span> <span class="hps">de posición({{domxref("Position")}})</span> <span class="hps">como único</span> <span class="hps">parámetro de entrada.</span></span></dd> + <dt><em>error</em> {{optional_inline}}</dt> + <dd><span id="result_box" lang="es"><span class="hps">Una función</span> <span class="hps">de devolución de llamada</span> <span class="hps">opcional que</span> <span class="hps">toma un objeto</span> {{domxref("PositionError")}} <span class="hps">como único</span> <span class="hps">parámetro de entrada.</span></span></dd> + <dt><em>options</em> {{optional_inline}}</dt> + <dd>Un objeto opcional {{domxref("PositionOptions")}}.</dd> +</dl> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush: js">var options = { + enableHighAccuracy: true, + timeout: 5000, + maximumAge: 0 +}; + +function success(pos) { + var crd = pos.coords; + + console.log('Your current position is:'); + console.log('Latitude : ' + crd.latitude); + console.log('Longitude: ' + crd.longitude); + console.log('More or less ' + crd.accuracy + ' meters.'); +}; + +function error(err) { + console.warn('ERROR(' + err.code + '): ' + err.message); +}; + +navigator.geolocation.getCurrentPosition(success, error, options); +</pre> + +<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('Geolocation')}}</td> + <td>{{Spec2('Geolocation')}}</td> + <td>Especificación inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegador">Compatibilidad de navegador</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>5</td> + <td>{{CompatGeckoDesktop("1.9.1")}}</td> + <td>9</td> + <td>10.60<br> + Eliminado en 15.0<br> + Reintroducido en 16.0</td> + <td>5</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Chrome para Android</th> + <th>Firefox Mobil (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobil</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatUnknown()}}</td> + <td>{{CompatUnknown()}}</td> + <td>{{CompatGeckoMobile("4")}}</td> + <td>{{CompatUnknown()}}</td> + <td>10.60</td> + <td>{{CompatUnknown()}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="/es/docs/Usar_la_Geolocalizaci%C3%B3n">Usar la geolocalización</a></li> + <li><a href="/es/docs/Web/API/Geolocalizaci%C3%B3n">Geolocalización</a></li> + <li><a href="/es/docs/Web/API/Geolocation.watchPosition">watchPosition()</a></li> +</ul> diff --git a/files/es/web/api/geolocation/index.html b/files/es/web/api/geolocation/index.html new file mode 100644 index 0000000000..56d37a2314 --- /dev/null +++ b/files/es/web/api/geolocation/index.html @@ -0,0 +1,114 @@ +--- +title: Geolocalización +slug: Web/API/Geolocation +translation_of: Web/API/Geolocation +--- +<div>{{APIRef("Geolocation API")}}</div> + +<p><span id="result_box" lang="es"><span class="hps">La interfaz</span> <strong><span class="hps">Geolocalización</span></strong> <span class="hps">representa</span> <span class="hps">un objeto</span> <span class="hps">capaz de</span> <span class="hps">obtener</span> <span class="hps">mediante programación</span> <span class="hps">la posición</span> <span class="hps">del dispositivo</span><span>.</span> <span class="hps">Se</span> <span class="hps">da</span> <span class="hps">acceso Web</span> de <span class="hps">la ubicación</span> <span class="hps">del dispositivo</span><span>.</span> <span class="hps">Esto</span> <span class="hps">permite a un sitio</span> <span class="hps">Web</span> <span class="hps">o aplicación</span> <span class="hps">ofrecer</span> <span class="hps">resultados personalizados</span> <span class="hps">basados en</span> <span class="hps">la ubicación del usuario</span><span>.</span></span></p> + +<p><span id="result_box" lang="es"><span class="hps">Se obtiene un</span> <span class="hps">objeto con</span> <span class="hps">esta interfaz</span> <span class="hps">mediante la propiedad </span></span>{{domxref("NavigatorGeolocation.geolocation")}} <span lang="es"><span class="hps">implementado</span> <span class="hps">por el objeto</span> <span class="hps">{{domxref("Navigator")}}.</span></span></p> + +<div class="note"> +<p><strong>Nota:</strong> <span id="result_box" lang="es"><span class="hps">Por razones de seguridad</span><span>,</span> <span class="hps">cuando una página</span> <span class="hps">web</span> <span class="hps">intenta obtener acceso a</span> <span class="hps">la información de ubicación</span><span>,</span> <span class="hps">se notifica al usuario</span> <span class="hps">y le pide </span><span class="hps">conceder el permiso</span><span>.</span> <span class="hps">Tenga en cuenta que</span> <span class="hps">cada navegador</span> <span class="hps">tiene sus</span> <span class="hps">propias políticas y</span> <span class="hps">métodos para solicitar</span> <span class="hps">este permiso.</span></span></p> +</div> + +<h2 id="Propiedades">Propiedades</h2> + +<p><span id="result_box" lang="es"><span class="hps">La</span> <span class="hps">interfaz de</span> <span class="hps">Geolocalización</span> no implementa<span> ni</span> <span class="hps">hereda</span> <span class="hps">propiedades</span><span>.</span></span></p> + +<h2 id="Métodos">Métodos</h2> + +<p><em><span id="result_box" lang="es"><span class="hps">La interfaz</span> <code><span class="hps">Geolocation</span></code> <span class="hps">no hereda</span> <span class="hps">ningún método.</span></span></em></p> + +<dl> + <dt><a href="/es/docs/Web/API/Geolocation.getCurrentPosition">Geolocation.getCurrentPosition()</a></dt> + <dd><span id="result_box" lang="es"><span class="hps">Determina</span> <span class="hps">la ubicación actual del</span> <span class="hps">dispositivo y</span> <span class="hps">devuelve</span> <span class="hps">un objeto</span> <span class="hps">de posición({{domxref("Position")}}) con</span> <span class="hps">los datos.</span></span></dd> + <dt><a href="/es/docs/Web/API/Geolocation.watchPosition">Geolocation.watchPosition()</a></dt> +</dl> + +<p><span id="result_box" lang="es"><span class="hps">Devuelve un</span> <span class="hps">valor de largo(<code>long</code>)</span> <span class="hps">que representa la función</span> <span class="hps">de devolución de llamada</span> <span class="hps">de reciente creación</span> <span class="hps">que se invoca</span> <span class="hps">cada vez que cambia</span> <span class="hps">la ubicación del dispositivo</span><span>.</span></span></p> + +<dl> + <dt><a href="/es/docs/Web/API/Geolocation.clearWatch">Geolocation.clearWatch()</a></dt> + <dd><span id="result_box" lang="es"><span class="hps">Elimina el controlador</span> <span class="hps">especial</span> <span class="hps">instalado</span> <span class="hps">previamente utilizando</span></span> <a href="/es/docs/Web/API/Geolocation.watchPosition"><code>watchPosition()</code></a>.</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('Geolocation')}}</td> + <td>{{Spec2('Geolocation')}}</td> + <td>Especificación inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_navegador">Compatibilidad en navegador</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>5</td> + <td>{{CompatGeckoDesktop("1.9.1")}}</td> + <td>9</td> + <td>10.60<br> + Removido en 15.0<br> + Reintroducido en 16.0</td> + <td>5</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Chrome para Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatUnknown()}}</td> + <td>{{CompatUnknown()}}</td> + <td>{{CompatGeckoMobile("4")}}</td> + <td>{{CompatUnknown()}}</td> + <td>10.60</td> + <td>{{CompatUnknown()}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="/es/docs/Usar_la_Geolocalizaci%C3%B3n">Usar la geolocalización</a></li> +</ul> diff --git a/files/es/web/api/geolocation/watchposition/index.html b/files/es/web/api/geolocation/watchposition/index.html new file mode 100644 index 0000000000..dbd6a1170d --- /dev/null +++ b/files/es/web/api/geolocation/watchposition/index.html @@ -0,0 +1,138 @@ +--- +title: Geolocation.watchPosition() +slug: Web/API/Geolocation/watchPosition +translation_of: Web/API/Geolocation/watchPosition +--- +<p>{{ APIref("Geolocation API") }}</p> + +<p><span id="result_box" lang="es"><span class="hps">El método</span> <strong><code>Geolocation.watchPosition()</code></strong> <span class="hps">se utiliza para registrar</span> <span class="hps">una función de controlador</span> <span class="hps">que se llamará</span> <span class="hps">automáticamente cada vez que</span> <span class="hps">la posición</span> <span class="hps">del dispositivo cambia</span><span>.</span> <span class="hps">También puede</span><span>,</span> <span class="hps">opcionalmente</span><span>,</span> <span class="hps">especificar una</span> <span class="hps">función de devolución de</span> <span class="hps">la gestión de errores</span><span>.</span></span></p> + +<p><span id="result_box" lang="es"><span class="hps">Este método devuelve un</span> <span class="hps">valor de ID de</span> <span class="hps">seguimiento</span> <span class="hps">que</span> <span class="hps">se puede utilizar para</span> <span class="hps">anular el registro del</span> <span class="hps">controlador</span> <span class="hps">pasándolo</span> <span class="hps">al método</span> </span><a href="/es/docs/Web/API/Geolocation.clearWatch">Geolocation.clearWatch()</a>.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><em>id</em> = navigator.geolocation.watchPosition(<em>success</em>, <em>error</em>, <em>options</em>)</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><em>success</em></dt> + <dd><span id="result_box" lang="es"><span class="hps">Una función de</span> <span class="hps">devolución de llamada que</span> <span class="hps">toma un objeto</span> <span class="hps">de posición</span>({{domxref("Position")}}) <span class="hps">como parámetro de entrada</span><span>.</span></span></dd> + <dt><em>error</em> {{optional_inline}}</dt> + <dd><span id="result_box" lang="es"><span class="hps">Una función</span> <span class="hps">de devolución de llamada</span> <span class="hps">opcional que</span> <span class="hps">toma un objeto</span> {{domxref("PositionError")}} <span class="hps">como parámetro de entrada</span><span>.</span></span></dd> + <dt><em>options</em> {{optional_inline}}</dt> + <dd>Un objeto opcional {{domxref("PositionOptions")}}.</dd> +</dl> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush: js">var id, target, option; + +function success(pos) { + var crd = pos.coords; + + if (target.latitude === crd.latitude && target.longitude === crd.longitude) { + console.log('Congratulation, you reach the target'); + navigator.geolocation.clearWatch(id); + } +}; + +function error(err) { + console.warn('ERROR(' + err.code + '): ' + err.message); +}; + +target = { + latitude : 0, + longitude: 0, +} + +options = { + enableHighAccuracy: false, + timeout: 5000, + maximumAge: 0 +}; + +id = navigator.geolocation.watchPosition(success, error, options); +</pre> + +<h2 id="Especificacines">Especificacines</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('Geolocation', '#watch-position', 'Geolocation.watchPosition()')}}</td> + <td>{{Spec2('Geolocation')}}</td> + <td>Especificación inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegador">Compatibilidad de navegador</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>5</td> + <td>{{CompatGeckoDesktop("1.9.1")}}</td> + <td>9</td> + <td>10.60<br> + Eliminado en 15.0<br> + Reintroducido en 16.0</td> + <td>5</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Chrome para Android</th> + <th>Firefox Mobil (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobil</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatUnknown()}}</td> + <td>{{CompatUnknown()}}</td> + <td>{{CompatGeckoMobile("4")}}</td> + <td>{{CompatUnknown()}}</td> + <td>10.60</td> + <td>{{CompatUnknown()}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="/es/docs/Usar_la_Geolocalizaci%C3%B3n">Uso de la geolocalización</a></li> + <li><a href="/es/docs/Web/API/Geolocalizaci%C3%B3n">Geolocalización</a>.</li> + <li><a href="/es/docs/Web/API/Geolocation.clearWatch">Geolocation.clearWatch()</a></li> + <li><a href="/es/docs/Web/API/Geolocation.getCurrentPosition">Geolocation.getCurrentPosition()</a></li> +</ul> diff --git a/files/es/web/api/geolocationcoordinates/index.html b/files/es/web/api/geolocationcoordinates/index.html new file mode 100644 index 0000000000..e59758e448 --- /dev/null +++ b/files/es/web/api/geolocationcoordinates/index.html @@ -0,0 +1,113 @@ +--- +title: Coordinates +slug: Web/API/GeolocationCoordinates +translation_of: Web/API/GeolocationCoordinates +--- +<div>{{APIRef("Geolocation API")}}</div> + +<p>La interfaz <strong><code>Coordinates</code></strong> representa la posición y altitud del dispositivo en la Tierra, así como la precisión con la cual estas propiedades son calculadas.</p> + +<h2 id="Propiedades">Propiedades</h2> + +<p><em>La interfaz <code>Coordinates</code> no hereda ninguna propiedad</em>.</p> + +<dl> + <dt>{{domxref("Coordinates.latitude")}} {{readonlyInline}}</dt> + <dd>Devuelve un <code>double</code> que representa la latitud de la posición en grados con decimales.</dd> + <dt>{{domxref("Coordinates.longitude")}} {{readonlyInline}}</dt> + <dd>Devuelve un <code>double</code> que representa la longitud de la posición en grados con decimales.</dd> + <dt>{{domxref("Coordinates.altitude")}} {{readonlyInline}}</dt> + <dd>Devuelve un <code>double</code> que representa la altitud de la posición en metros, relativo al nivel del mar. Este valor puede ser <code>null</code> si la implementación no puede proporcionar la información.</dd> + <dt>{{domxref("Coordinates.accuracy")}} {{readonlyInline}}</dt> + <dd>Devuelve un <code>double</code> que representa la precisión de las propiedades <code>latitude</code> y <code>longitude</code>, expresada en metros.</dd> + <dt>{{domxref("Coordinates.altitudeAccuracy")}} {{readonlyInline}}</dt> + <dd>Devuelve un <code>double</code> que representa la precisión de la propiedad <code>altitude</code> expresada en metros. Este valor puede ser <code>null</code>.</dd> + <dt>{{domxref("Coordinates.heading")}} {{readonlyInline}}</dt> + <dd>Devuelve un <code>double</code> que representa la dirección en la que el dispositivo está viajando. Este valor, indicado en grados, indica la distancia real a la que el dispositivo se encuentra del norte. <code>0</code> grados representa el norte real, y la dirección se determina en el sentido de la agujas del reloj (lo que significa que el este es <code>90</code> grados y el oeste es <code>270</code> grados). Si <code>speed</code> es <code>0</code>, <code>heading</code> es <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/NaN" title="/en-US/docs/JavaScript/Reference/Global_Objects/NaN">NaN</a></code>. En caso de que el dispositivo no pueda proporcionar la información de <code>heading</code>, este valor es <code>null</code>.</dd> + <dt>{{domxref("Coordinates.speed")}} {{readonlyInline}}</dt> + <dd>Devuelve un <code>double</code> que representa la velocidad del dispositivo en metros por segundo. Este valor puede ser <code>null</code>.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<p><em><em>La interfaz <code>Coordinates</code> no implementa ni edita ningún método<em>.</em></em></em></p> + +<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('Geolocation', '#coordinates', 'Coordinates')}}</td> + <td>{{Spec2('Geolocation')}}</td> + <td>Especificación inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_navegadores">Compatibilidad en navegadores</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>5</td> + <td>{{CompatGeckoDesktop("1.9.1")}}</td> + <td>9</td> + <td>10.60<br> + {{CompatNo}} 15.0<br> + 16.0</td> + <td>5</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Chrome para Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatUnknown()}}</td> + <td>{{CompatUnknown()}}</td> + <td>{{CompatGeckoMobile("4")}}</td> + <td>{{CompatUnknown()}}</td> + <td>10.60</td> + <td>{{CompatUnknown()}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/WebAPI/Using_geolocation" title="/en-US/docs/WebAPI/Using_geolocation">Utilizando la geolocalización</a></li> + <li>La interfaz {{domxref("Geolocation")}} que la utiliza.</li> +</ul> diff --git a/files/es/web/api/geolocationcoordinates/latitude/index.html b/files/es/web/api/geolocationcoordinates/latitude/index.html new file mode 100644 index 0000000000..0bff2b5c34 --- /dev/null +++ b/files/es/web/api/geolocationcoordinates/latitude/index.html @@ -0,0 +1,97 @@ +--- +title: Coordinates.latitude +slug: Web/API/GeolocationCoordinates/latitude +translation_of: Web/API/GeolocationCoordinates/latitude +--- +<div>{{APIRef("Geolocation API")}}</div> + +<p><code><strong>Coordinates.latitude</strong></code> es una propiedad de sólo lectura que devuelve un <code>double</code> representando la latitud de la posición en grados decimales.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="brush: js"><em>lat</em> = <code><em>coordinates</em><code>.latitude</code></code> +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estatus</th> + <th scope="col">Comentario</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('Geolocation', '#lat', 'Coordinates.latitude')}}</td> + <td>{{Spec2('Geolocation')}}</td> + <td>Especificación Inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>5</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("1.9.1")}}</td> + <td>9</td> + <td>10.60<br> + {{CompatNo}} 15.0<br> + 16.0</td> + <td>5</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("4")}}</td> + <td>{{CompatUnknown}}</td> + <td>10.60</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Mirar_también">Mirar también</h2> + +<ul> + <li><a href="/es/docs/WebAPI/Using_geolocation">Uso de geolocalización</a></li> + <li>La interfaz {{domxref("Coordinates")}} a la que pertenece.</li> +</ul> diff --git a/files/es/web/api/geolocationposition/index.html b/files/es/web/api/geolocationposition/index.html new file mode 100644 index 0000000000..23c3881e5c --- /dev/null +++ b/files/es/web/api/geolocationposition/index.html @@ -0,0 +1,63 @@ +--- +title: Position +slug: Web/API/GeolocationPosition +tags: + - API + - Contexto seguro + - Geolocalización + - Geolocation API + - Interfaz + - Posición + - Position +translation_of: Web/API/GeolocationPosition +--- +<div>{{securecontext_header}}{{APIRef("Geolocation API")}}</div> + +<p>La interfaz <strong><code>Position</code></strong> representa la posición del dispositivo en cuestión en un momento dado. La posición, representada por el objeto {{domxref("Coordinates")}}, comprende la posición en dos dimensiones del dispositivo en un esferoide representando la Tierra y además su altitud y velocidad.</p> + +<h2 id="Propiedades">Propiedades</h2> + +<p><em>La interfaz <code>Position</code> no hereda ninguna propiedad.</em></p> + +<dl> + <dt>{{domxref("Position.coords")}} {{readonlyInline}} {{securecontext_inline}}</dt> + <dd>Devuelve un objeto {{domxref("Coordinates")}} que indica la posición actual.</dd> + <dt>{{domxref("Position.timestamp")}} {{readonlyInline}} {{securecontext_inline}}</dt> + <dd>Devuelve un {{domxref("DOMTimeStamp")}} indicando el momento en que la localización ha sido recuperada.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<p><em><em>La interfaz <code>Position</code> no implementa ni hereda ningún método<em>.</em></em></em></p> + +<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('Geolocation', '#position', 'Position')}}</td> + <td>{{Spec2('Geolocation')}}</td> + <td>Especificación inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2> + +<div class="hidden">La tabla de compatibilidad de esta página está generada a partir de datos estructurados. Si quieres contribuir con datos, por favor, revisa <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> y envíanos una pull request.</div> + +<p>{{Compat("api.Position")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/WebAPI/Using_geolocation">Using geolocation</a></li> + <li>La interfaz {{domxref("Geolocation")}} que la usa.</li> +</ul> diff --git a/files/es/web/api/globaleventhandlers/index.html b/files/es/web/api/globaleventhandlers/index.html new file mode 100644 index 0000000000..7cc46be5aa --- /dev/null +++ b/files/es/web/api/globaleventhandlers/index.html @@ -0,0 +1,272 @@ +--- +title: GlobalEventHandlers +slug: Web/API/GlobalEventHandlers +tags: + - API + - DOM HTML + - GlobalEventHandlers + - Mixin + - Referencia + - combinación + - eventos +translation_of: Web/API/GlobalEventHandlers +--- +<div>{{ApiRef("DOM HTML")}}</div> + +<p><span class="seoSummary">La combinación («<em>mixin</em>» en inglés) <strong><code>GlobalEventHandlers</code> </strong> describe los controladores de eventos comunes a varias interfaces como {{DOMxRef("HTMLElement")}}, {{DOMxRef("Document")}} o {{DOMxRef("Window")}}.</span> Cada una de estas interfaces puede, por supuesto, agregar más controladores de eventos además de los que se enumeran a continuación.</p> + +<div class="note"> +<p><strong>Nota</strong>: <code>GlobalEventHandlers</code> es una combinación («<em>mixin</em>») y no una interfaz; en realidad, no puedes crear un objeto de tipo <code>GlobalEventHandlers</code>.</p> +</div> + +<h2 id="Propiedades_2">Propiedades</h2> + +<p><em>Esta interfaz no incluye ninguna propiedad excepto los controladores de eventos que se enumeran a continuación.</em></p> + +<h3 id="Controladores_de_eventos">Controladores de eventos</h3> + +<p>Estos controladores de eventos se definen en el mixin {{DOMxRef("GlobalEventHandlers")}} y se implementan mediante {{DOMxRef("HTMLElement")}}, {{DOMxRef("Document")}}, {{DOMxRef("Window ")}}, así como por {{DOMxRef("WorkerGlobalScope")}} para «<em>Web Workers</em>».</p> + +<div id="Propiedades"> +<dl> + <dt>{{DOMxRef("GlobalEventHandlers.onabort")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{DOMxRef("HTMLMediaElement/abort_event", "abort")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onanimationcancel")}} {{Non-standard_inline}}</dt> + <dd>Se llama a {{DOMxRef("EventHandler")}} cuando se envía un evento {{event("animationcancel")}}, lo cual indica que una {{web.link("/s/docs/Web/CSS/CSS_Animations", "animación CSS")}} se ha cancelado.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onanimationend")}} {{Non-standard_inline}}</dt> + <dd>Se llama a {{DOMxRef("EventHandler")}} cuando se envía un evento {{event("animationend")}}, lo cual indica que {{web.link("/es/docs/Web/CSS/CSS_Animations", "la animación CSS")}} se ha detenido.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onanimationiteration")}} {{Non-standard_inline}}</dt> + <dd>Un {{DOMxRef("EventHandler")}} llamado cuando se ha enviado un evento {{event("animationiteration")}}, indica que una {{web.link("/es/docs/Web/CSS/CSS_Animations", "animación CSS")}} ha comenzado a reproducir una nueva iteración de la secuencia de animación.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onanimationstart")}} {{Non-standard_inline}}</dt> + <dd>Se llama a {{DOMxRef("EventHandler")}} cuando se envía un evento {{event("animationstart")}}, lo cual indica que una {{web.link("/es/docs/Web/CSS/CSS_Animations", "animación CSS")}} se ha comenzado a reproducir.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onauxclick")}} {{Non-standard_inline}}</dt> + <dd>Se llama a {{DOMxRef("EventHandler")}} cuando se envía un evento {{event("auxclick")}}, el cual indica que se ha presionado un botón no principal en un dispositivo de entrada (por ejemplo, un botón central del ratón).</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onblur")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("blur")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onerror")}}</dt> + <dd>Es un {{DOMxRef("OnErrorEventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("error")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onfocus")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("focus")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.oncancel")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("cancel")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.oncanplay")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("canplay")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.oncanplaythrough")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("canplaythrough")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onchange")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("change")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onclick")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("click")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onclose")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("close")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.oncontextmenu")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("contextmenu")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.oncuechange")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("cuechange")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.ondblclick")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("dblclick")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.ondrag")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("drag")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.ondragend")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("dragend")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.ondragenter")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("dragenter")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.ondragexit")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("dragexit")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.ondragleave")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("dragleave")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.ondragover")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("dragover")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.ondragstart")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("dragstart")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.ondrop")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("drop")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.ondurationchange")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("durationchange")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onemptied")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("emptied")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onended")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("ended")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onformdata")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} para procesar eventos {{event("formdata")}}, que se activa después de que se construye la lista de entrada que representa los datos del formulario.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.ongotpointercapture")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el tipo de evento {{event("gotpointercapture")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.oninput")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("input")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.oninvalid")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("invalid")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onkeydown")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("keydown")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onkeypress")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("keypress")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onkeyup")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("keyup")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onload")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("load")}} event is raised.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onloadeddata")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("loadeddata ")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onloadedmetadata")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("loadedmetadata")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onloadend")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("loadend")}} (cuando el progreso se haya detenido en la carga de un recurso).</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onloadstart")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("loadstart")}} (cuando el progreso ha comenzado a cargar un recurso).</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onlostpointercapture")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el tipo de evento {{event("lostpointercapture")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onmousedown")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("mousedown")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onmouseenter")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("mouseenter")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onmouseleave")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("mouseleave")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onmousemove")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("mousemove")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onmouseout")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("mouseout")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onmouseover")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("mouseover")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onmouseup")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("mouseup")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onmousewheel")}} {{Non-standard_inline}} {{Deprecated_inline}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("mousewheel")}}. Desaprobado. Utiliza <code>onwheel</code> en su lugar.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onwheel")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("wheel")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onpause")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("pause")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onplay")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("play")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onplaying")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("playing")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onpointerdown")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("pointerdown")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onpointermove")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("pointermove")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onpointerup")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("pointerup")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onpointercancel")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("pointercancel")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onpointerover")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("pointerover")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onpointerout")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("pointerout")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onpointerenter")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("pointerenter")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onpointerleave")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("pointerleave")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onpointerlockchange")}} {{experimental_inline}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("pointerlockchange")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onpointerlockerror")}} {{experimental_inline}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("pointerlockerror")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onprogress")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("progress")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onratechange")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("ratechange")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onreset")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("reset")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onresize")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("resize")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onscroll")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("scroll")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onseeked")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("seeked")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onseeking")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("seek")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onselect")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("select")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onselectstart")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("selectionchange")}}, es decir, cuando el usuario comience a realizar una nueva selección de texto en una página web.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onselectionchange")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genera el evento {{event("selectionchange")}}, es decir, cuando cambia el texto seleccionado en una página web.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onshow")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("show")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onsort")}} {{experimental_inline}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("sort")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onstalled")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("stalled")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onsubmit")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("submit")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onsuspend")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("suspend")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.ontimeupdate")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("timeupdate")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onvolumechange")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("volumechange")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.ontouchcancel")}} {{Non-standard_inline}} {{Experimental_inline}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("touchcancel")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.ontouchend")}} {{Non-standard_inline}} {{Experimental_inline}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("touchend")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.ontouchmove")}} {{Non-standard_inline}} {{Experimental_inline}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("touchmove")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.ontouchstart")}} {{Non-standard_inline}} {{Experimental_inline}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("touchstart")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.ontransitioncancel")}}</dt> + <dd>Se llama a {{DOMxRef("EventHandler")}} cuando se envía un evento {{event("transitioncancel")}}, lo cual indica que {{web.link("/es/docs/Web/CSS/CSS_Transitions", "se canceló la transición CSS")}}.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.ontransitionend")}}</dt> + <dd>Se llama a {{DOMxRef("EventHandler")}} cuando se envía un evento {{event("transitionend")}}, lo cual indica que {{web.link("/es/docs/Web/CSS/CSS_Transitions", "la transición CSS")}} se ha terminado de reproducir.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.ontransitionrun")}}</dt> + <dd>Se llama a {{DOMxRef("EventHandler")}} cuando se envía un evento {{event("transitionrun")}}, lo cual indica que {{web.link("/es/docs/Web/CSS/CSS_Transitions", "la transición CSS")}} se está ejecutando, aunque no necesariamente se inició.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.ontransitionstart")}}</dt> + <dd>Se llama a {{DOMxRef("EventHandler")}} cuando se envía un evento {{event("transitionstart")}}, lo cual indica que {{web.link("/es/docs/Web/CSS/CSS_Transitions", "la transición CSS")}} ha comenzado a realizar la transición.</dd> + <dt>{{DOMxRef("GlobalEventHandlers.onwaiting")}}</dt> + <dd>Es un {{DOMxRef("EventHandler")}} que representa el código que se llamará cuando se genere el evento {{event("waiting")}}.</dd> +</dl> +</div> + +<h2 id="Métodos">Métodos</h2> + +<p><em>Esta interfaz no define métodos</em></p> + +<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("Selection API",'', 'Extensión a GlobalEventHandlers')}}</td> + <td>{{Spec2('Selection API')}}</td> + <td>Agrega <code>en el cambio de selección.</code></td> + </tr> + <tr> + <td>{{SpecName('Pointer Lock', '#extensions-to-the-document-interface', 'Extensión de Document')}}</td> + <td>{{Spec2('Pointer Lock')}}</td> + <td>Agrega <code>onpointerlockchange</code> y <code>onpointerlockerror</code> en {{DOMxRef("Document")}}. Está implementado experimentalmente en <code>GlobalEventHandlers</code>.</td> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', '#globaleventhandlers', 'GlobalEventHandlers')}}</td> + <td>{{ Spec2('HTML WHATWG') }}</td> + <td>Sin cambios desde la última instantánea, {{SpecName("HTML5.1")}}.</td> + </tr> + <tr> + <td>{{SpecName('HTML5.1', '#globaleventhandlers', 'GlobalEventHandlers')}}</td> + <td>{{Spec2('HTML5.1')}}</td> + <td>Instantánea de {{SpecName("HTML WHATWG")}}. Agregó <code>onsort</code> desde la instantánea de {{SpecName("HTML5 W3C")}}.</td> + </tr> + <tr> + <td>{{SpecName("HTML5 W3C", "#globaleventhandlers", "GlobalEventHandlers")}}</td> + <td>{{ Spec2('HTML5 W3C') }}</td> + <td>Instantánea de {{SpecName("HTML WHATWG")}}. Creación de <code>GlobalEventHandlers</code> (propiedades en el destino anterior).</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_del_navegador">Compatibilidad del navegador</h2> + +<div> +<div class="hidden">La tabla de compatibilidad de esta página se genera a partir de datos estructurados. Si deseas contribuir con los datos, consulta <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> y envíanos una solicitud de extracción.</div> + +<p>{{Compat("api.GlobalEventHandlers")}}</p> +</div> + +<h2 id="Ve_también">Ve también</h2> + +<ul> + <li>{{DOMxRef("Element")}}</li> + <li>{{DOMxRef("EventHandler")}}</li> + <li>{{DOMxRef("Event")}}</li> +</ul> diff --git a/files/es/web/api/globaleventhandlers/onblur/index.html b/files/es/web/api/globaleventhandlers/onblur/index.html new file mode 100644 index 0000000000..204cce4ab1 --- /dev/null +++ b/files/es/web/api/globaleventhandlers/onblur/index.html @@ -0,0 +1,90 @@ +--- +title: GlobalEventHandlers.onblur +slug: Web/API/GlobalEventHandlers/onblur +translation_of: Web/API/GlobalEventHandlers/onblur +--- +<div>{{ApiRef("HTML DOM")}}</div> + +<p>La propiedad <strong>onblur</strong> retorna el código del manejador de evento onBlur, si existe, en el elemento actual.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">element.onblur = function; +</pre> + +<ul> + <li><code>function</code> es el nombre de una función definida por el usuario, sin el sufijo () ni ningún parámetro, o una declaración de función anónima, como:</li> +</ul> + +<pre class="syntaxbox">element.onblur = function() { console.log("¡evento onblur detectado!"); }; +</pre> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush: html"><html> + +<head> +<title>ejemplo de evento onblur</title> + +<script type="text/javascript"> + +var elem = null; + +function initElement() +{ + elem = document.getElementById("foo"); + // NOTA: doEvent(); ó doEvent(param); no funcionará aquí. + // Debe ser una referencia a un nombre de función, no una llamada a función. + elem.onblur = doEvent; +}; + +function doEvent() +{ + elem.value = 'Bye-Bye'; + console.log("¡Evento onblur detectado!") +} +</script> + +<style type="text/css"> +<!-- +#foo { +border: solid blue 2px; +} +--> +</style> +</head> + +<body onload="initElement();"> +<form> +<input type="text" id="foo" value="Hola!" /> +</form> + +<p>Haga click en el elemento superior to darle el foco, luego click fuera del elemento.<br /> +Recarge la página desde la barra de navegación.</p> + +</body> +</html> +</pre> + +<h2 id="Notas">Notas</h2> + +<p>El evento blur es generado cuando un elemento pierde el foco.</p> + +<p>A diferencia de MSIE --en el cual la mayoría de tipos de elementos reciben el evento blur-- la mayoría de elementos de los navegadores basados en Gecko NO funcionan con este evento.</p> + +<h2 id="Especificación">Especificación</h2> + +<table class="spectable standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Observaciones</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG','webappapis.html#handler-onblur','onblur')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </td> + </tr> + </tbody> +</table> diff --git a/files/es/web/api/globaleventhandlers/onchange/index.html b/files/es/web/api/globaleventhandlers/onchange/index.html new file mode 100644 index 0000000000..a51f7d25d8 --- /dev/null +++ b/files/es/web/api/globaleventhandlers/onchange/index.html @@ -0,0 +1,97 @@ +--- +title: GlobalEventHandlers.onchange +slug: Web/API/GlobalEventHandlers/onchange +translation_of: Web/API/GlobalEventHandlers/onchange +--- +<div> +<div>{{ ApiRef("HTML DOM") }}</div> +</div> + +<p>La propiedad <code>onchange</code> establece y devuelve el <a href="/docs/Web/Guide/Events/Event_handlers" title="/en-US/docs/Web/Guide/DOM/Events/Event_handlers">event handler</a> para el evento {{event("change")}}.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox"><em><var>element</var></em>.onchange = <em>handlerFunction</em>; +var <em>handlerFunction</em> = <em><var>element</var></em>.onchange; +</pre> + +<p><code><em>handlerFunction</em></code> debería ser <em>null</em> o una <a href="/en-US/docs/Web/JavaScript/Reference/Functions" title="/en-US/docs/JavaScript/Reference/Functions_and_function_scope">Función de javascript</a> espeficiando el manejador para el evento.</p> + +<h2 id="Notes" name="Notes">Notas</h2> + +<p>Mir el la págna <a href="/en-US/docs/Web/Guide/Events/Event_handlers" title="/en-US/docs/Web/Guide/DOM/Events/Event_handlers">Manejadores de eventos DOM</a> para más información sobre cómo trabajar con los manejadore <code>on</code>.</p> + +<p>Mira la documentación para el evento {{event("change")}}.</p> + +<h2 id="Specification" name="Specification">Especificaciones</h2> + +<table class="spectable standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estatus</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG','webappapis.html#handler-onchange','onchange')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</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>Soporte báico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Android Webview</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> diff --git a/files/es/web/api/globaleventhandlers/onclick/index.html b/files/es/web/api/globaleventhandlers/onclick/index.html new file mode 100644 index 0000000000..62d6c622ec --- /dev/null +++ b/files/es/web/api/globaleventhandlers/onclick/index.html @@ -0,0 +1,139 @@ +--- +title: GlobalEventHandlers.onclick +slug: Web/API/GlobalEventHandlers/onclick +translation_of: Web/API/GlobalEventHandlers/onclick +--- +<div> +<div>{{ ApiRef("HTML DOM") }}</div> +</div> + +<div></div> + +<p>La propiedad <strong>onclick</strong> devuelve el manejador del evento <code>click</code> del elemento actual.</p> + +<div class="note"><strong>Note:</strong> Cuando uses el evento <code>click</code> para ejecutar algo, considera agregar la misma acción al evento <code>keydown</code>, para permitirle el uso a personas que no usan mouse o pantalla táctil.</div> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox"><var>element</var>.onclick = <var>functionRef</var>; +</pre> + +<p>Donde <em>functionRef</em> es una función - muchas veces el nombre de la función está declarado ya en otro sitio o como una <em>expresión de la función</em> .Ver "<a href="/en-US/docs/JavaScript/Guide/Functions">JavaScript Guide:Functions</a>" para más detalles.</p> + +<p>el único argumento pasado a la función manejador de evento especificamente {{domxref("MouseEvent")}} object. Dentro del manejador, <code>this</code> será el elemento sobre él el evento ha sido invocado.</p> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre class="brush:html"><!DOCTYPE html> +<html lang="en"> + <head> + <meta charset="UTF-8" /> + <title>onclick event example</title> + <script> + function initElement() { + var p = document.getElementById("foo"); + // NOTE: showAlert(); or showAlert(param); will NOT work here. + // Must be a reference to a function name, not a function call. + p.onclick = showAlert; + }; + + function showAlert(event) { + alert("onclick Event detected!"); + } + </script> + <style> + #foo { + border: solid blue 2px; + } + </style> + </head> + <body onload="initElement();"> + <span id="foo">My Event Element</span> + <p>click on the above element.</p> + </body> +</html> +</pre> + +<p>O se puede usar una función anoníma, como esa:</p> + +<pre class="brush:js">p.onclick = function(event) { alert("moot!"); }; +</pre> + +<h2 id="Notes" name="Notes">Notas</h2> + +<p>El evento <code>click</code> se genera cuando el usuario hace clic en un elemento. El evento clic ocurrirá después de los eventos <code>mousedown</code> y <code>mouseup</code>.</p> + +<p>Solo se puede asignar un controlador <code>click</code> a un objeto a la vez con esta propiedad. Puede que prefiera utilizar el método {{domxref ("EventTarget.addEventListener()")}} en su lugar, ya que es más flexible y forma parte de la especificación DOM Events.</p> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<table class="spectable standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estatus</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG','webappapis.html#handler-onclick','onclick')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_Navegadores">Compatibilidad de Navegadores</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>Soporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Android Webview</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> diff --git a/files/es/web/api/globaleventhandlers/onclose/index.html b/files/es/web/api/globaleventhandlers/onclose/index.html new file mode 100644 index 0000000000..20ddb639f5 --- /dev/null +++ b/files/es/web/api/globaleventhandlers/onclose/index.html @@ -0,0 +1,52 @@ +--- +title: GlobalEventHandlers.onclose +slug: Web/API/GlobalEventHandlers/onclose +tags: + - Propiedad + - Referencia +translation_of: Web/API/GlobalEventHandlers/onclose +--- +<div>{{ApiRef("HTML DOM")}}</div> + +<p>Un gestor de eventos para los eventos de cerrar enviados a la ventana. (No disponible con Firefox 2 o Safari)</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">window.onclose = funcRef; +</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<ul> + <li><code>funcRef</code> es una referencia a una función.</li> +</ul> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush: js">window.onclose = resetThatServerThing; +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="spectable standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG','webappapis.html#handler-onclose','onclose')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_Navegadores">Compatibilidad con Navegadores</h2> + +<div> +<div class="hidden">La tabla de compatibilidad en esta pagina es generada de datos estructurados. Si te gustaría contribuir a los datos, por favor haz check out de <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> y envianos una petición pull.</div> + +<p>{{Compat("api.GlobalEventHandlers.onclose")}}</p> +</div> diff --git a/files/es/web/api/globaleventhandlers/onerror/index.html b/files/es/web/api/globaleventhandlers/onerror/index.html new file mode 100644 index 0000000000..44c921b4ad --- /dev/null +++ b/files/es/web/api/globaleventhandlers/onerror/index.html @@ -0,0 +1,65 @@ +--- +title: GlobalEventHandlers.onerror +slug: Web/API/GlobalEventHandlers/onerror +translation_of: Web/API/GlobalEventHandlers/onerror +--- +<div>{{ ApiRef("HTML DOM") }}</div> + +<p>Un manejador de eventos para errores en scripts en tiempo de ejecución.</p> + +<p>Note that some/many <code>error</code> events do not trigger <code>window.onerror</code>, you have to listen for them specifically.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre>window.onerror = funcRef; +</pre> + +<h3 id="Parameters" name="Parameters">Parámetros</h3> + +<ul> + <li><code>funcRef</code> es una referencia a una función. Cuando la función devuelva <code>true</code>, se prevendrá el disparado del manejador de eventos por defecto. Parámetros de la función: + + <ul> + <li>Mensaje de error (string)</li> + <li>Url en la que el error fue lanzado (string)</li> + <li>Número de línea en la que el error fue lanzado (number)</li> + <li>Dentro de la línea en la que el error ocurrió, número de columna correspondiente (number) {{gecko_minversion_inline("31.0")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error">Error Object</a> (object) {{gecko_minversion_inline("31.0")}}</li> + </ul> + </li> +</ul> + +<h2 id="Example" name="Example">Ejemplos</h2> + +<pre class="brush: js">// Example 1: + +// Prevent error dialogs from displaying -which is the window's normal +// behavior- by overriding the default event handler for error events that +// go to the window. +window.onerror = null; + +// Example 2: + +var gOldOnError = window.onerror; +// Override previous handler. +window.onerror = function myErrorHandler(errorMsg, url, lineNumber) { + if (gOldOnError) + // Call previous handler. + return gOldOnError(errorMsg, url, lineNumber); + + // Just let default handler run. + return false; +} +</pre> + +<h2 id="Notes" name="Notes">Notas</h2> + +<p>El evento de error es lanzado cuando ocurre un error en el script.</p> + +<p>Cuando se use el marcado html en línea (<span class="nowiki"><body onerror="alert('an error occurred')>...</span>), los argumentos son anónimos. Pueden ser referenciados usando desde <code>arguments{{ mediawiki.external(0) }}</code> hasta <code>arguments{{ mediawiki.external(2) }}</code>.</p> + +<p>No hay llamante <code><a class="external" href="/en/Components.stack" title="https://developer.mozilla.org/En/Components.stack">Components.stack</a>.caller</code> que recuperar. (Vea <a class="link-https" href="https://bugzilla.mozilla.org/show_bug.cgi?id=355430"><strong>bug 355430</strong></a>.)</p> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<p><a class="external" href="http://devedge-temp.mozilla.org/library/manuals/2000/javascript/1.3/reference/handlers.html#1120097" title="http://devedge-temp.mozilla.org/library/manuals/2000/javascript/1.3/reference/handlers.html#1120097">JavaScript 1.1</a></p> diff --git a/files/es/web/api/globaleventhandlers/onfocus/index.html b/files/es/web/api/globaleventhandlers/onfocus/index.html new file mode 100644 index 0000000000..e29b3fb84b --- /dev/null +++ b/files/es/web/api/globaleventhandlers/onfocus/index.html @@ -0,0 +1,94 @@ +--- +title: GlobalEventHandlers.onfocus +slug: Web/API/GlobalEventHandlers/onfocus +translation_of: Web/API/GlobalEventHandlers/onfocus +--- +<div>{{ApiRef("HTML DOM")}}</div> + +<p>La propiedad <strong>onfocus</strong> devuelve un manejador de eventos para el evento onFocus en el elemento actual.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">element.onfocus = <em>event handling code</em> +</pre> + +<h2 id="Notas">Notas</h2> + +<p>El evento focus se dispara cuando el usuario establece el foco en el elemento.</p> + +<p>Para que el evento <code>onfocus</code> se dispare en elementos que no sean inputs, los mismos deben establecerse con el atributo {{htmlattrxref("tabindex")}} (vea <a href="/en-US/docs/Learn/Accessibility/HTML#Building_keyboard_accessibility_back_in">Building keyboard accessibility back in</a> para mas detalles).</p> + +<p>A diferencia de MSIE, en que casi toda clase de elemento puede recibir el evento focus, en los navegadores Gecko en los que casi todos los elementos NO reciben este evento.</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="spectable 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','webappapis.html#handler-onfocus','onfocus')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_los_Navegadores">Compatibilidad con los Navegadores</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>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Android Webview</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> diff --git a/files/es/web/api/globaleventhandlers/oninput/index.html b/files/es/web/api/globaleventhandlers/oninput/index.html new file mode 100644 index 0000000000..18785b9fe3 --- /dev/null +++ b/files/es/web/api/globaleventhandlers/oninput/index.html @@ -0,0 +1,86 @@ +--- +title: GlobalEventHandlers.oninput +slug: Web/API/GlobalEventHandlers/oninput +translation_of: Web/API/GlobalEventHandlers/oninput +--- +<div>{{ ApiRef("HTML DOM") }}</div> + +<p>Un controlador de eventos para el evento input en la ventana. El evento input es llamado cuando el valor de un elemento {{ HTMLElement("input") }} ha cambiado. </p> + +<p>Este evento se propaga. Si está soportado en la ventana, también estará soportado en elementos {{ HTMLElement("input") }}.</p> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre class="brush: html"><script> + +window.addEventListener('input', function (e) { + console.log("Evento keyup detectado! proveniente de este elemento:", e.target); +}, false); + +</script> + +<input placeholder="Tipee aquí y vea la consola."> +</pre> + +<h2 id="Specification" name="Specification">Especificaciones</h2> + +<p><a class="external" href="http://www.whatwg.org/specs/web-apps/current-work/multipage/common-input-element-attributes.html#event-input-input" title="http://www.whatwg.org/specs/web-apps/current-work/multipage/common-input-element-attributes.html#event-input-input">HTML - APIs de elementos de entrada comunes (<code>input</code>)</a></p> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>2</td> + <td>9</td> + <td>10</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Vea_también">Vea también</h2> + +<ul> + <li><a class="external" href="http://blog.danielfriesen.name/2010/02/16/html5-browser-maze-oninput-support/">Un laberinto de navegadores HTML5, soporte para oninput</a></li> + <li><a class="external" href="http://www.useragentman.com/blog/2011/05/12/fixing-oninput-in-ie9-using-html5widgets/">Corrigiendo oninput en IE con html5Widgets</a> incluye cobertura para IE6-8</li> + <li>Mathias Bynens sugiere <a class="external" href="http://mathiasbynens.be/notes/oninput" title="http://mathiasbynens.be/notes/oninput">enlazando a input y keydown</a></li> + <li><a class="external" href="http://help.dottoro.com/ljhxklln.php" title="http://help.dottoro.com/ljhxklln.php">evento oninput | dottoro</a> posee notas acerca de bugs en IE9</li> +</ul> diff --git a/files/es/web/api/globaleventhandlers/onkeydown/index.html b/files/es/web/api/globaleventhandlers/onkeydown/index.html new file mode 100644 index 0000000000..4eea7b0c68 --- /dev/null +++ b/files/es/web/api/globaleventhandlers/onkeydown/index.html @@ -0,0 +1,93 @@ +--- +title: GlobalEventHandlers.onkeydown +slug: Web/API/GlobalEventHandlers/onkeydown +translation_of: Web/API/GlobalEventHandlers/onkeydown +--- +<div>{{ApiRef("HTML DOM")}}</div> + +<p>La propiedad <code><strong>onkeydown</strong></code> devuelve un manejador para el evento <code>onKeyDown</code> del elemento actual.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">element.onkeydown = <var>event handling code</var></pre> + +<h2 id="Notas">Notas</h2> + +<p>El evento <code>keydown</code> se lanza cuando el usuario presiona una tecla.</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="spectable 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','webappapis.html#handler-onkeydown','onkeydown')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</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>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Android Webview</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> diff --git a/files/es/web/api/globaleventhandlers/onkeyup/index.html b/files/es/web/api/globaleventhandlers/onkeyup/index.html new file mode 100644 index 0000000000..f6b97819eb --- /dev/null +++ b/files/es/web/api/globaleventhandlers/onkeyup/index.html @@ -0,0 +1,100 @@ +--- +title: GlobalEventHandlers.onkeyup +slug: Web/API/GlobalEventHandlers/onkeyup +translation_of: Web/API/GlobalEventHandlers/onkeyup +--- +<div>{{ApiRef("HTML DOM")}}</div> + +<p>La propiedad <strong>onkeyup</strong> devuelve un manejador para el evento onKeyUp del elemento actual.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">element.onkeyup = <em>event handling code</em> +</pre> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush: js"> <input type="text" onKeyUp="keyWasPressed(event)"> + <script>function keyWasPressed(evt){ console.log(evt.keyCode) }</script> +</pre> + +<h2 id="Notas">Notas</h2> + +<p>El evento keyup se lanza cuando el usuario suelta la tecla que ha sido presionada.</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="spectable 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','webappapis.html#handler-onkeyup','onkeyup')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</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>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Android Webview</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> diff --git a/files/es/web/api/globaleventhandlers/onload/index.html b/files/es/web/api/globaleventhandlers/onload/index.html new file mode 100644 index 0000000000..b97cf40b4f --- /dev/null +++ b/files/es/web/api/globaleventhandlers/onload/index.html @@ -0,0 +1,51 @@ +--- +title: window.onload +slug: Web/API/GlobalEventHandlers/onload +tags: + - window.onload +translation_of: Web/API/GlobalEventHandlers/onload +--- +<p>{{ ApiRef() }}</p> +<h3 id="Summary" name="Summary">Sumario</h3> +<p>Un evento tipo handler para el evento <code>load</code> event de el {{ domxref("window") }}.</p> +<h3 id="Syntax" name="Syntax">Syntax</h3> +<pre class="eval">window.onload = <em>funcRef</em>; +</pre> +<ul> + <li><code>funcRef</code> es la función tipo handler function a ser llamada cuando el evento <code>load</code> de window se dispara.</li> +</ul> +<h3 id="Example" name="Example">Ejemplos</h3> +<pre class="brush: js">window.onload = function() { + init(); + doSomethingElse(); +}; +</pre> +<pre class="brush: html"><!doctype html> +<html> + <head> + <title>Ejemplo Onload</title> + <script> + function load() { + alert("evento load detectado!"); + } + window.onload = load; + </script> + </head> + <body> + <p>El Evento load se dispara cuando el documento ha terminado de cargarse!</p> + </body> +</html> +</pre> +<h3 id="Notes" name="Notes">Notas</h3> +<p>El evento <code>load</code> dispara el evento al final del proceso de carga del documento. En este punto, todos los objetos del documento son DOM, y todas las imágenes y sub-frames han terminado de cargarse.</p> +<p>Existen también los <a href="/en/Gecko-Specific_DOM_Events" title="en/Gecko-Specific_DOM_Events">Eventos DOM Específicos</a> como <code>DOMContentLoaded</code> y <code>DOMFrameContentLoaded</code> (los cuales pueden ser manejados usando {{ domxref("element.addEventListener()") }}) y son ejecutados despues de que el DOM de la página ha sido construido, pero no esperear a que otros recursos terminen de cargar.</p> +<h3 id="Specification" name="Specification">Especificación</h3> +<p>Este evento tipo handler se encuentra especificado en <a class="external" href="http://www.whatwg.org/html/#handler-window-onload" title="http://www.whatwg.org/html/#handler-window-onload">HTML</a>.</p> +<h3 id="Ver_También">Ver También</h3> +<ul> + <li> + <div class="syntaxbox"> + Evento <code>DOMContentLoaded</code> en <a href="/En/Listening_to_events#Simple_DOM.c2.a0events" title="En/Listening to events#Simple DOM.c2.a0events">Escuchando los Evento:Eventos DOM Simples</a></div> + </li> +</ul> +<p>{{ languages( { "fr": "fr/DOM/window.onload", "pl": "pl/DOM/window.onload" } ) }}</p> diff --git a/files/es/web/api/globaleventhandlers/onloadedmetadata/index.html b/files/es/web/api/globaleventhandlers/onloadedmetadata/index.html new file mode 100644 index 0000000000..01bbdcefd8 --- /dev/null +++ b/files/es/web/api/globaleventhandlers/onloadedmetadata/index.html @@ -0,0 +1,48 @@ +--- +title: GlobalEventHandlers.onloadedmetadata +slug: Web/API/GlobalEventHandlers/onloadedmetadata +translation_of: Web/API/GlobalEventHandlers/onloadedmetadata +--- +<div>{{ ApiRef("HTML DOM") }}</div> + +<p>The <strong><code>onloadedmetadata</code></strong> property of the {{domxref("GlobalEventHandlers")}} mixin is the {{domxref("EventHandler")}} for processing {{event("loadedmetadata")}} events.</p> + +<p>The <code>loadedmetadata</code> event is fired when the metadata has been loaded.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox notranslate"><em><var>element</var></em>.onloadedmetadata = <em>handlerFunction</em>; +var <em>handlerFunction</em> = <em><var>element</var></em>.onloadedmetadata; +</pre> + +<p><code>handlerFunction</code> should be either <code>null</code> or a <a href="/en-US/docs/Web/JavaScript/Reference/Functions" title="/en-US/docs/JavaScript/Reference/Functions_and_function_scope">JavaScript function</a> specifying the handler for the event.</p> + +<h2 id="Specification">Specification</h2> + +<table class="spectable 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','#handler-onloadedmetadata','onloadedmetadata')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("api.GlobalEventHandlers.onloadedmetadata")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{event("loadedmetadata")}}</li> + <li><a href="/en-US/docs/Web/Guide/Events/Event_handlers" title="/en-US/docs/Web/Guide/DOM/Events/Event_handlers">DOM event handlers</a></li> +</ul> diff --git a/files/es/web/api/globaleventhandlers/onresize/index.html b/files/es/web/api/globaleventhandlers/onresize/index.html new file mode 100644 index 0000000000..5d18902f04 --- /dev/null +++ b/files/es/web/api/globaleventhandlers/onresize/index.html @@ -0,0 +1,71 @@ +--- +title: GlobalEventHandlers.onresize +slug: Web/API/GlobalEventHandlers/onresize +tags: + - API + - DOM + - Propiedad +translation_of: Web/API/GlobalEventHandlers/onresize +--- +<p>{{ ApiRef() }}</p> + +<p>La propiedad <strong>GlobalEventHandlers.onresize</strong> contiene un {{domxref("EventHandler")}} desencadenado cuando un evento {{event("resize")}} es recibido.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="eval">window.onresize = <em>funcRef</em>; +</pre> + +<h3 id="Parameters" name="Parameters">Parametros</h3> + +<ul> + <li><code>funcRef</code> es una referencia a una función.</li> +</ul> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre>window.onresize = doFunc; +</pre> + +<pre><html> +<head> + +<title>onresize test</title> + +<script type="text/javascript"> + +window.onresize = resize; + +function resize() +{ + alert("resize event detected!"); +} +</script> +</head> + +<body> +<p>Resize the browser window to fire the resize event.</p> +</body> +</html> +</pre> + +<h2 id="Notes" name="Notes">Notas</h2> + +<p>El evento <u>resize</u> es activado después de que la ventana ha sido redimensionada.</p> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<table class="spectable standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Status</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG','webappapis.html#handler-onresize','onresize')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </td> + </tr> + </tbody> +</table> diff --git a/files/es/web/api/globaleventhandlers/onscroll/index.html b/files/es/web/api/globaleventhandlers/onscroll/index.html new file mode 100644 index 0000000000..017085065a --- /dev/null +++ b/files/es/web/api/globaleventhandlers/onscroll/index.html @@ -0,0 +1,80 @@ +--- +title: GlobalEventHandlers.onscroll +slug: Web/API/GlobalEventHandlers/onscroll +translation_of: Web/API/GlobalEventHandlers/onscroll +--- +<div>{{ApiRef("HTML DOM")}}</div> + +<p>Un manejador de eventos para desplazamiento en <code>element</code>.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">element.onscroll = <var>functionReference</var> +</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<p><code>functionReference</code> es una referencia a una función para ser ejecutada cuando <code>element</code> es desplazado (enrollado).</p> + +<h2 id="Example">Example</h2> + +<pre class="brush: html"><!DOCTYPE html> +<html lang="en"> + <head> + <meta charset="UTF-8" /> + <style> + #container { + position: absolute; + height: auto; + top: 0; + bottom: 0; + width: auto; + left: 0; + right: 0; + overflow: auto; + } + + #foo { + height:1000px; + width:1000px; + background-color: #777; + display: block; + } + + </style> + </head> + <body> + <div id="container"> + <div id="foo"></div> + </div> + + <script type="text/javascript"> + document.getElementById('container').onscroll = function() { + console.log("scrolling"); + }; + </script> + </body> +</html></pre> + +<h2 id="Notas">Notas</h2> + +<p>El evento es generado cuando el usuario realiza desplazamiento (scrolls) sobre el contenido de un elemento. <code>Element.onscroll</code> es equivalente a <code>element.addEventListener("scroll" ... )</code>.</p> + +<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">Observaciones</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("DOM3 Events", "#event-type-scroll", "onscroll")}}</td> + <td>{{Spec2("DOM3 Events")}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> diff --git a/files/es/web/api/globaleventhandlers/onselect/index.html b/files/es/web/api/globaleventhandlers/onselect/index.html new file mode 100644 index 0000000000..a97e18c74a --- /dev/null +++ b/files/es/web/api/globaleventhandlers/onselect/index.html @@ -0,0 +1,74 @@ +--- +title: GlobalEventHandlers.onselect +slug: Web/API/GlobalEventHandlers/onselect +translation_of: Web/API/GlobalEventHandlers/onselect +--- +<div> +<div>{{ ApiRef("HTML DOM") }}</div> + +<div>Un manejador de evento para el evento select en la ventana.</div> +</div> + +<p> </p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox">window.onselect = <em>funcRef</em>; +</pre> + +<ul> + <li><code>funcRef</code> es una función</li> +</ul> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre class="brush: html"><html> +<head> + +<title>onselect test</title> + +<style type="text/css"> +.text1 { border: 2px solid red; } +</style> + +<script type="text/javascript"> + +window.onselect = selectText; + +function selectText() +{ + alert("¡detectado evento select!"); +} +</script> +</head> + +<body> +<textarea class="text1" cols="30" rows="3"> +Resalte algo de este texto +con el puntero del ratón +para disparar el evento onselect. +</textarea> +</body> +</html> +</pre> + +<h2 id="Notes" name="Notes">Notas</h2> + +<p>El evento select sólo se genera cuando es seleccionado texto dentro de un control de entrada (INPUT) de tipo text o textarea. El evento es disparado <em>después</em> de que el texto haya sido seleccionado.</p> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<table class="spectable standard-table"> + <tbody> + <tr> + <th scope="col">Especifiación</th> + <th scope="col">Estado</th> + <th scope="col">Observaciones</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG','webappapis.html#handler-onselect','onselect')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </td> + </tr> + </tbody> +</table> diff --git a/files/es/web/api/globaleventhandlers/onselectstart/index.html b/files/es/web/api/globaleventhandlers/onselectstart/index.html new file mode 100644 index 0000000000..9ef1886a4f --- /dev/null +++ b/files/es/web/api/globaleventhandlers/onselectstart/index.html @@ -0,0 +1,98 @@ +--- +title: GlobalEventHandlers.onselectstart +slug: Web/API/GlobalEventHandlers/onselectstart +translation_of: Web/API/GlobalEventHandlers/onselectstart +--- +<div>{{ApiRef('DOM')}}{{SeeCompatTable}}</div> + +<p>La propiedad <code><strong>GlobalEventHandlers.onselectstart</strong></code> representa el manejador de evento que es invocado cuando un evento {{event("selectstart")}} alcanza el objeto.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><em>obj</em>.onselectstart = <em>function</em>; +</pre> + +<ul> + <li><code>function</code> es el nombre de una función definida por el usuario, sin el sufijo () ni ningún parámetro, o una declaración de función anónima.</li> +</ul> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush: html">document.onselectstart = function() { console.log("¡Selección iniciada!"); }; +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="spectable standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Observaciones</th> + </tr> + <tr> + <td>{{SpecName('Selection API','','GlobalEventHandlers.onselectstart')}}</td> + <td>{{Spec2('Selection API')}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Prestación</th> + <th>Firefox (Gecko)</th> + <th>Chrome</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatGeckoDesktop(43)}}<sup>[1]</sup></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Firefox Mobile (Gecko)</th> + <th>Android</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td><code>onselectionchange</code></td> + <td>{{CompatGeckoMobile(43)}}<sup>[1]</sup></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Esto está implementado subordinado a la preferencia <code>dom.select_events.enabled</code>, que por defecto es <code>false</code>, excepto en las versiones Nightly.</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{event("selectstart")}}</li> + <li>{{domxref("Document.onselectionchange")}} and {{event('selectionchange')}}.</li> +</ul> diff --git a/files/es/web/api/globaleventhandlers/onsubmit/index.html b/files/es/web/api/globaleventhandlers/onsubmit/index.html new file mode 100644 index 0000000000..948f7c9e57 --- /dev/null +++ b/files/es/web/api/globaleventhandlers/onsubmit/index.html @@ -0,0 +1,125 @@ +--- +title: GlobalEventHandlers.onsubmit +slug: Web/API/GlobalEventHandlers/onsubmit +translation_of: Web/API/GlobalEventHandlers/onsubmit +--- +<div>{{ApiRef("HTML DOM")}}</div> + +<p>Manejador de eventos del evento submit para el objeto window.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="eval">window.onsubmit = <em>funcRef</em>; +</pre> + +<h3 id="Parametros">Parametros</h3> + +<ul> + <li><code>funcRef</code> es una referencia a una función.</li> +</ul> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="eval"><html> +<script> +function reg() { + window.captureEvents(Event.SUBMIT); + window.onsubmit = hit; +} + +function hit() { + console.log('hit'); +} +</script> + +<body onload="reg();"> +<form> + <input type="submit" value="submit" /> +</form> +<div id="d"> </div> +</body> +</html> +</pre> + +<h2 id="Notas">Notas</h2> + +<p>El evento submit se genera cuando el usuario hace click en el boton submit en un formulario (<code><input type="submit"/></code>).</p> + +<p>El evento submit no se genera cuando el usuario llama a la función <code>form.submit()</code> directamente.</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="spectable 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','webappapis.html#handler-onsubmit','onsubmit')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </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>Edge</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>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Android Webview</th> + <th>Chrome for Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> diff --git a/files/es/web/api/globaleventhandlers/ontouchstart/index.html b/files/es/web/api/globaleventhandlers/ontouchstart/index.html new file mode 100644 index 0000000000..db51db726f --- /dev/null +++ b/files/es/web/api/globaleventhandlers/ontouchstart/index.html @@ -0,0 +1,126 @@ +--- +title: GlobalEventHandlers.ontouchstart +slug: Web/API/GlobalEventHandlers/ontouchstart +translation_of: Web/API/GlobalEventHandlers/ontouchstart +--- +<div>{{ApiRef("HTML DOM")}}</div> + +<p>Un {{domxref("GlobalEventHandlers","global event handler")}} para el evento {{event("touchstart")}}.</p> + +<p>{{SeeCompatTable}}</p> + +<div class="note"> +<p><strong>Nota:</strong> Este atributo <em>no</em> ha sido estandarizado formalmente. Está especificado en la especificación {{SpecName('Touch Events 2')}} {{Spec2('Touch Events 2')}} y no en {{SpecName('Touch Events')}} {{Spec2('Touch Events')}}. Este atributo no está totalmente implementado.</p> +</div> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="eval">var startHandler = cualquierElemento.ontouchstart; +</pre> + +<h3 id="Return_Value" name="Return_Value">Valor devuelto</h3> + +<dl> + <dt><code>startHandler</code></dt> + <dd>El manejador del evento <code>touchstart</code> para el elemento <code>cualquierElemento</code>.</dd> +</dl> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>Este ejemplo muestra dos formas de utilizar <code>ontouchstart</code> para establecer un manejador de evento <code>touchstart</code>.</p> + +<pre class="brush: js"><html> +<script> +function startTouch(ev) { + // Procesar el evento +} +function init() { + var el=document.getElementById("target1"); + el.ontouchstart = startTouch; +} +</script> +<body onload="init();"> +<div id="target1"> Tócame ... </div> +<div id="target2" ontouchstart="startTouch(event)"> Tócame ... </div> +</body> +</html> +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('Touch Events 2','#widl-GlobalEventHandlers-ontouchstart')}}</td> + <td>{{Spec2('Touch Events 2')}}</td> + <td>Versión no estable.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_navegadores">Compatibilidad en navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</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> </td> + <td> </td> + <td> </td> + <td> </td> + <td> </td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Android Webview</th> + <th>Chrome para Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td> </td> + <td> </td> + <td> </td> + <td> </td> + <td> </td> + <td> </td> + <td> </td> + <td> </td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{ event("touchstart") }}</li> +</ul> diff --git a/files/es/web/api/globaleventhandlers/onunload/index.html b/files/es/web/api/globaleventhandlers/onunload/index.html new file mode 100644 index 0000000000..a665fc2027 --- /dev/null +++ b/files/es/web/api/globaleventhandlers/onunload/index.html @@ -0,0 +1,45 @@ +--- +title: window.onunload +slug: Web/API/GlobalEventHandlers/onunload +translation_of: Web/API/WindowEventHandlers/onunload +--- +<p>{{ ApiRef() }}</p> +<h3 id="Summary" name="Summary">Test Summary</h3> +<p>The unload event is raised when the document is unloaded.</p> +<h3 id="Syntax" name="Syntax">Syntax</h3> +<pre class="eval">window.onunload = <em>funcRef</em>; +</pre> +<ul> + <li><code>funcRef</code> is a reference to a function.</li> +</ul> +<h3 id="Example" name="Example">Example</h3> +<pre><html> +<head> + +<title>onunload test</title> + +<script type="text/javascript"> + +window.onunload = unloadPage; + +function unloadPage() +{ + alert("unload event detected!"); +} +</script> +</head> + +<body> +<p>Reload a new page into the browser<br /> + to fire the unload event for this page.</p> +<p>You can also use the back or forward buttons<br /> + to load a new page and fire this event.</p> +</body> +</html> +</pre> +<h3 id="Notes" name="Notes">Notes</h3> +<p>Note that using this event handler in your page prevents Firefox 1.5 from caching the page in the in-memory bfcache. See <a href="/En/Using_Firefox_1.5_caching" title="En/Using_Firefox_1.5_caching">Using Firefox 1.5 caching</a> for details.</p> +<p>Browsers equipped with pop-up window blockers will ignore all window.open() method calls in onunload event handler functions.</p> +<h3 id="Specification" name="Specification">Specification</h3> +<p>{{ DOM0() }}</p> +<p>{{ languages( {"zh-cn": "zh-cn/DOM/window.onunload" } ) }}</p> diff --git a/files/es/web/api/headers/index.html b/files/es/web/api/headers/index.html new file mode 100644 index 0000000000..cb65b6aa11 --- /dev/null +++ b/files/es/web/api/headers/index.html @@ -0,0 +1,135 @@ +--- +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/history/index.html b/files/es/web/api/history/index.html new file mode 100644 index 0000000000..03bcb13185 --- /dev/null +++ b/files/es/web/api/history/index.html @@ -0,0 +1,86 @@ +--- +title: History +slug: Web/API/History +tags: + - API + - HTML DOM + - History API + - Interface + - NeedsTranslation + - TopicStub + - Web +translation_of: Web/API/History +--- +<div>{{ APIRef("History API") }}</div> + +<p>The <strong><code>History</code></strong> interface allows manipulation of the browser <em>session history</em>, that is the pages visited in the tab or frame that the current page is loaded in.</p> + +<h2 id="Properties">Properties</h2> + +<p><em>The <code>History</code></em><em> interface doesn't inherit any property.</em></p> + +<dl> + <dt>{{domxref("History.length","length")}} {{readOnlyInline}}</dt> + <dd>Returns an <code>Integer</code> representing the number of elements in the session history, including the currently loaded page. For example, for a page loaded in a new tab this property returns <code>1</code>.</dd> + <dt>{{domxref("History.scrollRestoration","scrollRestoration")}}</dt> + <dd>Allows web applications to explicitly set default scroll restoration behavior on history navigation. This property can be either <code>auto</code> or <code>manual</code>.</dd> + <dt>{{domxref("History.state","state")}} {{readOnlyInline}}</dt> + <dd>Returns an <code>any</code> value representing the state at the top of the history stack. This is a way to look at the state without having to wait for a {{event("popstate")}} event.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<p><em>The <code>History</code></em> <em>interface doesn't inherit any methods.</em></p> + +<dl> + <dt>{{domxref("History.back","back()")}}</dt> + <dd>This asynchronous method goes to the previous page in session history, the same action as when the user clicks the browser's <kbd>Back</kbd> button. Equivalent to <code>history.go(-1)</code>. + <div class="note">Calling this method to go back beyond the first page in the session history has no effect and doesn't raise an exception.</div> + </dd> + <dt>{{domxref("History.forward","forward()")}}</dt> + <dd>This asynchronous method goes to the next page in session history, the same action as when the user clicks the browser's <kbd>Forward</kbd> button; this is equivalent to <code>history.go(1)</code>. + <div class="note">Calling this method to go forward beyond the most recent page in the session history has no effect and doesn't raise an exception.</div> + </dd> + <dt>{{domxref("History.go","go()")}}</dt> + <dd>Asynchronously loads a page from the session history, identified by its relative location to the current page, for example <code>-1</code> for the previous page or <code>1</code> for the next page. If you specify an out-of-bounds value (for instance, specifying <code>-1</code> when there are no previously-visited pages in the session history), this method silently has no effect. Calling <code>go()</code> without parameters or a value of <code>0</code> reloads the current page. Internet Explorer lets you specify a string, instead of an integer, to go to a specific URL in the history list.</dd> + <dt>{{domxref("History.pushState","pushState()")}}</dt> + <dd>Pushes the given data onto the session history stack with the specified title (and, if provided, URL). The data is treated as opaque by the DOM; you may specify any JavaScript object that can be serialized. Note that all browsers but Safari currently ignore the <em>title</em> parameter. For more information, see <a href="/en-US/docs/Web/API/History_API/Working_with_the_History_API">Working with the History API</a>.</dd> + <dt>{{domxref("History.replaceState","replaceState()")}}</dt> + <dd>Updates the most recent entry on the history stack to have the specified data, title, and, if provided, URL. The data is treated as opaque by the DOM; you may specify any JavaScript object that can be serialized. Note that all browsers but Safari currently ignore the <em>title</em> parameter. For more information, see <a href="/en-US/docs/Web/API/History_API/Working_with_the_History_API">Working with the History API</a>.</dd> +</dl> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('HTML WHATWG', "browsers.html#the-history-interface", "History")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>Adds the <code>scrollRestoration</code> attribute.</td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', "browsers.html#the-history-interface", "History")}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("api.History")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>The {{domxref("Window.history")}} property returning the history of the current session.</li> +</ul> diff --git a/files/es/web/api/history/length/index.html b/files/es/web/api/history/length/index.html new file mode 100644 index 0000000000..f8d8bd65ba --- /dev/null +++ b/files/es/web/api/history/length/index.html @@ -0,0 +1,56 @@ +--- +title: History.length +slug: Web/API/History/length +tags: + - API + - DOM HTML + - Historial de navegación + - History + - Lectura + - Navegador + - Propiedad + - historial +translation_of: Web/API/History/length +--- +<div>{{APIRef("History API")}}</div> + +<p><span class="seoSummary">La propiedad de sólo lectura <code><strong>History.length</strong></code> retorna un entero representando el número de elementos en el historial de la sesión, incluyendo la página cargada actualmente. Por ejemplo, para una página cargada en una nueva pestaña esta propiedad retorna</span> <code>1</code>.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox notranslate">const <em>length</em> = history.length +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', "history.html#dom-history-length", "History.length")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>Sin cambios desde {{SpecName("HTML5 W3C")}}.</td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', "browsers.html#dom-history-length", "History.length")}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>Definición Inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_Navegadores">Compatibilidad de Navegadores</h2> + +<div class="hidden">La tabla de compatibilidad en esta página es generada desde datos estructurados. Si te gustaría contribuir a los datos, por favor revisa <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> y envíanos una <em>pull request</em>.</div> + +<p>{{Compat("api.History.length")}}</p> + +<h2 id="Mira_también">Mira también</h2> + +<ul> + <li>La interfaz {{domxref("History")}} a la que pertenece.</li> +</ul> diff --git a/files/es/web/api/history/pushstate/index.html b/files/es/web/api/history/pushstate/index.html new file mode 100644 index 0000000000..29de4cf521 --- /dev/null +++ b/files/es/web/api/history/pushstate/index.html @@ -0,0 +1,96 @@ +--- +title: History.pushState() +slug: Web/API/History/pushState +tags: + - API + - DOM HTML + - Historial de navegación + - History + - History API + - Navegador + - Sesion + - URL + - Web + - historial + - pushState +translation_of: Web/API/History/pushState +--- +<div>{{APIRef("History API")}}</div> + +<p>En un documento <a href="/en-US/docs/Web/HTML">HTML</a>, el método <strong><code>history.pushState()</code></strong> anexa un registro en la sesión de historial del navegador.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox notranslate">history.pushState(<var>state</var>, <var>title<span style="font-style: normal;">, [</span></var><var>url</var>])</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code>state</code></dt> + <dd>El objeto <code>state</code> es un objeto de JavaScript asociado al nuevo registro en el historial creado por <code>pushState()</code>. Cuando el usuario navega al nuevo registro, un evento {{event("popstate")}} es accionado, y la propiedad <code>state</code> del evento contiene una copia del objeto <code>state</code> del registro en el historial.</dd> + <dd>El objeto <code>state</code> puede ser cualquier cosa que pueda ser serializada. Porque Firefox guarda los objetos <code>state</code> en el disco del usuario para que así puedan ser restaurados luego de que el usuario reinicia el navegador, se impone un límite de 640k caracteres en la representación serializada de un objeto <code>state</code>. Si pasas un objeto <code>state</code> con una representación serializada más grande que lo mencionado, a <code>pushState()</code>, el método arrojará una excepción. Si necesitas más espacio que el mencionado, es recomendable que uses {{domxref("Window.sessionStorage", "sessionStorage")}} y/o {{domxref("Window.localStorage", "localStorage")}}.</dd> + <dt><code>title</code></dt> + <dd><a href="https://github.com/whatwg/html/issues/2174">La mayoría de los navegadores ignoran este parámetro</a>, sin embargo, podrían usarlo en el futuro. Pasar una cadena de texto vacía aquí, debería ser seguro contra futuros cambios en el método. Alternativamente, podrías pasar un título corto por el estado al cual te estás moviendo. Si necesitas que el título sea modificado, puedes usar {{domxref("Document.title", "document.title")}}.</dd> + <dt><code>url</code> {{optional_inline}}</dt> + <dd>La URL del nuevo registro en el historial, se define en este parámetro. Es importante destacar que el navegador no intentará cargar esta URL luego de una llamada a <code>pushState()</code>, pero podría intentar cargar esta URL luego, por ejemplo, luego de que el usuario reinicie el navegador. La nueva URL no necesita ser absoluta; puede ser relativa a la URL actual. La nueva URL debe tener el mismo {{glossary("origin")}} que la URL actual; de otra manera, <code>pushState()</code> arrojará una excepción. Si este parámetro no es especificado, por defecto se usa la URL del documento actual.</dd> +</dl> + +<h2 id="Descripción">Descripción</h2> + +<p>En cierto sentido, llamar a <code>pushState()</code> es similar a <code>window.location = "#foo"</code>, ambos crearán y activarán un nuevo registro en el historial asociado al documento actual. Pero <code>pushState()</code> tiene unas ventajas adicionales:</p> + +<ul> + <li>La nueva URL pueded ser cualquier URL con el mismo origen que la URL actual. En contraste, usar {{domxref("window.location")}} te mantiene en el mismo documento únicamente si modificas el <em>hash</em>.</li> + <li>No tienes que cambiar la URL si no quieres. En contraste, usar <code>window.location = "#foo";</code> sólo crea un nuevo registro en el historial si el <em>hash</em> actual no es <code>#foo</code>.</li> + <li>Puedes asociar datos arbitrarios a tu nuevo registro en el historial. Con el truco del <em>hash</em>, necesitas codificar todos los datos relevantes en una corta cadena de texto.</li> +</ul> + +<p>Cabe destacar que <code>pushState()</code> nunca hace que el evento {{event("hashchange")}} sea accionado, incluso si la nueva URL difiere de la URL antigua sólo en su <em>hash</em>.</p> + +<p>En otros documentos, crea u nelemento con una URI <code>null</code>.</p> + +<h2 id="Ejemplos">Ejemplos</h2> + +<p>Esto crea un nuevo registro en el historial del navegador, estableciendo <code><em>state</em></code>, <code><em>title</em></code>, y <code><em>url</em></code>.</p> + +<h3 id="JavaScript">JavaScript</h3> + +<pre class="brush: js notranslate">const state = { 'page_id': 1, 'user_id': 5 } +const title = '' +const url = 'hello-world.html' + +history.pushState(state, title, url)</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', "history.html#dom-history-pushstate", "History.pushState()")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>Ningún cambio desde {{SpecName("HTML5 W3C")}}.</td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', "history.html#dom-history-pushstate", "History.pushState()")}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>Definición Inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_Navegadores">Compatibilidad en Navegadores</h2> + +<div class="hidden">La tabla de compatibilidad en esta páginas es generada desde datos estructurados. Si te gustaría contribuir a los datos, por favor revisa <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> y envíanos una <em>pull request</em>.</div> + +<p>{{Compat("api.History.pushState")}}</p> + +<h2 id="Mira_también">Mira también</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/History_API/Working_with_the_History_API">Trabajando con la API History</a></li> +</ul> diff --git a/files/es/web/api/htmlanchorelement/index.html b/files/es/web/api/htmlanchorelement/index.html new file mode 100644 index 0000000000..57cb21820e --- /dev/null +++ b/files/es/web/api/htmlanchorelement/index.html @@ -0,0 +1,279 @@ +--- +title: HTMLAnchorElement +slug: Web/API/HTMLAnchorElement +tags: + - API + - HTML DOM + - Interfaz + - Referencia +translation_of: Web/API/HTMLAnchorElement +--- +<div>{{APIRef ("HTML DOM")}}<br> +La interfaz <strong>HTMLAnchorElement</strong> representa elementos de hipervínculo y proporciona propiedades y métodos especiales (más allá de los de la interfaz de objeto {{domxref ("HTMLElement")}} regular de la que heredan) para manipular el diseño y la presentación de dichos elementos.</div> + +<h2 id="Propiedades">Propiedades</h2> + +<p>{{InheritanceDiagram(600, 120)}}</p> + +<p>Hereda propiedades de su elemento primario, {{domxref ("HTMLElement")}}, y las implementa desde {{domxref ("HTMLHyperlinkElementUtils")}}.</p> + +<p>{{domxref ("HTMLAnchorElement.accessKey")}}<br> + Es un {{domxref ("DOMString")}} que representa un solo carácter que cambia el foco de entrada al hipervínculo.</p> + +<p><br> + {{domxref ("HTMLAnchorElement.charset")}} {{obsolete_inline}}<br> + Es un {{domxref ("DOMString")}} que representa la codificación de caracteres del recurso vinculado.</p> + +<p><br> + {{domxref ("HTMLAnchorElement.coords")}} {{obsolete_inline}}<br> + Es un {{domxref ("DOMString")}} que representa una lista de coordenadas separadas por comas.</p> + +<p> </p> + +<dl> + <dt>{{domxref ("HTMLAnchorElement.download")}} {{experimental_inline}}<br> + Es un {{domxref ("DOMString")}} que indica que el recurso vinculado está destinado a descargarse en lugar de mostrarse en el navegador. El valor representa el nombre propuesto del archivo. Si el nombre no es un nombre de archivo válido del sistema operativo subyacente, el navegador lo adaptará.</dt> + <dt><br> + {{domxref ("HTMLHyperlinkElementUtils.hash")}}<br> + Es un {{domxref ("USVString")}} que representa el identificador de fragmento, incluida la marca hash inicial ('#'), si la hay, en la URL a la que se hace referencia.</dt> + <dt><br> + {{domxref ("HTMLHyperlinkElementUtils.host")}}<br> + Es un {{domxref ("USVString")}} que representa el nombre de host y el puerto (si no es el puerto predeterminado) en la URL a la que se hace referencia.</dt> + <dt><br> + {{domxref ("HTMLHyperlinkElementUtils.hostname")}}<br> + Es un {{domxref ("USVString")}} que representa el nombre de host en la URL referenciada.</dt> + <dd> </dd> + <dt>{{domxref ("HTMLHyperlinkElementUtils.href")}}<br> + Es un {{domxref ("USVString")}} que refleja el atributo HTML {{htmlattrxref ("href", "a")}}, que contiene una URL válida de un recurso vinculado.</dt> + <dt><br> + {{domxref ("HTMLAnchorElement.hreflang")}}<br> + Es un {{domxref ("DOMString")}} que refleja el atributo HTML {{htmlattrxref ("hreflang", "a")}}, que indica el idioma del recurso vinculado.</dt> + <dt><br> + {{domxref ("HTMLAnchorElement.media")}}<br> + Es un {{domxref ("DOMString")}} que refleja el atributo HTML {{htmlattrxref ("media", "a")}}, que indica los medios previstos para el recurso vinculado.</dt> + <dt><br> + {{domxref ("HTMLAnchorElement.name")}} {{obsolete_inline}}<br> + Es un {{domxref ("DOMString")}} que representa el nombre del ancla.<br> + {{domxref ("HTMLHyperlinkElementUtils.password")}}<br> + Es un {{domxref ("USVString")}} que contiene la contraseña especificada antes del nombre de dominio.</dt> + <dd> </dd> + <dt>{{domxref ("HTMLHyperlinkElementUtils.origin")}} {{readonlyInline}}<br> + Devuelve un {{domxref ("USVString")}} que contiene el origen de la URL, que es su esquema, su dominio y su puerto.</dt> + <dt><br> + {{domxref ("HTMLHyperlinkElementUtils.pathname")}}<br> + Es un {{domxref ("USVString")}} que representa el componente del nombre de ruta, si lo hay, de la URL referenciada.</dt> + <dt><br> + {{domxref ("HTMLHyperlinkElementUtils.port")}}<br> + Es un {{domxref ("USVString")}} que representa el componente de puerto, si lo hay, de la URL a la que se hace referencia.</dt> + <dt><br> + {{domxref ("HTMLHyperlinkElementUtils.protocol")}}<br> + Es un {{domxref ("USVString")}} que representa el componente de protocolo, incluidos los puntos finales (':'), de la URL a la que se hace referencia.</dt> + <dt><br> + {{domxref ("HTMLAnchorElement.referrerPolicy")}} {{experimental_inline}}<br> + Es un {{domxref ("DOMString")}} que refleja el atributo {{htmlattrxref ("referrerpolicy", "a")}} HTML que indica qué referencia usar.</dt> + <dt><br> + {{domxref ("HTMLAnchorElement.rel")}}<br> + Es un {{domxref ("DOMString")}} que refleja el atributo HTML {{htmlattrxref ("rel", "a")}}, que especifica la relación del objeto de destino con el objeto vinculado.</dt> + <dt><br> + {{domxref ("HTMLAnchorElement.relList")}} {{readonlyInline}}<br> + Devuelve un {{domxref ("DOMTokenList")}} que refleja el atributo HTML {{htmlattrxref ("rel", "a")}}, como una lista de tokens.</dt> + <dt><br> + {{domxref ("HTMLAnchorElement.rev")}} {{obsolete_inline}}<br> + Es un {{domxref ("DOMString")}} que representa el atributo HTML {{htmlattrxref ("rev", "a")}}, que especifica la relación del objeto de enlace con el objeto de destino.</dt> + <dt><br> + {{domxref ("HTMLHyperlinkElementUtils.search")}}<br> + Es un {{domxref ("USVString")}} que representa el elemento de búsqueda, incluido el signo de interrogación principal ('?'), Si lo hay, de la URL a la que se hace referencia.</dt> + <dt><br> + {{domxref ("HTMLAnchorElement.shape")}} {{obsolete_inline}}<br> + Es un {{domxref ("DOMString")}} que representa la forma del área activa.</dt> + <dt><br> + {{domxref ("HTMLAnchorElement.tabindex")}}<br> + Es un largo que contiene la posición del elemento en el orden de navegación de tabulación para el documento actual.</dt> + <dt><br> + {{domxref ("HTMLAnchorElement.target")}}<br> + Es un {{domxref ("DOMString")}} que refleja el atributo HTML {{htmlattrxref ("target", "a")}}, que indica dónde mostrar el recurso vinculado.</dt> + <dt><br> + {{domxref ("HTMLAnchorElement.text")}}<br> + Es un {{domxref ("DOMString")}} un sinónimo de la propiedad {{domxref ("Node.textContent")}}.</dt> + <dt><br> + {{domxref ("HTMLAnchorElement.type")}}<br> + Es un {{domxref ("DOMString")}} que refleja el atributo HTML {{htmlattrxref ("type", "a")}}, que indica el tipo MIME del recurso vinculado.</dt> + <dt><br> + {{domxref ("HTMLHyperlinkElementUtils.nombre de usuario")}}<br> + Es un {{domxref ("USVString")}} que contiene el nombre de usuario especificado antes del nombre de dominio.</dt> +</dl> + +<h2 id="Metodos">Metodos</h2> + +<p>Hereda los métodos de su padre, {{domxref ("HTMLElement")}}, y los implementa desde {{domxref ("HTMLHyperlinkElementUtils")}}.</p> + +<p>{{domxref ("HTMLElement.blur ()")}}<br> + Elimina el foco del teclado del elemento actual.<br> + {{domxref ("HTMLElement.focus ()")}}<br> + Da el foco del teclado al elemento actual.<br> + {{domxref ("HTMLHyperlinkElementUtils.toString ()")}}<br> + Devuelve un {{domxref ("USVString")}} que contiene la URL completa. Es un sinónimo de {{domxref ("URLUtils.href")}}, aunque no se puede usar para modificar el valor.<br> + Los métodos blur () y focus () se heredan de {{domxref ("HTMLElement")}} de HTML5 on, pero se definieron en HTMLAnchorElement en DOM Level 2 HTML y especificaciones anteriores.</p> + +<p> </p> + +<p> </p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Epecificacion</th> + <th scope="col">Estado</th> + <th scope="col">Commentario</th> + </tr> + <tr> + <td>{{SpecName('Referrer Policy', '#referrer-policy-delivery-referrer-attribute', 'referrer attribute')}}</td> + <td>{{Spec2('Referrer Policy')}}</td> + <td>Se agregó la propiedad de referencia.</td> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', "text-level-semantics.html#the-a-element", "HTMLAnchorElement")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>Se agregó el refe. Se agregó la siguiente propiedad: descargar.<br> + Técnicamente, las propiedades relacionadas con URL, medios, host, nombre de host, ruta, puerto, protocolo, búsqueda y hash, se han movido a la interfaz {{domxref ("URLUtils")}}, y HTMLAreaElement implementa esta propiedad de interface.</td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', "text-level-semantics.html#the-a-element", "HTMLAnchorElement")}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>Los métodos blur () y focus (), así como las propiedades tabindex y accessKey, ahora están definidos en {{domxref ("HTMLElement")}}.<br> + Las siguientes propiedades ahora están obsoletas: charset, coords, name, rev y shape.<br> + Se han agregado las siguientes propiedades: hash, host, nombre de host, medios, ruta, puerto, protocolo, relList, búsqueda y texto.</td> + </tr> + <tr> + <td>{{SpecName('DOM2 HTML', 'html.html#ID-48250443', 'HTMLAnchorElement')}}</td> + <td>{{Spec2('DOM2 HTML')}}</td> + <td>Sin cambios desde {{SpecName ("DOM1")}}.</td> + </tr> + <tr> + <td>{{SpecName('DOM1', 'level-one-html.html#ID-48250443', 'HTMLAnchorElement')}}</td> + <td>{{Spec2('DOM1')}}</td> + <td>definicion Inicial .</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>Edge</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>{{CompatGeckoDesktop(1.0)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>download</code></td> + <td>{{CompatChrome(14)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>20</td> + <td>{{CompatUnknown}}</td> + <td>15</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>username</code>, <code>password</code>, and <code>origin</code></td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("26.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>referrerPolicy</code></td> + <td>{{CompatChrome(51)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("50")}}</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 Webview</th> + <th>Chrome for Android</th> + <th>Edge</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>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile(1.0)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>download</code></td> + <td>{{CompatChrome(14)}}</td> + <td>{{CompatChrome(14)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>username</code>, <code>password</code>, and <code>origin</code></td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("26.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>referrerPolicy</code></td> + <td>{{CompatChrome(51)}}</td> + <td>{{CompatChrome(51)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("50")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_tambien">Ver tambien</h2> + +<ul> + <li>El elemento HTML que implementa esta interfaz: {{HTMLElement ("a")}}</li> +</ul> diff --git a/files/es/web/api/htmlaudioelement/index.html b/files/es/web/api/htmlaudioelement/index.html new file mode 100644 index 0000000000..0d725ebb14 --- /dev/null +++ b/files/es/web/api/htmlaudioelement/index.html @@ -0,0 +1,77 @@ +--- +title: HTMLAudioElement +slug: Web/API/HTMLAudioElement +tags: + - DOM + - HTML + - Media + - para_revisar +translation_of: Web/API/HTMLAudioElement +--- +<div> +<div>{{APIRef("HTML DOM")}}</div> +</div> + +<p>La interfaz <code>HTMLAudioElement</code> proporciona acceso a las propiedades de los elementos {{ HTMLElement("audio") }}, así como métodos para manipularlos. Se deriva de la interfaz <a href="/en/DOM/HTMLMediaElement" title="en/DOM/HTMLMediaElement"><code>HTMLMediaElement</code></a>; se implementa por medio de {{ interface("nsIDOMHTMLMediaElement") }}.</p> + +<p>Para obtener más detalles sobre cómo usar las caracterísitcas de transmisión de sonido que expone esta interfaz, por favor consulta <a href="/en/Introducing_the_Audio_API_Extension" title="en/Introducing the Audio API Extension">Introducción a la extensión de la API de sonido</a>.</p> + +<h2 id="Propiedades">Propiedades</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Nombre</th> + <th scope="col">Tipo</th> + <th scope="col">Descripción</th> + </tr> + <tr> + <td><code>mozCurrentSampleOffset</code> {{ gecko_minversion_inline("2.0") }} {{ non-standard_inline() }}</td> + <td><span style="font-family: monospace;">unsigned long long</span></td> + <td>Indica el desplazamiento actual de la transmisión de sonido que fue creada por una llamada a <code>mozWriteAudio()</code>. Esta posición de desplazamiento se especifica como el número de muestras desde que se inició la transmisión.</td> + </tr> + </tbody> +</table> + +<h2 id="Métodos">Métodos</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Nombre y argumentos</th> + <th scope="col">Retorno</th> + <th scope="col">Descripción</th> + </tr> + <tr> + <td><code>Audio()</code></td> + <td><code>HTMLAudioElement</code></td> + <td>Constructor para elementos de audio. La propiedad <strong>preload</strong> del objeto devuelto se establece en <code>auto</code>.</td> + </tr> + <tr> + <td><code>Audio(en <a href="/En/DOM/DOMString" title="En/DOM/DOMString">DOMString</a> src)</code></td> + <td>HTMLAudioElement</td> + <td>Constructor para elementos de audio. La propiedad <strong>preload</strong> del objeto devuelto se establece a <code>auto</code>; la propiedad <strong>src</strong> se establece al valor del argumento . El navegador comienza una selección asíncrona del recurso antes de que devuelva el objeto.</td> + </tr> + <tr> + <td> + <p><code>mozSetup(in PRUint32 channels, in PRUint32 rate) </code>{{ gecko_minversion_inline("2.0") }} {{ non-standard_inline() }}</p> + </td> + <td>-</td> + <td>Configura la transmisión de sonido para escritura. Especificas como parámetros el número de canales (1 para mono o 2 para estéreo), a continuación la frecuencia de muestreo ((44100 for 44.1kHz, por ejemplo).</td> + </tr> + <tr> + <td><code>mozWriteAudio(in jsval data)</code> {{ gecko_minversion_inline("2.0") }} {{ non-standard_inline() }}</td> + <td><code>unsigned long</code></td> + <td>Inserta en la transmisión la escritura de sonido en la posición de desplazamiento actual . Devuelve el número de bytes que se han escrito en la transmisión.</td> + </tr> + </tbody> +</table> + +<h2 id="Consulta_también">Consulta también</h2> + +<ul> + <li><a href="/en/Introducing_the_Audio_API_Extension" title="en/Introducing the Audio API Extension">Introducción a la extensión de la API de sonido</a></li> + <li>{{ HTMLElement("audio") }}</li> +</ul> + +<p>{{ languages( { "en": "en/DOM/HTMLAudioElement" } ) }}</p> diff --git a/files/es/web/api/htmlcanvaselement/getcontext/index.html b/files/es/web/api/htmlcanvaselement/getcontext/index.html new file mode 100644 index 0000000000..cb77b1594e --- /dev/null +++ b/files/es/web/api/htmlcanvaselement/getcontext/index.html @@ -0,0 +1,284 @@ +--- +title: HTMLCanvasElement.getContext() +slug: Web/API/HTMLCanvasElement/getContext +translation_of: Web/API/HTMLCanvasElement/getContext +--- +<div>{{APIRef("Canvas API")}}</div> + +<p>El método <strong><code>HTMLCanvasElement.getContext()</code></strong> retorna un contexto de dibujo en el lienzo, o {{jsxref("null")}} si el identificador del contexto no está soportado.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><var><em>canvas</em>.getContext(<em>contextType, contextAttributes</em>);</var> +</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt>contextType</dt> + <dd>Es una {{domxref("DOMString")}} que contiene el identificador del contexto que define el contexto de dibujo asociado a el lienzo. Los posibles valores son: + <ul> + <li><code>"2d</code>", dando lugar a la creación de un objeto {{domxref("CanvasRenderingContext2D")}} que representa un contexto de renderizado de dos dimensiones.</li> + <li><code>"webgl"</code> (o <code>"experimental-webgl"</code>) el cual creará un objeto {{domxref("WebGLRenderingContext")}} que representa un contexto de renderizado de tres dimensiones. Este contexto sólo está disponible en navegadores que implementan <a href="https://developer.mozilla.org/en-US/docs/Web/WebGL">WebGL</a> version 1 (OpenGL ES 2.0).</li> + <li>"<code>webgl2</code>" (o "<code>experimental-webgl2</code>") el cual creará un objeto {{domxref("WebGL2RenderingContext")}} que representa un contexto de renderizado de tres dimensiones. Este contexto sólo está disponible en navegadores que implementan <a href="https://developer.mozilla.org/en-US/docs/Web/WebGL">WebGL</a> version 2 (OpenGL ES 3.0). {{experimental_inline}}</li> + <li><code>"bitmaprenderer"</code> el cuál creará un {{domxref("ImageBitmapRenderingContext")}} que únicamente provee funcionalidad para remplazar el contenido del lienzo con un {{domxref("ImageBitmap")}} dado.</li> + </ul> + + <p>Nota: Los identificadores "<code>experimental-webgl</code>" o "<code>experimental-webgl2</code>" son usados en nuevas implementaciones de WebGL. Estas implementaciones no han logrado aprobar el conjunto de pruebas de conformidad o la situación de los controladores gráficos en la plataforma no es estable aun. <a href="https://www.khronos.org/">Khronos Group</a> certifica las implementaciones de WebGL bajo ciertas <a href="https://www.khronos.org/registry/webgl/sdk/tests/CONFORMANCE_RULES.txt">reglas de conformidad</a>.</p> + </dd> + <dt><code>contextAttributes</code></dt> + <dd> + <p>Puedes usar varios atributos al momento de crear tu contexto de renderizado. Por ejemplo:</p> + + <pre class="brush: js">canvas.getContext('webgl', + { antialias: false, + depth: false });</pre> + Atributos del contexto 2d: + + <ul> + <li><strong><code>alpha</code></strong>: Booleano que indica si el lienzo contiene canal alfa. Si es asignado falso, el naveagdor sabe que el fondo siempre es opaco, lo cual puede acelerar el dibujado de contenido transparente e imágenes.</li> + <li>{{non-standard_inline}} (Gecko únicamente) <strong><code>willReadFrequently</code></strong>: Booleano que indica si muchas operaciones de read-back están planeadas o no. Esto forzará el uso de software (en lugar de aceleración de hardware) y puede ahorrar memoria al llamar {{domxref("CanvasRenderingContext2D.getImageData", "getImageData()")}} constantemente. Esta opción solo está disponible si <code>gfx.canvas.willReadFrequently.enable</code> es verdadero(lo cual solo está asignado por defecto en B2G/Firefox OS).</li> + <li>{{non-standard_inline}} (Blink únicamente) <strong><code>storage</code></strong>: Cadena que indica si el almacenamiento es usado ("persistent" por defecto).</li> + </ul> + Atributos del contexto WebGL: + + <ul> + <li><strong><code>alpha</code></strong>: Booleano que indica si el lienzo contiene un buffer alfa.</li> + <li><strong><code>depth</code></strong>: Booleano que indica si el buffer de dibujo tiene un buffer de profundidad de al menos 16 bits.</li> + <li><strong><code>stencil</code></strong>: Booleano que indica si el buffer de dibujo tiene un stencil de al menos 8 bits.</li> + <li><strong><code>antialias</code></strong>: Booleano que indica si se debe aplicar anti-aliasing.</li> + <li><strong><code>premultipliedAlpha</code></strong>: Booleano que indica que el compositor de páginas asumirá que el buffer de dibujo contiene colores con alfa premultiplicado.</li> + <li><strong><code>preserveDrawingBuffer</code></strong>: Si es verdadero los buffers no se limpiarán y mantendrán sus valores hasta que el autor los limpie o los sobreescriba.</li> + <li> + <p><code><strong>failIfMajorPerformanceCaveat</strong></code>: Booleano que indica si un contexto será creado si el rendimiento del sistema es bajo.</p> + </li> + </ul> + </dd> +</dl> + +<h3 id="Valor_de_retorno">Valor de retorno</h3> + +<p>Un {{domxref("RenderingContext")}} que puede ser:</p> + +<ul> + <li>{{domxref("CanvasRenderingContext2D")}} para <code>"2d"</code>,</li> + <li>{{domxref("WebGLRenderingContext")}} para<code>"webgl"</code> y <code>"experimental-webgl"</code>,</li> + <li>{{domxref("WebGL2RenderingContext")}} para <code>"webgl2"</code> y <code>"experimental-webgl2"</code>, o</li> + <li>{{domxref("ImageBitmapRenderingContext")}} para <code>"bitmaprenderer"</code>.</li> +</ul> + +<p>Si <em>contextType</em> no corresponde con un posible contexto de dibujo retorna null.</p> + +<h2 id="Ejemplos">Ejemplos</h2> + +<p>Dado este elemento {{HTMLElement("canvas")}}:</p> + +<pre class="brush: html"><canvas id="canvas" width="300" height="300"></canvas> +</pre> + +<p>Puedes obtener un contexto 2d del canvas con el código siguiente:</p> + +<pre class="brush: js">var canvas = document.getElementById('canvas'); +var ctx = canvas.getContext('2d'); +console.log(ctx); // CanvasRenderingContext2D { ... } +</pre> + +<p>Ahora tienes el <a href="/en-US/docs/Web/API/CanvasRenderingContext2D">contexto de renderizado 2D</a> para un canvas y puedes dibujar en él.</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentarios</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', "scripting.html#dom-canvas-getcontext", "HTMLCanvasElement.getContext")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>Sin cambios desde el último snapshot, {{SpecName('HTML5 W3C')}}</td> + </tr> + <tr> + <td>{{SpecName('HTML5.1', "scripting-1.html#dom-canvas-getcontext", "HTMLCanvasElement.getContext")}}</td> + <td>{{Spec2('HTML5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', "scripting-1.html#dom-canvas-getcontext", "HTMLCanvasElement.getContext")}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>Snapshot del {{SpecName('HTML WHATWG')}} que contiene la definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support (<code>2d</code> context)</td> + <td>{{CompatChrome(4)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("1.9.2")}}</td> + <td>{{CompatIE(9)}}</td> + <td>{{CompatOpera(9)}}</td> + <td>{{CompatSafari(3.1)}}</td> + </tr> + <tr> + <td><code>webgl</code> context</td> + <td>{{CompatChrome(9)}}<sup>[1]</sup><br> + {{CompatChrome(33)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop('1.9.2')}}<sup>[1]</sup><br> + {{CompatGeckoDesktop('24')}}</td> + <td>11.0<sup>[2]</sup></td> + <td>9.0<sup>[3]</sup></td> + <td>5.1<sup>[2]</sup></td> + </tr> + <tr> + <td><code>webgl2</code> context {{experimental_inline}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop('25')}}<sup>[4]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>2d <code>alpha</code> context attribute</td> + <td>32</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop(30)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td> + <p><code>failIfMajorPerformanceCaveat</code> attribute</p> + </td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop(41)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>bitmaprenderer context</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop(46)}}</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>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support (<code>2d</code> context)</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("1.9.2")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>webgl</code> context</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}<sup>[2]</sup></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>webgl2</code> context {{experimental_inline}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>2d <code>alpha</code> context attribute</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile(30)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>failIfMajorPerformanceCaveat</code> attribute</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile(41)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>bitmaprenderer context</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile(46)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Chrome 9 y Gecko 1.9.2 inicialmente implementaron esta como <code>experimental-webgl</code>. A partir de Chrome 33 y Gecko 24 es implementado como <code>webgl </code>estándar.</p> + +<p>[2] Internet Explorer 11, WebKit 5.1 y Firefox Mobile implementaron esto como <code>experimental-webgl</code>.</p> + +<p>[3] Opera 9 implementó esto como <code>experimental-webgl</code>, behind a user preference, in version 15.0 the user preference got removed.</p> + +<p>[4] Gecko 25 implements this as "<code>experimental-webgl2</code>" behind the user preference <code>webgl.enable-prototype-webgl2</code>. Starting with Gecko 42, the string "webgl2" is used behind the same preference.</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>The interface defining it, {{domxref("HTMLCanvasElement")}}.</li> + <li>{{domxref("OffscreenCanvas.getContext()")}}</li> + <li>Available rendering contexts: {{domxref("CanvasRenderingContext2D")}}, {{domxref("WebGLRenderingContext")}} and {{domxref("WebGL2RenderingContext")}} and {{domxref("ImageBitmapRenderingContext")}}.</li> +</ul> diff --git a/files/es/web/api/htmlcanvaselement/height/index.html b/files/es/web/api/htmlcanvaselement/height/index.html new file mode 100644 index 0000000000..0d2fa7f2e2 --- /dev/null +++ b/files/es/web/api/htmlcanvaselement/height/index.html @@ -0,0 +1,121 @@ +--- +title: HTMLCanvasElement.height +slug: Web/API/HTMLCanvasElement/height +tags: + - Propiedad +translation_of: Web/API/HTMLCanvasElement/height +--- +<div> +<div> +<div>{{APIRef("Canvas API")}}</div> +</div> +</div> + +<p>La propiedad <strong><code><span>HTMLCanvasElement.height es un entero positivo que refleja el atributo </span></code></strong>{{htmlattrxref("height", "canvas")}} del elemento {{HTMLElement("canvas")}} interpretado en pixeles CSS. Cuando el atributo no esta especificado o esta puesto en un valor invalido(ej. Número negativo), es usado el valor por defecto de 150.</p> + +<p>Esta es una de de las dos propiedades que controlan el tamaño del canvas, siendo la otra {{domxref("HTMLCanvasElement.width")}}.</p> + +<h2 id="Syntax" name="Syntax">Syntax</h2> + +<pre class="syntaxbox"><var>var <em>pxl</em> = <em>canvas</em></var>.height; +<em>canvas</em>.height = <em>pxl</em>; +</pre> + +<h2 id="Ejemplos">Ejemplos</h2> + +<p>Dado el siguiente elemento {{HTMLElement("canvas")}}:</p> + +<pre class="brush: html"><canvas id="canvas" width="300" height="300"></canvas> +</pre> + +<p>Puedes obtener la altura del canvas con el siguiente codigo:</p> + +<pre class="brush: js">var canvas = document.getElementById("canvas"); +console.log(canvas.height); // 300 +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Status</th> + <th scope="col">Comentarios</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', "scripting.html#attr-canvas-height", "HTMLCanvasElement.height")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>No hay cambios desde la ultima foto {{SpecName('HTML5 W3C')}}</td> + </tr> + <tr> + <td>{{SpecName('HTML5.1', "scripting-1.html#attr-canvas-height", "HTMLCanvasElement.height")}}</td> + <td>{{Spec2('HTML5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', "scripting-1.html#attr-canvas-height", "HTMLCanvasElement.height")}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>Foto que contiene la definición inicial {{SpecName('HTML WHATWG')}}.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_Navegadores">Compatibilidad de Navegadores</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>{{ CompatChrome(4) }}</td> + <td>{{ CompatGeckoDesktop("1.9.2") }}</td> + <td>{{ CompatIE(9) }}</td> + <td>{{ CompatOpera(9) }}</td> + <td>{{ CompatSafari(3.1) }}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</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>Soporte Básico</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatGeckoMobile("1.9.2") }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_Also" name="See_Also">Ver también</h2> + +<ul> + <li>La interfaz que lo define, {{domxref("HTMLCanvasElement")}}.</li> + <li>La otra propiedad que controla el tamaño del canvas, {{domxref("HTMLCanvasElement.width")}}.</li> +</ul> diff --git a/files/es/web/api/htmlcanvaselement/index.html b/files/es/web/api/htmlcanvaselement/index.html new file mode 100644 index 0000000000..07a570f193 --- /dev/null +++ b/files/es/web/api/htmlcanvaselement/index.html @@ -0,0 +1,249 @@ +--- +title: HTMLCanvasElement +slug: Web/API/HTMLCanvasElement +translation_of: Web/API/HTMLCanvasElement +--- +<div> +<div>{{APIRef("Canvas API")}}</div> +</div> + +<p>La interfaz <strong><code><span>HTMLCanvasElement</span></code></strong> provee propiedades y métodos para manipular la capa de presentación de los elementos de tipo canvas. La interfaz <code>HTMLCanvasElement</code> también hereda las propiedades y métodos de la interfaz {{domxref("HTMLElement")}} .</p> + +<h2 id="Propiedades">Propiedades</h2> + +<p><em>Hereda propiedades de la interfaz padre, </em><em>{{domxref("HTMLElement")}}.</em></p> + +<dl> + <dt>{{domxref("HTMLCanvasElement.height")}}</dt> + <dd>Un entero positivo que se asocia al atributo HTML {{htmlattrxref("height", "canvas")}} del elemento {{HTMLElement("canvas")}} interpretada en píxeles CSS. Cuando el atributo no está especificado, o si este se inicializa a un valor inválido, como un negativo, el valor 150 es usado por defecto.</dd> + <dt>{{domxref("HTMLCanvasElement.mozOpaque")}} {{non-standard_inline}}</dt> + <dd>Un {{jsxref("Boolean")}} asociado al atributo HTML {{htmlattrxref("moz-opaque", "canvas")}} del elemento {{HTMLElement("canvas")}} . Proporciona al canvas una forma de saber si la transparencia será considerada un factor. Si el canvas conoce que no hay transparencia, el desempeño de renderezación será optimizado.</dd> + <dt>{{domxref("HTMLCanvasElement.width")}}</dt> + <dd>Un entero positivo asociado al atributo HTML {{htmlattrxref("width", "canvas")}} del elemento canvas {{HTMLElement("canvas")}} interpretado en píxeles CSS. Cuando el atributo no está especificado, o si se inicializa a un valor inválido, como un negativo, se utiliza el valor 300 por defecto.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<p><em>Herada métodos de la interfaz padre, </em><em>{{domxref("HTMLElement")}}.</em></p> + +<dl> + <dt>{{domxref("HTMLCanvasElement.captureStream()")}} {{experimental_inline}}</dt> + <dd>Retorna un {{domxref("CanvasCaptureMediaStream")}} que es una captura de video en tiempo real, de la superficie del canvas.</dd> + <dt>{{domxref("HTMLCanvasElement.getContext()")}}</dt> + <dd>Retorna el contexto del dibujado del canvas, o bien null(nulo) si el ID de contexto no está soportado. Un contexto de dibujo, te permite dibujar sobre el canvas. Llamando al método getContext con el parámetro <code>"2d"</code> retorna un objeto {{domxref("CanvasRenderingContext2D")}} , mientras que el llamarlo con el parámetroca <code>"experimental-webgl"</code> (o <code>"webgl"</code>) retorna un objeto {{domxref("WebGLRenderingContext")}} . Este tipo de contexto sólo está disponible en navegadores que implementen <a href="/en-US/docs/Web/WebGL">WebGL</a>.</dd> + <dt>{{domxref("HTMLCanvasElement.toDataURL()")}}</dt> + <dd>Retorna una data-URL conteniendo una representación de la imagen en el formato especificado por el tipo de parámetro(png por defecto). La imagen de retorno se encuentra a una resolución de 96dpi.</dd> + <dt>{{domxref("HTMLCanvasElement.toBlob()")}}</dt> + <dd>Crea un objeto {{domxref("Blob")}} representando la imagen contenida en el canvas; este archivo puede ser cacheado en disco o bien almacenado en memoria, lo cual dependerá del "user-agent"(especificación del navegador).</dd> + <dt>{{domxref("HTMLCanvasElement.mozGetAsFile()")}} {{non-standard_inline}} {{deprecated_inline}}</dt> + <dd>Retorna un objeto {{domxref("File")}} representando una imagen contenida en el canvas; este archivo es del tipo memory-based, con su nombre especificado. Si el tipo no se especifica, el tipo usado por defecto es <code>image/png</code>.</dd> + <dt>{{domxref("HTMLCanvasElement.mozFetchAsStream()")}} {{non-standard_inline}}</dt> + <dd>Crea un nuevo flujo de entrada, el cual una vez listo, proveerá los contenidos del canvas como datos de imagen. Cuando el nuevo flujo está listo, la retrollamada específica el método {{ifmethod("nsIInputStreamCallback", "onInputStreamReady")}} es invocada. Si no se especifica el tipo, el tipo de imagen por defecto es <code>image/png.</code> + <div class="note"><strong>Nota:</strong> Sólo puede ser invocado desde Chrome.</div> + </dd> +</dl> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('Media Capture DOM Elements', '#html-media-element-media-capture-extensions', 'HTMLCanvasElement')}}</td> + <td>{{Spec2('Media Capture DOM Elements')}}</td> + <td>Añade el método <code>captureStream()</code>.</td> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', "#the-canvas-element", "HTMLCanvasElement")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>El método <code>getContext()</code>ahora retorna un objeto {{domxref("RenderingContext")}} en vez de un objeto opaco.<br> + Los métodos <code>probablySupportsContext()</code>, <code>setContext()</code> y <code>transferControlToProxy() han sido añadidos</code>.</td> + </tr> + <tr> + <td>{{SpecName('HTML5.1', "scripting-1.html#the-canvas-element", "HTMLCanvasElement")}}</td> + <td>{{Spec2('HTML5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', "scripting-1.html#the-canvas-element", "HTMLCanvasElement")}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>Definición Inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_Navegadores">Compatibilidad en Navegadores</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico (<code>2D</code> context)</td> + <td>4.0</td> + <td>{{CompatGeckoDesktop('1.9.2')}}</td> + <td>9.0</td> + <td>9.0 [1]</td> + <td>3.1</td> + </tr> + <tr> + <td><code>webgl</code> context</td> + <td>9.0 as <code>experimental-webgl</code><br> + ~33 as <code>webgl</code></td> + <td>{{CompatGeckoDesktop('1.9.2')}} as <code>experimental-webgl</code><br> + {{CompatGeckoDesktop('24')}} as <code>webgl</code></td> + <td>11.0 as <code>experimental-webgl</code></td> + <td>9.0 as <code>experimental-webgl</code>, behind a user pref.<br> + 15.0 as <code>experimental-webgl</code></td> + <td>5.1 as <code>experimental-webgl</code><br> + ~8.0 as <code>webgl</code></td> + </tr> + <tr> + <td><code>toBlob()</code></td> + <td>{{CompatNo}} (bug <a href="http://crbug.com/67587">67587</a>)</td> + <td>{{CompatGeckoDesktop('19')}} [2]</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}} (bug <a href="https://bugs.webkit.org/show_bug.cgi?id=71270">71270</a>)</td> + </tr> + <tr> + <td><code>probablySupportsContext()</code>,<br> + <code>setContext()</code>,<br> + <code>transferControlToProxy()</code> {{experimental_inline}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>mozGetAsFile()</code> {{non-standard_inline}} {{deprecated_inline}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop('2')}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>mozFetchAsStream()</code> {{non-standard_inline}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop('13')}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>captureStream()</code> {{experimental_inline}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop('41')}}</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>Característica</th> + <th>Android</th> + <th>Chrome para Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico (<code>2D</code> context)</td> + <td>2.1</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>10.0 [1]</td> + <td>3.2</td> + </tr> + <tr> + <td><code>webgl</code> context</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}} as <code>experimental-webgl</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>toBlob()</code></td> + <td>{{CompatNo}} (bug <a href="http://crbug.com/67587">67587</a>)</td> + <td>{{CompatNo}} (bug <a href="http://crbug.com/67587">67587</a>)</td> + <td>{{CompatGeckoMobile('18')}} [2]</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}} (bug <a href="https://bugs.webkit.org/show_bug.cgi?id=71270">71270</a>)</td> + </tr> + <tr> + <td><code>probablySupportsContext()</code>,<br> + <code>setContext()</code>,<br> + <code>transferControlToProxy() </code>{{experimental_inline}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>mozGetAsFile()</code> {{non-standard_inline}} {{deprecated_inline}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoMobile('2')}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>mozFetchAsStream()</code> {{non-standard_inline}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoMobile('13')}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>captureStream() </code>{{experimental_inline}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoMobile('41')}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Opera Mini 5.0 y posteriores poseen soporte parcial.</p> + +<p>[2] Soporte para un tercer parámetro, ha sido añadido sólo en Gecko 25: cuando se utiliza con el tipo <code>"image/jpeg"</code>, este argumento especifica la calida de imagen.</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>Elementos HTML implementando esta interfaz: {{HTMLElement("canvas")}}.</li> +</ul> diff --git a/files/es/web/api/htmlcanvaselement/toblob/index.html b/files/es/web/api/htmlcanvaselement/toblob/index.html new file mode 100644 index 0000000000..4759cd6250 --- /dev/null +++ b/files/es/web/api/htmlcanvaselement/toblob/index.html @@ -0,0 +1,261 @@ +--- +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/htmlcanvaselement/todataurl/index.html b/files/es/web/api/htmlcanvaselement/todataurl/index.html new file mode 100644 index 0000000000..30e2fdd71a --- /dev/null +++ b/files/es/web/api/htmlcanvaselement/todataurl/index.html @@ -0,0 +1,159 @@ +--- +title: HTMLCanvasElement.toDataURL() +slug: Web/API/HTMLCanvasElement/toDataURL +tags: + - API + - Canvas + - HTMLCanvasElement + - Lienzo + - Referencia + - metodo +translation_of: Web/API/HTMLCanvasElement/toDataURL +--- +<div> +<div> +<div>{{APIRef("Canvas API")}}</div> +</div> +</div> + +<p>El método <strong><code>HTMLCanvasElement.toDataURL()</code></strong> devuelve un <a href="/en-US/docs/Web/HTTP/data_URIs">data URI</a> el cual contiene una representación de la imagen en el formato especificado por el parámetro <code>type</code> (por defecto es <a href="https://en.wikipedia.org/wiki/Portable_Network_Graphics">PNG</a>). La imagen obtenida tendrá una resolución de 96 dpi.</p> + +<ul> + <li>Si la altura o anchura del canvas es <code>0</code>, devuelve un string con <code>"data:,"</code></li> + <li>Si el tipo solicitado no es <code>image/png</code> pero el valor devuelto empieza por <code>data:image/png</code>, entonces el formato especificado no esta soportado.</li> + <li>Chrome también soporta el tipo <code>image/webp</code>.</li> +</ul> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox"><var><em>canvas</em>.toDataURL(<em>tipo</em>, <em>opcionesCodificación</em>);</var> +</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code>tipo</code>{{optional_inline}}</dt> + <dd>Un {{domxref("DOMString")}} indicando el formato de la imagen. El tipo por defecto es <code>image/png</code>.</dd> + <dt><code>opcionesCodificación</code>{{optional_inline}}</dt> + <dd>Un {{jsxref("Number")}} entre <code>0</code> y <code>1</code> indicando la calidad de la imagen si el tipo solicitado es <code>image/jpeg</code> o <code>image/webp</code>.<br> + Si este argumento es cualquier otra cosa, se usa el valor por defecto de la imagen. El valor por defecto es <code>0.92</code>. Otros argumentos se ignoran.</dd> +</dl> + +<h3 id="Valor_devuelto">Valor devuelto</h3> + +<p>Un {{domxref("DOMString")}} que contiene el valor <a href="/en-US/docs/Web/HTTP/data_URIs">data URI</a>.</p> + +<h2 id="Ejemplos">Ejemplos</h2> + +<p>Dado un elemento {{HTMLElement("canvas")}}:</p> + +<pre class="brush: html"><canvas id="canvas" width="5" height="5"></canvas> +</pre> + +<p>Puedes obtener el data-URL del canvas con las siguientes líneas:</p> + +<pre class="brush: js">var canvas = document.getElementById('canvas'); +var dataURL = canvas.toDataURL(); +console.log(dataURL); +// "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNby +// blAAAADElEQVQImWNgoBMAAABpAAFEI8ARAAAAAElFTkSuQmCC" +</pre> + +<h3 id="Establecer_la_calidad_de_imagen_con_jpegs">Establecer la calidad de imagen con jpegs</h3> + +<pre class="brush: js">var fullQuality = canvas.toDataURL('image/jpeg', 1.0); +// "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQ...9oADAMBAAIRAxEAPwD/AD/6AP/Z" +var mediumQuality = canvas.toDataURL('image/jpeg', 0.5); +var lowQuality = canvas.toDataURL('image/jpeg', 0.1); +</pre> + +<h3 id="Example:_Dynamically_change_images" name="Example:_Dynamically_change_images">Ejemplo: Cambiar imágenes dinámicamente</h3> + +<p>Se puede usar esta técnica junto con los eventos del mouse para cambiar las imágenes de manera dinámica (escala de grises versus color en este ejemplo):</p> + +<h4 id="HTML">HTML</h4> + +<pre class="brush: html"><img class="grayscale" src="myPicture.png" alt="Description of my picture" /></pre> + +<h4 id="JavaScript">JavaScript</h4> + +<pre class="brush: js;highlight:[33]">window.addEventListener('load', quitarColor); + +function verImgEnColor() { + this.style.display = 'none'; + this.nextSibling.style.display = 'inline'; +} + +function verImgEnGris() { + this.previousSibling.style.display = 'inline'; + this.style.display = 'none'; +} + +function quitarColor() { + var aImages = document.getElementsByClassName('escalagrises'), + nImgsLen = aImages.length, + oCanvas = document.createElement('canvas'), + oCtx = oCanvas.getContext('2d'); + for (var nWidth, nHeight, oImgData, oGrayImg, nPixel, aPix, nPixLen, nImgId = 0; nImgId < nImgsLen; nImgId++) { + var oColorImg = aImages[nImgId]; + nWidth = oColorImg.offsetWidth; + nHeight = oColorImg.offsetHeight; + oCanvas.width = nWidth; + oCanvas.height = nHeight; + oCtx.drawImage(oColorImg, 0, 0); + oImgData = oCtx.getImageData(0, 0, nWidth, nHeight); + aPix = oImgData.data; + nPixLen = aPix.length; + for (nPixel = 0; nPixel < nPixLen; nPixel += 4) { + aPix[nPixel + 2] = aPix[nPixel + 1] = aPix[nPixel] = (aPix[nPixel] + aPix[nPixel + 1] + aPix[nPixel + 2]) / 3; + } + oCtx.putImageData(oImgData, 0, 0); + oGrayImg = new Image(); + oGrayImg.src = oCanvas.toDataURL(); + oGrayImg.onmouseover = verImgEnColor; + oColorImg.onmouseout = verImgEnGris; + oCtx.clearRect(0, 0, nWidth, nHeight); + oColorImg.style.display = "none"; + oColorImg.parentNode.insertBefore(oGrayImg, oColorImg); + } +}</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentarios</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', "scripting.html#dom-canvas-todataurl", "HTMLCanvasElement.toDataURL")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>Sin cambios desde el último snapshot, {{SpecName('HTML5 W3C')}}</td> + </tr> + <tr> + <td>{{SpecName('HTML5.1', "scripting-1.html#dom-canvas-todataurl", "HTMLCanvasElement.toDataURL")}}</td> + <td>{{Spec2('HTML5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', "scripting-1.html#dom-canvas-todataurl", "HTMLCanvasElement.toDataURL")}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>Snapshot del {{SpecName('HTML WHATWG')}} con la definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2> + +<div class="hidden">La tabla de compatibilidad de esta página se genera de datos estructurados. Si te gustaría contribuir a los datos, por favor revisa <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> y haznos una pull request.</div> + +<p>{{Compat("api.HTMLCanvasElement.toDataURL")}}</p> + +<h2 id="See_Also" name="See_Also">Ver también</h2> + +<ul> + <li>La interfaz que lo define, {{domxref("HTMLCanvasElement")}}.</li> + <li><a href="/en-US/docs/Web/HTTP/data_URIs">Data URIs</a> en la referencía <a href="/en-US/docs/Web/HTTP">HTTP</a>.</li> +</ul> diff --git a/files/es/web/api/htmlcanvaselement/width/index.html b/files/es/web/api/htmlcanvaselement/width/index.html new file mode 100644 index 0000000000..1eb26275af --- /dev/null +++ b/files/es/web/api/htmlcanvaselement/width/index.html @@ -0,0 +1,119 @@ +--- +title: HTMLCanvasElement.width +slug: Web/API/HTMLCanvasElement/width +translation_of: Web/API/HTMLCanvasElement/width +--- +<div> +<div> +<div>{{APIRef("Canvas API")}}</div> +</div> +</div> + +<p>TLa propiedad <strong><code><span>HTMLCanvasElement.width</span></code></strong> es un entero positivo que refleja el atributo {{htmlattrxref("width", "canvas")}} del elemento {{HTMLElement("canvas")}} interpretado en pixeles CSS. Cuando el atributo no esta especificado o se define con un valor invalido (ej. Número negativo), es usado el valor por defecto de 150.</p> + +<p>Esta es una de de las dos propiedades que controlan el tamaño del canvas, siendo la otra {{domxref("HTMLCanvasElement.height")}}, that controls the size of the canvas.</p> + +<h2 id="Syntax" name="Syntax">Syntax</h2> + +<pre class="syntaxbox"><var>var <em>pxl</em> = <em>canvas</em></var>.width; +<em>canvas</em>.width = <em>pxl</em>; +</pre> + +<h2 id="Ejemplos">Ejemplos</h2> + +<p>Dado el siguiente elemento {{HTMLElement("canvas")}} :</p> + +<pre class="brush: html"><canvas id="canvas" width="300" height="300"></canvas> +</pre> + +<p>Puedes obtener el ancho del canvas con el siguiente codigo:</p> + +<pre class="brush: js">var canvas = document.getElementById("canvas"); +console.log(canvas.width); // 300 +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Status</th> + <th scope="col">Comentarios</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', "scripting.html#attr-canvas-width", "HTMLCanvasElement.width")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>No hay cambios desde la ultima foto {{SpecName('HTML5 W3C')}}</td> + </tr> + <tr> + <td>{{SpecName('HTML5.1', "scripting-1.html#attr-canvas-width", "HTMLCanvasElement.width")}}</td> + <td>{{Spec2('HTML5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', "scripting-1.html#attr-canvas-width", "HTMLCanvasElement.width")}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>Foto que contiene la definición inicial {{SpecName('HTML WHATWG')}}.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_Navegadores">Compatibilidad de Navegadores</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>BSoporte Básico</td> + <td>{{ CompatChrome(4) }}</td> + <td>{{ CompatGeckoDesktop("1.9.2") }}</td> + <td>{{ CompatIE(9) }}</td> + <td>{{ CompatOpera(9) }}</td> + <td>{{ CompatSafari(3.1) }}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</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>Soporte Básico</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatGeckoMobile("1.9.2") }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_Also" name="See_Also">Ver también</h2> + +<ul> + <li>La interfaz que lo define, {{domxref("HTMLCanvasElement")}}.</li> + <li>La otra propiedad que controla el tamaño del canvas,{{domxref("HTMLCanvasElement.height")}}.</li> +</ul> diff --git a/files/es/web/api/htmlcollection/index.html b/files/es/web/api/htmlcollection/index.html new file mode 100644 index 0000000000..6d255f4536 --- /dev/null +++ b/files/es/web/api/htmlcollection/index.html @@ -0,0 +1,99 @@ +--- +title: HTMLCollection +slug: Web/API/HTMLCollection +tags: + - API + - DOM + - HTML DOM + - HTMLCollection + - Interfaz + - Lista de elementos + - Referencia + - Referência DOM +translation_of: Web/API/HTMLCollection +--- +<p>{{APIRef("HTML DOM")}}</p> + +<p>La interfaz <strong><code>HTMLCollection</code></strong> representa una colección genérica (objeto tipo array similar a arguments) de elementos (en orden de documento) y ofrece métodos y propiedades para seleccionarlos de la lista.</p> + +<div class="note"><strong>Nota: </strong>Esta interfaz se llama <code>HTMLCollection</code> por razones históricas (antes del DOM moderno, las colecciones que implementaban esta interfaz sólo podían tener elementos HTML como sus ítems).</div> + +<p>Una <code>HTMLCollection</code> en el DOM de HTML está viva; se actualiza automáticamente cuando el documento subyacente cambia.</p> + +<h2 id="Propiedades">Propiedades</h2> + +<dl> + <dt>{{domxref("HTMLCollection.length")}} {{readonlyInline}}</dt> + <dd>Devuelve el numero de ítems en la colección.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<dl> + <dt>{{domxref("HTMLCollection.item()")}}</dt> + <dd><span id="result_box" lang="es"><span class="hps">Devuelve el</span> <span class="hps">nodo específicado en el índice en base cero dentro de</span> <span class="hps">la lista.</span> <span class="hps">Devuelve</span> <span class="hps"><code>null</code> si</span> <span class="hps">el índice está fuera</span> <span class="hps">de rango.</span></span></dd> + <dt>{{domxref("HTMLCollection.namedItem()")}}</dt> + <dd><span id="result_box" lang="es"><span class="hps">Devuelve el</span> <span class="hps">nodo específico</span> <span class="hps">cuyo ID</span><span class="hps"> o</span><span>,</span> <span class="hps">en último caso</span><span>,</span> cuyo <span class="hps">nombre coincide con</span> <span class="hps">la cadena especificada</span> <span class="hps">por</span></span> <code>name</code><span lang="es"><span class="hps">.</span> La c<span class="hps">oincidencia</span> <span class="hps">por nombre</span> <span class="hps">sólo se hace</span> <span class="hps">como último recurso</span><span>,</span> <span class="hps">sólo en</span> <span class="hps">HTML,</span> <span class="hps">y sólo si el</span> <span class="hps">elemento referenciado</span> <span class="hps">soporta</span> <span class="hps">el atributo </span></span><code>name</code><span lang="es"><span>.</span> <span class="hps">Devuelve <code>null</code></span> <span class="hps">si no existe ningún</span> <span class="hps">nodo</span> <span class="hps">con el nombre</span> <span class="hps">indicado.</span></span></dd> +</dl> + +<h2 id="Uso_en_JavaScript">Uso en JavaScript</h2> + +<p><span id="result_box" lang="es"><code><span class="hps">HTMLCollection</span></code></span> también<span lang="es"><span class="hps"> expone a</span> <span class="hps">sus miembros</span> <span class="hps">directamente como</span> <span class="hps">propiedades tanto por</span> </span>name <span lang="es">como por<span class="hps"> </span></span>index<span lang="es"><span>. Los</span> <span class="hps">IDS de</span> <span class="hps">HTML</span> <span class="hps">deben contener </span><code><span>:</span></code> <span class="hps">y </span><code><span>.</span></code> <span class="hps">como caracteres</span> <span class="hps">válidos</span><span>, los cuales necesitan del uso de corchetes para acceder a sus propiedades</span><span>.</span> <span class="hps">Actualmente</span> las <span class="hps">HTMLCollections</span> <span class="hps">no reconocen</span> <span class="hps">los IDS</span> <span class="hps">puramente</span> <span class="hps">numéricos</span><span>, lo que causaría</span> <span class="hps">conflicto con el</span> <span class="hps">acceso</span> al estilo array<span class="hps">,</span> <span class="hps">aunque</span> <span class="hps">HTML5</span> <span class="hps">sí permite</span> <span class="hps">estos.</span></span></p> + +<p>Por ejemplo, suponiendo que hay un elemento <code><form></code> en el documento y que su <code>id</code> es<font face="Open Sans, Arial, sans-serif"> </font><code>"myForm"</code>:</p> + +<pre class="brush:js">var elem1, elem2; + +// document.forms es un HTMLCollection + +elem1 = document.forms[0]; +elem2 = document.forms.item(0); + +alert(elem1 === elem2); // muestra: "true" + +elem1 = document.forms.myForm; +elem2 = document.forms.namedItem("myForm"); + +alert(elem1 === elem2); // muestra: "true" + +elem1 = document.forms["named.item.with.periods"];</pre> + +<h2 id="Especificación">Especificación</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('DOM WHATWG', '#htmlcollection', 'HTMLCollection')}}</td> + <td>{{ Spec2('DOM WHATWG') }}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('DOM2 HTML', 'html.html#ID-75708506', 'HTMLCollection')}}</td> + <td>{{ Spec2('DOM2 HTML') }}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('DOM1', 'level-one-html.html#ID-75708506', 'HTMLCollection')}}</td> + <td>{{ Spec2('DOM1') }}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<p>{{Compat("api.HTMLCollection")}}</p> + +<h2 id="Vea_también">Vea también</h2> + +<ul> + <li>{{domxref("NodeList")}}</li> + <li>{{domxref("HTMLFormControlsCollection")}}, {{domxref("HTMLOptionsCollection")}}</li> +</ul> diff --git a/files/es/web/api/htmlcontentelement/getdistributednodes/index.html b/files/es/web/api/htmlcontentelement/getdistributednodes/index.html new file mode 100644 index 0000000000..c4aad9ddb8 --- /dev/null +++ b/files/es/web/api/htmlcontentelement/getdistributednodes/index.html @@ -0,0 +1,95 @@ +--- +title: HTMLContentElement.getDistributedNodes() +slug: Web/API/HTMLContentElement/getDistributedNodes +tags: + - Necesita traducción +translation_of: Web/API/HTMLContentElement/getDistributedNodes +--- +<p>{{ APIRef("Web Components") }}</p> + +<p>The <code><strong>HTMLContentElement.getDistributedNodes()</strong></code> method returns a static {{domxref("NodeList")}} of the {{glossary("distributed nodes")}} associated with this <code><content></code> element.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox">var <em>nodeList</em> = <em>object</em>.getDistributedNodes() +</pre> + +<h2 id="Specifications" name="Specifications">Example</h2> + +<pre class="brush: js">// Get the distributed nodes +var nodes = myContentObject.getDistributedNodes();</pre> + +<h2 id="Specifications" name="Specifications">Specifications</h2> + +<table class="spec-table standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('Shadow DOM', '#the-content-element', 'content')}}</td> + <td>{{Spec2('Shadow DOM')}}</td> + <td> </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 (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>35</td> + <td><span style="font-size: 12px; line-height: 18px;">{{CompatGeckoDesktop("28")}}</span> [1]</td> + <td>{{CompatNo}}</td> + <td>26</td> + <td><span style="font-size: 12px; line-height: 18px;">{{CompatNo}}</span></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 Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>37</td> + <td>{{CompatGeckoMobile("28")}} [1]</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] If Shadow DOM is not enabled in Firefox, <code><content></code> elements will behave like {{domxref("HTMLUnknownElement")}}. Shadow DOM was first implemented in Firefox 28 and is behind a preference, <code>dom.webcomponents.enabled</code>, which is disabled by default.</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/HTMLContentElement">HTMLContentElement</a></li> +</ul> diff --git a/files/es/web/api/htmlcontentelement/index.html b/files/es/web/api/htmlcontentelement/index.html new file mode 100644 index 0000000000..637210416d --- /dev/null +++ b/files/es/web/api/htmlcontentelement/index.html @@ -0,0 +1,110 @@ +--- +title: HTMLContentElement +slug: Web/API/HTMLContentElement +tags: + - Necesita traducción +translation_of: Web/API/HTMLContentElement +--- +<p>{{ APIRef("Web Components") }}</p> + +<p>{{Deprecated_header}}</p> + +<p>The <code><strong>HTMLContentElement</strong></code> interface represents a {{HTMLElement("content")}} HTML Element, which is used in <a href="/en-US/docs/Web/Web_Components/Shadow_DOM">Shadow DOM</a>. </p> + +<h2 id="Properties" name="Properties">Properties</h2> + +<p><em>This interface inherits the properties of {{domxref("HTMLElement")}}.</em></p> + +<dl> + <dt>{{domxref("HTMLContentElement.select")}}</dt> + <dd>Is a {{domxref("DOMString")}} that reflects the {{ htmlattrxref("select", "content") }} HTML attribute. The value is a comma-separated list of CSS selectors that select the content to insert in place of the <code><content></code> element.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<p><em>This interface inherits the methods of {{domxref("HTMLElement")}}.</em></p> + +<dl> + <dt>{{domxref("HTMLContentElement.getDistributedNodes()")}}</dt> + <dd>Returns a static {{domxref("NodeList")}} of the {{glossary("distributed nodes")}} associated with this <code><content></code> element. </dd> +</dl> + +<h2 id="Specifications">Specifications</h2> + +<table class="spec-table standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('Shadow DOM', '#the-content-element', 'content')}}</td> + <td>{{Spec2('Shadow DOM')}}</td> + <td> </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 (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>35</td> + <td><span style="font-size: 12px; line-height: 18px;">{{CompatGeckoDesktop("28")}}</span> [1]</td> + <td>{{CompatNo}}</td> + <td>26</td> + <td><span style="font-size: 12px; line-height: 18px;">{{CompatNo}}</span></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 Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>37</td> + <td>{{CompatGeckoMobile("28")}} [1]</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] If Shadow DOM is not enabled in Firefox, <content> elements will behave like {{domxref("HTMLUnknownElement")}}. Shadow DOM was first implemented in Firefox 28 and is behind a preference, <code>dom.webcomponents.enabled</code>, which is disabled by default.</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>The {{HTMLElement("content")}} HTML element, implementing this interface.</li> + <li><a href="/en-US/docs/Web/Web_Components/Shadow_DOM">Shadow DOM</a></li> +</ul> + +<dl> + <dt> </dt> +</dl> diff --git a/files/es/web/api/htmlcontentelement/select/index.html b/files/es/web/api/htmlcontentelement/select/index.html new file mode 100644 index 0000000000..916be57621 --- /dev/null +++ b/files/es/web/api/htmlcontentelement/select/index.html @@ -0,0 +1,95 @@ +--- +title: HTMLContentElement.select +slug: Web/API/HTMLContentElement/select +tags: + - Necesita traducción +translation_of: Web/API/HTMLContentElement/select +--- +<p>{{ APIRef("Web Components") }}</p> + +<p>The <code><strong>HTMLContentElement.select</strong></code> property reflects the <code>select</code> attribute. It is a {{domxref("DOMString")}} containing a space-separated list of CSS selectors that select the content to insert in place of the <content> element.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><em>object</em>.select = "<em>CSSselector</em> <em>CSSselector</em> ..."; +</pre> + +<h2 id="Specifications" name="Specifications">Example</h2> + +<pre class="brush: js">// Select <h1> elements and elements with class="error" +myContentObject.select = "h1 .error";</pre> + +<h2 id="Specifications" name="Specifications">Specifications</h2> + +<table class="spec-table standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('Shadow DOM', '#the-content-element', 'content')}}</td> + <td>{{Spec2('Shadow DOM')}}</td> + <td> </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 (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>35</td> + <td><span style="font-size: 12px; line-height: 18px;">{{CompatGeckoDesktop("28")}}</span> [1]</td> + <td>{{CompatNo}}</td> + <td>26</td> + <td><span style="font-size: 12px; line-height: 18px;">{{CompatNo}}</span></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 Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>37</td> + <td>{{CompatGeckoMobile("28")}} [1]</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] If Shadow DOM is not enabled in Firefox, <content> elements will behave like {{domxref("HTMLUnknownElement")}}. Shadow DOM was first implemented in Firefox 28 and is behind a preference, <code>dom.webcomponents.enabled</code>, which is disabled by default.</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/HTMLContentElement">HTMLContentElement</a></li> +</ul> diff --git a/files/es/web/api/htmldivelement/index.html b/files/es/web/api/htmldivelement/index.html new file mode 100644 index 0000000000..164b6f7108 --- /dev/null +++ b/files/es/web/api/htmldivelement/index.html @@ -0,0 +1,125 @@ +--- +title: HTMLDivElement +slug: Web/API/HTMLDivElement +tags: + - API + - HTML DOM + - Interfaz + - NeedsNewLayout + - Referencia +translation_of: Web/API/HTMLDivElement +--- +<div> +<div>{{ APIRef("HTML DOM") }}</div> +</div> + +<div> </div> + +<p>La interfaz <strong><code>HTMLDivElement</code></strong> provee propiedades especiales (más allá de la interfaz regular {{domxref("HTMLElement")}} que también está disponible por herencia) para manipular elementos div.</p> + +<p>{{InheritanceDiagram(600,120)}}</p> + +<h2 id="Propiedades">Propiedades</h2> + +<p><em>Hereda las propiedades de su padre, {{domxref("HTMLElement")}}.</em></p> + +<dl> + <dt>{{domxref("HTMLDivElement.align")}} {{obsolete_inline}}</dt> + <dd>Es un {{domxref("DOMString")}} que representa una propiedad enumerada que indica la alineación de los contenidos del elemento con respecto al contexto circundante. Los posibles valores son <code>"left"</code>, <code>"right"</code>, <code>"justify"</code>, and <code>"center"</code>.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<p><em>No hay métodos específicos; hereda los métodos de su padre, {{domxref("HTMLElement")}}.</em></p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', "grouping-content.html#the-div-element", "HTMLDivElement")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>No hay cambios de {{SpecName("HTML5 W3C")}}.</td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', "grouping-content.html#the-div-element", "HTMLDivElement")}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>No hay cambios de {{SpecName("DOM2 HTML")}}.</td> + </tr> + <tr> + <td>{{SpecName('DOM2 HTML', 'html.html#ID-22445964', 'HTMLDivElement')}}</td> + <td>{{Spec2('DOM2 HTML')}}</td> + <td>No hay cambios de {{SpecName("DOM1")}}.</td> + </tr> + <tr> + <td>{{SpecName('DOM1', 'level-one-html.html#ID-22445964', 'HTMLDivElement')}}</td> + <td>{{Spec2('DOM1')}}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidad</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(1.0)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidad</th> + <th>Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile(1.0)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>El elemento HTML que implementa esta interfaz: {{ HTMLElement("div") }}.</li> +</ul> diff --git a/files/es/web/api/htmlelement/change_event/index.html b/files/es/web/api/htmlelement/change_event/index.html new file mode 100644 index 0000000000..25642a5322 --- /dev/null +++ b/files/es/web/api/htmlelement/change_event/index.html @@ -0,0 +1,143 @@ +--- +title: 'HTMLElement: Evento change' +slug: Web/API/HTMLElement/change_event +tags: + - Change + - DOM + - Evento + - HTML + - Referencia + - Web +translation_of: Web/API/HTMLElement/change_event +--- +<div>{{APIRef}}</div> + +<p>El evento <code>change</code> se dispara para elementos {{HTMLElement("input")}}, {{HTMLElement("select")}}, y {{HTMLElement("textarea")}} cuando una alteración al valor de un elemento es confirmada por el usuario. A diferencia del evento {{event("input")}}, el evento <code>change</code> no es disparado necesariamente por cada alteración al valor <code>value</code> del elemento</p> + +<table class="properties"> + <tbody> + <tr> + <th scope="row">Burbujas</th> + <td>Sí</td> + </tr> + <tr> + <th scope="row">Cancelable</th> + <td>No</td> + </tr> + <tr> + <th scope="row">Interfaz</th> + <td>{{domxref("Event")}}</td> + </tr> + <tr> + <th scope="row">Propiedad del manejador del evento</th> + <td><code><a href="/en-US/docs/Web/API/GlobalEventHandlers/onchange">onchange</a></code></td> + </tr> + </tbody> +</table> + +<p>Dependiendo del tipo de elemento siendo cambiado y la forma en que el usuario interactua con el elemento, el evento <code>change</code> dispara en un momento diferente:</p> + +<ul> + <li>Cuando el elemento es <code>:checked</code> (ya sea dando click o usuando el teclado) para elementos <code><input type="radio"></code> y <code><input type="checkbox"></code>;</li> + <li>Cuando el usuario confirma el cambio explícitimante (por ejemplo, al seleccionar un valor de un menú desplegable {{HTMLElement("select")}} con un clic del ratón, al seleccionar una fecha de un selector de fecha de un elemento <code><input type="date"></code>, al seleccionar un archivo en un selector de archivo por un elemento <code><input type="file"></code>, etc.);</li> + <li>Cuando un elemento pierde el foco después de que su valor haya sido cambiado, pero no confirmado (es decir, despues de editar el valor de un elemento {{HTMLElement("textarea")}} o <code><input type="text"></code>).</li> +</ul> + +<p>La especificaciones HTML listan <a href="https://html.spec.whatwg.org/multipage/forms.html#concept-input-apply" title="https://html.spec.whatwg.org/multipage/forms.html#concept-input-apply">los tipos de <code><input></code> que deberían disparar el evento <code>change</code></a>.</p> + +<h2 id="Ejemplos">Ejemplos</h2> + +<h3 id="Ejemplos_Live_Elemento_select">Ejemplos Live: Elemento select</h3> + +<div class="select-example"> +<h4 id="HTML">HTML</h4> + +<pre class="brush: html"><label>Elija un sabor de nieve: + <select class="nieve" name="nieve"> + <option value="">Seleccione Uno …</option> + <option value="chocolate">Chocolate</option> + <option value="sardina">Sardina</option> + <option value="vainilla">Vainilla</option> + </select> +</label> + +<div class="resultado"></div></pre> + +<div class="hidden"> +<pre class="brush: css">body { + display: grid; + grid-template-areas: "select result"; +} + +select { + grid-area: select; +} + +.resultado { + grid-area: result; +} + +</pre> +</div> + +<h4 id="JS">JS</h4> + +<pre class="brush: js">const selectElement = document.querySelector('.nieve'); + +selectElement.addEventListener('change', (event) => { + const resultado = document.querySelector('.resultado'); + resultado.textContent = `Te gusta el sabor ${event.target.value}`; +}); +</pre> +</div> + +<h4 id="Resultado">Resultado</h4> + +<p>{{ EmbedLiveSample('select-example', '100%', '75px') }}</p> + +<h3 id="Elemento_de_entrada_de_texto">Elemento de entrada de texto</h3> + +<p>Para algunos elementos, incluyendo <code><input type="text"></code>, el evento <code>change</code> no se lanza hasta que el campo pierde el foco. Prueba a introducir algo en el campo anterior, y luego pulsa en algún otro lugar para lanzar el evento.</p> + +<h4 id="HTML_2">HTML</h4> + +<pre class="brush: html line-numbers language-html"><code class="language-html"><span class="tag token"><span class="tag token"><span class="punctuation token"><</span>input</span> <span class="attr-name token">placeholder</span><span class="attr-value token"><span class="punctuation token">=</span><span class="punctuation token">"</span>Enter some text<span class="punctuation token">"</span></span> <span class="attr-name token">name</span><span class="attr-value token"><span class="punctuation token">=</span><span class="punctuation token">"</span>name<span class="punctuation token">"</span></span><span class="punctuation token">/></span></span> +<span class="tag token"><span class="tag token"><span class="punctuation token"><</span>p</span> <span class="attr-name token">id</span><span class="attr-value token"><span class="punctuation token">=</span><span class="punctuation token">"</span>log<span class="punctuation token">"</span></span><span class="punctuation token">></span></span><span class="tag token"><span class="tag token"><span class="punctuation token"></</span>p</span><span class="punctuation token">></span></span></code></pre> + +<h4 id="JavaScript">JavaScript</h4> + +<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="keyword token">const</span> input <span class="operator token">=</span> document<span class="punctuation token">.</span><span class="function token">querySelector</span><span class="punctuation token">(</span><span class="string token">'input'</span><span class="punctuation token">)</span><span class="punctuation token">;</span> +<span class="keyword token">const</span> log <span class="operator token">=</span> document<span class="punctuation token">.</span><span class="function token">getElementById</span><span class="punctuation token">(</span><span class="string token">'log'</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + +input<span class="punctuation token">.</span><span class="function token">addEventListener</span><span class="punctuation token">(</span><span class="string token">'change'</span><span class="punctuation token">,</span> updateValue<span class="punctuation token">)</span><span class="punctuation token">;</span> + +<span class="keyword token">function</span> <span class="function token">updateValue</span><span class="punctuation token">(</span><span class="parameter token">e</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + log<span class="punctuation token">.</span>textContent <span class="operator token">=</span> e<span class="punctuation token">.</span>target<span class="punctuation token">.</span>value<span class="punctuation token">;</span> +<span class="punctuation token">}</span></code></pre> + +<h4 id="Result">Result</h4> + +<p>{{ EmbedLiveSample('Text_input_element', '100%', '75px') }}</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', "indices.html#event-change", "change")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_navegadores">Compatibilidad en navegadores</h2> + + + +<p>{{Compat("api.HTMLElement.change_event")}}</p> + +<p>Diferentes navegadores no siempre concuerdan cuando un evento <code>change</code> debería ser disparado para ciertos tipo de interacciones. Por ejemplo, navegación por teclado en en elementos {{HTMLElement("select")}} nunca disparan el evento <code>change</code> en Gecko hasta que el usuario presiona Enter o cambia el foco fuera del <code><select></code> (ver {{bug("126379")}}). A partir de Firefox 63 (Quantum), sin embargo, este comportamiento es consistente entre los mayores navegadores.</p> diff --git a/files/es/web/api/htmlelement/click/index.html b/files/es/web/api/htmlelement/click/index.html new file mode 100644 index 0000000000..0f6d7983c7 --- /dev/null +++ b/files/es/web/api/htmlelement/click/index.html @@ -0,0 +1,88 @@ +--- +title: HTMLElement.click() +slug: Web/API/HTMLElement/click +tags: + - HTMLElement + - Referencia + - metodo +translation_of: Web/API/HTMLElement/click +--- +<div> +<div>{{ APIRef("HTML DOM") }}</div> +</div> + +<p>El método <code><strong>HTMLElement.click()</strong></code> simula el click de un ratón físico en un elemento HTML.</p> + +<p>Cuando <code>click()</code> se usa en un elemento que soporte este método (como un elemento {{HTMLElement("input")}}), el elemento lanza el evento asociado al click. Luego, este evento iniciará otros eventos asociados al clicado en elementos más altos en la jerarquía del documento html (o de la cadena de eventos).</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><em>elemento</em>.click()</pre> + +<h2 id="Especificación">Especificación</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('DOM2 HTML', 'html.html#ID-2651361')}}</td> + <td>{{Spec2('DOM2 HTML')}}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_navegadores">Compatibilidad en navegadores</h2> + +<div class="hidden">La tabla de compatibilidad en esta página se genera a partir de datos estructurados. Si desea contribuir a los datos, consulte <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> y envíanos un pull request.</div> + +<p>{{Compat("api.HTMLElement.click")}}</p> + + +<h3 id="Traducción_en_Español">Traducción en Español:</h3> + + + +<article class="localized"> +<div class="guide-links"><a href="https://developer.mozilla.org/es/docs/MDN/Community">¿Necesitas ayuda?</a> • <a href="https://developer.mozilla.org/es/docs/MDN/Contribute/Editor">Guía editorial</a> • <a href="https://developer.mozilla.org/es/docs/MDN/Contribute/Content/Style_guide">Guía de estilo</a></div> + +<div class="editor-wrapper" id="editor-wrapper"> +<div class="draft-container"> +<div class="draft-old"> </div> + +<div class="draft-status"><span id="draft-action">Borrador autoguardado: <time class="time-ago" id="draft-time" title="2018-05-27T03:51:54.273Z">26/5/2018 21:51:54</time></span></div> +</div> + +<div class="ckeditor-container editor-container dirty"> +<div class="editor"> +<div class="editor-tools"> </div> + +<div style="height: 173px;"> +<div style="border: 1px solid rgb(182, 182, 182); width: 617px; position: fixed; top: 0px;"> </div> +</div> +</div> +</div> +</div> +</article> + +<article class="localized"> +<div class="editor-wrapper" id="editor-wrapper"> +<div class="ckeditor-container editor-container dirty"> +<div class="editor"> +<div class="cke" dir="ltr" id="cke_id_content" lang="es"> +<div> +<div id="cke_1_contents" style="height: 947px;"> </div> +</div> +</div> +</div> +</div> +</div> +</article> + +<p> </p> diff --git a/files/es/web/api/htmlelement/contenteditable/index.html b/files/es/web/api/htmlelement/contenteditable/index.html new file mode 100644 index 0000000000..bbb0749b7f --- /dev/null +++ b/files/es/web/api/htmlelement/contenteditable/index.html @@ -0,0 +1,57 @@ +--- +title: HTMLElement.contentEditable +slug: Web/API/HTMLElement/contentEditable +translation_of: Web/API/HTMLElement/contentEditable +--- +<div>{{APIRef("HTML DOM")}}</div> + +<p><span class="seoSummary">La propiedad <strong><code>contentEditable</code></strong> de la interfaz {{domxref("HTMLElement")}} especifica si el elemento es editable o no.</span> Este atributo puede tener los siguientes valores:</p> + +<ul> + <li><code>'true'</code> indica si el elemento es <code>contenteditable</code>.</li> + <li><code>'false'</code> indica que el elemento no puede ser editado.</li> + <li><code>'inherit'</code> indica que el elemento hereda el estado editable del padre.</li> +</ul> + +<p>Se puede usar la propiedad {{domxref("HTMLElement.isContentEditable")}} para comprobar el valor {{jsxref("Boolean")}} de esta propiedad.</p> + +<h2 id="Sintáxis">Sintáxis</h2> + +<pre class="syntaxbox"><em>editable</em> = <em>element</em>.contentEditable +<em>element</em>.contentEditable = 'true' +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('HTML WHATWG', 'interaction.html#contenteditable', 'contenteditable')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("api.HTMLElement.contentEditable")}}</p> + +<p>In Internet Explorer, <code>contenteditable</code> cannot be applied to the {{htmlelement("table")}}, {{htmlelement("col")}}, {{htmlelement("colgroup")}}, {{htmlelement("tbody")}}, {{htmlelement("td")}}, {{htmlelement("tfoot")}}, {{htmlelement("th")}}, {{htmlelement("thead")}}, and {{htmlelement("tr")}} elements directly. A content editable {{htmlelement("span")}} or {{htmlelement("div")}} element can be placed inside the individual table cells.</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/Guide/HTML/Editable_content">Making content editable</a></li> + <li>{{domxref("HTMLElement.isContentEditable")}}</li> + <li>The {{htmlattrxref("contenteditable")}} global attribute.</li> +</ul> diff --git a/files/es/web/api/htmlelement/dataset/index.html b/files/es/web/api/htmlelement/dataset/index.html new file mode 100644 index 0000000000..10c6f555f9 --- /dev/null +++ b/files/es/web/api/htmlelement/dataset/index.html @@ -0,0 +1,132 @@ +--- +title: HTMLElement.dataset +slug: Web/API/HTMLElement/dataset +translation_of: Web/API/HTMLOrForeignElement/dataset +--- +<div>{{ APIRef("HTML DOM") }}</div> + +<p><span class="seoSummary">La propiedad <code><strong>dataset</strong></code> en {{domxref("HTMLElement")}} proporciona una interfaz lectura/escritura para obtener todos los <a href="/es/HTML/Global_attributes#attr-data-*" title="https://developer.mozilla.org/en/HTML/Global_attributes#attr-data-*">atributos de datos personalizados</a> (<code>data-*</code>) de cada uno de los elementos.</span> Está disponible el acceso en HTML y en el DOM. Dentro del <a href="/en/DOM/DOMStringMap" title="en/DOM/DOMStringMap">map of DOMString</a>, aparece una entrada por cada atributo de datos. Hay que tener en cuenta que la propiedad<strong> </strong><code>dataset</code><strong> </strong>puede leerse, pero no modificarse directamente. En vez de eso, las escrituras deben ser realizadas a través de cada propiedad individual del <code>dataset</code>, que representan a cada atributo correspondiente. Además un HTML <code><strong>data-</strong></code><em>attribute</em> y su correspondiente DOM<strong> </strong><code>dataset.</code><em>property</em> no comparten el mismo nombre, pero son siempre similares:</p> + +<ul> + <li>El nombre de un attributo de datos comienza en HTML con <code>data-</code>. Sólo puede estar formado por letras minúsculas, números y los caracteres: guión (<code>-</code>), punto (<code>.</code>), dos puntos (<code>:</code>) y guión bajo (<code>_</code>) -- NUNCA una letra mayúscula (A a Z).</li> + <li>El nombre del atributo en JavaScript será el del correspondiente atributo HTML pero en camelCase, sin guiones, puntos, etc.</li> +</ul> + +<p>Adicionalmente, encontrarás una guía de como usar los atributos data de HTML en nuestro articulo <a href="/en-US/docs/Learn/HTML/Howto/Use_data_attributes">Using data attributes.</a></p> + +<h3 id="Conversion_de_nombres">Conversion de nombres</h3> + +<p><code>dash-style</code> a <code>camelCase</code>: Un atributo de datos personalizado se transforma en una clave para la entrada {{ domxref("DOMStringMap") }} con las siguientes reglas</p> + +<ul> + <li>el prefijo <code>data-</code> es eliminado (incluyendo el guión);</li> + <li>por cada guión (<code>U+002D</code>) seguido de un caracter ASCII que sea una letra en minuscula<span style="line-height: 1.5;"> </span><code>a</code><span style="line-height: 1.5;"> a la </span><code>z</code><span style="line-height: 1.5;">, el guión es removido y la letra se transforma en su contraparte en mayuscula;</span></li> + <li>otros caracteres (incluyendo otros guines) se mantienen intactos.</li> +</ul> + +<p><code>camelCase</code> a <code>dash-style</code>: La conversión opuesta, mapea una clave en un nombre de atributo, usa las siguientes reglas:</p> + +<ul> + <li>Restricción: Un guión no debe ser inmediatamente seguido por un un caracter ASCII que sea una letra minuscula de la <code>a</code> a la <code>z</code> (antes de la conversión);</li> + <li>se agrega el prefijo <code>data-</code>;</li> + <li>cualquier caracter ASCII que sea una letra mayuscula de la <code>A</code> a la <code>Z</code> se convierte en un guión seguido de se contraparte en minuscula;</li> + <li>otros caracteres se mantienen intactos.</li> +</ul> + +<p>La restricción en las reglas anteriores aseguran que las dos conversiones sean inversas una a la otra.</p> + +<p>Por ejemplo, el atributo nombrado <code>data-abc-def</code> corresponde a la clave <code>abcDef</code>.</p> + +<ul> +</ul> + +<h3 id="Accediendo_valores">Accediendo valores</h3> + +<ul> + <li>Los atributos pueden ser definidos y obtenidos usando el nombre camelCase (la clave) como la propiedad de un objeto del dataset, como en <code>element.dataset.keyname</code></li> + <li>Los atributos tambien pueden ser definidos y obtenidos usando la sintaxis de corchetes, como en <code>element.dataset[keyname]</code></li> + <li>El <a href="/en-US/docs/Web/JavaScript/Reference/Operators/in">operador <code>in</code></a> puede ser usado para checar si un atributo dado existe.</li> +</ul> + +<h3 id="Definiendo_valores">Definiendo valores</h3> + +<ul> + <li>Cuando un atributo es definido, su valor siempre se convierte a string. Por ejemplo, <code>null</code> siempre se convierte en el string "null".</li> + <li>Cuando quieras remover un atributo, puedes usar el <a href="/en-US/docs/Web/JavaScript/Reference/Operators/delete">operador <code>delete</code></a>.</li> +</ul> + +<h2 id="Sintaxis">Sintaxis</h2> + +<ul> + <li><em>string</em> = <em>element</em>.<strong>dataset</strong>.<em>camelCasedName</em>;</li> + <li><em>element.</em><strong>dataset</strong>.<em>camelCasedName</em> = <em>string</em>;</li> + <br> + <li><em>string</em> = <em>element</em>.<strong>dataset</strong>[<em>camelCasedName</em>];</li> + <li><em>element</em>.<strong>dataset</strong>[<em>camelCasedName</em>] = <em>string</em>;</li> + <br> + <li><em>Custom data attributes can also be set directly on HTML elements, but attribute names must use the data- syntax above. </em></li> +</ul> + +<h2 id="Ejemplos">Ejemplos</h2> + +<pre class="brush: html"><div id="user" data-id="1234567890" data-user="johndoe" data-date-of-birth>John Doe</div></pre> + +<pre class="brush: js">const el = document.querySelector('#user'); + +// el.id == 'user' +// el.dataset.id === '1234567890' +// el.dataset.user === 'johndoe' +// el.dataset.dateOfBirth === '' + +// set the data attribute +el.dataset.dateOfBirth = '1960-10-03'; +// Result: el.dataset.dateOfBirth === 1960-10-03 + +delete el.dataset.dateOfBirth; +// Result: el.dataset.dateOfBirth === undefined + +// 'someDataAttr' in el.dataset === false +el.dataset.someDataAttr = 'mydata'; +// Result: 'someDataAttr' in el.dataset === true +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', "dom.html#dom-dataset", "HTMLElement.dataset")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>No change from latest snapshot, {{SpecName('HTML5.1')}}</td> + </tr> + <tr> + <td>{{SpecName('HTML5.1', "dom.html#dom-dataset", "HTMLElement.dataset")}}</td> + <td>{{Spec2('HTML5.1')}}</td> + <td>Snapshot of {{SpecName('HTML WHATWG')}}, no change from {{SpecName('HTML5 W3C')}}</td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', "dom.html#dom-dataset", "HTMLElement.dataset")}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>Snapshot of {{SpecName('HTML WHATWG')}}, initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_navegadores">Compatibilidad en navegadores</h2> + + + +<p>{{Compat("api.HTMLElement.dataset")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>The HTML <code><a href="/en-US/docs/Web/HTML/Global_attributes/data-*"><strong>data-*</strong></a></code> class of global attributes.</li> + <li><a href="/en-US/docs/Learn/HTML/Howto/Use_data_attributes">Using data attributes</a></li> + <li>{{domxref("Element.getAttribute()")}} and {{domxref("Element.setAttribute()")}}</li> +</ul> diff --git a/files/es/web/api/htmlelement/focus/index.html b/files/es/web/api/htmlelement/focus/index.html new file mode 100644 index 0000000000..d615cbf12e --- /dev/null +++ b/files/es/web/api/htmlelement/focus/index.html @@ -0,0 +1,164 @@ +--- +title: HTMLElement.focus() +slug: Web/API/HTMLElement/focus +tags: + - API + - HTML DOM + - HTMLElement + - Referencia + - metodo +translation_of: Web/API/HTMLOrForeignElement/focus +--- +<div>{{ APIRef("HTML DOM") }}</div> + +<p>El método <code><strong>HTMLElement.focus()</strong></code> fija el foco del cursor en el elemento indicado, si éste puede ser enfocado.</p> + +<h2 id="Sintaxis" name="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">element.focus(); +element.focus(focusOption); // Object parameter</pre> + +<h3 id="Parámetros" name="Parámetros">Parámetros</h3> + +<dl> + <dt><code>focusOptions</code> {{optional_inline}} {{experimental_inline}}</dt> + <dd>Es un objeto con la siguiente propiedad:</dd> + <dd> + <dl> + <dt><code>preventScroll</code> {{optional_inline}}</dt> + <dd>Es un valor <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean" title="The Boolean object is an object wrapper for a boolean value."><code>Boolean</code></a>: + <ul> + <li>Si es <code>false</code>, el método hará scroll hasta que el elemento esté visible en la ventana del navegador</li> + <li>Si es <code>true</code>, el método NO hará scroll hasta que el elemento esté visible en la ventana del navegador.</li> + </ul> + </dd> + </dl> + </dd> +</dl> + +<h2 id="Ejemplos" name="Ejemplos">Ejemplos</h2> + +<h3 id="Enfocar_un_campo_de_texto" name="Enfocar_un_campo_de_texto">Enfocar un campo de texto</h3> + +<h4 id="JavaScript">JavaScript</h4> + +<pre class="brush: js">focusMethod = function getFocus() { + document.getElementById("myTextField").focus(); +}</pre> + +<h4 id="HTML">HTML</h4> + +<pre class="brush: html"><input type="text" id="myTextField" value="Campo de texto."> +<p></p> +<button type="button" onclick="focusMethod()">¡Púlsame para enfocar el campo de texto!</button> +</pre> + +<h4 id="Resultado">Resultado</h4> + +<p>{{ EmbedLiveSample('Focus_on_a_text_field') }}</p> + +<h3 id="Enfocar_un_botón" name="Enfocar_un_botón">Enfocar un botón</h3> + +<h4 id="JavaScript_2">JavaScript</h4> + +<pre class="brush: js">focusMethod = function getFocus() { + document.getElementById("myButton").focus(); +} +</pre> + +<h4 id="HTML_2">HTML</h4> + +<pre class="brush: html"><button type="button" id="myButton">Púlsame!</button> +<p></p> +<button type="button" onclick="focusMethod()">¡Púlsame para enfocar el botón!</button> +</pre> + +<h4 id="Resultado_2">Resultado</h4> + +<p>{{ EmbedLiveSample('Focus_on_a_button') }}</p> + + + +<h3 id="Enfocar_con_focusOption" name="Enfocar_con_focusOption">Enfocar con focusOption</h3> + +<h4 id="JavaScript_3">JavaScript</h4> + +<pre class="brush: js">focusScrollMethod = function getFocus() { + document.getElementById("myButton").focus({preventScroll:false}); +} +focusNoScrollMethod = function getFocusWithoutScrolling() { + document.getElementById("myButton").focus({preventScroll:true}); +} + +</pre> + +<h4 id="HTML_3">HTML</h4> + +<pre class="brush: html"><button type="button" onclick="focusScrollMethod()">¡Púlsame para enfocar el botón!</button> +<button type="button" onclick="focusNoScrollMethod()">¡Púlsame para enfocar el botón sin hacer scroll!</button> + +<div id="container" style="height: 1000px; width: 1000px;"> +<button type="button" id="myButton" style="margin-top: 500px;">¡Púlsame!</button> +</div> + +</pre> + +<h4 id="Resultado_3">Resultado</h4> + +<p>{{ EmbedLiveSample('Focus_prevent_scroll') }}</p> + +<h2 id="Especificación" name="Especificación">Especificación</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentarios</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('HTML WHATWG', 'editing.html#dom-focus', 'focus')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('HTML5.1', 'editing.html#focus()-0', 'focus')}}</td> + <td>{{Spec2('HTML5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', 'editing.html#dom-focus', 'focus')}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('DOM2 HTML', 'html.html#ID-32130014', 'focus')}}</td> + <td>{{Spec2('DOM2 HTML')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('DOM1', 'level-one-html.html#method-focus', 'focus')}}</td> + <td>{{Spec2('DOM1')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Notas">Notas</h2> + +<p>Si se llama a <code>HTMLElement.focus()</code> desde un gestor de eventos "mousedown" (ratón presionado), se debe también llamar al método <code>event.preventDefault()</code> para evitar que el foco abandone <code>HTMLElement</code><strong>.</strong></p> + +<h2 id="Compatibilidad_en_navegadores">Compatibilidad en navegadores</h2> + + + +<p>{{Compat("api.HTMLElement.focus")}}</p> + +<h2 id="Ver_también" name="Ver_también">Ver también</h2> + +<ul> + <li>Método DOM {{domxref("HTMLElement.blur()")}} para quitar el foco sobre un elemento.</li> + <li>{{ domxref("document.activeElement") }} para saber cuál es el elemento enfocado actualmente.</li> +</ul> diff --git a/files/es/web/api/htmlelement/index.html b/files/es/web/api/htmlelement/index.html new file mode 100644 index 0000000000..d27114fccc --- /dev/null +++ b/files/es/web/api/htmlelement/index.html @@ -0,0 +1,402 @@ +--- +title: HTMLElement +slug: Web/API/HTMLElement +tags: + - API +translation_of: Web/API/HTMLElement +--- +<div> +<div>{{ APIRef("HTML DOM") }}</div> +</div> + +<div></div> + +<div>La interfaz <strong><code>HTMLElement</code></strong> representa cualquier elemento <a href="/en-US/docs/Web/HTML" title="/en-US/docs/Web/HTML">HTML</a>. Algunos elementos implementan directamente esta interfaz, otros la implementan a través de una interfaz que hereda de ella.</div> + +<h2 id="Properties">Properties</h2> + +<p><em>Hereda propiedades de su padre, {{domxref("Element")}}, y los implementalo de {{domxref("GlobalEventHandlers")}} y {{domxref("TouchEventHandlers")}}.</em></p> + +<dl> + <dt>{{domxref("HTMLElement.accessKey")}}</dt> + <dd>Es un {{domxref("DOMString")}} que representa la clave de acceso al elemento.</dd> + <dt>{{domxref("HTMLElement.accessKeyLabel")}} {{readonlyInline}}</dt> + <dd>Devuelve un {{domxref("DOMString")}} que contiene la clave asignada del elemento.</dd> + <dt>{{domxref("HTMLElement.contentEditable")}}</dt> + <dd>Es un {{domxref("DOMString")}}, donde el valor <code>"true"</code> significa que el elemento es editable y si el valor es <code>"false"</code> significa que no lo es.</dd> + <dt>{{domxref("HTMLElement.isContentEditable")}} {{readonlyInline}}</dt> + <dd>Devuelve un {{domxref("Boolean")}} si el contenido del elemento puede ser editado.</dd> + <dt>{{domxref("HTMLElement.contextMenu")}}</dt> + <dd>Es un {{domxref("HTMLMenuElement")}} que representa el menú contextual asociado al elemento. Puede ser <code>null</code></dd> + <dt>{{domxref("HTMLElement.dataset")}} {{readonlyInline}}</dt> + <dd>Devuelve un {{domxref("DOMStringMap")}} que permite el acceso de lectura y escritura de los atributos personalizados del elemento (<code>data-*</code>) .</dd> + <dt>{{domxref("HTMLElement.dir")}}</dt> + <dd>Es un {{domxref("DOMString")}}, que refleja el atributo global <code>dir</code>, representando la direccionalidad del elemento. Los posibles valores son <code>"ltr"</code>, <code>"rtl"</code>, and <code>"auto"</code>.</dd> + <dt>{{domxref("HTMLElement.draggable")}}</dt> + <dd>Es un {{jsxref("Boolean")}} que indica si el elemento puede ser arrastrado..</dd> + <dt>{{domxref("HTMLElement.dropzone")}} {{readonlyInline}}</dt> + <dd>Devuelve un {{domxref("DOMSettableTokenList")}} que refleja el atributo global <code>dropzone</code> y describe el comportamiento del elemento con respecto a una operación de soltar.</dd> + <dt>{{domxref("HTMLElement.hidden")}}</dt> + <dd>Es un {{jsxref("Boolean")}} que indica si el elemento está oculto.</dd> + <dt>{{domxref("HTMLElement.itemScope")}} {{experimental_inline}}</dt> + <dd>Es un {{jsxref("Boolean")}}...</dd> + <dt>{{domxref("HTMLElement.itemType")}} {{readonlyInline}}{{experimental_inline}}</dt> + <dd>Devuelve un {{domxref("DOMSettableTokenList")}}…</dd> + <dt>{{domxref("HTMLElement.itemId")}} {{experimental_inline}}</dt> + <dd>Es un {{domxref("DOMString")}}…</dd> + <dt>{{domxref("HTMLElement.itemRef")}} {{readonlyInline}}{{experimental_inline}}</dt> + <dd>Devuelve un {{domxref("DOMSettableTokenList")}}…</dd> + <dt>{{domxref("HTMLElement.itemProp")}} {{readonlyInline}}{{experimental_inline}}</dt> + <dd>Devuelve un {{domxref("DOMSettableTokenList")}}…</dd> + <dt>{{domxref("HTMLElement.itemValue")}} {{experimental_inline}}</dt> + <dd>Devuelve un {{jsxref("Object")}}…</dd> + <dt>{{domxref("HTMLElement.lang")}}</dt> + <dd>Es un {{domxref("DOMString")}} que representa el lenguaje de los atributos del elemento, texto, y contenido del elemento.</dd> + <dt>{{domxref("HTMLElement.offsetHeight")}} {{readonlyInline}}{{experimental_inline}}</dt> + <dd>Devuelve un <code>double</code> que contiene la altura de, en relación al diseño (<code>layout)</code>.</dd> + <dt>{{domxref("HTMLElement.offsetLeft")}}{{readonlyInline}}{{experimental_inline}}</dt> + <dd>Devuelve un <code>double</code>, que representa la distancia desde el borde izquierdo del elemento hasta el borde izquierdo del elemento padre <code>offsetParent</code>'.</dd> + <dt>{{domxref("HTMLElement.offsetParent")}}{{readonlyInline}}{{experimental_inline}}</dt> + <dd>Returns an {{domxref("Element")}} that is the element from which all offset calculations are currently computed.</dd> + <dt>{{domxref("HTMLElement.offsetTop")}}{{readonlyInline}}{{experimental_inline}}</dt> + <dd>Returns a <code>double</code>, the distance from this element's top border to its <code>offsetParent</code>'s top border.</dd> + <dt>{{domxref("HTMLElement.offsetWidth")}}{{readonlyInline}}{{experimental_inline}}</dt> + <dd>Returns a <code>double</code> containing the width of an element, relative to the layout.</dd> + <dt>{{domxref("HTMLElement.properties")}} {{readonlyInline}}{{experimental_inline}}</dt> + <dd>Returns an {{domxref("HTMLPropertiesCollection")}}…</dd> + <dt>{{domxref("HTMLElement.spellcheck")}}{{ gecko_minversion_inline("1.9")}}</dt> + <dd>Is a {{jsxref("Boolean")}} that controls <a href="/en-US/docs/HTML/Controlling_spell_checking_in_HTML_forms" title="en/Controlling_spell_checking_in_HTML_forms">spell-checking</a>. It is present on all HTML elements, though it hasn't an effect on all of them.</dd> + <dt>{{domxref("HTMLElement.style")}}</dt> + <dd>Is {{domxref("CSSStyleDeclaration")}}, an object representing the declarations of an element's style attributes.</dd> + <dt>{{domxref("HTMLElement.tabIndex")}}</dt> + <dd>Is a <code>long</code> representing the position of the element in the tabbing order.</dd> + <dt>{{domxref("HTMLElement.title")}}</dt> + <dd>Is a {{domxref("DOMString")}} containing the text that appears in a popup box when mouse is over the element.</dd> + <dt>{{domxref("HTMLElement.translate")}} {{experimental_inline}}</dt> + <dd>Is a {{jsxref("Boolean")}}</dd> +</dl> + +<h3 id="Event_handlers">Event handlers</h3> + +<p>La mayoria de las propiedades de los eventos, del formulario <code>onXYZ</code>, estan definidas en las interfaces {{domxref("GlobalEventHandlers")}} or {{domxref("TouchEventHandlers")}}, implementadas por <code>HTMLElement</code>. Otras pocas son especificas de <code>HTMLElement</code>.</p> + +<dl> + <dt>{{ domxref("HTMLElement.oncopy") }} {{ non-standard_inline() }}</dt> + <dd>Returns the event handling code for the <code>copy</code> event ({{bug("280959")}}).</dd> + <dt>{{ domxref("HTMLElement.oncut") }} {{ non-standard_inline() }}</dt> + <dd>Returns the event handling code for the <code>cut</code> event ({{bug("280959")}}).</dd> + <dt>{{ domxref("HTMLElement.onpaste") }} {{ non-standard_inline() }}</dt> + <dd>Returns the event handling code for the <code>paste</code> event ({{bug("280959")}}).</dd> + <dt>{{domxref("TouchEventHandlers.ontouchstart")}} {{non-standard_inline}}</dt> + <dd>Returns the event handling code for the {{event("touchstart")}} event.</dd> + <dt>{{domxref("TouchEventHandlers.ontouchend")}} {{non-standard_inline}}</dt> + <dd>Returns the event handling code for the {{event("touchend")}} event.</dd> + <dt>{{domxref("TouchEventHandlers.ontouchmove")}} {{non-standard_inline}}</dt> + <dd>Returns the event handling code for the {{event("touchmove")}} event.</dd> + <dt>{{domxref("TouchEventHandlers.ontouchenter")}} {{non-standard_inline}}</dt> + <dd>Returns the event handling code for the {{event("touchenter")}} event.</dd> + <dt>{{domxref("TouchEventHandlers.ontouchleave")}} {{non-standard_inline}}</dt> + <dd>Returns the event handling code for the {{event("touchleave")}} event.</dd> + <dt>{{domxref("TouchEventHandlers.ontouchcancel")}} {{non-standard_inline}}</dt> + <dd>Returns the event handling code for the {{event("touchcancel")}} event.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<p><em>Inherits methods from its parent, {{domxref("Element")}}.</em></p> + +<dl> + <dt>{{domxref("HTMLElement.blur()")}}</dt> + <dd>Removes keyboard focus from the currently focused element.</dd> + <dt>{{domxref("HTMLElement.click()")}}</dt> + <dd>Sends a mouse click event to the element.</dd> + <dt>{{domxref("HTMLElement.focus()")}}</dt> + <dd>Makes the element the current keyboard focus.</dd> + <dt>{{domxref("HTMLElement.forceSpellCheck()")}} {{experimental_inline}}</dt> + <dd>Makes the spell checker runs on the element.</dd> +</dl> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('CSSOM View', '#extensions-to-the-htmlelement-interface', 'HTMLElement')}}</td> + <td>{{Spec2('CSSOM View')}}</td> + <td>Added the following properties: <code>offsetParent</code>, <code>offsetTop</code>, <code>offsetLeft</code>, <code>offsetWidth</code>, and <code>offsetHeight</code>.</td> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', 'elements.html#htmlelement', 'HTMLElement')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>Added the following properties: <code>translate</code>, <code>itemScope</code>, <code>itemType</code>, <code>itemId</code>, <code>itemRef</code>, <code>itemProp</code>, <code>properties</code>, and <code>itemValue</code>.<br> + Added the following method: <code>forceSpellcheck()</code>.<br> + Moved the <code>onXYZ</code> attributes to the {{domxref("GlobalEventHandlers")}} interface and added an inheritance from it.</td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', 'dom.html#htmlelement', 'HTMLElement')}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>Added the following properties: <code>dataset</code>, <code>hidden</code>, <code>tabindex</code>, <code>accessKey</code>, <code>accessKeyLabel</code>, <code>draggable</code>, <code>dropzone</code>, <code>contentEditable</code>, <code>isContentEditable</code>, <code>contextMenu</code>, <code>spellcheck</code>, <code>commandType</code>, <code>commandLabel</code>, <code>commandIcon</code>, <code>commandHidden</code>, <code>commandDisabled</code>, <code>commandChecked</code>, <code>style</code>, and all the <code>onXYZ</code> properties.<br> + Moved the <code>id</code> and <code>className</code> properties to the {{domxref("Element")}} interface.</td> + </tr> + <tr> + <td>{{SpecName('DOM2 HTML', 'html.html#ID-011100101', 'HTMLElement')}}</td> + <td>{{Spec2('DOM2 HTML')}}</td> + <td>No change from {{SpecName('DOM2 HTML')}}</td> + </tr> + <tr> + <td>{{SpecName('DOM1', 'level-one-html.html#ID-011100101', 'HTMLElement')}}</td> + <td>{{Spec2('DOM1')}}</td> + <td>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>Firefox (Gecko)</th> + <th>Chrome</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatGeckoDesktop("1.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>{{domxref("HTMLElement.accessKey", "accessKey")}}</td> + <td>{{CompatGeckoDesktop("5.0")}}</td> + <td>17.0</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}(<a class="external" href="http://trac.webkit.org/changeset/107483">535.10</a>)</td> + </tr> + <tr> + <td>{{domxref("HTMLElement.accessKeyLabel", "accessKeyLabel")}}</td> + <td>{{CompatGeckoDesktop("8.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}{{WebkitBug(72715)}}</td> + </tr> + <tr> + <td>{{domxref("HTMLElement.blur()", "blur()")}}</td> + <td>{{CompatGeckoDesktop("5.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>{{domxref("HTMLElement.click()", "click()")}}</td> + <td>{{CompatGeckoDesktop("5.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}(<a class="external" href="http://trac.webkit.org/changeset/107483">535.24</a>)</td> + </tr> + <tr> + <td>{{domxref("HTMLElement.dataset", "dataset")}}</td> + <td>{{CompatGeckoDesktop("6.0")}}</td> + <td>9.0</td> + <td>{{CompatUnknown}}</td> + <td>11.10</td> + <td>5.1</td> + </tr> + <tr> + <td>{{domxref("HTMLElement.focus()", "focus()")}}</td> + <td>{{CompatGeckoDesktop("5.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>{{domxref("HTMLElement.contentEditable", "contentEditable")}}</td> + <td>{{CompatGeckoDesktop("1.9")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>5.5</td> + <td>9</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>{{domxref("HTMLElement.spellcheck", "spellcheck")}}</td> + <td>{{CompatGeckoDesktop("1.8.1")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>{{domxref("HTMLElement.style", "style")}}</td> + <td>{{CompatVersionUnknown}} (returns a {{domxref("CSS2Properties")}}, rather than a {{domxref("CSSStyleDeclaration")}})</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>{{domxref("HTMLElement.forceSpellCheck", "forceSpellCheck()")}} {{experimental_inline}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>{{domxref("HTMLElement.dataset", "dataset")}}</td> + <td>{{CompatGeckoDesktop("6.0")}}</td> + <td>8.0</td> + <td>11</td> + <td>11.10</td> + <td>6</td> + </tr> + <tr> + <td>{{domxref("HTMLElement.draggable", "draggable")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>12.0</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>{{domxref("HTMLElement.dropzone", "dropzone")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>12.0</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>{{domxref("HTMLElement.offsetLeft", "offsetLeft")}}, {{domxref("HTMLElement.offsetTop", "offsetTop")}}, {{domxref("HTMLElement.offsetParent", "offsetParent")}}, {{domxref("HTMLElement.offsetHeight", "offsetHeight")}} and {{domxref("HTMLElement.offsetWidth", "offsetWidth")}} {{experimental_inline}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>{{domxref("HTMLElement.translate", "translate")}} {{experimental_inline}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>{{domxref("HTMLElement.itemScope", "itemScope")}}, {{domxref("HTMLElement.itemType", "itemType")}}, {{domxref("HTMLElement.itemRef", "itemRef")}}, {{domxref("HTMLElement.itemId", "itemId")}}, {{domxref("HTMLElement.itemProp", "itemProp")}}, and {{domxref("HTMLElement.itemValue", "itemValue")}} {{experimental_inline}}</td> + <td>{{CompatGeckoDesktop("6.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>11.60<br> + (Removed in Opera 15)</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>{{domxref("HTMLElement.properties", "properties")}} {{experimental_inline}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>{{domxref("HTMLElement.ontouchstart")}}, {{domxref("HTMLElement.ontouchend")}}, {{domxref("HTMLElement.ontouchmove")}}, {{domxref("HTMLElement.ontouchenter")}}, {{domxref("HTMLElement.ontouchleave")}}, and {{domxref("HTMLElement.ontouchcancel")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>{{domxref("HTMLElement.oncopy")}}, {{domxref("HTMLElement.oncut")}}, and {{domxref("HTMLElement.onpaste")}} {{Non-standard_inline}}</td> + <td>{{CompatGeckoDesktop("1.9")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Firefox Mobile (Gecko)</th> + <th>Android</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td> + <p>{{CompatGeckoMobile("1.0")}}</p> + </td> + <td rowspan="7">{{CompatUnknown}}</td> + <td rowspan="7">{{CompatUnknown}}</td> + <td rowspan="7">{{CompatUnknown}}</td> + <td rowspan="7">{{CompatUnknown}}</td> + </tr> + <tr> + <td>{{domxref("HTMLElement.accessKey", "accessKey")}}</td> + <td>{{CompatGeckoMobile("5.0")}}</td> + </tr> + <tr> + <td>{{domxref("HTMLElement.accessKeyLabel", "accessKeyLabel")}}</td> + <td>{{CompatGeckoMobile("8.0")}}</td> + </tr> + <tr> + <td>{{domxref("HTMLElement.blur()", "blur()")}}</td> + <td>{{CompatGeckoMobile("5.0")}}</td> + </tr> + <tr> + <td>{{domxref("HTMLElement.click()", "click()")}}</td> + <td>{{CompatGeckoMobile("5.0")}}</td> + </tr> + <tr> + <td>{{domxref("HTMLElement.dataset", "dataset")}}</td> + <td>{{CompatGeckoMobile("6.0")}}</td> + </tr> + <tr> + <td>{{domxref("HTMLElement.focus()", "focus()")}}</td> + <td>{{CompatGeckoMobile("5.0")}}</td> + </tr> + <tr> + <td>{{domxref("HTMLElement.oncopy")}}, {{domxref("HTMLElement.oncut")}}, and {{domxref("HTMLElement.onpaste")}} {{Non-standard_inline}}</td> + <td>{{CompatGeckoMobile("1.9")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{domxref("Element")}}</li> +</ul> diff --git a/files/es/web/api/htmlelement/innertext/index.html b/files/es/web/api/htmlelement/innertext/index.html new file mode 100644 index 0000000000..403f3c0bc1 --- /dev/null +++ b/files/es/web/api/htmlelement/innertext/index.html @@ -0,0 +1,84 @@ +--- +title: HTMLElement.innerText +slug: Web/API/HTMLElement/innerText +translation_of: Web/API/HTMLElement/innerText +--- +<div>{{APIRef("HTML DOM")}}</div> + +<p><span class="seoSummary">The <code><strong>innerText</strong></code> property of the {{domxref("HTMLElement")}} interface represents the "rendered" text content of a node and its descendants.</span> As a getter, it approximates the text the user would get if they highlighted the contents of the element with the cursor and then copied it to the clipboard.</p> + +<div class="blockIndicator note"> +<p><strong>Note:</strong> <code>innerText</code> is easily confused with {{domxref("Node.textContent")}}, but there are important differences between the two. Basically, <code>innerText</code> is aware of the rendered appearance of text, while <code>textContent</code> is not.</p> +</div> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox notranslate">const <em>renderedText</em> = <em>htmlElement</em>.innerText +<em>htmlElement</em>.innerText = <em>string</em></pre> + +<h3 id="Value">Value</h3> + +<p>A {{domxref("DOMString")}} representing the rendered text content of an element. If the element itself is not <a href="https://html.spec.whatwg.org/multipage/rendering.html#being-rendered">being rendered</a> (e.g detached from the document or is hidden from view), the returned value is the same as the {{domxref("Node.textContent")}} property.</p> + +<h2 id="Example">Example</h2> + +<p>This example compares <code>innerText</code> with {{domxref("Node.textContent")}}. Note how <code>innerText</code> is aware of things like {{htmlElement("br")}} elements, and ignores hidden elements.</p> + +<h3 id="HTML">HTML</h3> + +<pre class="brush: html notranslate"><h3>Source element:</h3> +<p id="source"> + <style>#source { color: red; }</style> +Take a look at<br>how this text<br>is interpreted + below. + <span style="display:none">HIDDEN TEXT</span> +</p> +<h3>Result of textContent:</h3> +<textarea id="textContentOutput" rows="6" cols="30" readonly>...</textarea> +<h3>Result of innerText:</h3> +<textarea id="innerTextOutput" rows="6" cols="30" readonly>...</textarea></pre> + +<h3 id="JavaScript">JavaScript</h3> + +<pre class="brush: js notranslate">const source = document.getElementById('source'); +const textContentOutput = document.getElementById('textContentOutput'); +const innerTextOutput = document.getElementById('innerTextOutput'); + +textContentOutput.innerHTML = source.textContent; +innerTextOutput.innerHTML = source.innerText;</pre> + +<h3 id="Result">Result</h3> + +<p>{{EmbedLiveSample("Example", 700, 450)}}</p> + +<h2 id="Specification">Specification</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('HTML WHATWG', 'dom.html#the-innertext-idl-attribute', 'innerText')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>Introduced, based on the <a href="https://github.com/rocallahan/innerText-spec">draft of the innerText specification</a>. See <a href="https://github.com/whatwg/html/issues/465">whatwg/html#465</a> and <a href="https://github.com/whatwg/compat/issues/5">whatwg/compat#5</a> for history.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("api.HTMLElement.innerText")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{domxref("HTMLElement.outerText")}}</li> + <li>{{domxref("Element.innerHTML")}}</li> +</ul> diff --git a/files/es/web/api/htmlelement/input_event/index.html b/files/es/web/api/htmlelement/input_event/index.html new file mode 100644 index 0000000000..ab082e4a06 --- /dev/null +++ b/files/es/web/api/htmlelement/input_event/index.html @@ -0,0 +1,329 @@ +--- +title: Evento input +slug: Web/API/HTMLElement/input_event +tags: + - DOM + - Evento + - InputEvent + - Referencia +translation_of: Web/API/HTMLElement/input_event +--- +<div>{{APIRef}}</div> + +<p>El evento <strong><code>input</code></strong> se dispara cuando el valor (<code>value</code>) de un elemento {{HTMLElement("input")}}, {{HTMLElement("select")}}, o {{HTMLElement("textarea")}} ha sido cambiado. </p> + +<table class="properties"> + <tbody> + <tr> + <th scope="row">Burbujas</th> + <td>Yes</td> + </tr> + <tr> + <th scope="row">Cancelable</th> + <td>No</td> + </tr> + <tr> + <th scope="row">Interfaz</th> + <td>{{DOMxRef("InputEvent")}}</td> + </tr> + <tr> + <th scope="row">Objectivo</th> + <td>{{domxref("Element")}}</td> + </tr> + <tr> + <th scope="row">Acción por defecto</th> + <td>None</td> + </tr> + <tr> + <th scope="row">Propiedad del manejador del evento</th> + <td>{{domxref("GlobalEventHandlers.oninput")}}</td> + </tr> + </tbody> +</table> + +<p>El evento también aplica a los elementos con la propiedad {{domxref("HTMLElement.contentEditable", "contenteditable")}} habilidado, y para cualquier otro elemento cuando la propiedad {{domxref("Document.designMode", "designMode")}} esta encendida. En el caso de un <code>contenteditable</code> y <code>designMode</code>, el objetivo del evento es el the event target is the <em>editing host</em>. Si estas propiedades aplian a múltiples elementos, el host de edición es el elemento ancestro más cercano cuyo padre no es editable.</p> + +<p>Para elementos <code><input></code> con <code>type=checkbox</code> o <code>type=radio</code>, el evento <code>input</code> debería disparar cuando el usuario alterna el control, por <a href="https://html.spec.whatwg.org/multipage/input.html#the-input-element:event-input-2">la especificación HTML5</a>. Sin embargo, históricamente no siempre es el caso. Revise la compatibilidad o use el evento {{event("change")}} en su lugar para estos tipos.</p> + +<div class="blockIndicator note"> +<p><strong>Nota:</strong> A diferencia de <code>input</code>, el evento {{event("change")}} no es disparado necesariamente por cada alteración al valor (<code>value</code>) de un elemento.</p> +</div> + +<h2 id="Ejemplos">Ejemplos</h2> + +<p>Este ejemplo registra el valor siempre que se cambia el valor del elemento {{HtmlElement("input")}}.</p> + +<h3 id="HTML">HTML</h3> + +<pre class="brush: html"><input placeholder="Ingrese algún texto" name="nombre"/> +<p id="valores"></p></pre> + +<h3 id="JavaScript">JavaScript</h3> + +<pre class="brush: js">const input = document.querySelector('input'); +const log = document.getElementById('valores'); + +input.addEventListener('input', updateValue); + +function updateValue(e) { + log.textContent = e.srcElement.value; +}</pre> + +<h3 id="Resultado">Resultado</h3> + +<p>{{EmbedLiveSample("Examples")}}</p> + +<p>(Funciona en la versión en inglés)</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', "forms.html#event-input-input", "input event")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + </tr> + <tr> + <td>{{SpecName('DOM3 Events', "#event-type-input", "input event")}}</td> + <td>{{Spec2('DOM3 Events')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_los_navegadores">Compatibilidad de los navegadores</h2> + + + +<p>{{Compat("api.HTMLElement.input")}}</p> + +<div class="hidden"> +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}<sup>[1]</sup></td> + <td>9<sup>[2][3]</sup></td> + <td>{{CompatVersionUnknown}}<sup>[4]</sup></td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>immediately after <code>compositionupdate</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("12")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>15</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>on <code>contenteditable</code> element</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("14")}}</td> + <td>{{CompatNo}}</td> + <td>15</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>when <code>designMode</code> is <code>"on"</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("14")}}</td> + <td>{{CompatNo}}</td> + <td>15</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>data</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>isComposing</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("31")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>on <code><select></code> element</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop("49")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>on <code><input></code> element of type <code>checkbox</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("49")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>on <code><input></code> element of type <code>radio</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("49")}}</td> + <td>{{CompatNo}}</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>Chrome for Android</th> + <th>Edge</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}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>immediately after <code>compositionupdate</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("12")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>on <code>contenteditable</code> element</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("14")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>when <code>designMode</code> is <code>"on"</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("14")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>data</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>isComposing</code></td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("31")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>on <code><select></code> element</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>on <code><input></code> element of type <code>checkbox</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>on <code><input></code> element of type <code>radio</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Prior to Gecko 12.0 {{geckoRelease("12.0")}}, Gecko didn't fire <code>input</code> events while composition was ongoing using IMEs or when dead keys were used on macOS X.</p> + +<p>[2] IE 9 does not fire an <code>input</code> event when the user deletes characters from an input (e.g. by pressing Backspace or Delete, or using the "Cut" operation).</p> + +<p>[3] IE 10 and IE 11 have a bug where the <code>input</code> event fires on placeholder attribute changes.</p> + +<p>[4] Prior to Opera 15, Opera did not fire an <code>input</code> event after dropping text in an input field.</p> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/InputEvent">InputEvent</a></li> + <li>{{domxref("GlobalEventHandlers.oninput")}}</li> + <li>Eventos relacionados + <ul> + <li>{{event("beforeinput")}}</li> + <li>{{event("change")}}</li> + <li><code><a href="/en-US/docs/Web/API/Constraint_validation/invalid_event">invalid</a></code></li> + </ul> + </li> +</ul> diff --git a/files/es/web/api/htmlelement/offsetheight/index.html b/files/es/web/api/htmlelement/offsetheight/index.html new file mode 100644 index 0000000000..82f683d7c5 --- /dev/null +++ b/files/es/web/api/htmlelement/offsetheight/index.html @@ -0,0 +1,65 @@ +--- +title: HTMLElement.offsetHeight +slug: Web/API/HTMLElement/offsetHeight +tags: + - API + - Propiedad + - Referencia +translation_of: Web/API/HTMLElement/offsetHeight +--- +<div>{{ APIRef("HTML DOM") }}</div> + +<p>La propiedad de sólo lectura <strong><code>HTMLElement.offsetHeight</code></strong> devuelve el alto de un elemento, incluyendo el <em>padding</em> vertical y los bordes, en píxeles, como un número entero.</p> + +<p>Generalmente, <code>offsetHeight</code> es una medida en píxeles que representa la altura CSS del elemento, incluyendo cualquier borde, padding, y barras de desplazamiento horizontales (si existieran). No incluye el alto de pseudo-elementos como <code>::before</code> y <code>::after</code>. Para el objeto body del documento, la medida incluye la altura total del contenido lineal en lugar de la altura CSS del elemento. Los elementos flotantes que se extienden por debajo de otros contenidos lineales son ignorados</p> + +<p>Si un elemento está oculto (por ejemplo, al establecer <code>style.display</code> a <code>"none"</code> en el elemento o uno de sus ancestros), se devuelve <code>0</code>.</p> + +<div class="note"> +<p>Esta propiedad redondea el valor a un entero. Si necesitas un valor decimal, usa {{ domxref("element.getBoundingClientRect()") }}.</p> +</div> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var <em>intElemOffsetHeight</em> = <em>element</em>.offsetHeight;</pre> + +<p><code><em>intElemOffsetHeight</em></code> es una variable que almacena el entero correspondiente al valor de <code>offsetHeight</code> en píxeles de un elemento. La propiedad <code>offsetHeight</code> es de sólo lectura.</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p><img alt="Image:Dimensions-offset.png" class="internal" src="/@api/deki/files/186/=Dimensions-offset.png"></p> + +<p>El ejemplo de la imagen de superior muestra una barra de desplazamiento y un <code>offsetHeight</code> que cabe en la ventana. Sin embargo, los elementos no desplazables podrían tener un <code>offsetHeight</code> mucho más grande que el área visible. Esos elementos están típicamente contenidos en elementos desplazables (scroll); con lo cual esos elementos no desplazables podrían ser parcial o completamente invisibles, dependiendo de la configuración de <code>scrollTop</code> del elemento contenedor.</p> + +<h2 id="Especificación">Especificación</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('CSSOM View', '#dom-htmlelement-offsetHeight', 'offsetLeft')}}</td> + <td>{{Spec2('CSSOM View')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h3 id="Notas">Notas</h3> + +<p><code>offsetHeight</code> es una pripiedad del modelo del objeto <abbr title="Dynamic HyperText Markup Language">DHTML</abbr> que fue inicialmente introducido por MSIE. A veces se le conoce como las dimensiones físicas/gráficas de un elemento, o la altura <code>border-box</code> del elemento.</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("Element.clientHeight")}}</li> + <li>{{domxref("Element.scrollHeight")}}</li> + <li>{{domxref("HTMLElement.offsetWidth")}}</li> + <li><a href="/en-US/docs/Web/API/CSS_Object_Model/Determining_the_dimensions_of_elements" title="en/Determining_the_dimensions_of_elements">Determinando las dimensiones de los elementos</a></li> + <li><a href="https://docs.microsoft.com/en-us/previous-versions//hh781509(v=vs.85)">MSDN Midiendo las dimensiones y ubicación de los elementos</a></li> +</ul> diff --git a/files/es/web/api/htmlelement/offsetleft/index.html b/files/es/web/api/htmlelement/offsetleft/index.html new file mode 100644 index 0000000000..0067faf65f --- /dev/null +++ b/files/es/web/api/htmlelement/offsetleft/index.html @@ -0,0 +1,141 @@ +--- +title: HTMLElement.offsetLeft +slug: Web/API/HTMLElement/offsetLeft +translation_of: Web/API/HTMLElement/offsetLeft +--- +<div>{{ APIRef("HTML DOM") }}</div> + +<p>La propiedad de solo lectura <strong><code>HTMLElement.offsetLeft</code></strong> devuelve el número de <em>píxeles a la izquierda </em>del elemento actual con respecto al nodo {{domxref("HTMLElement.offsetParent")}} .</p> + +<p>Para los elementos de bloque, <code>offsetTop</code>, <code>offsetLeft</code>, <code>offsetWidth</code>, y <code>offsetHeight</code> determina el borde de la caja del elemento relativo al <code>offsetParent.</code></p> + +<p>Sin embargo, para los elementos inline (por ejemplo <strong>span</strong>), que puede ser cortado de un línea a otra, <code>offsetTop,</code> and <code>offsetLeft </code>describe la posición de la primer borde de la caja (usar {{domxref("Element.getClientRects()")}} para obtener el ancho y el alto), mientras que <code>offsetWidth </code>y <code>offsetHeight </code>describen las dimensiones de los límites (usar {{domxref("Element.getBoundingClientRect()")}} para obtener su posición). Por lo tanto, una caja con left, top, width y height del <code>offsetLeft</code>, <code>offsetTop</code>, <code>offsetWidth</code>, <code>offsetHeight</code>, no definirá los límites para un span con texto que continúa en otra línea.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="eval"><em>left</em> = <em>element</em>.offsetLeft; +</pre> + +<p><code>left</code> es un entero que representa la posición de la izquierda del elemento actual con respecto al padre.</p> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre>var colorTable = document.getElementById("t1"); +var tOLeft = colorTable.offsetLeft; + +if (tOLeft > 5) { + // posición izquierda muy larga: hacer algo +} +</pre> + +<p>This example shows a 'long' sentence that wraps within a div with a blue border, and a red box that one might think should describe the boundaries of the span.</p> + +<p><img alt="Image:offsetLeft.jpg" class="internal" src="/@api/deki/files/790/=OffsetLeft.jpg"></p> + +<pre><div style="width: 300px; border-color:blue; + border-style:solid; border-width:1;"> + <span>Short span. </span> + <span id="long">Long span that wraps within this div.</span> +</div> + +<div id="box" style="position: absolute; border-color: red; + border-width: 1; border-style: solid; z-index: 10"> +</div> + +<script> + var box = document.getElementById("box"); + var long = document.getElementById("long"); + box.style.left = long.offsetLeft + document.body.scrollLeft + "px"; + box.style.top = long.offsetTop + document.body.scrollTop + "px"; + box.style.width = long.offsetWidth + "px"; + box.style.height = long.offsetHeight<span style="line-height: normal;"> + "px"</span><span style="line-height: normal;">; +</span><span style="line-height: normal;"></script> </span></pre> + +<h2 id="Specification" name="Specification">Specification</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('CSSOM View', '#dom-htmlelement-offsetleft', 'offsetLeft')}}</td> + <td>{{Spec2('CSSOM View')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibility" name="Compatibility">Browser compatibility</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</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>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Android Webview</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>In compliance with the specification, this property will return <code>null</code> on Webkit if the element is hidden (the <code>style.display</code> of this element or any ancestor is <code>"none"</code>) or if the <code>style.position</code> of the element itself is set to <code>"fixed"</code>.</p> + +<p>This property will return <code>null</code> on Internet Explorer (9) if the <code>style.position</code> of the element itself is set to <code>"fixed"</code>. (Having <code>display:none</code> does not affect this browser.)</p> + +<h2 id="See_also" name="See_also">See also</h2> + +<ul> + <li>{{domxref("HTMLElement.offsetParent")}}, {{domxref("HTMLElement.offsetTop")}}, {{domxref("HTMLElement.offsetWidth")}}, {{domxref("HTMLElement.offsetHeight")}}</li> +</ul> diff --git a/files/es/web/api/htmlelement/offsetparent/index.html b/files/es/web/api/htmlelement/offsetparent/index.html new file mode 100644 index 0000000000..4fb14be33d --- /dev/null +++ b/files/es/web/api/htmlelement/offsetparent/index.html @@ -0,0 +1,52 @@ +--- +title: HTMLElement.offsetParent +slug: Web/API/HTMLElement/offsetParent +tags: + - API + - CSSOM View + - Propiedad + - Reference + - Referencia +translation_of: Web/API/HTMLElement/offsetParent +--- +<div> +<div>{{ APIRef("HTML DOM") }}</div> +</div> + +<p>La propiedad de solo lectura <strong><code>HTMLElement.offsetParent</code></strong> retorna una referencia al objeto, el cual es el elemento contenedor posicionado más cercano (más cercano en la jerarquía contenedora). Si el elemento es no-posicionado, <code>td</code>, <code>th</code>, <code>table</code> o el <code>body</code> más cercano es retornado.</p> + +<p><code>offsetParent</code> retorna <code>null</code> cuando el elemento <code>style.display</code> tiene asignado <code>none</code>. <code>offsetParent</code> es útil porque {{domxref("HTMLElement.offsetTop","offsetTop")}} y {{domxref("HTMLElement.offsetLeft","offsetLeft")}} son relativos a su borde de relleno.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox"><var>parentObj</var> = element.offsetParent; +</pre> + +<ul> + <li><var>parentObj</var> es una referencia de objeto al elemento en el cual el elemento actual es offset.</li> +</ul> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estatus</th> + <th scope="col">Comentario</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('CSSOM View', '#dom-htmlelement-offsetparent', 'offsetParent')}}</td> + <td>{{Spec2('CSSOM View')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibility" name="Compatibility">Compatibilidad de Browser</h2> + +<div class="hidden">La tabla de compatibilidad de esta página es generada desde datos estructurados. Si gusta contribuir a los datos, por favor revise <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> y envíenos un pull request.</div> + +<p>{{Compat("api.HTMLElement.offsetParent")}}</p> diff --git a/files/es/web/api/htmlelement/offsettop/index.html b/files/es/web/api/htmlelement/offsettop/index.html new file mode 100644 index 0000000000..0b5f19708a --- /dev/null +++ b/files/es/web/api/htmlelement/offsettop/index.html @@ -0,0 +1,61 @@ +--- +title: HTMLElement.offsetTop +slug: Web/API/HTMLElement/offsetTop +translation_of: Web/API/HTMLElement/offsetTop +--- +<div> +<div>{{ APIRef("HTML DOM") }}</div> +</div> + +<p>La propiedad de sólo lectura <strong><code>HTMLElement.offsetTop</code></strong> retorna la distancia del elemento actual respecto al borde superior del nodo {{domxref("HTMLelement.offsetParent","offsetParent")}}.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox"><var>topPos</var> = element.offsetTop; +</pre> + +<h3 id="Parameters" name="Parameters">Parámetros</h3> + +<ul> + <li><code>topPos</code> es el número de pixels desde el borde superior del elemento padre <em>más cercano posicionado de forma relativa</em>.</li> +</ul> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre class="brush:js">var d = document.getElementById("div1"); +var topPos = d.offsetTop; + +if (topPos > 10) { + // objeto está posicionado a más de + // de 10 pixels de distancia de su padre +}</pre> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Observaciones</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('CSSOM View', '#dom-htmlelement-offsettop', 'offsetTop')}}</td> + <td>{{Spec2('CSSOM View')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + + + + +<p>{{Compat("api.HTMLElement.offsetTop")}}</p> + +<p>In compliance with the specification, this property will return <code>null</code> on Webkit if the element is hidden (the <code>style.display</code> of this element or any ancestor is <code>"none"</code>) or if the <code>style.position</code> of the element itself is set to <code>"fixed"</code>.</p> + +<p>This property will return <code>null</code> on Internet Explorer (9) if the <code>style.position</code> of the element itself is set to <code>"fixed"</code>. (Having <code>display:none</code> does not affect this browser.)</p> diff --git a/files/es/web/api/htmlelement/offsetwidth/index.html b/files/es/web/api/htmlelement/offsetwidth/index.html new file mode 100644 index 0000000000..13a9a7e454 --- /dev/null +++ b/files/es/web/api/htmlelement/offsetwidth/index.html @@ -0,0 +1,62 @@ +--- +title: HTMLElement.offsetWidth +slug: Web/API/HTMLElement/offsetWidth +translation_of: Web/API/HTMLElement/offsetWidth +--- +<div>{{ APIRef("HTML DOM") }}</div> + +<p>La propiedad de solo lectura <code><strong>HTMLElement.offsetWidth</strong></code> devuelve el ancho del layout del elemento. Esta medida incluye los bordes del elemento asignados al mismo en los estilos CSS.</p> + +<h2 id="Sintáxis">Sintáxis</h2> + +<pre class="syntaxbox">var<em> offsetWidth</em> =<em>element</em>.offsetWidth; +</pre> + +<p><strong><code>offsetWidth</code> </strong>es una propiedad de solo lectura.</p> + +<div class="note"> +<p>Esta propiedad redondeará el valor a un entero. Si necesitas un valor fraccional usa: {{ domxref("element.getBoundingClientRect()") }}.</p> +</div> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p> </p> + +<p> <img alt="Image:Dimensions-offset.png" class="internal" src="/@api/deki/files/186/=Dimensions-offset.png"></p> + + +<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('CSSOM View', '#dom-htmlelement-offsetwidth', 'offsetWidth')}}</td> + <td>{{Spec2('CSSOM View')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h3 id="Notas">Notas</h3> + +<p><code>offsetWidth</code> es una propiedad del <abbr title="Dynamic HyperText Markup Language">DHTML</abbr> "object model" que fue inicialmente introducido por MSIE. A veces es referido como box-width.</p> + +<h2 id="Compatibilidad_con_Navegadores">Compatibilidad con Navegadores</h2> + +<p>{{Compat("api.HTMLElement.offsetWidth")}}</p> + +<h2 id="Links_Relacionados">Links Relacionados</h2> + +<ul> + <li>{{domxref("Element.clientWidth")}}</li> + <li>{{domxref("Element.scrollWidth")}}</li> + <li><a href="/en-US/docs/Determining_the_dimensions_of_elements">Determining the dimensions of elements</a></li> + <li><a href="https://docs.microsoft.com/en-us/previous-versions//hh781509(v=vs.85)">MSDN Measuring Element Dimension and Locati</a></li> +</ul> diff --git a/files/es/web/api/htmlelement/style/index.html b/files/es/web/api/htmlelement/style/index.html new file mode 100644 index 0000000000..62c8903b72 --- /dev/null +++ b/files/es/web/api/htmlelement/style/index.html @@ -0,0 +1,52 @@ +--- +title: Element.style +slug: Web/API/HTMLElement/style +translation_of: Web/API/ElementCSSInlineStyle/style +--- +<p>{{ ApiRef("HTML DOM") }}</p> + +<h3 id="Summary" name="Summary">Resumen</h3> + +<p>Devuelve un objeto que representa el atributo <code>style </code>del elemento.</p> + +<h3 id="Example" name="Example">Ejemplo</h3> + +<pre class="eval">var div = document.getElementById("div1"); +div.style.marginTop = ".25in"; +</pre> + +<h3 id="Notes" name="Notes">Notas</h3> + +<p>Ya que la propiedad <code>style </code>tiene la misma (y más alta) prioridad en la cascada CSS que las declaraciones <em>in-line</em> hechas mediante el atributo style, resulta muy útil para establecer el estilo en un elemento específico. </p> + +<p>Sin embargo, no resulta útil para aprender acerca del estilo original de un elemento, ya que representa sólo la declaración CSS en el atributo style <em>in-line</em> y no aquellos atributos que vienen de alguna otra parte, como las declaraciones en la sección <head> o en hojas de estilo.</p> + +<p>Para recoger los valores de todas las propiedades CSS de un elemento, deberías usar <a href="/Es/DOM/Window.getComputedStyle" title="en/DOM/window.getComputedStyle">window.getComputedStyle</a> en su lugar.</p> + +<p>Mira la lista de Propiedades CSS del DOM (<a href="/es/DOM/CSS" title="en/DOM/CSS">DOM CSS Properties List</a>) para tener una lista completa de las propiedades CSS que están disponibles en el Gecko DOM.</p> + +<p>Generalmente es mejor usarla propiedad <code>style </code>que usar <code>elt.setAttribute('style', '...')</code>, ya que el uso de la propiedad <code>style </code>no reemplazará otras propiedades CSS que puedan especificarse en el atributo <code>style</code>.</p> + +<p>Los estilos <em>no</em> pueden establecerse asignando una cadena a la propiedad (solo lectura) style, como en <code>elt.style = "color: blue;"</code>. Esto es porque el atributo <code>style </code>devuelve un objeto del tipo <code>CSSStyleDeclaration</code>. En su lugar, pueds establecer las propiedades como:</p> + +<pre class="eval">elt.style.color = "blue"; // Asignación directa + +var st = elt.style; +st.color = "blue"; // Asignación Indirecta +</pre> + +<p>El siguiente código presenta los nombres de todas las propiedades style, los valores se establecen de forma explícita para los elementos<code> elt </code>y sus valores heredados: </p> + +<pre class="eval">var elt = document.getElementById("elementIdHere"); +var out = ""; +var st = elt.style; +var cs = window.getComputedStyle(elt, null); +for (x in st) + out += " " + x + " = '" + st[x] + "' > '" + cs[x] + "'\n"; +</pre> + +<p> </p> + +<h3 id="Specification" name="Specification">Especificación</h3> + +<p><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-ElementCSSInlineStyle">DOM Level 2 Style: ElementCSSInlineStyle.style</a></p> diff --git a/files/es/web/api/htmlformelement/index.html b/files/es/web/api/htmlformelement/index.html new file mode 100644 index 0000000000..4409f7e160 --- /dev/null +++ b/files/es/web/api/htmlformelement/index.html @@ -0,0 +1,109 @@ +--- +title: form +slug: Web/API/HTMLFormElement +tags: + - DOM + - Referencia_DOM_de_Gecko + - Todas_las_Categorías +translation_of: Web/API/HTMLFormElement +--- +<div>{{APIRef("HTML DOM")}}</div> +<h3 id="Interfaz_del_elemento_formulario_de_HTML" name="Interfaz_del_elemento_formulario_de_HTML">Interfaz del elemento formulario de HTML</h3> + +<p>Los elementos <code>FORM</code> comparten todas las propiedades y métodos de los otros elementos HTML descritos en el capítulo del <a href="es/DOM/element">elemento</a>. También tienen la interfaz especial <a class="external" href="http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-40002357">HTMLFormElement</a>.</p> + +<p>Esta interfaz proporciona métodos para crear y modificar los elementos <code>FORM</code> usando el DOM. El siguiente ejemplo muestra como crear un nuevo formulario, como modificar sus atributos y enviarlo:</p> + +<pre>// Crea un formulario +var f = document.createElement("form"); + +// Lo añade en el cuerpo ('body') del documento +document.body.appendChild(f); + +// Añade los atributos de acción y método +f.action = "/cgi-bin/some.cgi"; +f.method = "POST" + +// Llama el método de enviar el formulario +f.submit(); +</pre> + +<p>Además, el siguiente documento HTML muestra como se puede extraer información de un formulario y cambiar algunos de sus atributos.</p> + +<pre><title>Ejemplo de formulario</title> +<script type="text/javascript"> + function getFormInfo() { + var info; + + // Obtiene una referencia utilizando la colección de formularios + var f = document.forms["formularioA"]; + info = "f.elements: " + f.elements + "\n" + + "f.length: " + f.length + "\n" + + "f.name: " + f.elements + "\n" + + "f.acceptCharset: " + f.acceptCharset + "\n" + + "f.action: " + f.action + "\n" + + "f.enctype: " + f.enctype + "\n" + + "f.encoding: " + f.encoding + "\n" + + "f.method: " + f.method + "\n" + + "f.target: " + f.target; + document.forms["formularioA"].elements['tex'].value = info; + } + + // Se pasa la referencia al formulario desde el + // atributo al hacer clic ('onclick') del botón con la ayuda de este.formulario ('this.form') + function setFormInfo(f) { + f.method = "GET"; + f.action = "/cgi-bin/evil_executable.cgi"; + f.name = "totally_new"; + } +</script> + +<h1>Ejemplo de formulario</h1> + +<form name="formularioA" id="formularioA" + action="/cgi-bin/test" method="POST"> + <p>Haga clic en "Info" para ver informaciones de este formulario. + Haga clic en "Set" para cambiar los parámetros y otra vez en "Info" para ver los efectos</p> + <p> + <input type="button" value="Info" + onclick="getFormInfo();"> + <input type="button" value="Set" + onclick="setFormInfo(this.form);"> + <input type="reset" value="Reset"> + <br> + <textarea id="tex" style="height:15em; width:20em"> + </p> +</form> +</pre> + +<h3 id="Propiedades" name="Propiedades">Propiedades</h3> + +<dl> + <dt><a href="es/DOM/form.elements">form.elements</a> (todos los elementos del formulario) </dt> + <dd><code>.elements</code> devuelve una colección de todos los controles que hay en el formulario <code>FORM</code>.</dd> + <dt><a href="es/DOM/form.length">form.length</a></dt> + <dd><code>.length</code> devuelve la cantidad de controles que hay en el formulario</dd> + <dt><a href="es/DOM/form.name">form.name</a></dt> + <dd><code>.name</code> devuelve el nombre del formulario actual en forma de cadena.</dd> + <dt><a href="es/DOM/form.acceptCharset">form.acceptCharset</a></dt> + <dd><code>.acceptCharset</code> devuelve una lista del conjunto de caracteres soportados para el actual elemento <code>FORM</code>.</dd> + <dt><a href="es/DOM/form.action">form.action</a></dt> + <dd><code>.action</code> obtiene/configura la acción del elemento <code>FORM</code>.</dd> + <dt><a href="es/DOM/form.enctype">form.enctype</a></dt> + <dd><code>.enctype</code> gets/sets the content type of the <code>FORM</code> element.</dd> + <dt><a href="es/DOM/form.encoding">form.encoding</a></dt> + <dd><code>.encoding</code> gets/sets the content type of the <code>FORM</code> element.</dd> + <dt><a href="es/DOM/form.method">form.method</a></dt> + <dd><code>.method</code> obtiene/configura el método HTTP utilizado para enviar el formulario.</dd> + <dt><a href="es/DOM/form.target">form.target</a></dt> + <dd><code>.target</code> obtiene/configura el objetivo de la acción (i.e., the frame to render its output in).</dd> +</dl> + +<h3 id="M.C3.A9todos" name="M.C3.A9todos">Métodos</h3> + +<dl> + <dt><a href="es/DOM/form.submit">form.submit</a></dt> + <dd>submit() manda el formulario.</dd> + <dt><a href="es/DOM/form.reset">form.reset</a></dt> + <dd>reset() restaura el formulario, lo devuelve al estado inicial.</dd> +</dl> diff --git a/files/es/web/api/htmlformelement/reset/index.html b/files/es/web/api/htmlformelement/reset/index.html new file mode 100644 index 0000000000..43f3df8e37 --- /dev/null +++ b/files/es/web/api/htmlformelement/reset/index.html @@ -0,0 +1,59 @@ +--- +title: HTMLFormElement.reset() +slug: Web/API/HTMLFormElement/reset +tags: + - API + - HTML DOM + - HTMLFormElement + - Method + - NeedsMarkupWork + - NeedsSpecTable + - Referencia +translation_of: Web/API/HTMLFormElement/reset +--- +<div>{{APIRef("HTML DOM")}}</div> + +<p>El método <strong><code>HTMLFormElement.reset()</code></strong> restaura los elementos de un formulario a sus valores por defecto. Este método hace lo mismo que haciendo clic en el botón de restauración.</p> + +<p>Si un control del formulario (como el botón de restaurar) tiene el nombre o un id de <em>reset</em> enmascarará el método de restauración del formulario. No restaura otros atributos del campo, como el de <code>disabled</code>.</p> + +<h2 id="Syntax" name="Syntax">Síntaxis</h2> + +<pre class="syntaxbox notranslate"><em>HTMLFormElement</em>.reset() +</pre> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre class="brush: js notranslate">document.getElementById('myform').reset(); +</pre> + +<h2 id="Specification" name="Specification">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('HTML WHATWG', '#dom-form-reset', 'HTMLFormElement: reset')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + + + +<p>{{Compat("api.HTMLFormElement.reset")}}</p> + +<h2 id="Vea_también">Vea también</h2> + +<ul> + <li>{{domxref("HTMLFormElement.submit()")}}</li> +</ul> diff --git a/files/es/web/api/htmlheadelement/index.html b/files/es/web/api/htmlheadelement/index.html new file mode 100644 index 0000000000..0327683cbe --- /dev/null +++ b/files/es/web/api/htmlheadelement/index.html @@ -0,0 +1,72 @@ +--- +title: HTMLHeadElement +slug: Web/API/HTMLHeadElement +translation_of: Web/API/HTMLHeadElement +--- +<div>{{APIRef("HTML DOM")}}</div> + +<p>La interfaz <strong><code>HTMLHeadElement</code></strong> contiene la información descriptiva, o metadata, para un documento. Este objeto hereda las propiedades y métodos descritos en la interfaz {{domxref("HTMLElement")}}.</p> + +<p>{{InheritanceDiagram(600, 120)}}</p> + +<h2 id="Propiedades">Propiedades</h2> + +<p><em>Hereda las propiedades del padre, {{domxref("HTMLElement")}}.</em></p> + +<dl> + <dt>{{domxref("HTMLHeadElement.profile")}} {{obsolete_inline}}</dt> + <dd>Es un {{domxref("DOMString")}} que representa las URI de uno o más perfiles de metadatos (separados por espacios en blanco).</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<p><em>No hay un método especifico; hereda los métodos del padre, {{domxref("HTMLElement")}}.</em></p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentarios</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', "#htmlheadelement", "HTMLHeadElement")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('HTML5.1', "document-metadata.html#the-head-element", "HTMLHeadElement")}}</td> + <td>{{Spec2('HTML5.1')}}</td> + <td>Sin cambio desde {{SpecName('HTML5 W3C')}}.</td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', "document-metadata.html#the-head-element", "HTMLHeadElement")}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>La siguiente propiedad ha sido removida: <code>profile</code>.</td> + </tr> + <tr> + <td>{{SpecName('DOM2 HTML', 'html.html#ID-77253168', 'HTMLHeadElement')}}</td> + <td>{{Spec2('DOM2 HTML')}}</td> + <td>Sin cambio</td> + </tr> + <tr> + <td>{{SpecName('DOM1', 'level-one-html.html#ID-77253168', 'HTMLHeadElement')}}</td> + <td>{{Spec2('DOM1')}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_Navegadores">Compatibilidad con Navegadores</h2> + +<div class="hidden">La tabla de compatibilidad de esta página es generada a partir de datos estructurados. Si desea contribuir con los datos, por favor consulte <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> y envíenos una solicitud.</div> + +<p>{{Compat("api.HTMLHeadElement")}}</p> + +<h2 id="Vea_también">Vea también</h2> + +<ul> + <li>El elemento HTML que implementa esta interfaz: {{HTMLElement("head")}}</li> +</ul> diff --git a/files/es/web/api/htmlhtmlelement/index.html b/files/es/web/api/htmlhtmlelement/index.html new file mode 100644 index 0000000000..f079c9a07a --- /dev/null +++ b/files/es/web/api/htmlhtmlelement/index.html @@ -0,0 +1,121 @@ +--- +title: HTMLHtmlElement +slug: Web/API/HTMLHtmlElement +tags: + - API + - HTML DOM + - Interface + - Referencia +translation_of: Web/API/HTMLHtmlElement +--- +<div>{{ APIRef("HTML DOM") }}</div> + +<p>The <strong><code>HTMLHtmlElement</code></strong> interface serves as the root node for a given HTML document. This object inherits the properties and methods described in the {{domxref("HTMLElement")}} interface.</p> + +<p>You can retrieve the <code>HTMLHtmlElement</code> object for a given document by reading the value of the {{domxref("document.documentElement")}} property.</p> + +<h2 id="Properties">Properties</h2> + +<p><em>Inherits properties from its parent, {{domxref("HTMLElement")}}.</em></p> + +<dl> + <dt>{{domxref("HTMLHtmlElement.version")}} {{ obsolete_inline() }}</dt> + <dd>Is a {{domxref("DOMString")}} representing the version of the HTML Document Type Definition (DTD) that governs this document. This property should not be used any more as it is non-conforming. Simply omit it.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<p><em>No specific method; inherits methods from its parent, {{domxref("HTMLElement")}}.</em></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', "semantics.html#the-html-element", "HTMLHtmlElement")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>Live specification, no change since last snapshot</td> + </tr> + <tr> + <td>{{SpecName('HTML5.1', "semantics.html#the-html-element", "HTMLHtmlElement")}}</td> + <td>{{Spec2('HTML5.1')}}</td> + <td>No change since the last snapshot</td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', "semantics.html#the-html-element", "HTMLHtmlElement")}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>The <code>version</code> element has been removed, as it is non-conforming.</td> + </tr> + <tr> + <td>{{SpecName('DOM2 HTML', 'html.html#ID-33759296', 'HTMLHtmlElement')}}</td> + <td>{{Spec2('DOM2 HTML')}}</td> + <td>Reflecting the element change in {{SpecName("HTML4.01")}}, the <code>version</code> property is now deprecated.</td> + </tr> + <tr> + <td>{{SpecName('DOM1', 'level-one-html.html#ID-33759296', 'HTMLHtmlElement')}}</td> + <td>{{Spec2('DOM1')}}</td> + <td>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 (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(1.0)}}</td> + <td>{{CompatVersionUnknown}}</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>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile(1.0)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>HTML element implementing this interface: {{HTMLElement("html")}}.</li> +</ul> diff --git a/files/es/web/api/htmlimageelement/image/index.html b/files/es/web/api/htmlimageelement/image/index.html new file mode 100644 index 0000000000..7bf5d299b5 --- /dev/null +++ b/files/es/web/api/htmlimageelement/image/index.html @@ -0,0 +1,46 @@ +--- +title: Image() +slug: Web/API/HTMLImageElement/Image +translation_of: Web/API/HTMLImageElement/Image +--- +<div>{{ APIRef("HTML DOM") }}</div> + +<h3 id="Constructor_del_elemento_de_Imagen">Constructor del elemento de Imagen</h3> + +<p><span style="line-height: 1.572;">Acepta dos parametros opcionales: </span><span style="font-family: courier new,andale mono,monospace; line-height: normal;">Image([unsigned long <em><strong>width</strong></em>, unsigned long <em><strong>height</strong></em>]</span><span style="font-family: courier new,andale mono,monospace; line-height: normal;">)</span></p> + +<p>Devuelve un <a href="/en-US/docs/Web/API/HTMLImageElement" style="line-height: 1.572;" title="en/DOM/HTMLImageElement">HTMLImageElement</a><span style="line-height: 1.572;"> instanciado justo como</span><span style="line-height: 1.572;"> </span><code style="font-size: 14px;">document.createElement('img')</code><span style="line-height: 1.572;"> would.</span></p> + +<p><span style="line-height: 1.572;">Ejemplo:</span></p> + +<pre class="brush: js">var myImage = new Image(100, 200); +myImage.src = 'picture.jpg'; +console.log(myImage);</pre> + +<div>Resultado:</div> + +<pre class="brush: html"><img width="100" height="200" src="picture.jpg"> +</pre> + +<div> +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td><a class="external external-icon" href="http://www.w3.org/TR/html5/embedded-content-0.html#dom-image" hreflang="en" lang="en">HTML5<br> + <small>La definición del constructor de imagen, en esta especificación.</small></a></td> + <td><span class="spec-REC">Recommendación</span></td> + <td>Un constructor (con 2 parametros opcionales) han sido agregados.<br> + Las siguientes propiedades ahora son obsoletas: <code>name</code>, <code>border</code>, <code>align</code>, <code>hspace</code>, <code>vspace</code>, and <code>longdesc</code>.<br> + The following properties are now <code>unsigned long</code>, instead of <code>long</code>: <code>height</code>, and <code>width</code>.<br> + Las siguientes propiedadeas ahora han sido agrgados: <code>crossorigin</code>,</td> + </tr> + </tbody> +</table> +</div> + +<div> </div> diff --git a/files/es/web/api/htmlimageelement/index.html b/files/es/web/api/htmlimageelement/index.html new file mode 100644 index 0000000000..55c8a5e306 --- /dev/null +++ b/files/es/web/api/htmlimageelement/index.html @@ -0,0 +1,344 @@ +--- +title: HTMLImageElement +slug: Web/API/HTMLImageElement +tags: + - API + - HTML DOM + - Interfaz + - Reference +translation_of: Web/API/HTMLImageElement +--- +<div>{{APIRef("HTML DOM")}}</div> + +<p>La interfaz <strong><code>HTMLImageElement</code></strong> provee de propiedas especiales y métodos (más allá de las interfaces {{domxref("HTMLElement")}}, también tiene disponible la herencia) para manipular el diseño y la presentación de elementos {{HTMLElement("img")}}.</p> + +<h2 id="Propiedades">Propiedades</h2> + +<p><em>Heredadas de su padre, {{domxref("HTMLElement")}}.</em></p> + +<dl> + <dt>{{domxref("HTMLImageElement.align")}} {{obsolete_inline}}</dt> + <dd>Es un {{domxref("DOMString")}} que indica el alineamiento de la imagen respecto al contexto que la rodea.</dd> + <dt>{{domxref("HTMLImageElement.alt")}}</dt> + <dd>Es un {{domxref("DOMString")}} que refleja el atributo HTML {{htmlattrxref("alt", "img")}}, indicando texto de respaldo a la imagen.</dd> + <dt>{{domxref("HTMLImageElement.border")}} {{obsolete_inline}}</dt> + <dd>Es un {{domxref("DOMString")}} que indica el ancho del borde alrededor de la imagen. Este está desaprobado y debe usarse la propiedad CSS {{cssxref("border")}} en su lugar.</dd> + <dt>{{domxref("HTMLImageElement.complete")}} {{readonlyInline}}</dt> + <dd>Devuelve un {{domxref("Boolean")}} que es <code>true</code> si el navegador ha terminado de buscar la imagen, sea o no exitoso. También devuelve <code>true</code> si la imagen no tiene valor {{domxref("HTMLImageElement.src", "src")}}.</dd> + <dt>{{domxref("HTMLImageElement.crossOrigin")}}</dt> + <dd>Es un {{domxref("DOMString")}} representa la configuración CORS para el elemento imagen. Ver <a href="/es/docs/Web/HTML/Atributos_de_configuracion_CORS">Atributos de configuración CORS</a> para más detalles.</dd> + <dt>{{domxref("HTMLImageElement.currentSrc")}} {{readonlyInline}}{{experimental_inline}}</dt> + <dd>Devuelve un {{domxref("DOMString")}}</dd> + <dt>{{domxref("HTMLImageElement.height")}}</dt> + <dd>Es un <code>unsigned long</code> que refleja el atributo HTML {{htmlattrxref("height", "img")}}, indica el alto de la imagen en píxeles CSS.</dd> + <dt>{{domxref("HTMLImageElement.hspace")}} {{obsolete_inline}}</dt> + <dd>Es un <code>long</code> que representa el espacio a izquierda y derecha de la imagen.</dd> + <dt>{{domxref("HTMLImageElement.isMap")}}</dt> + <dd>Es un {{domxref("Boolean")}} que refleja el atributo HTML {{htmlattrxref("ismap", "img")}}, indica que la imagen es parte del mapa de imagen del lado del servidor.</dd> + <dt>{{domxref("HTMLImageElement.longDesc")}} {{obsolete_inline}}</dt> + <dd>Es un {{domxref("DOMString")}} que representa la URI de una larga descripción de la imagen.</dd> + <dt>{{domxref("HTMLImageElement.lowSrc")}} {{obsolete_inline}}</dt> + <dd>Es un {{domxref("DOMString")}} que referencia una copia de la imagen en mala calidad (pero más rápida cargando)</dd> + <dt>{{domxref("HTMLImageElement.name")}} {{obsolete_inline}}</dt> + <dd>Es un {{domxref("DOMString")}}.</dd> + <dt>{{domxref("HTMLImageElement.naturalHeight")}} {{readonlyInline}}</dt> + <dd>Devuelve un <code>unsigned long</code> que representa el alto intrínseco de la imagen en píxeles CSS, si está disponible, de otro modo, es 0.</dd> + <dt>{{domxref("HTMLImageElement.naturalWidth")}} {{readonlyInline}}</dt> + <dd>Devuelve un <code>unsigned long</code> que representa el ancho intrínseco de la imagen en píxeles CSS, si está disponible, de otro modo, es 0.</dd> + <dt>{{domxref("HTMLImageElement.referrerPolicy")}} {{experimental_inline}}</dt> + <dd>Es un {{domxref("DOMString")}} que refleja el atributo HTML {{htmlattrxref("referrerpolicy", "img")}} indica la referencia a usar para buscar la imagen.</dd> + <dt>{{domxref("HTMLImageElement.src")}}</dt> + <dd>Es un {{domxref("DOMString")}} que refleja el atributo HTML {{htmlattrxref("src", "img")}} HTML attribute, contiene la URL completa de la imagen, incluido la base del URI</dd> + <dt>{{domxref("HTMLImageElement.sizes")}} {{experimental_inline}}</dt> + <dd>Es un {{domxref("DOMString")}}</dd> + <dt>{{domxref("HTMLImageElement.srcset")}} {{experimental_inline}}</dt> + <dd>Es un {{domxref("DOMString")}} que refleja el atributo HTML {{htmlattrxref("srcset", "img")}}, contiene una ista de imágenes candidatas, separadas por una coma (<code>',', U+002C COMMA</code>). Una imagen candidata es una URL seguida por <code>'w'</code> con el ancho, o una <code>'x'</code> seguida de la densidad del píxel.</dd> + <dt>{{domxref("HTMLImageElement.useMap")}}</dt> + <dd>Es un {{domxref("DOMString")}} que refleja el atributo HTML {{htmlattrxref("usemap", "img")}}, contiene una URL parcial del mapa del elemento.</dd> + <dt>{{domxref("HTMLImageElement.vspace")}} {{obsolete_inline}}</dt> + <dd>Es un <code>long</code> que representa el espacio sobre y bajo la imagen.</dd> + <dt>{{domxref("HTMLImageElement.width")}}</dt> + <dd>Es un <code>unsigned long</code> que refleja el atributo HTML {{htmlattrxref("width", "img")}}, indica el ancho de la imagen en píxeles CSS.</dd> + <dt>{{domxref("HTMLImageElement.x")}} {{readonlyInline}}{{experimental_inline}}</dt> + <dd>Devuelve un <code>long</code> que representa el hueco horizontal hasta la capa más cercana. Esta propiedad copia el comportamiento de Netscape 4.</dd> + <dt>{{domxref("HTMLImageElement.y")}} {{readonlyInline}} {{experimental_inline}}</dt> + <dd>Devuelve un <code>long</code> que representa el hueco vertical hasta la capa más cercana. Esta propiedad copia el comportamiento de Netscape 4.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<p><em>Heredados de su padre, {{domxref("HTMLElement")}}.</em></p> + +<dl> + <dt>{{domxref("HTMLImageElement.Image()", "Image()")}}</dt> + <dd>El constructor <code>Image()</code>, toma dos <code>unsigned long</code> opcionales, ancho y alto del recurso, crea una instacia de creates <code>HTMLImageElement</code> no insertada en el árbol DOM.</dd> +</dl> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush: js">var img1 = new Image(); // HTML5 Constructor +img1.src = 'image1.png'; +img1.alt = 'alt'; +document.body.appendChild(img1); + +var img2 = document.createElement('img'); // Uso DOM <a href="http://mxr.mozilla.org/mozilla-central/source/dom/interfaces/html/nsIDOMHTMLImageElement.idl">HTMLImageElement</a> +img2.src = 'image2.jpg'; +img2.alt = 'alt text'; +document.body.appendChild(img2); + +// Usando la primera imagen en el documento +alert(document.images[0].src); +</pre> + +<h2 id="Especificiaciones">Especificiaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especicifación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('Referrer Policy', '#referrer-policy-delivery-referrer-attribute', 'referrer attribute')}}</td> + <td>{{Spec2('Referrer Policy')}}</td> + <td>Añadida la propiedad <code>referrerPolicy</code>.</td> + </tr> + <tr> + <td>{{SpecName("CSSOM View", "#excensions-to-the-htmlimageelement-interface", "Extensions to HTMLImageElement")}}</td> + <td>{{Spec2('CSSOM View')}}</td> + <td>Añadidas propiedades <code>x</code> e <code>y</code></td> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', "embedded-content.html#the-img-element", "HTMLImageElement")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>Las siguientes propiedades han sido añadidas: <code>srcset</code>, <code>currentSrc</code> y <code>sizes</code>.</td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', "embedded-content-0.html#the-img-element", "HTMLImageElement")}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>Un constructor (con 2 parámetros opcionales) añadido. Las siguientes propiedades quedaron obsoletas: <code>name</code>, <code>border</code>, <code>align</code>, <code>hspace</code>, <code>vspace</code>, y <code>longdesc</code>. Las siguientes propiedades son ahora <code>unsigned long</code>, en lugar de <code>long</code>: <code>height</code>, y width.Las siguientes propiedades fueron añadidas: <code>crossorigin</code>, <code>naturalWidth</code>, <code>naturalHeight</code>, <code>y</code> <code>complete</code>.</td> + </tr> + <tr> + <td>{{SpecName('DOM2 HTML', 'html.html#ID-17701901', 'HTMLImgElement')}}</td> + <td>{{Spec2('DOM2 HTML')}}</td> + <td>La propiedad <code>lowSrc</code> fue eliminada.<br> + Las siguientes propiedades son ahora <code>long</code>, en lugar de <code>DOMString</code>: <code>height</code>, <code>width</code>, <code>hspace</code>, y <code>vspace</code>.</td> + </tr> + <tr> + <td>{{SpecName('DOM1', 'level-one-html.html#ID-17701901', 'HTMLImgElement')}}</td> + <td>{{Spec2('DOM1')}}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegador">Compatibilidad con navegador</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(1.0)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>lowSrc</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>naturalWidth</code>, <code>naturalHeight</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>9</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>crossorigin</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>complete</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>5<sup>[4]</sup></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>srcset</code> {{experimental_inline}}</td> + <td>{{CompatChrome(34)}}</td> + <td>{{CompatGeckoDesktop(32)}}<sup>[2]</sup></td> + <td>{{CompatNo}}</td> + <td>21</td> + <td>{{CompatSafari(7.1)}}</td> + </tr> + <tr> + <td><code>currentSrc </code>{{experimental_inline}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(32)}}<sup>[2]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>sizes</code> {{experimental_inline}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(33)}}<sup>[3]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>x</code> e <code>y</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>14<sup>[1]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>referrerPolicy</code> {{experimental_inline}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop(42)}} [5]</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>Característica</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile(1.0)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>lowSrc</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>naturalWidth</code>, <code>naturalHeight</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>9</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>crossorigin</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>complete</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>srcset</code> {{experimental_inline}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoMobile(32)}}<sup>[2]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>iOS 8</td> + </tr> + <tr> + <td><code>currentSrc </code>{{experimental_inline}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoMobile(32)}}<sup>[2]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>sizes</code> {{experimental_inline}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoMobile(33)}}<sup>[3]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>x</code> e <code>y</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>14<sup>[1]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>referrerPolicy</code> {{experimental_inline}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoMobile(42)}} [5]</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Las propiedades <code>x</code> e <code>y</code> fueron eliminadas en Gecko 7.0 {{geckoRelease("7.0")}} pero reestablecidas en Gecko 14.0 {{geckoRelease("14.0")}} por razones de compatibilidad.</p> + +<p>[2] Esta característica está detras de la preferencia <code>dom.image.srcset.enabled</code>, por defecto <code>false</code>.</p> + +<p>[3] Esta característica está detras de la preferencia <code>dom.image.picture.enabled</code>, por defecto <code>false</code>.</p> + +<p>[4] IE reporta <code>false</code> para imágenes rotas.</p> + +<p>[5] Esta propiedad fue nombrada <code>referrer</code> desde Firefox 42 a 44.</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>El elemento HTML implementa esta interfaz: {{HTMLElement("img")}}</li> +</ul> diff --git a/files/es/web/api/htmlinputelement/index.html b/files/es/web/api/htmlinputelement/index.html new file mode 100644 index 0000000000..049ddd7942 --- /dev/null +++ b/files/es/web/api/htmlinputelement/index.html @@ -0,0 +1,673 @@ +--- +title: HTMLInputElement +slug: Web/API/HTMLInputElement +tags: + - API + - HTML DOM + - HTMLInputElement + - Input + - Interface + - NeedsContent + - NeedsMarkupWork + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/HTMLInputElement +--- +<div>{{ APIRef("HTML DOM") }}</div> + +<p>La interface <strong><code>HTMLInputElement</code></strong> proporciona propiedades y métodos especiales para manipular las opciones, estructura y presentacion de los elementos {{HtmlElement("input")}}.</p> + +<p>{{InheritanceDiagram(600,120)}}</p> + +<h2 id="Properties" name="Properties">Propiedades</h2> + +<table class="standard-table"> + <caption>Propiedades relacionadas al formulario padre</caption> + <thead> + </thead> + <tbody> + <tr> + <td><code>form </code>{{readonlyInline}}</td> + <td><em><code>{{domxref("HTMLFormElement")}} object:</code></em> Retorna una referencia al elemento {{HtmlElement("form")}} padre</td> + </tr> + <tr> + <td><code>formAction</code></td> + <td><em><code>string</code>: </em><strong>Retorna / Establece</strong> los atributos de los elementos {{ htmlattrxref("formaction", "input") }}, conteniendo la URI de un programa que procesa la información enviada por el elemento. Esto invalida al atributo {{ htmlattrxref("action", "form") }} del formulario padre.</td> + </tr> + <tr> + <td><code>formEncType</code></td> + <td><em><code>string</code>:</em> <strong>Returns / Sets</strong> the element's {{ htmlattrxref("formenctype", "input") }} attribute, containing the type of content that is used to submit the form to the server. This overrides the {{ htmlattrxref("enctype", "form") }} attribute of the parent form.</td> + </tr> + <tr> + <td><code>formMethod</code></td> + <td><em><code>string</code>:</em> <strong>Returns / Sets</strong> the element's {{ htmlattrxref("formmethod", "input") }} attribute, containing the HTTP method that the browser uses to submit the form. This overrides the {{ htmlattrxref("method", "form") }} attribute of the parent form.</td> + </tr> + <tr> + <td><code>formNoValidate</code></td> + <td><em><code>boolean</code>:</em> <strong>Returns / Sets</strong> the element's {{ htmlattrxref("formnovalidate", "input") }} attribute, indicating that the form is not to be validated when it is submitted. This overrides the {{ htmlattrxref("novalidate", "form") }} attribute of the parent form.</td> + </tr> + <tr> + <td><code>formTarget</code></td> + <td><em><code>string</code>:</em> <strong>Returns / Sets</strong> the element's {{ htmlattrxref("formtarget", "input") }} attribute, containing a name or keyword indicating where to display the response that is received after submitting the form. This overrides the {{ htmlattrxref("target", "form") }} attribute of the parent form.</td> + </tr> + </tbody> +</table> + +<table class="standard-table"> + <caption>Propiedades que aplican a cualquier tipo de elemento input que no se encuentre escondido</caption> + <tbody> + <tr> + <td><code>name</code></td> + <td><em><code>string</code>:</em> <strong>Returns / Sets</strong> the element's {{ htmlattrxref("name", "input") }} attribute, containing a name that identifies the element when submitting the form.</td> + </tr> + <tr> + <td><code>type</code></td> + <td><code><em>string:</em></code> <strong>Returns / Sets</strong> the element's {{ htmlattrxref("type", "input") }} attribute, indicating the type of control to display. See {{ htmlattrxref("type", "input") }} attribute of {{ HTMLElement("input") }} for possible values.</td> + </tr> + <tr> + <td><code>disabled</code></td> + <td><em><code>boolean</code>:</em> <strong>Returns / Sets</strong> the element's {{ htmlattrxref("disabled", "input") }} attribute, indicating that the control is not available for interaction. The input values will not be submitted with the form. See also {{ htmlattrxref("readOnly", "input") }} </td> + </tr> + <tr> + <td><code>autofocus</code></td> + <td><code><em>boolean:</em></code> <strong>Returns / Sets</strong> the element's {{ htmlattrxref("autofocus", "input") }} attribute, which specifies that a form control should have input focus when the page loads, unless the user overrides it, for example by typing in a different control. Only one form element in a document can have the {{htmlattrxref("autofocus","input")}} attribute. It cannot be applied if the {{htmlattrxref("type","input")}} attribute is set to <code>hidden</code> (that is, you cannot automatically set focus to a hidden control).</td> + </tr> + <tr> + <td><code>required</code></td> + <td><em><code>boolean</code>:</em> <strong>Returns / Sets</strong> the element's {{ htmlattrxref("required", "input") }} attribute, indicating that the user must fill in a value before submitting a form.</td> + </tr> + <tr> + <td><code>value</code></td> + <td><code><em>string:</em></code> <strong>Returns / Sets</strong> the current value of the control. + <p class="note"><strong>Nota:</strong> Si el usuario ingresa un valor diferente al esperado, esto puede retornar una cadena vacía.</p> + </td> + </tr> + <tr> + <td><code>validity</code> {{readonlyInline}}</td> + <td><code><em>{{domxref("ValidityState")}} object:</em></code> Returns the validity state that this element is in.</td> + </tr> + <tr> + <td><code>validationMessage</code> {{readonlyInline}}</td> + <td><code><em>string:</em></code> <strong>Returns</strong> a localized message that describes the validation constraints that the control does not satisfy (if any). This is the empty string if the control is not a candidate for constraint validation ({{htmlattrxref("willValidate","input")}} is false), or it satisfies its constraints.</td> + </tr> + <tr> + <td><code>willValidate </code>{{readonlyInline}}</td> + <td><em><code>{{jsxref("Boolean")}}:</code></em> <strong>Indicates</strong> whether the element is a candidate for constraint validation. It is false if any conditions bar it from constraint validation.</td> + </tr> + </tbody> +</table> + +<table class="standard-table"> + <caption><a id="Properties_checkbox_radio" name="Properties_checkbox_radio"></a>Propiedades que aplican solo a los elementos de tipo <code>checkbox</code> o <code>radio</code></caption> + <tbody> + <tr> + <td><code>checked</code></td> + <td> <code><em>boolean:</em> </code><strong>Returns / Sets</strong> the current state of the element when {{htmlattrxref("type","input")}} is <code>checkbox</code> or <code>radio</code>.</td> + </tr> + <tr> + <td><code>defaultChecked</code></td> + <td><em><code>boolean:</code></em> <strong>Returns / Sets</strong> the default state of a radio button or checkbox as originally specified in HTML that created this object.</td> + </tr> + <tr> + <td><code><a id="indeterminate" name="indeterminate"></a>indeterminate</code></td> + <td><code><em>boolean:</em></code> <strong>indicates</strong> that the checkbox is neither on nor off. Changes the appearance to resemble a third state. Does not affect the value of the <strong>checked</strong> attribute, and clicking the checkbox will set the value to false.</td> + </tr> + </tbody> +</table> + +<table class="standard-table"> + <caption>Propiedades que sólo aplican a los elementos de tipo <code>image</code></caption> + <tbody> + <tr> + <td><code>alt</code></td> + <td><em><code>string</code>: </em><strong>Returns / Sets</strong> the element's {{ htmlattrxref("alt", "input") }} attribute, containing alternative text to use when {{htmlattrxref("type","input")}} is <code>image.</code></td> + </tr> + <tr> + <td><code>height</code></td> + <td><em><code>string</code>: </em><strong>Returns / Sets</strong> the element's {{ htmlattrxref("height", "input") }} attribute, which defines the height of the image displayed for the button, if the value of {{htmlattrxref("type","input")}} is <code>image</code>.</td> + </tr> + <tr> + <td><code>src</code></td> + <td><code><em>string:</em></code> <strong>Returns / Sets</strong> the element's {{ htmlattrxref("src", "input") }} attribute, which specifies a URI for the location of an image to display on the graphical submit button, if the value of {{htmlattrxref("type","input")}} is <code>image</code>; otherwise it is ignored.</td> + </tr> + <tr> + <td><code>width</code></td> + <td><code><em>string:</em></code> <strong>Returns / Sets</strong> the document's {{ htmlattrxref("width", "input") }} attribute, which defines the width of the image displayed for the button, if the value of {{htmlattrxref("type","input")}} is <code>image</code>.</td> + </tr> + </tbody> +</table> + +<table class="standard-table"> + <caption>Propiedades que sólo aplican a los elementos de tipo <code>file</code></caption> + <tbody> + <tr> + <td><code>accept</code></td> + <td><em><code>string</code>: </em><strong>Returns / Sets</strong> the element's {{ htmlattrxref("accept", "input") }} attribute, containing comma-separated list of file types accepted by the server when {{htmlattrxref("type","input")}} is <code>file</code>.</td> + </tr> + <tr> + <td><code>allowdirs</code> {{non-standard_inline}}</td> + <td>boolean: Part of the non-standard Directory Upload API; <strong>indicates</strong> whether or not to allow directories and files both to be selected in the file list. Implemented only in Firefox and is hidden behind a preference.</td> + </tr> + <tr> + <td><a id="files_prop" name="files_prop"><code>files</code></a></td> + <td><strong>Returns/accepts</strong> a {{domxref("FileList")}} object, which contains a list of {{domxref("File")}} objects representing the files selected for upload.</td> + </tr> + <tr> + <td>{{domxref("HTMLInputElement.webkitdirectory", "webkitdirectory")}} {{Non-standard_inline}}</td> + <td>boolean:<strong> Returns</strong> the {{htmlattrxref("webkitdirectory", "input")}} attribute; if true, the file system picker interface only accepts directories instead of files.</td> + </tr> + <tr> + <td>{{domxref("HTMLInputElement.webkitEntries", "webkitEntries")}} {{Non-standard_inline}}</td> + <td>Array of {{domxref("FileSystemEntry")}} objects <strong>describing</strong> the currently-selected files or directories.</td> + </tr> + </tbody> +</table> + +<table class="standard-table"> + <caption>Properties that apply only to text/number-containing or elements</caption> + <tbody> + <tr> + <td><code>autocomplete</code></td> + <td><em><code>string</code>: </em><strong>Returns / Sets</strong> the element's {{htmlattrxref("autocomplete", "input")}} attribute, indicating whether the value of the control can be automatically completed by the browser. Ignored if the value of the {{htmlattrxref("type","input")}} attribute is <code>hidden</code>, <code>checkbox</code>, <code>radio</code>, <code>file</code>, or a button type (<code>button</code>, <code>submit</code>, <code>reset</code>, <code>image</code>). Possible values are:<br> + "on": the browser can autocomplete the value using previously stored value<br> + "off": the user must explicity enter a value</td> + </tr> + <tr> + <td><code>maxLength</code></td> + <td><em><code>long</code>:</em> <strong>Returns / Sets</strong> the element's {{ htmlattrxref("maxlength", "input") }} attribute, containing the <u><strong>maximum <strong>l</strong>ength of characters</strong></u> (in Unicode code points) that the value can have. (If you set this to a negative number, an exception will be thrown.)</td> + </tr> + <tr> + <td><code>size</code></td> + <td><em><code>unsigned long</code>:</em> <strong>Returns / Sets </strong>the element's {{ htmlattrxref("size", "input") }} attribute, containing <u><strong>size of the control</strong></u>. This value is in pixels unless the value of {{htmlattrxref("type","input")}} is <code>text</code> or <code>password</code>, in which case, it is an integer number of characters. Applies only when {{htmlattrxref("type","input")}} is set to <code>text</code>, <code>search</code>, <code>tel</code>, <code>url</code>, <code>email</code>, or <code>password</code>; otherwise it is ignored.</td> + </tr> + <tr> + <td><code>pattern</code></td> + <td><em><code>string</code>:</em> <strong>Returns / Sets</strong> the element's {{ htmlattrxref("pattern", "input") }} attribute, containing a <u><strong>regular expression</strong></u> that the control's value is checked against. Use the {{htmlattrxref("title","input")}} attribute to describe the pattern to help the user. This attribute applies when the value of the {{htmlattrxref("type","input")}} attribute is <code>text</code>, <code>search</code>, <code>tel</code>, <code>url</code> or <code>email</code>; otherwise it is ignored.</td> + </tr> + <tr> + <td><code>placeholder</code></td> + <td><em><code>string</code>: </em><strong>Returns / Sets </strong>the element's {{ htmlattrxref("placeholder", "input") }} attribute, containing a hint to the user of what can be entered in the control. The placeholder text must not contain carriage returns or line-feeds. This attribute applies when the value of the {{htmlattrxref("type","input")}} attribute is <code>text</code>, <code>search</code>, <code>tel</code>, <code>url</code> or <code>email</code>; otherwise it is ignored.</td> + </tr> + <tr> + <td><code>readOnly</code></td> + <td><em><code>boolean</code>:</em><strong> Returns / Sets</strong> the element's {{ htmlattrxref("readonly", "input") }} attribute, indicating that the user cannot modify the value of the control.<br> + {{HTMLVersionInline(5)}}This is ignored if the value of the {{htmlattrxref("type","input")}} attribute is <code>hidden</code>, <code>range</code>, <code>color</code>, <code>checkbox</code>, <code>radio</code>, <code>file</code>, or a button type.</td> + </tr> + <tr> + <td><code>min</code></td> + <td><em><code>string</code>:</em> <strong>Returns / Sets</strong> the element's {{ htmlattrxref("min", "input") }} attribute, containing the minimum (numeric or date-time) value for this item, which must not be greater than its maximum ({{htmlattrxref("max","input")}} attribute) value.</td> + </tr> + <tr> + <td><code>max</code></td> + <td><em><code>string</code>:</em> <strong>Returns / Sets</strong> the element's {{ htmlattrxref("max", "input") }} attribute, containing the maximum (numeric or date-time) value for this item, which must not be less than its minimum (<strong>min</strong> attribute) value.</td> + </tr> + <tr> + <td><code>selectionStart</code></td> + <td><em><code>unsigned long</code>:</em> <strong>Returns / Sets</strong> the beginning index of the selected text. When nothing is selected, this returns the position of the text input cursor (caret) inside of the {{HTMLElement("input")}} element.</td> + </tr> + <tr> + <td><code>selectionEnd</code></td> + <td><em><code>unsigned long</code>:</em> <strong>Returns / Sets </strong>the end index of the selected text. When there's no selection, this returns the offset of the character immediately following the current text input cursor position.</td> + </tr> + <tr> + <td><code>selectionDirection</code></td> + <td><em><code>string</code>:</em> <strong>Returns / Sets</strong> the direction in which selection occurred. Possible values are:<br> + <code>"forward"</code> if selection was performed in the start-to-end direction of the current locale,<br> + <code>"backward"</code> for the opposite direction,<br> + <code>"none"</code> if the direction is unknown."</td> + </tr> + </tbody> +</table> + +<table class="standard-table"> + <caption>Propiedades aun no categorizadas</caption> + <tbody> + <tr> + <td><code>defaultValue</code></td> + <td><em><code>string:</code></em> <strong>Returns / Sets</strong> the default value as originally specified in the HTML that created this object.</td> + </tr> + <tr> + <td><code>dirName</code></td> + <td><em><code>string:</code></em> <strong>Returns / Sets </strong>the directionality of the element.</td> + </tr> + <tr> + <td><code>accessKey</code></td> + <td><em><code>string</code>: </em><strong>Returns</strong> a string containing a single character that switches input focus to the control when pressed.</td> + </tr> + <tr> + <td><code>list</code> {{readonlyInline}}</td> + <td><em><code>{{domxref("HTMLElement")}} object:</code></em> <strong>Returns</strong> the element pointed by the {{ htmlattrxref("list", "input") }} attribute. The property may be <code>null</code> if no HTML element found in the same tree.</td> + </tr> + <tr> + <td><code>multiple</code></td> + <td><em><code>boolean</code>:</em> <strong>Returns / Sets</strong> the element's {{ htmlattrxref("multiple", "input") }} attribute, indicating whether more than one value is possible (e.g., multiple files).</td> + </tr> + <tr> + <td><code>files</code></td> + <td><em><code>{{domxref("FileList")}} array:</code></em> <strong>Returns</strong> the list of selected files.</td> + </tr> + <tr> + <td>{{domxref("HTMLInputElement.labels")}} {{readonlyInline}}</td> + <td><code><em>{{domxref("NodeList")}} array:</em></code> <strong>Returns</strong> a list of {{ HTMLElement("label") }} elements that are labels for this element.</td> + </tr> + <tr> + <td><code>step</code></td> + <td><code><em>string:</em></code> <strong>Returns / Sets</strong> the element's {{ htmlattrxref("step", "input") }} attribute, which works with<strong> </strong>{{htmlattrxref("min","input")}} and {{htmlattrxref("max","input")}} to limit the increments at which a numeric or date-time value can be set. It can be the string <code>any</code> or a positive floating point number. If this is not set to <code>any</code>, the control accepts only values at multiples of the step value greater than the minimum.</td> + </tr> + <tr> + <td><code>valueAsDate</code></td> + <td><code><em>{{jsxref("Date")}} object:</em></code> Returns / Sets the value of the element, interpreted as a date, or <code>null</code> if conversion is not possible.</td> + </tr> + <tr> + <td><code>valueAsNumber</code></td> + <td><code>double</code>: <strong>Returns</strong> the value of the element, interpreted as one of the following, in order: + <ul> + <li>a time value</li> + <li>a number</li> + <li>NaN if conversion is impossible</li> + </ul> + </td> + </tr> + <tr> + <td><code>autocapitalize</code> {{experimental_inline}}</td> + <td><code><em>string:</em></code> <strong>defines</strong> the capitalization behavior for user input. Valid values are <code>none</code>, <code>off</code>, <code>characters</code>, <code>words</code>, or <code>sentences</code>.</td> + </tr> + </tbody> +</table> + +<dl> + <dt>{{domxref("HTMLInputElement.align")}} {{obsolete_inline}}</dt> + <dd><code><em>string:</em></code> <strong>represents</strong> the alignment of the element. <em>Use CSS instead.</em></dd> + <dt>{{domxref("HTMLInputElement.useMap")}} {{ obsolete_inline }}</dt> + <dd><code><em>string:</em></code> <strong>represents</strong> a client-side image map.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<table class="standard-table"> + <tbody> + <tr> + <td><code>focus()</code></td> + <td>Focus on the input element; keystrokes will subsequently go to this element.</td> + </tr> + <tr> + <td><code>blur()</code></td> + <td>Removes focus from input; keystrokes will subsequently go nowhere.</td> + </tr> + <tr> + <td><code><a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select">select()</a></code></td> + <td>Selects the input text in the element, and focuses it so the user can subsequently replace the whole entry.</td> + </tr> + <tr> + <td><code><a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/click">click()</a></code></td> + <td>Simulates a click on the element.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/API/HTMLInputElement/setSelectionRange">setSelectionRange()</a></code></td> + <td>Selects a range of text in the element (but does not focus it). The optional selectionDirection parameter may be "forward" or "backward" to establish the direction in which selection was set, or "none" if the direction is unknown or not relevant. The default is "none". Specifying a selectionDirection parameter sets the value of the selectionDirection property.</td> + </tr> + <tr> + <td><code>setRangeText()</code></td> + <td> + <dl> + <dd> + <p>Replaces a range of text with the new text. If the <var>start</var> and <var>end</var> arguments are not provided, the range is assumed to be the selection.The final argument determines how the selection should be set after the text has been replaced. The possible values are:</p> + + <dl> + <dt>"<code>select</code>"</dt> + <dd>Selects the newly inserted text.</dd> + <dt>"<code>start</code>"</dt> + <dd>Moves the selection to just before the inserted text.</dd> + <dt>"<code>end</code>"</dt> + <dd>Moves the selection to just after the selected text.</dd> + <dt>"<code>preserve</code>"</dt> + <dd>Attempts to preserve the selection. This is the default.</dd> + </dl> + </dd> + </dl> + </td> + </tr> + <tr> + <td><code>setCustomValidity()</code></td> + <td>Sets a custom validity message for the element. If this message is not the empty string, then the element is suffering from a custom validity error, and does not validate.</td> + </tr> + <tr> + <td><code>checkValidity()</code></td> + <td>Returns a {{jsxref("Boolean")}} that is <code>false</code> if the element is a candidate for constraint validation, and it does not satisfy its constraints. In this case, it also fires an {{event("invalid")}} event at the element. It returns <code>true</code> if the element is not a candidate for constraint validation, or if it satisfies its constraints.</td> + </tr> + </tbody> +</table> + +<dl> + <dt>{{domxref("HTMLInputElement.stepDown()")}}</dt> + <dd>Decrements the {{htmlattrxref("value","input")}} by ({{htmlattrxref("step","input")}} * n), where n defaults to 1 if not specified. Throws an INVALID_STATE_ERR exception: + <ul> + <li>if the method is not applicable to for the current {{htmlattrxref("type","input")}} value,</li> + <li>if the element has no {{htmlattrxref("step","input")}} value,</li> + <li>if the {{htmlattrxref("value","input")}} cannot be converted to a number,</li> + <li>if the resulting value is above the {{htmlattrxref("max","input")}} or below the {{htmlattrxref("min","input")}}. </li> + </ul> + </dd> + <dt>{{domxref("HTMLInputElement.stepUp()")}}</dt> + <dd>Increments the {{htmlattrxref("value","input")}} by ({{htmlattrxref("step","input")}} * n), where n defaults to 1 if not specified. Throws an INVALID_STATE_ERR exception: + <ul> + <li>if the method is not applicable to for the current {{htmlattrxref("type","input")}} value.,</li> + <li>if the element has no {{htmlattrxref("step","input")}} value,</li> + <li>if the {{htmlattrxref("value","input")}} cannot be converted to a number,</li> + <li>if the resulting value is above the {{htmlattrxref("max","input")}} or below the {{htmlattrxref("min","input")}}.</li> + </ul> + </dd> + <dt> + <h3 id="Métodos_no_estandarizados">Métodos no estandarizados</h3> + </dt> + <dt> + <p>{{domxref("HTMLInputElement.mozSetFileArray()")}}{{non-standard_inline}}</p> + </dt> + <dd>Sets the files selected on the input to the given array of {{domxref("File")}} objects. This is an alternative to <code>mozSetFileNameArray()</code> which can be used in frame scripts: a chrome script can <a href="/en-US/docs/Extensions/Using_the_DOM_File_API_in_chrome_code">open files as File objects</a> and send them via <a href="/en-US/Firefox/Multiprocess_Firefox/The_message_manager">message manager</a>.</dd> + <dt>{{domxref("HTMLInputElement.mozGetFileNameArray()")}}{{non-standard_inline}}</dt> + <dd>Returns an array of all the file names from the input.</dd> + <dt>{{domxref("HTMLInputElement.mozSetFileNameArray()")}}{{non-standard_inline}}</dt> + <dd>Sets the filenames for the files selected on the input. Not for use in <a href="/en-US/Firefox/Multiprocess_Firefox/Limitations_of_frame_scripts">frame scripts</a>, because it accesses the file system.</dd> +</dl> + +<h2 id="Eventos">Eventos</h2> + +<p>Responde a este elemento usando <code><a href="https://wiki.developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener">addEventListener()</a></code> o asignando una respuesta a la propiedad <code>on<em>eventname</em></code> de esta interface:</p> + +<dl> + <dt><a href="https://wiki.developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event"><code>input</code></a></dt> + <dd>Se activa cuando el <code>value</code> de un elemento {{HTMLElement("input")}}, {{HTMLElement("select")}}, o {{HTMLElement("textarea")}} ha sido modificado.</dd> + <dd> + <p><strong>Nota:</strong> Esto es actualmente gatillado en la interface {{domxref("HTMLElement")}} y también aplica a los elementos <code><a href="https://wiki.developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/contenteditable">contenteditable</a></code>, pero lo hemos listado acá porque es más utilizado con los elementos de entrada de formularios.</p> + </dd> + <dd> + <p>También disponible por la propiedad manipuladora <code><a href="https://wiki.developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/oninput">oninput</a></code>.</p> + </dd> + <dt><code><a href="https://wiki.developer.mozilla.org/en-US/docs/Web/API/HTMLElement/invalid_event">invalid</a></code></dt> + <dd>Fired when an element does not satisfy its constraints during constraint validation.</dd> + <dd>Also available via the <code><a href="https://wiki.developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/oninvalid">oninvalid</a></code> event handler property.</dd> + <dt><code><a href="https://wiki.developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/search_event">search</a></code></dt> + <dd>Fired when a search is initiated on an {{HTMLElement("input")}} of <code>type="search"</code>.</dd> + <dd>Also available via the <code><a href="https://wiki.developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onsearch">onsearch</a></code> event handler property.</dd> +</dl> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', "forms.html#the-input-element", "HTMLInputElement")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>No change from {{SpecName("HTML5 W3C")}}</td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', "forms.html#the-input-element", "HTMLInputElement")}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>Technically, the tabindex and accesskey properties, as well as the blur(), click(), and focus() methods, are now defined on {{domxref("HTMLElement")}}.<br> + The following properties are now obsolete: align and useMap.<br> + The following properties have been added: autocomplete, autofocus, dirName, files, formAction, formEncType, formMethod, formNoValidate, formTarget, height, indeterminate, labels, list, max, min, multiple, pattern, placeholder, required, selectionDirection, selectionEnd, selectionStart, step, validationMessage, validity, valueAsDate, valueAsNumber, width, and willValidate.<br> + The following methods have been added: checkValidity(), setCustomValidity(), setSelectionRange(), stepUp(), and stepDown().</td> + </tr> + <tr> + <td>{{SpecName('DOM2 HTML', 'html.html#ID-6043025', 'HTMLInputElement')}}</td> + <td>{{Spec2('DOM2 HTML')}}</td> + <td>The size property is now an unsigned long. The type property must be entirely given in lowercase characters.</td> + </tr> + <tr> + <td>{{SpecName('DOM1', 'level-one-html.html#ID-6043025', 'HTMLInputElement')}}</td> + <td>{{Spec2('DOM1')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Edge</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>{{CompatGeckoDesktop(1.0)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>autocomplete & autofocus properties</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>files property</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(1.9)}}<sup>[2]</sup></td> + <td>10</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>multiple property</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("1.9.2")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>indeterminate property</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>list property</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>formAction, formEncType, formMethod, formTarget properties</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(2)}}<sup>[3]</sup></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>formNoValidate, validationMessage, validity, willValidate properties and setCustomValidity() and checkValidity() methods.</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(2)}}</td> + <td>10</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>pattern, placeholder, required properties</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(2)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>height and weight properties</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(16)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>labels</code> property</td> + <td>{{CompatChrome(14.0)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop("56")}}<sup>[1]</sup></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>min, max, and step for <input type="number"></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>Experimental, and without specific UI, since {{CompatGeckoDesktop(16)}}: behind the pref dom.experimental_forms</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>stepUp and stepDown methods</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>Experimental since {{CompatGeckoDesktop(16)}}: behind the pref dom.experimental_forms<br> + <br> + There are still differences with the latest spec: {{bug(835773)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>min, max, and step properties for <input type="range"></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(23)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>min, max, and step properties for <input type="date"></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>Experimental, and without specific UI, since {{CompatGeckoDesktop(20)}}: behind the pref dom.experimental_forms</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>min, max, and step properties for other date-related type values</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>mozGetFileNameArray() and mozSetFileNameArray() methods {{non-standard_inline}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop("1.9.2")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>mozSetFileArray() method {{non-standard_inline}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop("38")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>autocapitalize</td> + <td>{{CompatChrome(43.0)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Android Webview</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile(1.0)}}<sup>[3]</sup></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>autocapitalize</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(43.0)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td><span style="font-size: 12px; line-height: 16.3636360168457px;">{{CompatUnknown}}</span></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatChrome(43.0)}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Implemented in {{bug("556743")}}.</p> + +<p>[2] The <code>files</code> property was made settable in Firefox 57 ({{bug(1384030)}}).</p> + +<p>[3] In Firefox 56, the implementation has been updated so that the <code>formAction</code> property returns the correct form submission URL, as per spec, when the associated <code><input></code> is being used to submit a form ({{bug(1366361)}}).</p> + +<h2 id="Vea_también">Vea también</h2> + +<ul> + <li>HTML element implementing this interface: {{ HTMLElement("input") }}.</li> +</ul> diff --git a/files/es/web/api/htmlinputelement/invalid_event/index.html b/files/es/web/api/htmlinputelement/invalid_event/index.html new file mode 100644 index 0000000000..e5dec7a141 --- /dev/null +++ b/files/es/web/api/htmlinputelement/invalid_event/index.html @@ -0,0 +1,108 @@ +--- +title: Evento invalid +slug: Web/API/HTMLInputElement/invalid_event +tags: + - Evento + - Referencia + - eventos + - formulários + - invalid + - inválido +translation_of: Web/API/HTMLInputElement/invalid_event +--- +<div>{{APIRef}}</div> + +<p>El evento <strong><code>invalid</code></strong> se dispara cuando se ha comprobado la validez de un elemento que se puede enviar y no satisface sus restricciones.</p> + +<table class="properties"> + <tbody> + <tr> + <th>Interfaz</th> + <td>{{DOMxRef("Event")}}</td> + </tr> + <tr> + <th>Burbujas</th> + <td>No</td> + </tr> + <tr> + <th>Cancelable</th> + <td>Sí</td> + </tr> + <tr> + <th>Objetivos</th> + <td>{{domxref("Element")}}</td> + </tr> + <tr> + <th>Acción por defecto</th> + <td>Varía (puede prevenir que un formulario sea enviado)</td> + </tr> + </tbody> +</table> + +<p>Este evento puede ser útil para desplegar un resumen de los problemas con un formulario al enviarlo. Cuando un formulario se envía, los eventos <code>invalid</code> son disparados en cada control del formulario que es inválido, y entonces en el mismo elemento <code><a href="https://www.w3.org/TR/html51/sec-forms.html#elementdef-form" id="ref-for-elementdef-form-16">form</a></code>. La válidez de los elementos presentados se comprueba antes de enviar al propio {{HtmlElement("form")}}, o despúes del método <a href="/en-US/docs/HTML/Forms_in_HTML#Constraint_Validation_API" title="/en-US/docs/HTML/Forms_in_HTML#Constraint_Validation_API"><code>checkValidity()</code></a> de un elemento o su propio <code><form></code> es llamado. No es revisada al perder el foco (on blur).</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>Si un formulario es enviado con un valor inválido, los elementos pressentados son revisados, y si un error es encontrado, el evento <code>invalid</code> se disparará en el elemento <code>invalid</code>. En este ejemplo, el valor inválido del input dispara un evento <code>invalid</code>, y el valor inválido es registrado.</p> + +<h3 id="HTML">HTML</h3> + +<pre class="brush: html"><form action="#"> + <ul> + <li><label>Enter an integer between 1 and 10: <input type="number" min="0" max="10" required></label></li> + <li><input type="submit" value="submit"></li> + </ul> +</form><p id="log"></p></pre> + +<h3 id="JavaScript">JavaScript</h3> + +<pre class="brush: js">const input = document.querySelector('input'); +const log = document.getElementById('log'); + +input.addEventListener('invalid', logValue); + +function logValue(e) { + log.textContent += e.srcElement.value; +}</pre> + +<h3 id="Resultado">Resultado</h3> + +<p>{{EmbedLiveSample("Example")}}</p> + +<p>(Funciona en la versión en inglés)</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{ SpecName('HTML WHATWG', 'forms.html#the-constraint-validation-api', 'Invalid event') }}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </td> + </tr> + <tr> + <td>{{ SpecName('HTML5.1', 'sec-forms.html#the-constraint-validation-api', 'Invalid event') }}</td> + <td>{{Spec2('HTML5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{ SpecName('HTML5 W3C', 'forms.html#the-constraint-validation-api', 'Invalid event') }}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("GlobalEventHandlers.oninvalid")}}</li> + <li>Elemento HTML {{HtmlElement("form")}}</li> + <li>Evento relacionado: {{Event("submit")}}</li> + <li><a href="/en-US/docs/Web/CSS/:invalid">CSS <code>:invalid </code>pseudo class</a></li> +</ul> diff --git a/files/es/web/api/htmlinputelement/select/index.html b/files/es/web/api/htmlinputelement/select/index.html new file mode 100644 index 0000000000..645932d012 --- /dev/null +++ b/files/es/web/api/htmlinputelement/select/index.html @@ -0,0 +1,51 @@ +--- +title: HTMLInputElement.select() +slug: Web/API/HTMLInputElement/select +tags: + - API + - HTML DOM + - HTMLInputElement + - NeedsCompatTable + - Referencia + - metodo +translation_of: Web/API/HTMLInputElement/select +--- +<div>{{ APIRef("HTML DOM") }}</div> + +<p>El método <strong><code>HTMLInputElement.select()</code></strong> selecciona todo el texto en un elemento {{HTMLElement("textarea")}} o un elemento{{HTMLElement("input")}} con un campo de texto.</p> + +<h2 id="Sintaxis" name="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">element.select()</pre> + +<h2 id="Especificación" name="Especificación">Especificación</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('HTML WHATWG', 'forms.html#dom-textarea/input-select', 'select')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Notas">Notas</h2> + +<p>Llamando a <code>element.select()</code> no necesariamente se enfoca el campo, por lo que suele utilizarse junto con {{domxref("HTMLElement.focus()")}}.</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{ HTMLElement("input") }}</li> + <li>{{ HTMLElement("textarea") }}</li> + <li>{{ domxref("HTMLInputElement") }}</li> + <li>{{ domxref("HTMLInputElement.setSelectionRange") }}</li> +</ul> diff --git a/files/es/web/api/htmllabelelement/index.html b/files/es/web/api/htmllabelelement/index.html new file mode 100644 index 0000000000..50df0281c2 --- /dev/null +++ b/files/es/web/api/htmllabelelement/index.html @@ -0,0 +1,82 @@ +--- +title: HTMLLabelElement +slug: Web/API/HTMLLabelElement +tags: + - API + - HTML DOM + - HTMLLabeledElement + - Interface + - Referencia +translation_of: Web/API/HTMLLabelElement +--- +<div>{{ APIRef("HTML DOM") }}</div> + +<p>La interfaz <strong><code>HTMLLabelElement</code></strong> proporciona acceso a propiedades especificas de los elementos {{HTMLElement("label")}}. A su vez, hereda métodos y propiedades de la interfaz base {{domxref("HTMLElement")}}.</p> + +<p>{{InheritanceDiagram(600,120)}}</p> + +<h2 id="Propiedades">Propiedades</h2> + +<p><em>Heredando propiedades de los elementos padres {{domxref("HTMLElement")}}.</em></p> + +<dl> + <dt>{{domxref("HTMLLabelElement.control")}} {{ReadOnlyInline}}</dt> + <dd>Es un {{domxref("HTMLElement")}} representando el control a la cual cada etiqueta esta asociado.</dd> + <dt>{{domxref("HTMLLabelElement.form")}} {{ReadOnlyInline}}</dt> + <dd>Es un objeto {{domxref("HTMLFormElement")}} representado el formulario al cual el control etiquetado está asociado, arrojando el valor <code>null</code>, si no hay asociado ningun control o si ese control no está asociado con un formulario. En otras palabras, esto es un atajo para: <code><em>HTMLLabelElement</em>.control.form</code>.</dd> + <dt>{{domxref("HTMLLabelElement.htmlFor")}}</dt> + <dd>Este es un contenedor de caracteres que contiene el ID del control etiquetado, esto es lo que refleja el atributo {{htmlattrxref("for", "label")}}</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<p><em>No hay metodos específicos, hereda los metodos de los elelemtos padres, {{domxref("HTMLElement")}}.</em></p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estatus</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', "#htmllabelelement", "HTMLLabelElement")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', "forms.html#the-label-element", "HTMLLabelElement")}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>La propiedad <code>accessKey</code> ahora está definida en: {{domxref("HTMLElement")}}.<br> + La siguiente propiedad ha sido agregada: <code>control</code>.</td> + </tr> + <tr> + <td>{{SpecName('DOM2 HTML', 'html.html#ID-13691394', 'HTMLLabelElement')}}</td> + <td>{{Spec2('DOM2 HTML')}}</td> + <td>Sin cambios desde: {{SpecName("DOM1")}}.</td> + </tr> + <tr> + <td>{{SpecName('DOM1', 'level-one-html.html#ID-13691394', 'HTMLLabelElement')}}</td> + <td>{{Spec2('DOM1')}}</td> + <td>definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_Navegador_Web">Compatibilidad de Navegador Web</h2> + +<div> +<div class="hidden">La tabla de compatibilidad en esta página es generada por datos estructurados. si ud. desea contribuir a estos datos, por favor ingrese al siguiente link: <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> y envienos un requerimeinto (pull request)</div> + +<p>{{Compat("api.HTMLLabelElement")}}</p> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>Elementos HTML implementando esta interfaz: {{HTMLElement("label")}}</li> + <li>{{HTMLElement("form")}}</li> + <li>{{domxref("HTMLFormElement")}}</li> +</ul> diff --git a/files/es/web/api/htmllielement/index.html b/files/es/web/api/htmllielement/index.html new file mode 100644 index 0000000000..93c6555b63 --- /dev/null +++ b/files/es/web/api/htmllielement/index.html @@ -0,0 +1,118 @@ +--- +title: HTMLLIElement +slug: Web/API/HTMLLIElement +tags: + - API + - HTML DOM +translation_of: Web/API/HTMLLIElement +--- +<div> +<div>{{ APIRef("HTML DOM") }}</div> +</div> + +<p>La interfaz <strong>HTMLLIElement </strong>expone las propiedades y los métodos específicos (más allá de los definidos por la interfaz regular {{domxref ("HTMLElement")}} que también tiene disponible por herencia) para manipular elementos de la lista.</p> + +<h2 id="Propiedades">Propiedades</h2> + +<p><em>Hereda las propiedades de su elemento primario, {{domxref ("HTMLElement")}}.</em></p> + +<dl> + <dt>{{domxref("HTMLLIElement.type")}} {{obsolete_inline}}</dt> + <dd>Es un {{domxref ("DOMString")}} que representa el tipo de las viñetas, "disco", "cuadrado" o "círculo". Como la forma estándar de definir el tipo de lista es a través de la propiedad CSS {{cssxref ("list-style-type")}}, use los métodos CSSOM para establecerlo a través de un script.</dd> + <dt>{{domxref("HTMLLIElement.value")}}</dt> + <dd>Es un largo que indica la posición ordinal del elemento de lista dentro de un {{HTMLElement ("ol")}} dado. Refleja el atributo {{htmlattrxref ("valor", "li")}} del elemento HTML {{HTMLElement ("li")}} y puede ser menor que 0. Si el elemento {{HTMLElement ("li")}} Elemento no es hijo de un elemento {{HTMLElement ("ol")}}, la propiedad no tiene ningún significado.</dd> +</dl> + +<h2 id="Metodos">Metodos</h2> + +<p><em>No specific method; inherits properties from its parent, {{domxref("HTMLElement")}}.</em></p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificacion</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', "grouping-content.html#the-li-element", "HTMLLIElement")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>No change from {{SpecName("HTML5 W3C")}}.</td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', "grouping-content.html#the-li-element", "HTMLLIElement")}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>The following property is now obsolete: <code>type</code>.</td> + </tr> + <tr> + <td>{{SpecName('DOM2 HTML', 'html.html#ID-74680021', 'HTMLLIElement')}}</td> + <td>{{Spec2('DOM2 HTML')}}</td> + <td>No change from {{SpecName("DOM1")}}.</td> + </tr> + <tr> + <td>{{SpecName('DOM1', 'level-one-html.html#ID-74680021', 'HTMLLIElement')}}</td> + <td>{{Spec2('DOM1')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_Navegadores">Compatibilidad con Navegadores</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>{{CompatGeckoDesktop(1.0)}} [1]</td> + <td>{{CompatVersionUnknown}}</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>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile(1.0)}} [1]</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Prior to Firefox 10, Gecko incorrectly reflected negative {{htmlattrxref("value", "li")}} attributes to <code>0</code>.</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>El elemento HTML que implementa esta interfaz: {{HTMLElement("li")}}</li> +</ul> diff --git a/files/es/web/api/htmlmediaelement/canplay_event/index.html b/files/es/web/api/htmlmediaelement/canplay_event/index.html new file mode 100644 index 0000000000..4eb6386c37 --- /dev/null +++ b/files/es/web/api/htmlmediaelement/canplay_event/index.html @@ -0,0 +1,109 @@ +--- +title: 'HTMLMediaElement: canplay' +slug: Web/API/HTMLMediaElement/canplay_event +translation_of: Web/API/HTMLMediaElement/canplay_event +--- +<p>El evento canplay es lanzado cuando el elemento <a href="/es/docs/Web/HTML/Elemento/video"><video></a> o <a href="/es/docs/Web/HTML/Elemento/Audio"><audio></a> puede ser iniciado o fue iniciado satisfactoriamente.</p> + +<p>Lo que puede evitar que el evento <code>canplay </code>se dispare puede ser por alguna de estás razones:</p> + +<ul> + <li>El ruta del <code>audio</code> o <code>video </code>están mal especificadas.</li> + <li>El navegador no soporta la etiqueta. <code> </code></li> +</ul> + +<pre class="brush: html"><!DOCTYPE html> +<html lang="en"> +<head> + <meta charset="UTF-8"> + <title>Evento oncanplay - Javascript</title> + <script> + function Start() { + alert("Start") + } + </script> +</head> +<body> + +<video controls autoplay oncanplay="Start()"> + <source src="audio.mp4" type="video/mp4"> +</video> + +</body> +</html></pre> + +<p>Intente especificar mal la ruta del <code>src </code>y comprobrará que el evento no funciona.</p> + +<h2 id="General_info">General info</h2> + +<dl> + <dt style="float: left; text-align: right; width: 120px;">Specification</dt> + <dd style="margin: 0 0 0 120px;"><a class="external" href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#event-media-canplay">HTML5 media</a></dd> + <dt style="float: left; text-align: right; width: 120px;">Interface</dt> + <dd style="margin: 0 0 0 120px;">Event</dd> + <dt style="float: left; text-align: right; width: 120px;">Bubbles</dt> + <dd style="margin: 0 0 0 120px;">No</dd> + <dt style="float: left; text-align: right; width: 120px;">Cancelable</dt> + <dd style="margin: 0 0 0 120px;">No</dd> + <dt style="float: left; text-align: right; width: 120px;">Target</dt> + <dd style="margin: 0 0 0 120px;">Element</dd> + <dt style="float: left; text-align: right; width: 120px;">Default Action</dt> + <dd style="margin: 0 0 0 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="Related_Events">Related Events</h2> + +<ul> + <li>{{event("playing")}}</li> + <li>{{event("waiting")}}</li> + <li>{{event("seeking")}}</li> + <li>{{event("seeked")}}</li> + <li>{{event("ended")}}</li> + <li>{{event("loadedmetadata")}}</li> + <li>{{event("loadeddata")}}</li> + <li>{{event("canplay")}}</li> + <li>{{event("canplaythrough")}}</li> + <li>{{event("durationchange")}}</li> + <li>{{event("timeupdate")}}</li> + <li>{{event("play")}}</li> + <li>{{event("pause")}}</li> + <li>{{event("ratechange")}}</li> + <li>{{event("volumechange")}}</li> + <li>{{event("suspend")}}</li> + <li>{{event("emptied")}}</li> + <li>{{event("stalled")}}</li> +</ul> diff --git a/files/es/web/api/htmlmediaelement/index.html b/files/es/web/api/htmlmediaelement/index.html new file mode 100644 index 0000000000..c507549375 --- /dev/null +++ b/files/es/web/api/htmlmediaelement/index.html @@ -0,0 +1,231 @@ +--- +title: HTMLMediaElement +slug: Web/API/HTMLMediaElement +translation_of: Web/API/HTMLMediaElement +--- +<p>{{APIRef("HTML DOM")}}</p> + +<p>La interfaz HTMLMediaElement añade a {{domxref("HTMLElement")}} las propiedades y métodos necesarios para soportar las capacidades básicas relacionadas con los medios de comunicación que son comunes en audio y vídeo. Los elementos {{domxref("HTMLVideoElement")}}} y {{domxref("HTMLAudioElement")}}} heredan esta interfaz.</p> + +<p>{{InheritanceDiagram(600, 120)}}</p> + +<h2 id="Properties">Properties</h2> + +<p>Esta interfaz también hereda propiedades de sus antepasados {{domxref("HTMLElement")}}, {{domxref("Element")}}, {{domxref("Node")}} y {{domxref("EventTarget")}}.</p> + +<dl> + <dt>{{domxref("HTMLMediaElement.audioTracks")}}</dt> + <dd>Un {{domxref("AudioTrackList")}}} que lista los {{domxref("AudioTrack")}} objetos contenidos en el elemento.</dd> + <dt>{{domxref("HTMLMediaElement.autoplay")}}</dt> + <dd>Un {{jsxref("Booleano")}} que refleja el {{htmlattrxref("autoplay", "video")}}. Atributo HTML, que indica si la reproducción debe comenzar automáticamente tan pronto como haya suficiente material disponible para hacerlo sin interrupción. + <div class="note">Los sitios que reproducen automáticamente audio (o vídeos con una pista de audio) pueden ser una experiencia desagradable para los usuarios, por lo que deben evitarse en la medida de lo posible. Si debe ofrecer la funcionalidad de autojuego, debe hacer que se active (requiriendo que el usuario lo habilite específicamente). Sin embargo, esto puede ser útil a la hora de crear elementos multimedia cuya fuente se establecerá más adelante, bajo el control del usuario.</div> + </dd> + <dt>{{domxref("HTMLMediaElement.buffered")}} {{readonlyinline}}</dt> + <dd>Devuelve un objeto {{domxref("TimeRanges")}}} que indica los rangos de la fuente de medios que el navegador ha almacenado en el búfer (si existe) en el momento en que se accede a la propiedad almacenada en el búfer.</dd> + <dt>{{domxref("HTMLMediaElement.controller")}}</dt> + <dd>Es un objeto {{domxref("MediaController")}}} que representa el controlador de medios asignado al elemento, o nulo si no se asigna ninguno.</dd> + <dt>{{domxref("HTMLMediaElement.controls")}}</dt> + <dd>Es un {{jsxref('booleano')}} que refleja el {{htmlattrxref("controles", "vídeo")}}}[1]. Atributo HTML, que indica si deben visualizarse las posiciones de la interfase de usuario para controlar el recurso.</dd> + <dt>{{domxref("HTMLMediaElement.controlsList")}} {{readonlyinline}}</dt> + <dd>Devuelve un {{domxref("DOMTokenList")}} que ayuda al agente de usuario a seleccionar qué controles mostrar en el elemento multimedia cuando el agente de usuario muestra su propio conjunto de controles. La DOMTokenList toma uno o más de los tres valores posibles: nodownload, nofullscreen y noremoteplayback.</dd> + <dt>{{domxref("HTMLMediaElement.crossOrigin")}}</dt> + <dd>Es un {{domxref("DOMString")}}} que indica la configuración CORS para este elemento multimedia.</dd> + <dt>{{domxref("HTMLMediaElement.currentSrc")}} {{readonlyinline}}</dt> + <dd>Devuelve un {{domxref("DOMString")}}} con la URL absoluta del recurso multimedia elegido.</dd> + <dt>{{domxref("HTMLMediaElement.currentTime")}}</dt> + <dd>Es un doble indicador del tiempo de reproducción actual en segundos. Fijar este valor busca que los medios de comunicación se adapten a los nuevos tiempos.</dd> + <dt>{{domxref("HTMLMediaElement.defaultMuted")}}</dt> + <dd>Es un {{jsxref('booleano')}} que refleja el {{htmlattrxref("silenciado", "video")}}}. Atributo HTML, que indica si la salida de audio del elemento multimedia debe silenciarse de forma predeterminada.</dd> + <dt>{{domxref("HTMLMediaElement.defaultPlaybackRate")}}</dt> + <dd>Es un doble que indica la velocidad de reproducción predeterminada del material.</dd> + <dt>{{domxref("HTMLMediaElement.disableRemotePlayback")}}</dt> + <dd>Es un {{jsxref('Booleano')}} que establece o devuelve el estado de reproducción remota, indicando si el elemento multimedia puede tener una interfaz de reproducción remota.</dd> + <dt>{{domxref("HTMLMediaElement.duration")}} {{readonlyinline}}</dt> + <dd>Devuelve un doble indicando la longitud del material en segundos, o 0 si no hay datos de material disponibles.</dd> + <dt>{{domxref("HTMLMediaElement.ended")}} {{readonlyinline}}</dt> + <dd>Devuelve un {{jsxref('Booleano')}} que indica si el elemento multimedia ha terminado de reproducirse.</dd> + <dt>{{domxref("HTMLMediaElement.error")}} {{readonlyinline}}</dt> + <dd>Returns a {{domxref("MediaError")}} object for the most recent error, or <code>null</code> if there has not been an error.</dd> + <dt>{{domxref("HTMLMediaElement.loop")}}</dt> + <dd>Is a {{jsxref('Boolean')}} that reflects the {{htmlattrxref("loop", "video")}} HTML attribute, which indicates whether the media element should start over when it reaches the end.</dd> + <dt>{{domxref("HTMLMediaElement.mediaGroup")}}</dt> + <dd>Is a {{domxref("DOMString")}} that reflects the {{ htmlattrxref("mediagroup", "video")}} HTML attribute, which indicates the name of the group of elements it belongs to. A group of media elements shares a common {{domxref('MediaController')}}.</dd> + <dt>{{domxref("HTMLMediaElement.mediaKeys")}} {{readonlyinline}} {{experimental_inline}}</dt> + <dd>Returns a {{domxref("MediaKeys")}} object or <code>null</code>. MediaKeys is a set of keys that an associated HTMLMediaElement can use for decryption of media data during playback.</dd> + <dt>{{domxref("HTMLMediaElement.mozAudioCaptured")}} {{readonlyinline}} {{non-standard_inline}}</dt> + <dd>Returns a {{jsxref('Boolean')}}. Related to audio stream capture.</dd> + <dt>{{domxref("HTMLMediaElement.mozFragmentEnd")}} {{non-standard_inline}}</dt> + <dd>Is a <code>double</code> that provides access to the fragment end time if the media element has a fragment URI for <code>currentSrc</code>, otherwise it is equal to the media duration.</dd> + <dt>{{domxref("HTMLMediaElement.mozFrameBufferLength")}} {{non-standard_inline}} {{deprecated_inline}}</dt> + <dd> + <p>Is a <code>unsigned long</code> that indicates the number of samples that will be returned in the framebuffer of each <code>MozAudioAvailable</code> event. This number is a total for all channels, and by default is set to be the number of channels * 1024 (e.g., 2 channels * 1024 samples = 2048 total).</p> + + <p>The <code>mozFrameBufferLength</code> property can be set to a new value for lower latency, larger amounts of data, etc. The size given <em>must</em> be a number between 512 and 16384. Using any other size results in an exception being thrown. The best time to set a new length is after the <a href="/en-US/docs/Web/Events/loadedmetadata">loadedmetadata</a> event fires, when the audio info is known, but before the audio has started or <code>MozAudioAvailable</code> events have begun firing.</p> + </dd> + <dt>{{domxref("HTMLMediaElement.mozSampleRate")}} {{readonlyinline}} {{non-standard_inline}} {{deprecated_inline}}</dt> + <dd>Returns a <code>double</code> representing the number of samples per second that will be played. For example, 44100 samples per second is the sample rate used by CD audio.</dd> + <dt>{{domxref("HTMLMediaElement.muted")}}</dt> + <dd>Is a {{jsxref('Boolean')}} that determines whether audio is muted. <code>true</code> if the audio is muted and <code>false</code> otherwise.</dd> + <dt>{{domxref("HTMLMediaElement.networkState")}} {{readonlyinline}}</dt> + <dd>Returns a <code>unsigned short</code> (enumeration) indicating the current state of fetching the media over the network.</dd> + <dt>{{domxref("HTMLMediaElement.paused")}} {{readonlyinline}}</dt> + <dd>Returns a {{jsxref('Boolean')}} that indicates whether the media element is paused.</dd> + <dt>{{domxref("HTMLMediaElement.playbackRate")}}</dt> + <dd>Is a <code>double</code> that indicates the rate at which the media is being played back. </dd> + <dt>{{domxref("HTMLMediaElement.played")}} {{readonlyinline}}</dt> + <dd>Returns a {{domxref('TimeRanges')}} object that contains the ranges of the media source that the browser has played, if any.</dd> + <dt>{{domxref("HTMLMediaElement.preload")}}</dt> + <dd>Is a {{domxref("DOMString")}} that reflects the {{htmlattrxref("preload", "video")}} HTML attribute, indicating what data should be preloaded, if any. Possible values are: <code>none</code>, <code>metadata</code>, <code>auto</code>.</dd> + <dt>{{domxref("HTMLMediaElement.preservesPitch")}} {{non-standard_inline}}</dt> + <dd>Is a {{jsxref('Boolean')}} that determines if the pitch of the sound will be preserved. If set to <code>false</code>, the pitch will adjust to the speed of the audio. This is implemented with prefixes in Firefox (<code>mozPreservesPitch</code>) and WebKit (<code>webkitPreservesPitch</code>).</dd> + <dt>{{domxref("HTMLMediaElement.readyState")}} {{readonlyinline}}</dt> + <dd>Returns a <code>unsigned short</code> (enumeration) indicating the readiness state of the media.</dd> + <dt>{{domxref("HTMLMediaElement.seekable")}} {{readonlyinline}}</dt> + <dd>Returns a {{domxref('TimeRanges')}} object that contains the time ranges that the user is able to seek to, if any.</dd> + <dt>{{domxref("HTMLMediaElement.seeking")}} {{readonlyinline}}</dt> + <dd>Returns a {{jsxref('Boolean')}} that indicates whether the media is in the process of seeking to a new position.</dd> + <dt>{{domxref("HTMLMediaElement.sinkId")}} {{readonlyinline}} {{experimental_inline}}</dt> + <dd>Returns a {{domxref("DOMString")}} that is the unique ID of the audio device delivering output, or an empty string if it is using the user agent default. This ID should be one of the <code>MediaDeviceInfo.deviceid</code> values returned from {{domxref("MediaDevices.enumerateDevices()")}}, <code>id-multimedia</code>, or <code>id-communications</code>.</dd> + <dt>{{domxref("HTMLMediaElement.src")}}</dt> + <dd>Is a {{domxref("DOMString")}} that reflects the {{htmlattrxref("src", "video")}} HTML attribute, which contains the URL of a media resource to use.</dd> + <dt>{{domxref("HTMLMediaElement.srcObject")}}</dt> + <dd>Is a {{domxref('MediaStream')}} representing the media to play or that has played in the current <code>HTMLMediaElement</code>, or <code>null</code> if not assigned.</dd> + <dt>{{domxref("HTMLMediaElement.textTracks")}} {{readonlyinline}}</dt> + <dd>Returns the list of {{domxref("TextTrack")}} objects contained in the element.</dd> + <dt>{{domxref("HTMLMediaElement.videoTracks")}} {{readonlyinline}}</dt> + <dd>Returns the list of {{domxref("VideoTrack")}} objects contained in the element. + <div class="note"> + <p>Gecko sólo soporta la reproducción de una sola pista, y el análisis de los metadatos de las pistas sólo está disponible para los medios con el formato de contenedor Ogg.</p> + </div> + </dd> + <dt>{{domxref("HTMLMediaElement.volume")}}</dt> + <dd>Is a <code>double</code> indicating the audio volume, from 0.0 (silent) to 1.0 (loudest).</dd> +</dl> + +<h3 id="Event_handlers">Event handlers</h3> + +<dl> + <dt> </dt> + <dt>{{domxref("HTMLMediaElement.onencrypted")}}</dt> + <dd>Sets the {{domxref('EventHandler')}} called when the media is encrypted.</dd> + <dt>{{domxref("HTMLMediaElement.onwaitingforkey")}}</dt> + <dd>Sets the {{domxref('EventHandler')}} called when playback is blocked while waiting for an encryption key.</dd> +</dl> + +<h2 id="Obsolete_attributes">Obsolete attributes</h2> + +<p>These attributes are obsolete and should not be used, even if a browser still supports them.</p> + +<dl> + <dt>{{domxref("HTMLMediaElement.initialTime")}} {{readonlyinline}} {{non-standard_inline}} {{obsolete_inline}}</dt> + <dd>Returns a <code>double</code> that indicates the initial playback position in seconds.</dd> + <dt>{{domxref("HTMLMediaElement.mozChannels")}} {{readonlyinline}} {{non-standard_inline}} {{deprecated_inline}}</dt> + <dd>Returns a <code>double</code> representing the number of channels in the audio resource (e.g., <code>2</code> for stereo).</dd> +</dl> + +<h3 id="Obsolete_event_handlers">Obsolete event handlers</h3> + +<dl> + <dt>{{domxref("HTMLMediaElement.onmozinterruptbegin")}} {{non-standard_inline}} {{obsolete_inline}}</dt> + <dd>Sets the {{domxref("EventHandler")}} called when the media element is interrupted because of the Audio Channel manager. This was Firefox-specific, having been implemented for Firefox OS, and was removed in Firefox 55.</dd> + <dt>{{domxref("HTMLMediaElement.onmozinterruptend")}} {{non-standard_inline}} {{obsolete_inline}}</dt> + <dd>Sets the {{domxref('EventHandler')}} called when the interruption is concluded. This was Firefox-specific, having been implemented for Firefox OS, and was removed in Firefox 55.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<p><em>This interface also inherits methods from its ancestors {{domxref("HTMLElement")}}, {{domxref('Element')}}, {{domxref('Node')}}, and {{domxref('EventTarget')}}.</em></p> + +<dl> + <dt>{{domxref("HTMLMediaElement.addTextTrack()")}}</dt> + <dd>Adds a text track (such as a track for subtitles) to a media element.</dd> + <dt>{{domxref("HTMLMediaElement.captureStream()")}} {{experimental_inline}}</dt> + <dd>Returns {{domxref("MediaStream")}}, captures a stream of the media content.</dd> + <dt>{{domxref("HTMLMediaElement.canPlayType()")}}</dt> + <dd>Determines whether the specified media type can be played back.</dd> + <dt>{{domxref("HTMLMediaElement.fastSeek()")}}</dt> + <dd>Directly seeks to the given time.</dd> + <dt>{{domxref("HTMLMediaElement.load()")}}</dt> + <dd>Resets the media to the beginning and selects the best available source from the sources provided using the {{htmlattrxref("src", "video")}} attribute or the {{HTMLElement("source")}} element.</dd> + <dt>{{domxref("HTMLMediaElement.mozCaptureStream()")}} {{non-standard_inline}}</dt> + <dd>[enter description]</dd> + <dt>{{domxref("HTMLMediaElement.mozCaptureStreamUntilEnded()")}} {{non-standard_inline}}</dt> + <dd>[enter description]</dd> + <dt>{{domxref("HTMLMediaElement.mozGetMetadata()")}} {{non-standard_inline}}</dt> + <dd>Returns {{jsxref('Object')}}, which contains properties that represent metadata from the playing media resource as <code>{key: value}</code> pairs. A separate copy of the data is returned each time the method is called. This method must be called after the <a href="/en-US/docs/Web/Events/loadedmetadata">loadedmetadata</a> event fires.</dd> + <dt>{{domxref("HTMLMediaElement.pause()")}}</dt> + <dd>Pauses the media playback.</dd> + <dt>{{domxref("HTMLMediaElement.play()")}}</dt> + <dd>Begins playback of the media.</dd> + <dt>{{domxref("HTMLMediaElement.seekToNextFrame()")}} {{non-standard_inline}} {{experimental_inline}}</dt> + <dd>Seeks to the next frame in the media. This non-standard, experimental method makes it possible to manually drive reading and rendering of media at a custom speed, or to move through the media frame-by-frame to perform filtering or other operations.</dd> + <dt>{{domxref("HTMLMediaElement.setMediaKeys()")}} {{experimental_inline}}</dt> + <dd>Returns {{jsxref("Promise")}}. Sets the {{domxref("MediaKeys")}} keys to use when decrypting media during playback.</dd> + <dt>{{domxref("HTMLMediaElement.setSinkId()")}} {{experimental_inline}}</dt> + <dd>Sets the ID of the audio device to use for output and returns a {{jsxref("Promise")}}. This only works when the application is authorized to use the specified device.</dd> +</dl> + +<h2 id="Obsolete_methods">Obsolete methods</h2> + +<p>These methods are obsolete and should not be used, even if a browser still supports them.</p> + +<dl> + <dt>{{domxref("HTMLMediaElement.mozLoadFrom()")}} {{non-standard_inline}} {{deprecated_inline}}</dt> + <dd>This method, available only in Mozilla's implementation, loads data from another media element. This works similarly to <code>load()</code> except that instead of running the normal resource selection algorithm, the source is simply set to the <code>other</code> element's <code>currentSrc</code>. This is optimized so this element gets access to all of the <code>other</code> element's cached and buffered data; in fact, the two elements share downloaded data, so data downloaded by either element is available to both.</dd> +</dl> + +<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', "the-video-element.html#htmlmediaelement", "HTMLMediaElement")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>No change from {{SpecName('HTML5 W3C')}}</td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', "embedded-content-0.html#htmlmediaelement", "HTMLMediaElement")}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('EME', '#introduction', 'Encrypted Media Extensions')}}</td> + <td>{{Spec2('EME')}}</td> + <td>Adds {{domxref("MediaKeys")}}, {{domxref("MediaEncryptedEvent")}}, {{domxref("setMediaKeys")}}, {{domxref("onencrypted")}}, and {{domxref("onwaitingforkey")}}.</td> + </tr> + <tr> + <td>{{SpecName('Media Capture','#htmlmediaelement-extensions','HTMLMediaElement')}}</td> + <td>{{Spec2('Media Capture')}}</td> + <td>Adds <code>sinkId</code> and <code>setSinkId()</code>, and <code>captureStream()</code>.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div class="hidden">La tabla de compatibilidad de esta página se genera a partir de datos estructurados. Si desea contribuir con los datos, visite <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> y envíenos una solicitud de extracción.</div> + +<p>{{Compat("api.HTMLMediaElement")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>References + <ul> + <li>{{HTMLElement("video")}} and {{HTMLElement("audio")}} HTML elements.</li> + <li>{{domxref("HTMLVideoElement")}} and {{domxref("HTMLAudioElement")}} interfaces, derived from <code>HTMLMediaElement</code>.</li> + </ul> + </li> + <li>Articles + <ul> + <li><a class="internal" href="/en-US/docs/Using_HTML5_audio_and_video">Using HTML5 audio and video</a></li> + <li><a class="internal" href="/en-US/docs/Media_formats_supported_by_the_audio_and_video_elements">Media formats supported by the audio and video elements</a></li> + <li><a href="/en-US/docs/Web_Audio_API">Web Audio API</a></li> + </ul> + </li> +</ul> diff --git a/files/es/web/api/htmlmediaelement/loadeddata_event/index.html b/files/es/web/api/htmlmediaelement/loadeddata_event/index.html new file mode 100644 index 0000000000..6606275c6a --- /dev/null +++ b/files/es/web/api/htmlmediaelement/loadeddata_event/index.html @@ -0,0 +1,130 @@ +--- +title: 'HTMLMediaElement: loadeddata event' +slug: Web/API/HTMLMediaElement/loadeddata_event +tags: + - Audio + - HTMLMediaElement + - Referências + - Video + - eventos +translation_of: Web/API/HTMLMediaElement/loadeddata_event +--- +<p>{{APIRef("HTMLMediaElement")}}</p> + +<p><span class="seoSummary">El evento <strong><code>loadeddata</code></strong> se arroja cuando el cuadro en la posición de reproducción actual del medio ha terminado de cargarse; a menudo el primer marco</span></p> + +<table class="properties"> + <tbody> + <tr> + <th scope="row">Burbujas</th> + <td>No</td> + </tr> + <tr> + <th scope="row">Cancelable</th> + <td>No</td> + </tr> + <tr> + <th scope="row">Interfaz</th> + <td>{{DOMxRef("Event")}}</td> + </tr> + <tr> + <th scope="row">Objetivo</th> + <td>Element</td> + </tr> + <tr> + <th scope="row">Acción por defecto</th> + <td>Ninguno</td> + </tr> + <tr> + <th scope="row">Propiedad del controlador de eventos</th> + <td>{{domxref("GlobalEventHandlers.onloadeddata")}}</td> + </tr> + <tr> + <th scope="row">Especificación</th> + <td><a class="external" href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#event-media-playing">HTML5 media</a></td> + </tr> + </tbody> +</table> + +<div class="note"> +<p>Tenga en cuenta que este evento no se activará en dispositivos móviles / tablet, si el protector de datos está activado en configuración del navegador.</p> +</div> + +<h2 id="Ejemplos">Ejemplos</h2> + +<p>Estos ejemplos agregan un escucha de eventos para el evento de <code>loadeddata</code> del HTMLMediaElement, luego publican un mensaje cuando ese controlador de eventos ha respondido al disparo del evento.</p> + +<p>Utilizando <code>addEventListener()</code>:</p> + +<pre class="brush: js">const video = document.querySelector('video'); + +video.addEventListener('loadeddata', (event) => { + console.log('Hurra! El readyState solo aumentó a ' + + 'HAVE_CURRENT_DATA or mayor por primera vez.'); +});</pre> + +<p>Utilizando el <code>onloadeddata</code> propiedad del controlador de eventos:</p> + +<pre class="brush: js">const video = document.querySelector('video'); + +video.onloadeddata = (event) => { + console.log('Hurra! El readyState solo aumentó a ' + + 'HAVE_CURRENT_DATA or mayor por primera vez.'); +};</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificaciones</th> + <th scope="col">Estado</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', "media.html#event-media-loadeddata", "loadeddata media event")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', "embedded-content-0.html#event-media-loadeddata", "loadeddata media event")}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_del_navegador">Compatibilidad del navegador</h2> + +<div class="hidden">La tabla de compatibilidad en esta página se genera a partir de datos estructurados. Si desea contribuir con los datos, consulte <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> y envíenos una solicitud de extracción.</div> + +<p>{{Compat("api.HTMLMediaElement.loadeddata_event")}}</p> + +<h2 id="Eventos_Relacionados">Eventos Relacionados</h2> + +<ul> + <li>{{domxref("HTMLMediaElement.playing_event", 'HTMLMediaElement: playing event')}}</li> + <li>{{domxref("HTMLMediaElement.waiting_event", 'HTMLMediaElement: waiting event')}}</li> + <li>{{domxref("HTMLMediaElement.seeking_event", 'HTMLMediaElement: seeking event')}}</li> + <li>{{domxref("HTMLMediaElement.seeked_event", 'HTMLMediaElement: seeked event')}}</li> + <li>{{domxref("HTMLMediaElement.ended_event", 'HTMLMediaElement: ended event')}}</li> + <li>{{domxref("HTMLMediaElement.loadedmetadata_event", 'HTMLMediaElement: loadedmetadata event')}}</li> + <li>{{domxref("HTMLMediaElement.loadeddata_event", 'HTMLMediaElement: loadeddata event')}}</li> + <li>{{domxref("HTMLMediaElement.canplay_event", 'HTMLMediaElement: canplay event')}}</li> + <li>{{domxref("HTMLMediaElement.canplaythrough_event", 'HTMLMediaElement: canplaythrough event')}}</li> + <li>{{domxref("HTMLMediaElement.durationchange_event", 'HTMLMediaElement: durationchange event')}}</li> + <li>{{domxref("HTMLMediaElement.timeupdate_event", 'HTMLMediaElement: timeupdate event')}}</li> + <li>{{domxref("HTMLMediaElement.play_event", 'HTMLMediaElement: play event')}}</li> + <li>{{domxref("HTMLMediaElement.pause_event", 'HTMLMediaElement: pause event')}}</li> + <li>{{domxref("HTMLMediaElement.ratechange_event", 'HTMLMediaElement: ratechange event')}}</li> + <li>{{domxref("HTMLMediaElement.volumechange_event", 'HTMLMediaElement: volumechange event')}}</li> + <li>{{domxref("HTMLMediaElement.suspend_event", 'HTMLMediaElement: suspend event')}}</li> + <li>{{domxref("HTMLMediaElement.emptied_event", 'HTMLMediaElement: emptied event')}}</li> + <li>{{domxref("HTMLMediaElement.stalled_event", 'HTMLMediaElement: stalled event')}}</li> +</ul> + +<h2 id="Ver_También">Ver También</h2> + +<ul> + <li>{{domxref("HTMLAudioElement")}}</li> + <li>{{domxref("HTMLVideoElement")}}</li> + <li>{{HTMLElement("audio")}}</li> + <li>{{HTMLElement("video")}}</li> +</ul> diff --git a/files/es/web/api/htmlmediaelement/pause/index.html b/files/es/web/api/htmlmediaelement/pause/index.html new file mode 100644 index 0000000000..10e276e508 --- /dev/null +++ b/files/es/web/api/htmlmediaelement/pause/index.html @@ -0,0 +1,52 @@ +--- +title: HTMLMediaElement.pause() +slug: Web/API/HTMLMediaElement/pause +translation_of: Web/API/HTMLMediaElement/pause +--- +<p>{{APIRef("HTML DOM")}}</p> + +<p>El método <strong><code>HTMLMediaElement.pause()</code></strong> pausará la reproducción de los medios, si los medios ya están en pausa, este método no tendrá efecto.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><em>HTMLMediaElement</em>.pause()</pre> + +<h3 id="Parametros">Parametros</h3> + +<p>Ninguno.</p> + +<h3 id="Valor_de_retorno">Valor de retorno</h3> + +<p>Ninguno.</p> + +<h3 id="Excepciones">Excepciones</h3> + +<p>Ninguno.</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th>Especificación</th> + <th>Estado</th> + <th>Comentarios</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', 'embedded-content.html#dom-media-pause', 'pause()')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>Initial definition; living specification.</td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C','embedded-content-0.html#dom-media-pause','pause()')}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2> + +<div class="hidden">La tabla de compatibilidad en esta página se genera a partir de datos estructurados. Si desea contribuir con los datos, consulte <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> y envíenos un pull request.</div> + +<p>{{Compat("api.HTMLMediaElement.pause")}}</p> diff --git a/files/es/web/api/htmlmediaelement/paused/index.html b/files/es/web/api/htmlmediaelement/paused/index.html new file mode 100644 index 0000000000..3bf4430dae --- /dev/null +++ b/files/es/web/api/htmlmediaelement/paused/index.html @@ -0,0 +1,56 @@ +--- +title: HTMLMediaElement.paused +slug: Web/API/HTMLMediaElement/paused +translation_of: Web/API/HTMLMediaElement/paused +--- +<div>{{APIRef("HTML DOM")}}</div> + +<p>La propiedad <strong><code>HTMLMediaElement.paused</code></strong> es solo de lectura, indica si el elemento multimedia está en pausa.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox">var <em>pausado</em> = <em>audioOVideo</em>.<strong>paused</strong></pre> + +<h3 id="Valor">Valor</h3> + +<p>Es un {{domxref("Boolean")}}. <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">Mostrara <strong>true </strong>si está pausado y <strong>false </strong>en caso contrario.</span></font></p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush: js">var obj = document.createElement('video'); +console.log(obj.paused); // true +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', "#dom-media-paused", "HTMLMediaElement.paused")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', "embedded-content-0.html#htmlmediaelement", "HTMLMediaElement.paused")}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<div class="hidden">La tabla de compatibilidad de esta página es generada a partir de datos estructurados. Si te gustaría contribuir con la información, por favor verifícalo en <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> y envianos un pull request.</div> + +<p>{{Compat("api.HTMLMediaElement.paused")}}</p> + +<h2 id="See_Also" name="See_Also">Ver también</h2> + +<ul> + <li>La interfaz que lo define, {{domxref("HTMLMediaElement")}}.</li> +</ul> diff --git a/files/es/web/api/htmlmediaelement/play/index.html b/files/es/web/api/htmlmediaelement/play/index.html new file mode 100644 index 0000000000..3931470b78 --- /dev/null +++ b/files/es/web/api/htmlmediaelement/play/index.html @@ -0,0 +1,124 @@ +--- +title: HTMLMediaElement.play() +slug: Web/API/HTMLMediaElement/play +translation_of: Web/API/HTMLMediaElement/play +--- +<div>{{APIRef("HTML DOM")}}</div> + +<p><span class="seoSummary">El método <code>play()</code> de {{domxref("HTMLMediaElement")}} intenta comenzar la reproducción de los medios. Devuelve una promesa ({{jsxref("Promise")}}) que se resuelve cuando la reproducción se ha iniciado con éxito.</span> Si no se inicia la reproducción por cualquier motivo, como problemas de permisos, la promesa será rechazada.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var <em>promesa</em> = <em>HTMLMediaElement</em>.play();</pre> + +<h3 id="Parametros">Parametros</h3> + +<p>Ninguno.</p> + +<h3 id="Valor_de_retorno">Valor de retorno</h3> + +<p>Es una promesa({{jsxref("Promise")}}) que se resuelve cuando se inicia la reproducción, o se rechaza si por algún motivo no se puede iniciar la reproducción.</p> + +<div class="note"> +<p><strong>Nota:</strong> Los navegadores más antiguos pueden no devolver un valor de <code>play()</code>.</p> +</div> + +<h3 id="Excepciones">Excepciones</h3> + +<p>El <strong>controlador de rechazo</strong> de la promesas se llama con un nombre de excepción pasado como su único parámetro de entrada (a diferencia de una excepción tradicional que se lanza). Los posibles errores incluyen:</p> + +<dl> + <dt><code>NotAllowedError</code>( <em>Error no permitido</em>)</dt> + <dd>El agente de usuario(navegador) o el sistema operativo no permiten la reproducción de medios en el contexto o situación actual. Esto puede suceder, por ejemplo, si el navegador requiere que el usuarion inicie explícitamente la reproducción de medios haciendo clic en el botón "reproducir".</dd> + <dt>NotSupportedError(<em> Error no admitido</em>)</dt> + <dd>La fuente de medios (que puede especificarse como {{domxref("MediaStream")}}, {{domxref("MediaSource")}}, {{domxref("Blob")}}, o {{domxref("File")}}) no representa un formato de medios compatible.</dd> +</dl> + +<p>Se pueden informar otras excepciones, según los detalles de implementación del navegador, la implementación del reproductor de medios, etc.</p> + +<h2 id="Notas">Notas</h2> + +<p>Aunque generalmente se considera que el término "reproducción automática" se refiere a páginas que comienzan a reproducir contenido multimedia inmediatamente después de cargarse, las políticas de reproducción automática de los navegadores web también se aplican a cualquier reproducción de contenido multimedia que inicia por script, incluidas las llamadas a el método <code>play()</code>.</p> + +<p>Si el {{Glossary("user agent")}} está configurado para no permitir la reproducción automática o iniciada por script de medios, llamando el método <code>play()</code> hara que la promesa devuelta sea rechazada inmediatamente con un <code>NotAllowedError</code>. Los sitios web deben estar preparados para manejar esta situación. Por ejemplo, un sitio no debe presentar una interfaz de usuario que suponga que la reproducción ha comenzado automáticamenta, sino que debe actualizar su interfaz de usuario en función de si la promesa devuelta se resulve o se rechaza. Mira el {{anch("Example", "Ejemplo")}} abajo para más información.</p> + +<div class="note"> +<p><strong>Nota:</strong> El método <code>play()</code> puede hacer que se le pida al usuario que otorgue permiso para reproducir medios, lo que puede ocacionar un posible retraso antes de que se resuelva la promesa devuelta. Asegúrese de que su código no espere una respuesta inmediata.</p> +</div> + +<p>Para obtener información más detallada sobre la reproducción automática y el bloqueo de reproducción automática, consulte nuestro artículo <a href="/en-US/docs/Web/Media/Autoplay_guide">Guía de reproducción automática para medios y API de audio web</a>.</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>Este ejemplo muestra cómo confirmar que la reproducción ha comenzado y cómo manejar adecuadamente la reproducción automática bloqueada:</p> + +<pre class="brush: js">let videoElem = document.getElementById("video"); +let playButton = document.getElementById("playbutton"); + +playButton.addEventListener("click", handlePlayButton, false); +playVideo(); + +async function playVideo() { + try { + await videoElem.play(); + playButton.className = "playing"; + } catch(err) { + playButton.className = ""; + } +} + +function handlePlayButton() { + if (videoElem.paused) { + playVideo(); + } else { + videoElem.pause(); + playButton.className = ""; + } +}</pre> + +<p>En este ejemplo, la reproducción de video se activa y desactiva por la función <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/async_function">async</a></code> <code>playVideo()</code>. Intenta reproducir el video y, si tiene éxito, establece el nombre de clase del elemento <code>playButton</code> en "playing". Si la reproducción no se inicia, la clase del elemento <code>playButton</code> se borra, restaurando su apariencia predeterminada. Esto garantiza que el bóton de reproducción coincida con el estado real de reproducción al observar la resolución o el rechazo de {{jsxref("Promise")}} devuelto por el método <code>play()</code>.</p> + +<p>Cuando se ejecuta este ejemplo, comienza recogiendo referencias al elemento {{HTMLElement("video")}}, así como al {{HTMLElement("button")}} utilizado para activar y desactivar la reproducción. Luego configura un controlador de eventos para el evento {{event("click")}} en el botón de alternancia de reproducción e intenta comenzar automáticamente la reproducción llamando al método <code>playVideo()</code>.</p> + +<p>Puedes <a href="https://media-play-promise.glitch.me/">probar o remezclar este ejemplo en tiempo real en Glitch</a>.</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th>Especificación</th> + <th>Estatus</th> + <th>Comentarios</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', 'embedded-content.html#dom-media-play', 'play()')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>Initial definition; living specification.</td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C','embedded-content-0.html#dom-media-play','play()')}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<div class="note"> +<p><strong>Nota:</strong> Las versiones WHATWG y W3C de la especificación difieren (a partir de agosto de 2018) en cuanto a si este método devuelve una {{jsxref("Promise")}} o nada en absoluto, respectivamente.</p> +</div> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<div class="hidden">La tabla de compatibilidad en esta página se genera a partir de datos estructurados. Si desea contribuir con los datos, consulte <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> y envíenos un pull request.</div> + +<p>{{Compat("api.HTMLMediaElement.play")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/Web/Media">Web media technologies</a></li> + <li>Learning: <a href="/en-US/docs/Learn/HTML/Multimedia_and_embedding/Video_and_audio_content">Video and audio content</a></li> + <li><a href="/en-US/docs/Web/Media/Autoplay_guide">Autoplay guide for media and Web Audio APIs</a></li> + <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/htmlmediaelement/timeupdate_event/index.html b/files/es/web/api/htmlmediaelement/timeupdate_event/index.html new file mode 100644 index 0000000000..e7c931cf64 --- /dev/null +++ b/files/es/web/api/htmlmediaelement/timeupdate_event/index.html @@ -0,0 +1,82 @@ +--- +title: 'HTMLMediaElement: timeupdate' +slug: Web/API/HTMLMediaElement/timeupdate_event +translation_of: Web/API/HTMLMediaElement/timeupdate_event +--- +<p>El evento <code>timeupdate es llamado cuando el tiempo indicado por el atributo currentTime es actualizado.</code></p> + +<p>La frecuencia del evento depende de la carga del sistema, pero se encuentra en un rango de 4Hz y 66Hz (asumiendo que los manejadores de eventos no toman mas de 250ms para correr). Se recomienda a los User agents variar la frecuencia del evento basados en la carga del sistema y el costo promedio de procesamiento del evento cada vez que corre, para que las actualizaciones a la UI no sean mas frecuentes que las que el user agent puede manejar confortablemente mientras se decodifica el video.</p> + +<h2 id="Información_General">Información General</h2> + +<dl> + <dt style="float: left; text-align: right; width: 120px;">Specification</dt> + <dd style="margin: 0 0 0 120px;"><a class="external" href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#event-media-timeupdate">HTML5 media</a></dd> + <dt style="float: left; text-align: right; width: 120px;">Interface</dt> + <dd style="margin: 0 0 0 120px;">Event</dd> + <dt style="float: left; text-align: right; width: 120px;">Bubbles</dt> + <dd style="margin: 0 0 0 120px;">No</dd> + <dt style="float: left; text-align: right; width: 120px;">Cancelable</dt> + <dd style="margin: 0 0 0 120px;">No</dd> + <dt style="float: left; text-align: right; width: 120px;">Target</dt> + <dd style="margin: 0 0 0 120px;">Element</dd> + <dt style="float: left; text-align: right; width: 120px;">Default Action</dt> + <dd style="margin: 0 0 0 120px;">None.</dd> +</dl> + +<h2 id="Propiedades">Propiedades</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="Eventos_Relacionados">Eventos Relacionados</h2> + +<ul> + <li>{{event("playing")}}</li> + <li>{{event("waiting")}}</li> + <li>{{event("seeking")}}</li> + <li>{{event("seeked")}}</li> + <li>{{event("ended")}}</li> + <li>{{event("loadedmetadata")}}</li> + <li>{{event("loadeddata")}}</li> + <li>{{event("canplay")}}</li> + <li>{{event("canplaythrough")}}</li> + <li>{{event("durationchange")}}</li> + <li>{{event("timeupdate")}}</li> + <li>{{event("play")}}</li> + <li>{{event("pause")}}</li> + <li>{{event("ratechange")}}</li> + <li>{{event("volumechange")}}</li> + <li>{{event("suspend")}}</li> + <li>{{event("emptied")}}</li> + <li>{{event("stalled")}}</li> +</ul> diff --git a/files/es/web/api/htmlselectelement/checkvalidity/index.html b/files/es/web/api/htmlselectelement/checkvalidity/index.html new file mode 100644 index 0000000000..fe4755de95 --- /dev/null +++ b/files/es/web/api/htmlselectelement/checkvalidity/index.html @@ -0,0 +1,53 @@ +--- +title: HTMLSelectElement.checkValidity() +slug: Web/API/HTMLSelectElement/checkValidity +tags: + - API + - Constraint Validation API + - HTML DOM + - HTMLSelectElement + - Referencia + - metodo +translation_of: Web/API/HTMLSelectElement/checkValidity +--- +<div>{{ APIRef("HTML DOM") }}</div> + +<p>El método <code><strong>HTMLSelectElement.checkValidity()</strong></code> comprueba si el elemento tiene restricciones y si las cumple. Si el elemento no cumple sus restricciones, el navegador lanza un evento cancelable {{event("invalid")}} al momento y luego devuelve <code>false</code>.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="eval language-html"><code class="language-html">var <em>result</em> = <em>selectElt</em>.checkValidity();</code></pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', '#dom-cva-checkvalidity', 'HTMLSelectElement.checkValidity()')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>Sin cambios desde el último snapshot, {{SpecName('HTML5 W3C')}}.</td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', 'forms.html#dom-cva-checkvalidity', 'HTMLSelectElement.checkValidity()')}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>Definición inicial, snapshot de {{SpecName('HTML WHATWG')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_navegadores">Compatibilidad en navegadores</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("api.HTMLSelectElement.checkValidity")}}</p> + +<h2 id="Ver también" name="Ver también">Ver también</h2> + +<ul> + <li><a href="/es/docs/HTML/HTML5/Validacion_de_restricciones">Validación de restricciones.</a></li> +</ul> diff --git a/files/es/web/api/htmlselectelement/index.html b/files/es/web/api/htmlselectelement/index.html new file mode 100644 index 0000000000..058aabd1e2 --- /dev/null +++ b/files/es/web/api/htmlselectelement/index.html @@ -0,0 +1,152 @@ +--- +title: HTMLSelectElement +slug: Web/API/HTMLSelectElement +tags: + - API + - HTML DOM + - Interface + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/HTMLSelectElement +--- +<div>{{APIRef("HTML DOM")}}</div> + +<p>The <code><strong>HTMLSelectElement</strong></code> interface represents a {{HTMLElement("select")}} HTML Element. These elements also share all of the properties and methods of other HTML elements via the {{domxref("HTMLElement")}} interface.</p> + +<p>{{InheritanceDiagram(600, 120)}}</p> + +<h2 id="Properties">Properties</h2> + +<p><em>This interface inherits the properties of {{domxref("HTMLElement")}}, and of {{domxref("Element")}} and {{domxref("Node")}}.</em></p> + +<dl> + <dt>{{domxref("HTMLSelectElement.autofocus")}}</dt> + <dd>A {{jsxref("Boolean")}} reflecting the {{htmlattrxref("autofocus", "select")}} HTML attribute, which indicates whether the control should have input focus when the page loads, unless the user overrides it, for example by typing in a different control. Only one form-associated element in a document can have this attribute specified. {{gecko_minversion_inline("2.0")}}</dd> + <dt>{{domxref("HTMLSelectElement.disabled")}}</dt> + <dd>A {{jsxref("Boolean")}} reflecting the {{htmlattrxref("disabled", "select")}} HTML attribute, which indicates whether the control is disabled. If it is disabled, it does not accept clicks.</dd> + <dt>{{domxref("HTMLSelectElement.form")}}{{ReadOnlyInline}}</dt> + <dd>An {{domxref("HTMLFormElement")}} referencing the form that this element is associated with. If the element is not associated with of a {{HTMLElement("form")}} element, then it returns <code>null</code>.</dd> + <dt>{{domxref("HTMLSelectElement.labels")}}{{ReadOnlyInline}}</dt> + <dd>A {{domxref("NodeList")}} of {{HTMLElement("label")}} elements associated with the element.</dd> + <dt>{{domxref("HTMLSelectElement.length")}}</dt> + <dd>An <code>unsigned long </code>The number of {{HTMLElement("option")}} elements in this <code>select</code> element.</dd> + <dt>{{domxref("HTMLSelectElement.multiple")}}</dt> + <dd>A {{jsxref("Boolean")}} reflecting the {{htmlattrxref("multiple", "select")}} HTML attribute, which indicates whether multiple items can be selected.</dd> + <dt>{{domxref("HTMLSelectElement.name")}}</dt> + <dd>A {{domxref("DOMString")}} reflecting the {{htmlattrxref("name", "select")}} HTML attribute, containing the name of this control used by servers and DOM search functions.</dd> + <dt>{{domxref("HTMLSelectElement.options")}}{{ReadOnlyInline}}</dt> + <dd>An {{domxref("HTMLOptionsCollection")}} representing the set of {{HTMLElement("option")}} elements contained by this element.</dd> + <dt>{{domxref("HTMLSelectElement.required")}}</dt> + <dd>A {{jsxref("Boolean")}} reflecting the {{htmlattrxref("required", "select")}} HTML attribute, which indicates whether the user is required to select a value before submitting the form. {{gecko_minversion_inline("2.0")}}</dd> + <dt>{{domxref("HTMLSelectElement.selectedIndex")}}</dt> + <dd>A <code>long</code> reflecting the index of the first selected {{HTMLElement("option")}} element. The value <code>-1</code> indicates no element is selected.</dd> + <dt>{{domxref("HTMLSelectElement.selectedOptions")}}{{ReadOnlyInline}}</dt> + <dd>An {{domxref("HTMLCollection")}} representing the set of {{HTMLElement("option")}} elements that are selected.</dd> + <dt>{{domxref("HTMLSelectElement.size")}}</dt> + <dd>A <code>long</code> reflecting the {{htmlattrxref("size", "select")}} HTML attribute, which contains the number of visible items in the control. The default is 1, unless <code>multiple</code> is true, in which case it is 4.</dd> + <dt>{{domxref("HTMLSelectElement.type")}}{{ReadOnlyInline}}</dt> + <dd>A {{domxref("DOMString")}} represeting the form control's type. When <code>multiple</code> is <code>true</code>, it returns <code>"select-multiple"</code>; otherwise, it returns <code>"select-one"</code>.</dd> + <dt>{{domxref("HTMLSelectElement.validationMessage")}}{{ReadOnlyInline}}</dt> + <dd>A {{domxref("DOMString")}} representing a localized message that describes the validation constraints that the control does not satisfy (if any). This attribute is the empty string if the control is not a candidate for constraint validation (<code>willValidate</code> is false), or it satisfies its constraints.</dd> + <dt>{{domxref("HTMLSelectElement.validity")}}{{ReadOnlyInline}}</dt> + <dd>A {{domxref("ValidityState")}} reflecting the validity state that this control is in.</dd> + <dt>{{domxref("HTMLSelectElement.value")}}</dt> + <dd>A {{domxref("DOMString")}} reflecting the value of the form control (the first selected option). Returns the value attribute of the option element or if it is missing, the text attribute.</dd> + <dt>{{domxref("HTMLSelectElement.willValidate")}}{{ReadOnlyInline}}</dt> + <dd>A {{jsxref("Boolean")}} that indicates whether the button is a candidate for constraint validation. It is false if any conditions bar it from constraint validation.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<p><em>This interface inherits the methods of {{domxref("HTMLElement")}}, and of {{domxref("Element")}} and {{domxref("Node")}}.</em></p> + +<dl> + <dt>{{domxref("HTMLSelectElement.add()")}}</dt> + <dd>Adds an element to the collection of <code>option</code> elements for this <code>select</code> element.</dd> + <dt>{{domxref("HTMLSelectElement.blur()")}}{{obsolete_inline}}</dt> + <dd>Removes input focus from this element. <em>This method is now implemented on {{domxref("HTMLElement")}}</em>.</dd> + <dt>{{domxref("HTMLSelectElement.checkValidity()")}}</dt> + <dd>Checks whether the element has any constraints and whether it satisfies them. If the element fails its constraints, the browser fires a cancelable {{event("invalid")}} event at the element (and returns <code>false</code>).</dd> + <dt>{{domxref("HTMLSelectElement.focus()")}}{{obsolete_inline}}</dt> + <dd>Gives input focus to this element. <em>This method is now implemented on {{domxref("HTMLElement")}}</em>.</dd> + <dt>{{domxref("HTMLSelectElement.item()")}}</dt> + <dd>Gets an item from the options collection for this {{HTMLElement("select")}} element. You can also access an item by specifying the index in array-style brackets or parentheses, without calling this method explicitly.</dd> + <dt>{{domxref("HTMLSelectElement.namedItem()")}}</dt> + <dd>Gets the item in the options collection with the specified name. The name string can match either the <code>id</code> or the <code>name</code> attribute of an option node. You can also access an item by specifying the name in array-style brackets or parentheses, without calling this method explicitly.</dd> + <dt>{{domxref("HTMLSelectElement.remove()")}}</dt> + <dd>Removes the element at the specified index from the options collection for this select element.</dd> + <dt>{{domxref("HTMLSelectElement.setCustomValidity()")}}</dt> + <dd>Sets the custom validity message for the selection element to the specified message. Use the empty string to indicate that the element does <em>not</em> have a custom validity error.</dd> +</dl> + +<h2 id="Example">Example</h2> + +<h3 id="Get_information_about_the_selected_option">Get information about the selected option</h3> + +<pre class="brush: js">/* assuming we have the following HTML +<select id='s'> + <option>First</option> + <option selected>Second</option> + <option>Third</option> +</select> +*/ + +var select = document.getElementById('s'); + +// return the index of the selected option +console.log(select.selectedIndex); // 1 + +// return the value of the selected option +console.log(select.options[select.selectedIndex].value) // Second +</pre> + +<p>A better way to track changes to the user's selection is to watch for the {{event("change")}} event to occur on the <code><select></code>. This will tell you when the value changes, and you can then update anything you need to. See <a href="/en-US/docs/Web/Events/change#Example_Change_event_on_a_select">the example provided</a> in the documentation for the <code>change</code> event for details.</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', '#htmlselectelement', 'HTMLSelectElement')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>Since the latest snapshot, {{SpecName('HTML5 W3C')}}, it adds the <code>autocomplete</code> property and the <code>reportValidity()</code> method.</td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', 'forms.html#htmlselectelement', 'HTMLSelectElement')}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>Is a snapshot of {{SpecName("HTML WHATWG")}}.<br> + It adds the <code>autofocus</code>, <code>form</code>, <code>required</code>, <code>labels</code>, <code>selectedOptions</code>, <code>willValidate</code>, <code>validity</code> and <code>validationMessage</code> properties.<br> + The <code>tabindex</code> property and the <code>blur()</code> and <code>focus()</code> methods have been moved to {{domxref("HTMLElement")}}.<br> + The methods <code>item()</code>, <code>namedItem()</code>, <code>checkValidity()</code> and <code>setCustomValidity()</code>.</td> + </tr> + <tr> + <td>{{SpecName('DOM2 HTML', 'html.html#ID-94282980', 'HTMLSelectElement')}}</td> + <td>{{Spec2('DOM2 HTML')}}</td> + <td><code>options</code> now returns an {{domxref("HTMLOptionsCollection")}}.<br> + <code>length</code> now returns an <code>unsigned long</code>.</td> + </tr> + <tr> + <td>{{SpecName('DOM1', 'level-one-html.html#ID-94282980', 'HTMLSelectElement')}}</td> + <td>{{Spec2('DOM1')}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("api.HTMLSelectElement")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>The {{HTMLElement("select")}} HTML element, which implements this interface.</li> +</ul> diff --git a/files/es/web/api/htmlselectelement/setcustomvalidity/index.html b/files/es/web/api/htmlselectelement/setcustomvalidity/index.html new file mode 100644 index 0000000000..b5477a5ed0 --- /dev/null +++ b/files/es/web/api/htmlselectelement/setcustomvalidity/index.html @@ -0,0 +1,52 @@ +--- +title: HTMLSelectElement.setCustomValidity() +slug: Web/API/HTMLSelectElement/setCustomValidity +translation_of: Web/API/HTMLSelectElement/setCustomValidity +--- +<div>{{ APIRef("HTML DOM") }}</div> + +<p>El metodo <code><strong>HTMLSelectElement.setCustomValidity()</strong></code> define el mensaje de validación personalizado para el elemento seleccionado con el mensaje especifico. Usa una string vacia para indicar que ese elemento no tiene error de validación customizado.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><em>selectElt</em>.setCustomValidity(<em>string</em>);</pre> + +<h3 id="Parameters">Parameters</h3> + +<ul> + <li><code>string</code> is the {{domxref("DOMString")}} containing the error message.</li> +</ul> + +<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-cva-setcustomvalidity', 'HTMLSelectElement.setCustomValidity()')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>No change since the latest snapshot, {{SpecName('HTML5 W3C')}}.</td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', 'forms.html#dom-cva-setcustomvalidity', 'HTMLSelectElement.setCustomValidity()')}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>Initial definition, snapshot of {{SpecName('HTML WHATWG')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("api.HTMLSelectElement.setCustomValidity")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation">Form validation.</a></li> +</ul> diff --git a/files/es/web/api/htmlshadowelement/getdistributednodes/index.html b/files/es/web/api/htmlshadowelement/getdistributednodes/index.html new file mode 100644 index 0000000000..782506dff6 --- /dev/null +++ b/files/es/web/api/htmlshadowelement/getdistributednodes/index.html @@ -0,0 +1,93 @@ +--- +title: HTMLShadowElement.getDistributedNodes() +slug: Web/API/HTMLShadowElement/getDistributedNodes +tags: + - Necesita traducción +translation_of: Web/API/HTMLShadowElement/getDistributedNodes +--- +<div>{{APIRef("Web Components")}}</div> + +<p>The <code><strong>HTMLShadowElement.getDistributedNodes()</strong></code> method returns a static {{domxref("NodeList")}} of the {{glossary("distributed nodes")}} associated with this <code><shadow></code> element.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox">var <var>nodeList</var> = <var>object</var>.getDistributedNodes() +</pre> + +<h2 id="Example">Example</h2> + +<pre class="brush: js">// Get the distributed nodes +var nodes = myShadowObject.getDistributedNodes();</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="spec-table standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('Shadow DOM', '#the-shadow-element', 'shadow')}}</td> + <td>{{Spec2('Shadow DOM')}}</td> + <td>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 (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>35</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>26</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>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>37</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/HTMLShadowElement">HTMLShadowElement</a></li> +</ul> diff --git a/files/es/web/api/htmlshadowelement/index.html b/files/es/web/api/htmlshadowelement/index.html new file mode 100644 index 0000000000..4a83b2f733 --- /dev/null +++ b/files/es/web/api/htmlshadowelement/index.html @@ -0,0 +1,117 @@ +--- +title: HTMLShadowElement +slug: Web/API/HTMLShadowElement +tags: + - Necesita traducción +translation_of: Web/API/HTMLShadowElement +--- +<div>{{APIRef("Web Components")}}{{obsolete_header}}</div> + +<p>The <code><strong>HTMLShadowElement</strong></code> interface represents a {{HTMLElement("shadow")}} HTML Element, which is used in <a href="/en-US/docs/Web/Web_Components/Shadow_DOM">Shadow DOM</a>.</p> + +<p>{{InheritanceDiagram(600, 120)}}</p> + +<h2 id="Properties">Properties</h2> + +<p><em>This interface inherits the properties of {{domxref("HTMLElement")}}.</em></p> + +<h2 id="Methods">Methods</h2> + +<p><em>This interface inherits the methods of {{domxref("HTMLElement")}}.</em></p> + +<dl> + <dt>{{domxref("HTMLShadowElement.getDistributedNodes()")}}</dt> + <dd>Returns a static {{domxref("NodeList")}} of the {{glossary("distributed nodes")}} associated with this <code><shadow></code> element. </dd> +</dl> + +<h2 id="Specifications">Specifications</h2> + +<table class="spec-table standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('Shadow DOM', '#the-shadow-element', 'shadow')}}</td> + <td>{{Spec2('Shadow DOM')}}</td> + <td>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 (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>35</td> + <td>{{CompatGeckoDesktop("28")}}<sup>[1]</sup></td> + <td>{{CompatNo}}</td> + <td>26</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>{{domxref("HTMLShadowElement.getDistributedNodes", "getDistributedNodes()")}}</td> + <td>35</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>26</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>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>37</td> + <td>{{CompatGeckoMobile("28")}}<sup>[1]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>{{domxref("HTMLShadowElement.getDistributedNodes", "getDistributedNodes()")}}</td> + <td>37</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] If Shadow DOM is not enabled in Firefox, <shadow> elements will behave like {{domxref("HTMLUnknownElement")}}. Shadow DOM was first implemented in Firefox 28 and is behind a preference, <code>dom.webcomponents.enabled</code>, which is disabled by default.</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>The {{HTMLElement("shadow")}} HTML element, implementing this interface.</li> + <li><a href="/en-US/docs/Web/Web_Components/Shadow_DOM">Shadow DOM</a></li> +</ul> diff --git a/files/es/web/api/htmlstyleelement/index.html b/files/es/web/api/htmlstyleelement/index.html new file mode 100644 index 0000000000..33ffecb551 --- /dev/null +++ b/files/es/web/api/htmlstyleelement/index.html @@ -0,0 +1,125 @@ +--- +title: HTMLStyleElement +slug: Web/API/HTMLStyleElement +tags: + - DOM + - Referencia_DOM_de_Gecko + - Todas_las_Categorías + - para_revisar +translation_of: Web/API/HTMLStyleElement +--- +<div> +<div>{{APIRef("HTML DOM")}}</div> +</div> + +<h3 id="Notas" name="Notas">Notas</h3> + +<p>Vea las siguientes páginas para información sobre alguno de los objetos utilizados para manipular propiedades CSS especificadas utilizando el DOM:</p> + +<ul> + <li><a href="/Es/DOM/Element.style" title="es/DOM/element.style">Objeto DOM element.style</a></li> + <li><a href="/Es/DOM/Stylesheet" title="es/DOM/stylesheet">Objeto DOM stylesheet</a></li> + <li><a href="/Es/DOM/CssRule" title="es/DOM/cssRule">Objeto DOM cssRule</a></li> + <li><a href="/Es/DOM/CSS" title="es/DOM/CSS">Lista de Propiedades DOM CSS</a></li> +</ul> + +<h3 id="Material_que_se_mover.C3.A1_a_otras_p.C3.A1ginas" name="Material_que_se_mover.C3.A1_a_otras_p.C3.A1ginas">Material que se moverá a otras páginas</h3> + +<p>El objeto básico <code>style</code>, presenta los estilos definidos para el DOM en su especificación de nivel 2. Los estilos se definen mediante <code>las interfaces StyleSheet </code>y <code>CSSStyleSheet</code>. Estas interfaces contienen miembros tales como <code>insertRule</code>, <code>selectorText</code>, y <code>parentStyleSheet</code> que permiten acceder y manipular las reglas de estilo individuales de que se compone una hoja de estilos CSS.</p> + +<p>Para obtener los objetos <code>style </code>de un <code>document</code>, podemos usar la propiedad <code>document.styleSheets</code> y llegar a los distintos objetos por su índice (por ejemplo: <code>document.styleSheets{{ mediawiki.external(0) }}</code> es la primer stylesheet definida en el documento, etc.). Aunque hay varias formas y sintaxis para expresar una stylsheet para un documento, Netscape implementa exclusivamente, CSS, de manera que el objeto <code>style </code>obtenido por este método, es a la vez StyleSheet y CSSStyleSheet.</p> + +<pre class="eval">var ss = document.styleSheets[1]; +ss.cssRules[0].style.backgroundColor="blue"; +</pre> + +<p>La lista de propiedades disponibles en el DOM se encuentra en la página: <a href="/Es/DOM/CSS" title="es/DOM/CSS">DOM CSS Properties List</a>.</p> + +<p>El elemento propiedad <a href="/es/DOM/style" title="es/DOM/style">style</a> puede ser usado también para leer o establecer el estilo de un elemento. Sin embargo, esta propiedad solo devuelve atributos de estilo que han sido establecidos in-line (por ejemplo: <td style="background-color: lightblue"> devuelve la cadena "background-color: lightblue" o directamente para ese elemento usando element.style.propertyName, aún si hay otros estilos definidos para ese elemento en un stylesheet).</p> + +<p>De igual manera, cuando establecemos esa propiedad en un elemento, sobreescribimos y borramos cualquier estilo que hubiera sido fijado en alguna otra parte para la propiedad particular de ese elemento que estamos estableciendo. Por ejemplo, estableciendo la propiedad border sobreescribimos cualquier asignación que se establezca en la sección principal o en una hoja de estilo externa, sobre la propiedad border del elemento. Sin embargo, esto no afectará ninguna otra declaración de propiedad que se haga para el estilo del elemento, tales como padding o margin o font-size, por ejemplo.</p> + +<p>Para cambiar el estilo de un elemento en particular, podemos adaptar el siguiente ejemplo para el elemento al que quieres cambiar su estilo/s.</p> + +<pre><html> +<head> +<title>ejemplo simple de estilo</title> + +<script type="text/javascript"> + +function alterStyle(elem) { + elem.style.background = 'green'; +} + +function resetStyle(elemId) { + elem = document.getElementById(elemId); + elem.style.background = 'white'; +} +</script> + +<style type="text/css"> +#p1 { + border: solid blue 2px; +} +</style> +</head> + +<body> + +<!-- pasar la referencia al objeto del elemento, como parámetro 'this'. --> +<p id="p1" onclick="alterStyle(this)";> + Haz clic aquí para cambiar el color de fondo. </p> + +<!-- pasar el identificador 'pl' de otro elemento a modificar. --> +<button onclick="resetStyle('p1');">Volver al color de fondo original</button> + +</body> +</html> +</pre> + +<p>El método <code>getComputedStyle()</code> en el objeto <code>document.defaultView</code> devuelve todos los estilos que han sido asignados al elemento. Para una explicación del uso de este método, consulta el capítulo de ejemplos en: <a href="/en/Gecko_DOM_Reference/Examples#Example_6:_getComputedStyle" title="en/Gecko_DOM_Reference/Examples#Example_6:_getComputedStyle">Example 6: getComputedStyle</a> (en).</p> + +<h4 id="El_objeto_estilo_.28style.29_de_DOM" name="El_objeto_estilo_.28style.29_de_DOM">El objeto estilo (<code>style</code>) de DOM</h4> + +<p>El objeto <code>style</code> representa una sentencia de estilo individual. Al contrario de las reglas individuales disponibles en la colección: <code><a href="/Es/DOM/Document.styleSheets" title="es/DOM/document.styleSheets">document.styleSheets</a></code>, se accede al objeto style a partir del <code>document</code> o desde el elemento para el cual se aplica el estilo. Representa pues, el estilo <em>in-line</em> de ese elemento.</p> + +<p>Más importante que los dos procedimientos que señalamos aquí, es el uso del objeto <code>style </code>para establecer las propiedades de un elemento:</p> + +<pre><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> +<html> + <head> + <title>Ejemplo de la Propiedad style</title> + <link rel="StyleSheet" href="example.css" type="text/css"> + <script type="text/javascript"> + function stilo() + { + document.getElementById("d").style.color = "orange"; + } + </script> + </head> + + <body> + <div id="d" class="thunder">Trueno</div> + <button onclick="stilo()">ss</button> + </body> +</html> +</pre> + +<p>Los atributos <strong>media </strong>y <strong>type </strong>de style pueden o no estar presentes. Ten en cuenta que también puedes cambiar el estilo de un elemento haciendo una referencia a él y luego usando el método <code><a href="/Es/DOM/Element.setAttribute" title="es/DOM/element.setAttribute">setAttribute</a></code> para especificar la propiedad CSS y su valor.</p> + +<pre>var el = document.getElementById("some-element"); +el.setAttribute("style", "background-color:darkblue;"); +</pre> + +<p>Ten presente, si embargo, que el método <code>setAttribute </code>eliminará cualquier otra propiedad que haya podido ser definida en el estilo del objeto. Si el elemento some-element arriba, tenia un atributo de estilo in-line como <code>style="font-size: 18px"</code>, ese valor habrá sido eliminado por el uso de <code>setAttribute</code>.</p> + +<h5 id="Propiedades" name="Propiedades">Propiedades</h5> + +<dl> + <dt><a href="/Es/DOM/Style.media" title="es/DOM/style.media">style.media</a> </dt> + <dd>Especifica el destino intencionado de la información de estilo</dd> + <dt><a href="/Es/DOM/Style.type" title="es/DOM/style.type">style.type</a> </dt> + <dd>Devuelve el tipo de estilo que esta siendo aplicado por esta declaración.</dd> +</dl> + +<p>{{ languages( { "en": "en/DOM/style", "fr": "fr/DOM/style", "pl": "pl/DOM/style" } ) }}</p> diff --git a/files/es/web/api/htmltableelement/align/index.html b/files/es/web/api/htmltableelement/align/index.html new file mode 100644 index 0000000000..de10e6cbc6 --- /dev/null +++ b/files/es/web/api/htmltableelement/align/index.html @@ -0,0 +1,40 @@ +--- +title: HTMLTableElement.align +slug: Web/API/HTMLTableElement/align +translation_of: Web/API/HTMLTableElement/align +--- +<div> +<div>{{APIRef("HTML DOM")}}{{deprecated_header()}}</div> +</div> + +<p>La propiedad <strong><code>HTMLTableElement.align</code></strong> representa la alineación de la tabla.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox"><em>HTMLTableElement</em>.align =<em>alignment</em>; +var<em>alignment</em> =<em>HTMLTableElement</em>.align;</pre> + +<h3 id="Parameters" name="Parameters">Parámetros</h3> + +<dl> + <dt><code>alignment</code> {{deprecatedGeneric('inline','HTML4')}}</dt> + <dd><code>alignment</code> es una cadena con uno de los siguientes valores: + <ul> + <li>left</li> + <li>center</li> + <li>right</li> + </ul> + </dd> +</dl> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre class="brush:js">// Establecer la alineación de una tabla +var t = document.getElementById('TableA'); +t.align = 'center';</pre> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<ul> + <li>Especificación W3C DOM 2 HTML <a class="external" href="http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-23180977"><em>HTMLTableElement</em> .align</a>.</li> +</ul> diff --git a/files/es/web/api/htmltableelement/index.html b/files/es/web/api/htmltableelement/index.html new file mode 100644 index 0000000000..56ef6ad502 --- /dev/null +++ b/files/es/web/api/htmltableelement/index.html @@ -0,0 +1,72 @@ +--- +title: table +slug: Web/API/HTMLTableElement +tags: + - DOM + - Referencia_DOM_de_Gecko + - Todas_las_Categorías + - para_revisar +translation_of: Web/API/HTMLTableElement +--- +<div>{{ ApiRef() }}</div> + +<h2 id="Interfaz_del_elemento_tabla_HTML" name="Interfaz_del_elemento_tabla_HTML">Interfaz del elemento tabla HTML</h2> + +<p>Los objetos <code>table</code> revelan la interfaz del <a class="external" href="http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-64060425"><code>HTMLTableElement</code></a> la cual posee métodos y propiedades especiales (más allá del interfaz regular del objeto del <a href="/es/docs/DOM/element">elemento</a> que también tienen disponibles mediante herencia) para manipular la vista y presentación de tablas en HTML.</p> + +<h2 id="Propiedades" name="Propiedades">Propiedades</h2> + +<dl> + <dt><a href="/es/docs/DOM/table.caption">table.caption</a></dt> + <dd><strong>caption</strong> devuelve la leyenda de la tabla.</dd> + <dt><a href="/es/docs/DOM/table.tHead">table.tHead</a></dt> + <dd><strong>tHead</strong> devuelve el encabezado de la tabla.</dd> + <dt><a href="/es/docs/DOM/table.tFoot">table.tFoot</a></dt> + <dd><strong>tFoot</strong> devuelve el pie de la tabla.</dd> + <dt><a href="/es/docs/DOM/table.rows">table.rows</a></dt> + <dd><strong>rows</strong> devuelve las filas de la tabla.</dd> + <dt><a href="/es/docs/DOM/table.tBodies">table.tBodies</a></dt> + <dd><strong>tBodies</strong> devuelve los cuerpos de la tabla.</dd> +</dl> + +<dl> + <dt><a href="/es/docs/DOM/table.align">table.align</a> {{Deprecated_inline}}</dt> + <dd><strong>align</strong> da/define el alineamiento de la tabla.</dd> + <dt><a href="/es/docs/DOM/table.bgColor">table.bgColor</a>{{Deprecated_inline}}</dt> + <dd><strong>bgColor</strong> da/define el color de fondo de la tabla.</dd> + <dt><a href="/es/docs/DOM/table.border">table.border</a> {{Deprecated_inline()}}</dt> + <dd><strong>border</strong> da/define el borde de la tabla.</dd> + <dt><a href="/es/docs/DOM/table.cellPadding">table.cellPadding</a></dt> + <dd><strong>cellPadding</strong> da/define el relleno interno de las celdas.</dd> + <dt><a href="/es/docs/DOM/table.cellSpacing">table.cellSpacing</a></dt> + <dd><strong>cellSpacing</strong> da/define el espacio entre celdas.</dd> + <dt><a href="/es/docs/DOM/table.frame">table.frame</a></dt> + <dd><strong>frame</strong> especifica que lados de la tabla tienen borde.</dd> + <dt><a href="/es/docs/DOM/table.rules">table.rules</a></dt> + <dd><strong>rules</strong> especifica cuales de los bordes internos son visibles.</dd> + <dt><a href="/es/docs/DOM/table.summary">table.summary</a></dt> + <dd><strong>summary</strong> da/define el resumen de la tabla.</dd> + <dt><a href="/es/docs/DOM/table.width">table.width</a></dt> + <dd><strong>width</strong> da/define el ancho de la tabla.</dd> +</dl> + +<h2 id="M.C3.A9todos" name="M.C3.A9todos">Métodos</h2> + +<dl> + <dt><a href="/es/docs/DOM/table.createTHead">table.createTHead</a></dt> + <dd><strong>createTHead</strong> crea el encabezado de la tabla.</dd> + <dt><a href="/es/docs/DOM/table.deleteTHead">table.deleteTHead</a></dt> + <dd><strong>deleteTHead</strong> elimina el encabezado de la tabla.</dd> + <dt><a href="/es/docs/DOM/table.createTFoot">table.createTFoot</a></dt> + <dd><strong>createTFoot</strong> crea el pie de tabla.</dd> + <dt><a href="/es/docs/DOM/table.deleteTFoot">table.deleteTFoot</a></dt> + <dd><strong>deleteTFoot</strong> elimina el pie de tabla.</dd> + <dt><a href="/es/docs/DOM/table.createCaption">table.createCaption</a></dt> + <dd><strong>createCaption</strong> crea una nueva leyenda para la tabla.</dd> + <dt><a href="/es/docs/DOM/table.deleteCaption">table.deleteCaption</a></dt> + <dd><strong>deleteCaption</strong> elimina la leyenda de tabla.</dd> + <dt><a href="/es/docs/DOM/table.insertRow">table.insertRow</a></dt> + <dd><strong>insertRow</strong> inserta una nueva fila.</dd> + <dt><a href="/es/docs/DOM/table.deleteRow">table.deleteRow</a></dt> + <dd><strong>deleteRow</strong> elimina una fila.</dd> +</dl> diff --git a/files/es/web/api/htmltableelement/insertrow/index.html b/files/es/web/api/htmltableelement/insertrow/index.html new file mode 100644 index 0000000000..a3e49f3ac0 --- /dev/null +++ b/files/es/web/api/htmltableelement/insertrow/index.html @@ -0,0 +1,144 @@ +--- +title: HTMLTableElement.insertRow() +slug: Web/API/HTMLTableElement/insertRow +translation_of: Web/API/HTMLTableElement/insertRow +--- +<div> +<div> +<div>{{APIRef("HTML DOM")}}</div> +</div> +</div> + +<p>El método <strong><code>HTMLTableElement.insertRow()</code></strong> inserta una nueva fila en la tabla.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var <em>row</em> = <em>HTMLTableElement</em>.insertRow(<em>optional index = -1</em>);</pre> + +<ul> + <li><a href="/en-US/docs/DOM/HTMLTableElement"><code>HTMLTableElement</code></a> es una referencia a un elemento table HTML.</li> + <li><code>index</code> es el índice de fila de la nueva fila.</li> + <li><code>row</code> queda asignada a una referencia a la nueva fila. Una referencia a un <a href="/en-US/docs/Web/API/HTMLTableRowElement">HTMLTableRowElement</a>.<br> + Si <code>index</code> es -1 o igual al número de filas, la nueva fila es añadida detrás de la última. Si <code>index</code> es mayor que el números defilas, es lanzada una excepción IndexSizeError. Si index se omite, se asume por defecto -1.</li> + <li>Si una tabla tiene múltiples elementos <code>tbody</code>, por defecto la nueva fila es insertada en el último <code>tbody</code>. Para insertar una fila dentro de un <code>tbody</code> especifico pued hacer:<br> + <code>var <em>specific_tbody</em>=document.getElementById(<em>tbody_id</em>);<br> + var <em>row</em>=specific_tbody.insertRow(<em>index</em>)</code></li> +</ul> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush:html"><table id="TableA"> +<tr> +<td>Antigua fila superior</td> +</tr> +</table> +<script type="text/javascript"> + +function addRow(tableID) { + // Obtiene una referencia a la tabla + var tableRef = document.getElementById(tableID); + + // Inserta una fila en la tabla, en el índice 0 + var newRow = tableRef.insertRow(0); + + // Inserta una celda en la fila, en el índice 0 + var newCell = newRow.insertCell(0); + + // Añade un nodo de texto a la celda + var newText = document.createTextNode('Nueva fila superior'); + newCell.appendChild(newText); +} + +// Llama a addRow() con el ID de la tabla +addRow('TableA'); + +</script></pre> + +<p>Para ser válida en un documento HTML, una TR debe contener al menos un elemento TD.</p> + +<p>Observese que <code>insertRow</code> inserta la fila diréctamente en la tabla y retorna una referencia a la nueva fila. La fila no necesita ser añadida separadamente (p.e. con <code><a href="/es/docs/DOM/document.appendChild">document.appendChild()</a></code>) tal sería el caso si se usase <code><a href="/en-US/docs/DOM/document.createElement">document.createElement()</a></code> para crear el nuevo elemento TR.</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th>Especificación</th> + <th>Estado</th> + <th>Observaciones</th> + </tr> + <tr> + <td>{{SpecName("HTML WHATWG", "tables.html#dom-table-insertrow", "HTMLTableElement.insertRow()")}}</td> + <td>{{Spec2("HTML WHATWG")}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName("DOM2 HTML", "html.html#ID-93995626", "HTMLTableElement.insertRow()")}}</td> + <td>{{Spec2("DOM2 HTML")}}</td> + <td>Especificó con más detalle dónde se inserta la fila.</td> + </tr> + <tr> + <td>{{SpecName("DOM1", "level-one-html.html#ID-39872903", "HTMLTableElement.insertRow()")}}</td> + <td>{{Spec2("DOM1")}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Prestación</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>4</td> + <td>3<sup>[1]</sup></td> + <td>5.5</td> + <td>10</td> + <td>4</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Prestación</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] A partir deGecko 20.0 {{geckoRelease("20.0")}} el argumento index se estableció como opcional y con valor por defecto -1 según la especificación HTML.</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("HTMLTableRowElement.insertCell()")}}</li> +</ul> diff --git a/files/es/web/api/idbcursor/continue/index.html b/files/es/web/api/idbcursor/continue/index.html new file mode 100644 index 0000000000..90679783b1 --- /dev/null +++ b/files/es/web/api/idbcursor/continue/index.html @@ -0,0 +1,194 @@ +--- +title: IDBCursor.continue() +slug: Web/API/IDBCursor/continue +tags: + - API + - Almacen + - Basededatos + - Continuar + - CursorIDB + - IndexadoIDB + - Referencia + - metodo +translation_of: Web/API/IDBCursor/continue +--- +<p>{{APIRef("IndexedDB")}}</p> + +<p><strong><code>El siguiente()</code></strong> método de la {{domxref("IDBCursor")}} interfaz, avanza el cursor hacia la siguiente posición a lo largo de su dirección, para el elemento cuya tecla marque la opción de una tecla parámetro. si ninguna tecla es especificada, el cursor avanzará hacia la siguiente posición, bazado en su dirección actual.</p> + +<p>{{AvailableInWorkers}}</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="brush: js">cursor.continue(<em>optionalKey</em>);</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><em>Tecla opcional</em></dt> + <dd>La tecla para posisionar al cursor en.</dd> +</dl> + +<h3 id="Excepciones"><span style="line-height: 1.5;">Excepciones</span></h3> + +<p>Este método puede plantear un{{domxref("DOMException")}} con una {{domxref("DOMError")}} de uno de los siguientes tipos:</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Excepción</th> + <th scope="col">Descripción</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>TransactionInactiveError</code></td> + <td>Esta transacción en el Cursor IDB está inactiva.</td> + </tr> + <tr> + <td><code>DataError</code></td> + <td> + <p>El parámetro de una tecla podría tener una de las siguientes condiciones:</p> + + <ul> + <li>La tecla no es una tecla valida.</li> + <li>La tecla está más atrás o en el mismo sitio que la posición del cursor y además la dirección del cursor es la siguiente o la única siguiente.</li> + <li>La tecla está más adelante o en el mismo sitio que la posición del cursor y además la dirección del cursor es previa o la única previa.</li> + </ul> + </td> + </tr> + <tr> + <td><code>InvalidStateError</code></td> + <td>El cursor está siendo reiterado o se ha reiterado mas allá de su final.<br> + </td> + </tr> + </tbody> +</table> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>En este simple fragmento nosotros creamos una transacción, recuperar un objeto del almacen, despues usamos un cursor para interactuar a traves de todos los registros en almacen de objetos. El cursor no requiere que nosotros seleccionemos los datos basados en una tecla; podemos tomarlo todo. También es importante resaltar que en cada interacción de la cadena, puedes tomar datos desde el registro actual debajo del objeto del cursor usando<code> </code><code style="font-style: normal; line-height: 1.5;">cursor.value.foo</code><span style="line-height: 1.5;">. Para dar un ejemplo completo, puedes mirar nuestra <a href="https://github.com/mdn/IDBcursor-example/">IDBCursor example</a></span><span style="line-height: 1.5;"> (</span><a href="http://mdn.github.io/IDBcursor-example/" style="line-height: 1.5;">view example live</a><span style="line-height: 1.5;">.)</span></p> + +<pre style="font-size: 14px;"><span style="line-height: 1.5;">function displayData() {</span> + var transaction = db.transaction(['rushAlbumList'], "readonly"); + var objectStore = transaction.objectStore('rushAlbumList'); + + objectStore.openCursor().onsuccess = function(event) { + var cursor = event.target.result; + if(cursor) { + var listItem = document.createElement('li'); + listItem.innerHTML = cursor.value.albumTitle + ', ' + cursor.value.year; + list.appendChild(listItem); + + cursor.continue(); + } else { + console.log('Entries all displayed.'); + } + }; +};</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Estado</th> + <th scope="col">Comentarios</th> + </tr> + <tr> + <td>{{SpecName('IndexedDB', '#widl-IDBCursor-continue-void-any-key', 'continue()')}}</td> + <td>{{Spec2('IndexedDB')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">Compatibilidad del navegador</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Características</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>23{{property_prefix("webkit")}}<br> + 24</td> + <td>10 {{property_prefix("moz")}}<br> + {{CompatGeckoDesktop("16.0")}}</td> + <td>10, parcial</td> + <td>15</td> + <td>7.1</td> + </tr> + <tr> + <td>Disponible en workers</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("37.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Características</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>4.4</td> + <td>{{CompatGeckoMobile("22.0")}}</td> + <td>1.0.1</td> + <td>10</td> + <td>22</td> + <td>8</td> + </tr> + <tr> + <td>Disponible en workers</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("37.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div class="warning"> +<p>Ten cuidado en Chrome ya que todavía están siendo implementado las antiguas especificaciones con las nuevas. Del mismo modo que todavía tiene la propiedad <code>webkitIndexedDB</code> aun si el<code> indexedDB</code> sin prefijo esta presente.</p> +</div> + +<h2 id="Te_puede_interesar">Te puede interesar</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB">Using IndexedDB</a></li> + <li>Starting transactions: {{domxref("IDBDatabase")}}</li> + <li>Using transactions: {{domxref("IDBTransaction")}}</li> + <li>Setting a range of keys: {{domxref("IDBKeyRange")}}</li> + <li>Retrieving and making changes to your data: {{domxref("IDBObjectStore")}}</li> + <li>Using cursors: {{domxref("IDBCursor")}}</li> + <li>Reference example: <a class="external" href="https://github.com/mdn/to-do-notifications/tree/gh-pages">To-do Notifications</a> (<a class="external" href="http://mdn.github.io/to-do-notifications/">view example live</a>.)</li> +</ul> + +<p> </p> diff --git a/files/es/web/api/idbcursor/index.html b/files/es/web/api/idbcursor/index.html new file mode 100644 index 0000000000..841bf6f9be --- /dev/null +++ b/files/es/web/api/idbcursor/index.html @@ -0,0 +1,194 @@ +--- +title: IDBCursor +slug: Web/API/IDBCursor +tags: + - API + - Database + - IDBCursor + - IndexedDB + - Interface + - NeedsTranslation + - Reference + - Référence(2) + - Storage + - TopicStub +translation_of: Web/API/IDBCursor +--- +<p>{{APIRef("IndexedDB")}}</p> + +<p>La interfaz <strong><code>IDBCursor</code></strong> de la <a href="/en-US/docs/IndexedDB">IndexedDB API</a> representa un <a href="/en-US/docs/IndexedDB/Basic_Concepts_Behind_IndexedDB#gloss_cursor">cursor</a> para atravesar o iterar varios registros de una base de datos.</p> + +<p>El cursor tiene una fuente que indica el índice o el almacén de objetos sobre el que se está iterando. Tiene una posición dentro del rango y se mueve en una dirección que aumenta o disminuye en el orden de las Keys de registro. El cursor permite a una aplicación procesar asincrónicamente todos los registros del rango del cursor.</p> + +<p>Puede tener un número ilimitado de cursores al mismo tiempo. Siempre se obtiene el mismo objeto <code>IDBCursor</code> que representa un cursor determinado. Las operaciones se realizan en el índice subyacente o en el almacén de objetos.</p> + +<p>{{AvailableInWorkers}}</p> + +<h2 id="Methods">Methods</h2> + +<dl> + <dt>{{domxref("IDBCursor.advance()")}}</dt> + <dd>Establece el número de veces que un cursor debe mover su posición hacia adelante.</dd> + <dt>{{domxref("IDBCursor.continue()")}}</dt> + <dd>Avanza el cursor a la siguiente posición a lo largo de su dirección, hasta el elemento cuya <code>key</code> coincide con el parámetro clave opcional.</dd> +</dl> + +<dl> + <dt>{{domxref("IDBCursor.delete()")}}</dt> + <dd>Devuelve un objeto {{domxref("IDBRequest")}} y, en un hilo separado, elimina el registro en la posición del cursor, sin cambiar la posición del cursor. Esto se puede utilizar para borrar registros específicos.</dd> + <dd>{{domxref("IDBCursor.update()")}}</dd> + <dd>Devuelve un objeto {{domxref("IDBRequest")}} y, en un hilo separado, actualiza el valor en la posición actual del cursor en el almacén de objetos. Esto se puede utilizar para actualizar registros específicos.</dd> +</dl> + +<h2 id="Propiedades">Propiedades</h2> + +<dl> + <dt>{{domxref("IDBCursor.source")}} {{readonlyInline}}</dt> + <dd>Devuelve {{domxref("IDBObjectStore")}} o {{domxref("IDBIndex")}}} que el cursor está iterando. Esta función nunca devuelve nulo o lanza una excepción, incluso si el cursor está siendo iterado, ha iterado más allá de su final, o su transacción no está activa.</dd> + <dt>{{domxref("IDBCursor.direction")}} {{readonlyInline}}</dt> + <dd></dd> + <dd>Devuelve la dirección de desplazamiento del cursor. Ver <a href="#const_next">Constants</a> para valores posibles.</dd> + <dd>{{domxref("IDBCursor.key")}} {{readonlyInline}}</dd> + <dd>Devuelve la <code>key</code> del registro en la posición del cursor. Si el cursor está fuera de su rango, se fija en <code>undefined</code>. La <code>key</code> del cursor puede ser de cualquier tipo de datos.</dd> + <dd>{{domxref("IDBCursor.primaryKey")}} {{readonlyInline}}</dd> + <dd>Devuelve la <code>key</code> primaria efectiva actual del cursor. Si el cursor está siendo iterado o ha iterado fuera de su rango, se fija en <code>undefined</code>. La <code>key</code> principal del cursor puede ser cualquier tipo de datos.</dd> +</dl> + +<h2 id="Constants" name="Constants">Constants</h2> + +<div>{{ deprecated_header(13) }}</div> + +<div class="warning"> +<p>These constants are no longer available — they were removed in Gecko 25. You should use the string constants directly instead. ({{ bug(891944) }})</p> +</div> + +<ul> + <li><code>NEXT </code>: <code>"next"</code> : The cursor shows all records, including duplicates. It starts at the lower bound of the key range and moves upwards (monotonically increasing in the order of keys).</li> + <li><code>NEXTUNIQUE</code> : <code>"nextunique"</code> : The cursor shows all records, excluding duplicates. If multiple records exist with the same key, only the first one iterated is retrieved. It starts at the lower bound of the key range and moves upwards.</li> + <li><code>PREV </code>: <code>"prev"</code> : The cursor shows all records, including duplicates. It starts at the upper bound of the key range and moves downwards (monotonically decreasing in the order of keys).</li> + <li><code>PREVUNIQUE </code>: <code>"prevunique"</code> : The cursor shows all records, excluding duplicates. If multiple records exist with the same key, only the first one iterated is retrieved. It starts at the upper bound of the key range and moves downwards.</li> +</ul> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>En este simple fragmento creamos una transacción, recuperamos un almacén de objetos y usamos un cursor para iterar todos los registros del almacén de objetos. El cursor no nos obliga a seleccionar los datos en base a una <code>key</code>; podemos simplemente cogerlos todos. También tenga en cuenta que en cada iteración del bucle, puede tomar datos del registro actual bajo el objeto del cursor utilizando <code style="font-style: normal; line-height: 1.5;">cursor.value.foo</code>. Para un ejemplo completo de funcionamiento, vea nuestro <span style="line-height: 1.5;"><a href="https://github.com/mdn/IDBcursor-example/">IDBCursor example</a></span><span style="line-height: 1.5;"> (</span><a href="http://mdn.github.io/IDBcursor-example/" style="line-height: 1.5;">view example live</a><span style="line-height: 1.5;">.)</span></p> + +<pre class="brush: js"><span style="line-height: 1.5;">function displayData() {</span> + var transaction = db.transaction(['rushAlbumList'], "readonly"); + var objectStore = transaction.objectStore('rushAlbumList'); + + objectStore.openCursor().onsuccess = function(event) { + var cursor = event.target.result; + if(cursor) { + var listItem = document.createElement('li'); + listItem.innerHTML = cursor.value.albumTitle + ', ' + cursor.value.year; + list.appendChild(listItem); + + cursor.continue(); + } else { + console.log('Entries all displayed.'); + } + }; +}</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('IndexedDB', '#idl-def-IDBCursor', 'cursor')}}</td> + <td>{{Spec2('IndexedDB')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="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{{property_prefix("webkit")}}<br> + 24 [1]</td> + <td>10 {{property_prefix("moz")}}<br> + {{CompatGeckoDesktop("16.0")}}</td> + <td>10, partial</td> + <td>15</td> + <td>7.1</td> + </tr> + <tr> + <td>Available in workers</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("37.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</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</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>4.4</td> + <td>{{CompatGeckoMobile("22.0")}}</td> + <td>1.0.1</td> + <td>10</td> + <td>22</td> + <td>8</td> + </tr> + <tr> + <td>Available in workers</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("37.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1]Be careful in Chrome as it still implements the old specification along with the new one. Similarly it still has the prefixed <code>webkitIndexedDB</code> property even if the unprefixed <code>indexedDB</code> is present.</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB">Using IndexedDB</a></li> + <li>Starting transactions: {{domxref("IDBDatabase")}}</li> + <li>Using transactions: {{domxref("IDBTransaction")}}</li> + <li>Setting a range of keys: {{domxref("IDBKeyRange")}}</li> + <li>Retrieving and making changes to your data: {{domxref("IDBObjectStore")}}</li> + <li>Using cursors: {{domxref("IDBCursor")}}</li> + <li>Reference example: <a class="external" href="https://github.com/mdn/to-do-notifications/tree/gh-pages">To-do Notifications</a> (<a class="external" href="http://mdn.github.io/to-do-notifications/">view example live</a>.)</li> +</ul> diff --git a/files/es/web/api/idbdatabase/index.html b/files/es/web/api/idbdatabase/index.html new file mode 100644 index 0000000000..c16635051b --- /dev/null +++ b/files/es/web/api/idbdatabase/index.html @@ -0,0 +1,258 @@ +--- +title: IDBDatabase +slug: Web/API/IDBDatabase +tags: + - API + - Database + - IDBDatabase + - IndexedDB + - Interface + - NeedsTranslation + - Reference + - Storage + - TopicStub + - accessing data + - asynchronous access + - transactions +translation_of: Web/API/IDBDatabase +--- +<p>{{APIRef("IndexedDB")}}</p> + +<div> +<p>The <strong><code>IDBDatabase</code></strong> interface of the IndexedDB API provides a <a href="/en-US/docs/IndexedDB#database_connection">connection to a database</a>; you can use an <code>IDBDatabase</code> object to open a <a href="/en-US/docs/IndexedDB#gloss_transaction">transaction</a> on your database then create, manipulate, and delete objects (data) in that database. The interface provides the only way to get and manage versions of the database.</p> + +<p>{{AvailableInWorkers}}</p> +</div> + +<div class="note"> +<p><strong>Note</strong>: Everything you do in IndexedDB always happens in the context of a <a href="/en-US/docs/IndexedDB/Basic_Concepts_Behind_IndexedDB#gloss_transaction">transaction</a>, representing interactions with data in the database. All objects in IndexedDB — including object stores, indexes, and cursors — are tied to a particular transaction. Thus, you cannot execute commands, access data, or open anything outside of a transaction.</p> +</div> + +<h2 id="Methods">Methods</h2> + +<p>Inherits from: <a href="/en-US/docs/DOM/EventTarget">EventTarget</a></p> + +<dl> + <dt>{{domxref("IDBDatabase.close()")}}</dt> + <dd>Returns immediately and closes the connection to a database in a separate thread.</dd> + <dt>{{domxref("IDBDatabase.createObjectStore()")}}</dt> + <dd>Creates and returns a new object store or index.</dd> + <dt>{{domxref("IDBDatabase.deleteObjectStore()")}}</dt> + <dd>Destroys the object store with the given name in the connected database, along with any indexes that reference it.</dd> + <dt>{{domxref("IDBDatabase.transaction()")}}</dt> + <dd>Immediately returns a transaction object ({{domxref("IDBTransaction")}}) containing the {{domxref("IDBTransaction.objectStore")}} method, which you can use to access your object store. Runs in a separate thread.</dd> +</dl> + +<h2 id="Properties">Properties</h2> + +<dl> + <dt>{{domxref("IDBDatabase.name")}} {{readonlyInline}}</dt> + <dd>A {{ domxref("DOMString") }} that contains the name of the connected database.</dd> + <dt>{{domxref("IDBDatabase.version")}} {{readonlyInline}}</dt> + <dd>A <a href="/en-US/docs/NSPR_API_Reference/Long_Long_(64-bit)_Integers">64-bit integer</a> that contains the version of the connected database. When a database is first created, this attribute is an empty string.</dd> + <dt>{{domxref("IDBDatabase.objectStoreNames")}} {{readonlyInline}}</dt> + <dd>A {{ domxref("DOMStringList") }} that contains a list of the names of the <a href="/en-US/docs/IndexedDB#gloss_object_store">object stores</a> currently in the connected database.</dd> +</dl> + +<h3 id="Event_handlers">Event handlers</h3> + +<dl> + <dt>{{domxref("IDBDatabase.onabort")}}</dt> + <dd>Fires when access of the database is aborted.</dd> + <dt>{{domxref("IDBDatabase.onclose")}}</dt> + <dd>Fires when the {{event("close")}} event occurs; this happens when the database is unexpectedly closed, such as during application shutdown.</dd> + <dt>{{domxref("IDBDatabase.onerror")}}</dt> + <dd>Fires when access to the database fails.</dd> + <dt>{{domxref("IDBDatabase.onversionchange")}}</dt> + <dd> + <p>Fires when a database structure change ({{domxref("IDBOpenDBRequest.onupgradeneeded")}} event or<code> </code>{{domxref("IDBFactory.deleteDatabase()")}} was requested elsewhere (most probably in another window/tab on the same computer). This is different from the version change transaction (see {{domxref("IDBVersionChangeEvent")}}), but it is related.</p> + </dd> +</dl> + +<h2 id="example" name="example">Example</h2> + +<p>In the following code snippet, we open a database asynchronously ({{domxref("IDBFactory")}}), handle success and error cases, and create a new object store in the case that an upgrade is needed ({{ domxref("IDBdatabase") }}). For a complete working example, see our <a href="https://github.com/mdn/to-do-notifications/">To-do Notifications</a> app (<a href="http://mdn.github.io/to-do-notifications/">view example live</a>.)</p> + +<pre class="brush: js;highlight:[13,24,26,27,28,32]">// Let us open our database + var DBOpenRequest = window.indexedDB.open("toDoList", 4); + + // these two event handlers act on the IDBDatabase object, when the database is opened successfully, or not + DBOpenRequest.onerror = function(event) { + note.innerHTML += '<li>Error loading database.</li>'; + }; + + DBOpenRequest.onsuccess = function(event) { + note.innerHTML += '<li>Database initialised.</li>'; + + // store the result of opening the database in the db variable. This is used a lot later on + db = DBOpenRequest.result; + + // Run the displayData() function to populate the task list with all the to-do list data already in the IDB + displayData(); + }; + + // This event handles the event whereby a new version of the database needs to be created + // Either one has not been created before, or a new version number has been submitted via the + // window.indexedDB.open line above + + DBOpenRequest.onupgradeneeded = function(event) { + var db = event.target.result; + + db.onerror = function(event) { + note.innerHTML += '<li>Error loading database.</li>'; + }; + + // Create an objectStore for this database using IDBDatabase.createObjectStore + + var objectStore = db.createObjectStore("toDoList", { keyPath: "taskTitle" }); + + // define what data items the objectStore will contain + + objectStore.createIndex("hours", "hours", { unique: false }); + objectStore.createIndex("minutes", "minutes", { unique: false }); + objectStore.createIndex("day", "day", { unique: false }); + objectStore.createIndex("month", "month", { unique: false }); + objectStore.createIndex("year", "year", { unique: false }); + + objectStore.createIndex("notified", "notified", { unique: false }); + + note.innerHTML += '<li>Object store created.</li>'; + };</pre> + +<p>This next line opens up a transaction on the Database, then opens an object store that we can then manipulate the data inside of.</p> + +<pre class="brush: js"> var objectStore = db.transaction('toDoList').objectStore('toDoList'); </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('IndexedDB', '#idl-def-IDBDatabase', 'IDBDatabase')}}</td> + <td>{{Spec2('IndexedDB')}}</td> + <td>Initial version</td> + </tr> + <tr> + <td>{{SpecName("IndexedDB 2", "#database-interface", "IDBDatabase")}}</td> + <td>{{Spec2("IndexedDB 2")}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="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)<sup>[1]</sup></th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>23 {{property_prefix("webkit")}}<br> + 24</td> + <td>10 {{property_prefix("moz")}}<br> + {{CompatGeckoDesktop(16)}}</td> + <td>10, partial</td> + <td>15</td> + <td>7.1</td> + </tr> + <tr> + <td>Available in workers</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(37)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>{{event("close")}} event</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(50)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Android Webview</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>4.4</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile(22)}}</td> + <td>1.0.1</td> + <td>10</td> + <td>22</td> + <td>8</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Available in workers</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile(37)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>{{event("close")}} event</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile(50)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] As of Firefox 40, IndexedDB transactions have relaxed durability guarantees to increase performance (see {{Bug("1112702")}}). Previously in a <code>readwrite</code> transaction {{domxref("IDBTransaction.oncomplete")}} was fired only when all data was guaranteed to have been flushed to disk. In Firefox 40+ the <code>complete</code> event is fired after the OS has been told to write the data but potentially before that data has actually been flushed to disk. The <code>complete</code> event may thus be delivered quicker than before, however, there exists a small chance that the entire transaction will be lost if the OS crashes or there is a loss of system power before the data is flushed to disk. Since such catastrophic events are rare most consumers should not need to concern themselves further. If you must ensure durability for some reason (e.g. you're storing critical data that cannot be recomputed later) you can force a transaction to flush to disk before delivering the <code>complete</code> event by creating a transaction using the experimental (non-standard) <code>readwriteflush</code> mode (see {{domxref("IDBDatabase.transaction")}}).</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB">Using IndexedDB</a></li> + <li>Starting transactions: {{domxref("IDBDatabase")}}</li> + <li>Using transactions: {{domxref("IDBTransaction")}}</li> + <li>Setting a range of keys: {{domxref("IDBKeyRange")}}</li> + <li>Retrieving and making changes to your data: {{domxref("IDBObjectStore")}}</li> + <li>Using cursors: {{domxref("IDBCursor")}}</li> + <li>Reference example: <a class="external" href="https://github.com/mdn/to-do-notifications/tree/gh-pages">To-do Notifications</a> (<a class="external" href="http://mdn.github.io/to-do-notifications/">view example live</a>.)</li> +</ul> + +<p> </p> diff --git a/files/es/web/api/idbdatabase/transaction/index.html b/files/es/web/api/idbdatabase/transaction/index.html new file mode 100644 index 0000000000..8e8fcfedd6 --- /dev/null +++ b/files/es/web/api/idbdatabase/transaction/index.html @@ -0,0 +1,229 @@ +--- +title: IDBDatabase.transaction() +slug: Web/API/IDBDatabase/transaction +tags: + - Almacenamiento + - Base de datos + - Referencia + - metodo + - transacción +translation_of: Web/API/IDBDatabase/transaction +--- +<p>{{ APIRef("IndexedDB") }}</p> + +<div> +<p>El método <strong><code>transaction()</code></strong> <em><strong><code>[transacción]</code></strong></em> de la interfaz {{domxref("IDBDatabase")}} retorna inmediatamente un objeto de transacción<span style="line-height: 1.5;"> ({{domxref("IDBTransaction")}}) que contiene el método {{domxref("IDBTransaction.objectStore")}}, el cual puedes usar para acceder a tu almacén de objetos.</span></p> + +<p>{{AvailableInWorkers}}</p> +</div> + +<h2 id="Sintáxis">Sintáxis</h2> + +<pre class="brush: js">var transaccion = db.transaction(["toDoList"], "readwrite");</pre> + +<h3 id="Retorna">Retorna</h3> + +<p>Un objeto {{domxref("IDBTransaction")}}.</p> + +<h3 id="Excepciones">Excepciones</h3> + +<p>Éste método puede invocar una excepción {{domxref("DOMException")}} de alguno de los siguientes tipos:</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Excepción</th> + <th scope="col">Descripción</th> + </tr> + </thead> + <tbody> + <tr> + <td><code><a href="/en-US/docs/">InvalidStateError</a></code></td> + <td> + <p>El método <code>close()</code> ha sido llamado previamente en esta instancia de {{domxref("IDBDatabase")}}.</p> + </td> + </tr> + <tr> + <td><code>NotFoundError</code></td> + <td>Un almacén de objetos especificado en el parámetro <code>storeNames</code> ha sido borrado o removido.</td> + </tr> + <tr> + <td><code>TypeError</code></td> + <td>El valor para el parámetro <code>mode</code> es inválido.</td> + </tr> + <tr> + <td><code>InvalidAccessError</code></td> + <td>La función fue llamada con una lista vacía de nombres de almacenes.<br> + </td> + </tr> + </tbody> +</table> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>En este ejemplo abrimos la conexión a una base de datos, luego usamos <code>transaction()</code> para abrir una transacción en dicha base de datos. Para un ejemplo completo, vea nuestra aplicación <a href="https://github.com/mdn/to-do-notifications/" style="line-height: 1.5;">To-do Notifications</a> <span style="line-height: 1.5;">(</span><a href="http://mdn.github.io/to-do-notifications/" style="line-height: 1.5;">ver ejemplo en vivo</a><span style="line-height: 1.5;">).</span></p> + +<pre class="brush: js">var db; + +// Abrimos nuestra base de datos: +var DBOpenRequest = window.indexedDB.open("toDoList", 4); + +DBOpenRequest.onsuccess = function(event) { + note.innerHTML += '<li>Base de datos inicializada.</li>'; + + // almacenar el resultado de la apertura de la base de datos en la variable db. Esto es bastante usado más abajo: + db = DBOpenRequest.result; + + // ejecutar la función displayData() para popular la lista de tareas con los datos "to-do" que existen actualmente en la Base de Datos Indizada (IDB): + displayData(); + +}; + +// abrir una transacción lectura/escritura, lista para añadir los datos: +var transaction = db.transaction(["toDoList"], "readwrite"); + +// reportar cuando haya éxito al abrir la transacción +transaction.oncomplete = function(event) { + note.innerHTML += '<li>Transacción completa: modificación a la base de datos finalizada.</li>'; +}; + +transaction.onerror = function(event) { + note.innerHTML += '<li>Transacción no abierta debido a un error. No se permite duplicar ítems.</li>'; +}; + +// después deberías continuar y hacerle algo a esta base de datos a través del almacén de objetos: +var objectStore = transaction.objectStore("toDoList"); +// etc.</pre> + +<h2 id="Parámetros">Parámetros</h2> + +<dl> + <dt>storeNames</dt> + <dd>Son los nombres de los almacenes de objetos e índices que están en el ámbito de la nueva transacción, declarados como un arreglo de cadenas de texto. Especifíca solamente aquellos a los que necesitas acceso.<br> + Si necesitas acceder a un solo almacén, puedes especificar su nombre como una cadena. Por tanto las siguientes líneas son equivalentes:</dd> + <dd> + <pre><code class="brush:js;">var transaction = db.transaction(['my-store-name']); +var transaction = db.transaction('my-store-name');</code></pre> + </dd> + <dd>Si necesitas acceder a todos los almacenes de objetos en la base de datos, puedes usar la propiedad {{domxref("IDBDatabase.objectStoreNames")}}: + <pre><code class="brush:js;">var transaction = db.transaction(db.objectStoreNames);</code></pre> + </dd> + <dd>Pasar un arreglo vació como parámetro arrojará una excepción.</dd> + <dt>mode</dt> + <dd><em>Opcional</em>. Los tipos de acceso que pueden desempeñarse en la transacción. Las transacciones son abiertas en uno de tres modos: <code>readonly <em>[sólo lectura], </em>readwrite <em>[lectura/escritura],</em></code> y <code>readwriteflush <em>[descarga de lectura/escritura]</em></code> (no-estándar, sólo para Firefox). El modo <code>versionchange <em>[cambio de versión] </em></code>no puede ser especificado aquí. Si no provees un parámetro, el modo predeterminado será <code>readonly <em>[sólo lectura]</em></code>. Para evitar ralentizar las cosas, no abras una transacción <code>readwrite <em>[lectura/escritura]</em></code> a menos que realmente necesites escribir en la base de datos.</dd> + <dd>Si necesitas abrir un almacén de objetos en modo <code>readwrite</code> para cambiar los datos, usa lo siguiente: + <pre class="brush:js;">var transaction = db.transaction('my-store-name', "readwrite");</pre> + + <p>Desde Firefox 40, las transacciones de IndexedDB tienen garantías de durabilidad relajadas para aumentar el rendimiento (ver {{Bug("1112702")}}), lo cual es el mismo comportamiento de otros navegadores que soportan IndexedDB. Es decir, anteriormente en una transacción <code>readwrite</code> el evento {{domxref("IDBTransaction.oncomplete")}} era invocado sólo cuando se garantizaba que todos los datos habían sido vaciados al disco duro. En Firefox 40+ el evento <code>complete</code> es accionado después de indicársele al Sistema Operativo que escriba los datos al disco pero esta confirmación podría suceder poco antes de que los datos hayan sido verdaderamente escritos en él. Si bien dicho evento puede entonces ser entregado un poco antes de tiempo, de cualquier modo, existe una pequeña probabilidad de que la entera transacción se pierda si el SO se bloquea o si ha ocurrido una pérdida de energía antes de que los datos efectivamente se descarguen al disco duro. Como esas catastróficas circunstancias son más bien raras, la mayoría de los consumidores no deberían preocuparse demasiado.</p> + + <div class="note"> + <p><strong>Nota</strong>: En Firefox, si deseas asegurar la durabilidad por alguna razón (por ejemplo, que estés almacenando datos críticos que no puedan ser recalculados después) puedes forzar una transacción a descargar al disco antes de invocar el evento <code>complete</code> creando una transacción que use un modo experimental <code>readwriteflush</code> (no-estándar) (ver {{domxref("IDBDatabase.transaction")}}). Esto actualmente es experimental, y puede usarse únicamente si la configuración <code>dom.indexedDB.experimental</code> es igual a <code>true</code> en <code>about:config</code>.</p> + </div> + </dd> +</dl> + +<h2 id="Especificación"><span style="font-size: 2.14285714285714rem;">Especificación</span></h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('IndexedDB', '#widl-IDBDatabase-transaction-IDBTransaction-DOMString-sequence-DOMString--storeNames-IDBTransactionMode-mode', 'transaction()')}}</td> + <td>{{Spec2('IndexedDB')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">Compatibilidad con Navegadores</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>23{{property_prefix("webkit")}}<br> + 24</td> + <td>10 {{property_prefix("moz")}}<br> + {{CompatGeckoDesktop("16.0")}}</td> + <td>10, parcial</td> + <td>15</td> + <td>7.1</td> + </tr> + <tr> + <td>Disponible en workers <em>[obreros web]</em></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("37.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Android Webview</th> + <th>Firefox Móvil (Gecko)</th> + <th>Firefox OS</th> + <th>IE Phone</th> + <th>Opera Móvil</th> + <th>Safari Móvil</th> + <th>Chrome para Android</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>4.4</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("22.0")}}</td> + <td>1.0.1</td> + <td>10</td> + <td>22</td> + <td>8</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Disponible en workers <em>[obreros web]</em></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("37.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB">Usando IndexedDB</a></li> + <li>Iniciando transacciones: {{domxref("IDBDatabase")}}</li> + <li>Usando transacciones: {{domxref("IDBTransaction")}}</li> + <li>Configurar un rango de llaves: {{domxref("IDBKeyRange")}}</li> + <li>Recuperando y haciendo cambios a tus datos: {{domxref("IDBObjectStore")}}</li> + <li>Usando cursores: {{domxref("IDBCursor")}}</li> + <li>Ejemplo de referencia: <a class="external" href="https://github.com/mdn/to-do-notifications/tree/gh-pages">To-do Notifications</a> (<a class="external" href="http://mdn.github.io/to-do-notifications/">ver ejemplo en vivo</a>).</li> +</ul> diff --git a/files/es/web/api/idbobjectstore/add/index.html b/files/es/web/api/idbobjectstore/add/index.html new file mode 100644 index 0000000000..1a28ff194c --- /dev/null +++ b/files/es/web/api/idbobjectstore/add/index.html @@ -0,0 +1,193 @@ +--- +title: IDBObjectStore.add +slug: Web/API/IDBObjectStore/add +tags: + - API + - Add + - Almacenamiento + - Base de datos + - IDBObjectStore + - IndexedDB + - Referencia +translation_of: Web/API/IDBObjectStore/add +--- +<p>{{ APIRef("IDBObjectStore") }}</p> +<div> + <p>El metodo <code>add()</code> de la interfaz {{domxref("IDBObjectStore")}} retorna un objeto {{domxref("IDBRequest")}}, y, un hilo separado, crea un <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/common-dom-interfaces.html#structured-clone">clone estructurado</a> del valor, y almacena el valor clonado en el almacén de objetos. Esto es para agregar nevos registros a un almacén de objetos.</p> + <p>Para determinar si la operación de agregar fue completada satisfactoriamente, escucha el evento <code>complete</code> de la transaccion en adicion al evento <code>success</code> de la peticion <code>IDBojectStore.add</code>, porque la transaccion y todavía puede fallar después de lanzar el evento success. En otras palabras, el eventos success sólo es lanzado cuando la transacción ha sido puesta en cola satisfactoriamente.</p> + <p>El método agregar es un método de <em>sólo inserción</em>. Si un registro ya existe en el almacén de objetos con el argumento <code>key</code> como su clave, entonces un error <code>ConstrainError</code> es lanzado en el objeto petición devuelto. Para actualizar registros existentes, debes usar el método {{domxref("IDBObjectStore.put")}} en su lugar.</p> +</div> +<h2 id="Sintaxis">Sintaxis</h2> +<pre class="brush: js">var request = objectStore.add(myItem, optionalKey);</pre> +<h3 id="Retorno">Retorno</h3> +<p>Un objeto <span style="line-height: 1.5;">{{domxref("IDBRequest")}} en el que los eventos subsecuentes relacionados a esta operación son lanzados.</span></p> +<h3 id="Excepciones">Excepciones</h3> +<p>Este método puede generar un <span style="line-height: 1.5;">{{domxref("DOMException")}}</span> con un <span style="line-height: 1.5;">{{domxref("DOMError")}}</span> de uno de los siguiente tipos:</p> +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Excepción</th> + <th scope="col">Descripción</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>ReadOnlyError</code></td> + <td>La transacción asociada con esta operación está en un <a href="/en-US/docs/IndexedDB/IDBTransaction#mode_constants" title="/en-US/docs/IndexedDB/IDBTransaction#mode_constants">modo</a> de sólo lectura.</td> + </tr> + <tr> + <td><code>TransactionInactiveError</code></td> + <td>Esta transacción de {{domxref("IDBObjectStore")}}'s está inactiva.</td> + </tr> + <tr> + <td><code><span style="line-height: normal;">DataError</span></code></td> + <td> + <p>Cualquiera de los siguientes condiciones aplica:</p> + <ul> + <li>El almacén de objetos usa llaves en línea o tiene un generador de llaves, y una argumento llave fue proporcionado.</li> + <li>El almacén de objetos usa llaves fuera de línea y no tiene un generador de llaves, y un argumento llave fue proporcionado.</li> + <li>El almacén de objetos usa llaves en línea pero no un generador de llaves, y la ruta de la llave del almacén de objetos no da una llave válida.</li> + <li>El argumento llave fue proporcionado pero no contiene una llave válida.</li> + </ul> + </td> + </tr> + <tr> + <td><code>InvalidStateError</code></td> + <td>El {{domxref("IDBObjectStore")}} ha sido borrado o removido.</td> + </tr> + <tr> + <td><code>DataCloneError</code></td> + <td>Los datos siendo almacenados no pueden ser clonados por el algoritmo de clonado estructurado interno.</td> + </tr> + </tbody> +</table> +<h2 id="Ejemplo">Ejemplo</h2> +<p>En el siguiente código, abrimos una transacción read/write en nuestra base de datos y agregado algunos datos al almacén de datos usando <code>add()</code>. También ten en cuenta que las funciones adjuntas a los manejadores de eventos de la transacción para informar en la salida de la apertura de transacciones en el evento de éxito o falla. Para un ejemplo completo funcionando, mira nuestra aplicación <a href="https://github.com/mdn/to-do-notifications/" style="line-height: 1.5;">To-do Notifications</a><span style="line-height: 1.5;"> (</span><a href="http://mdn.github.io/to-do-notifications/" style="line-height: 1.5;">ver ejemplo</a><span style="line-height: 1.5;">)</span>.</p> +<pre class="brush: js" style="font-size: 14px;">// Abrimos nuestra base de datos +<span style="line-height: 1.5;">var DBOpenRequest = window.indexedDB.open("toDoList", 4); + +</span><span style="line-height: 1.5;">DBOpenRequest.onsuccess = function(event) {</span> + note.innerHTML += '<li>Database initialised.</li>'; + + // Almacenar el resultado de la apertura de la base de datos en la variable db. Esta es usada mucho después + db = DBOpenRequest.result; + + // Ejecuta la función addData() para agregar los datos + addData(); +}; + +function addData() { + // Crea un nuevo objeto listo para ser insertado en la IDB + var newItem = [ { taskTitle: "Walk dog", hours: 19, minutes: 30, day: 24, month: "December", year: 2013, notified: "no" } ]; + + // Inicia una transacción de lectura/escritura db transaction, lista para agregar los datos + var transaction = db.transaction(["toDoList"], "readwrite"); + + // Informa sobre el éxito de la inicio de la transacción + transaction.oncomplete = function(event) { + note.innerHTML += '<li>Transaction completed: database modification finished.</li>'; + }; + + + transaction.onerror = function(event) { + note.innerHTML += '<li>Transaction not opened due to error. Duplicate items not allowed.</li>'; + }; + + // Crea una almacén de objetos en la transacción + var objectStore = transaction.objectStore("toDoList"); + + // Agrega nuestro objeto newItem al almacén de objetos + var objectStoreRequest = objectStore.add(newItem[0]); + + objectStoreRequest.onsuccess = function(event) { + //Informa sobre el éxito de nuestro nuevo elemento en la base de datos + note.innerHTML += '<li>New item added to database.</li>'; + }; +};</pre> +<h2 id="Parámetros">Parámetros</h2> +<dl> + <dt> + value</dt> + <dd> + El valor para ser almacenado.</dd> + <dt> + key</dt> + <dd> + La llave a usar para identificar el registro. Si no es especificada, el resultado es nulo.</dd> +</dl> +<h2 id="Especificación"><span style="font-size: 2.14285714285714rem;">Especificación</span></h2> +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('IndexedDB', '#widl-IDBObjectStore-add-IDBRequest-any-value-any-key', 'add()')}}</td> + <td>{{Spec2('IndexedDB')}}</td> + <td> </td> + </tr> + </tbody> +</table> +<h2 id="Browser_compatibility" name="Browser_compatibility">Compatibilidad de navegadores</h2> +<div> + {{CompatibilityTable}}</div> +<div id="compat-desktop"> + <table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>23{{property_prefix("webkit")}}<br> + 24</td> + <td>10 {{property_prefix("moz")}}<br> + {{CompatGeckoDesktop("16.0")}}</td> + <td>10, partial</td> + <td>15</td> + <td>7.1</td> + </tr> + </tbody> + </table> +</div> +<div id="compat-mobile"> + <table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>4.4</td> + <td>{{CompatGeckoMobile("22.0")}}</td> + <td>1.0.1</td> + <td>10</td> + <td>22</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> + </table> +</div> +<h2 id="Ver_también">Ver también</h2> +<ul> + <li><a href="/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB">Usando IndexedDB</a></li> + <li>Iniciando transacciones: {{domxref("IDBDatabase")}}</li> + <li>Usando transacciones: {{domxref("IDBTransaction")}}</li> + <li>Estableciendo un rango de llaves: {{domxref("IDBKeyRange")}}</li> + <li>Obteniendo y haciendo cambios a tus datos: {{domxref("IDBObjectStore")}}</li> + <li>Usando cursores: {{domxref("IDBCursor")}}</li> + <li>Ejemplo de referencia: <a class="external" href="https://github.com/mdn/to-do-notifications/tree/gh-pages">To-do Notifications</a> (<a class="external" href="http://mdn.github.io/to-do-notifications/">ver ejemplo</a>.)</li> +</ul> diff --git a/files/es/web/api/idbobjectstore/index.html b/files/es/web/api/idbobjectstore/index.html new file mode 100644 index 0000000000..32bb499284 --- /dev/null +++ b/files/es/web/api/idbobjectstore/index.html @@ -0,0 +1,207 @@ +--- +title: IDBObjectStore +slug: Web/API/IDBObjectStore +tags: + - API +translation_of: Web/API/IDBObjectStore +--- +<p>{{APIRef("IndexedDB")}}</p> + +<div> +<p>The <code>IDBObjectStore</code> interface of the <a href="/en/IndexedDB" title="en/IndexedDB">IndexedDB API</a> represents an <a href="/en/IndexedDB#gloss_object_store" title="en/IndexedDB#gloss object store">object store</a> in a database. Records within an object store are sorted according to their keys. This sorting enables fast insertion, look-up, and ordered retrieval.</p> +</div> + +<h2 id="Methods">Methods</h2> + +<dl> + <dt>{{domxref("IDBObjectStore.add")}}</dt> + <dd>Returns an {{domxref("IDBRequest")}} object, and, in a separate thread, creates a <a class="external" href="http://www.whatwg.org/specs/web-apps/current-work/multipage/common-dom-interfaces.html#structured-clone">structured clone</a> of the <code>value</code>, and stores the cloned value in the object store. This is for adding new records to an object store.</dd> + <dt>{{domxref("IDBObjectStore.clear")}}</dt> + <dd>Creates and immediately returns an {{domxref("IDBRequest")}} object, and clears this object store in a separate thread. This is for deleting all current records out of an object store.</dd> + <dt>{{domxref("IDBObjectStore.delete")}}</dt> + <dd>returns an {{domxref("IDBRequest")}} object, and, in a separate thread, deletes the current object store. This is for deleting individual records out of an object store.</dd> + <dt>{{domxref("IDBObjectStore.get")}}</dt> + <dd>returns an {{domxref("IDBRequest")}} object, and, in a separate thread, returns the object store selected by the specified key. This is for retrieving specific records from an object store.</dd> + <dt>{{domxref("IDBObjectStore.createIndex")}}</dt> + <dd>Creates a new index during a version upgrade, returning a new {{domxref("IDBIndex")}} object in the connected database.</dd> + <dt>{{domxref("IDBObjectStore.deleteIndex")}}</dt> + <dd>Destroys the specified index in the connected database, used during a version upgrade.</dd> + <dt>{{domxref("IDBObjectStore.index")}}</dt> + <dd>Opens an index from this object store after which it can, for example, be used to return a sequence of records sorted by that index using a cursor.</dd> + <dt>{{domxref("IDBObjectStore.put")}}</dt> + <dd>Returns an {{domxref("IDBRequest")}} object, and, in a separate thread, creates a <a class="external" href="http://www.whatwg.org/specs/web-apps/current-work/multipage/common-dom-interfaces.html#structured-clone">structured clone</a> of the <code>value</code>, and stores the cloned value in the object store. This is for updating existing records in an object store when the transaction's mode is <code>readwrite</code>.</dd> + <dt>{{domxref("IDBObjectStore.openCursor")}}<span style="line-height: 1.5;"> </span></dt> + <dd>Returns an {{domxref("IDBRequest")}} object, and, in a separate thread, returns a new {{domxref("IDBCursorWithValue")}} object. Used for iterating through an object store by primary key with a cursor.</dd> +</dl> + +<h2 id="Properties">Properties</h2> + +<dl> + <dt>{{domxref("IDBObjectStore.indexNames")}} {{readonlyInline}}</dt> + <dd>A list of the names of <a href="/en/IndexedDB#gloss_index" title="en/IndexedDB#gloss index">indexes</a> on objects in this object store.</dd> + <dt>{{domxref("IDBObjectStore.keyPath")}} {{readonlyInline}}</dt> + <dd>The <a href="/en/IndexedDB#gloss_key_path" title="en/IndexedDB#gloss key path">key path</a> of this object store. If this attribute is null, the application must provide a key for each modification operation.</dd> + <dt>{{domxref("IDBObjectStore.name")}} {{readonlyInline}}</dt> + <dd>The name of this object store.</dd> + <dt>{{domxref("IDBObjectStore.transaction")}} {{readonlyInline}}</dt> + <dd>The name of the transaction to which this object store belongs.</dd> + <dt>{{domxref("IDBObjectStore.autoIncrement")}} {{readonlyInline}}</dt> + <dd>The value of the auto increment flag for this object store.</dd> +</dl> + +<h2 id="Obsolete_methods">Obsolete methods</h2> + +<dl> + <dt>{{domxref("IDBObjectStore.openKeyCursor")}}<span style="line-height: 1.5;"> </span></dt> + <dd>Returns an {{domxref("IDBRequest")}} object, and, in a separate thread, returns a new {{domxref("IDBCursorWithValue")}}. Used for iterating through an object store with a key. However, this is now handled by {{domxref("IDBObjectStore.openCursor")}}, if a value is specified.</dd> +</dl> + +<h2 id="Example">Example</h2> + +<p>This example shows a variety of different uses of ObjectStores, from updating the data structure with {{domxref("IDBObjectStore.createIndex")}} inside an <code>onupgradeneeded</code> function, to adding a new item to our object store with {{domxref("IDBObjectStore.add")}}. For a full working example, see our <a href="https://github.com/mdn/to-do-notifications/" style="line-height: 1.5;">To-do Notifications</a><span style="line-height: 1.5;"> app (</span><a href="http://mdn.github.io/to-do-notifications/" style="line-height: 1.5;">view example live</a><span style="line-height: 1.5;">.)</span></p> + +<pre class="brush: js">// Let us open our database +var DBOpenRequest = window.indexedDB.open("toDoList", 4); + +DBOpenRequest.onsuccess = function(event) { + note.innerHTML += '<li>Database initialised.</li>'; + + // store the result of opening the database in the db variable. + db = DBOpenRequest.result; +}; + +// This event handles the event whereby a new version of the database needs to be created +// Either one has not been created before, or a new version number has been submitted via the +// window.indexedDB.open line above +DBOpenRequest.onupgradeneeded = function(event) { + var db = event.target.result; + + db.onerror = function(event) { + note.innerHTML += '<li>Error loading database.</li>'; + }; + + // Create an objectStore for this database + + var objectStore = db.createObjectStore("toDoList", { keyPath: "taskTitle" }); + + // define what data items the objectStore will contain + + objectStore.createIndex("hours", "hours", { unique: false }); + objectStore.createIndex("minutes", "minutes", { unique: false }); + objectStore.createIndex("day", "day", { unique: false }); + objectStore.createIndex("month", "month", { unique: false }); + objectStore.createIndex("year", "year", { unique: false }); + + objectStore.createIndex("notified", "notified", { unique: false }); + + note.innerHTML += '<li>Object store created.</li>'; +}; + +// Create a new item to add in to the object store +var newItem = [ + { taskTitle: "Walk dog", hours: 19, minutes: 30, day: 24, month: 'December', year: 2013, notified: "no" } +]; + +// open a read/write db transaction, ready for adding the data +var transaction = db.transaction(["toDoList"], "readwrite"); + +// report on the success of opening the transaction +transaction.oncomplete = function(event) { + note.innerHTML += '<li>Transaction opened for task addition.</li>'; +}; + +transaction.onerror = function(event) { + note.innerHTML += '<li>Transaction not opened due to error. Duplicate items not allowed.</li>'; +}; + +// create an object store on the transaction +var objectStore = transaction.objectStore("toDoList"); +// add our newItem object to the object store +var objectStoreRequest = objectStore.add(newItem[0]); + +objectStoreRequest.onsuccess = function(event) { + note.innerHTML += '<li>New item added to database.</li>'; +}</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('IndexedDB', '#idl-def-IDBObjectStore', 'IDBObjectStore')}}</td> + <td>{{Spec2('IndexedDB')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="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{{property_prefix("webkit")}}<br> + 24</td> + <td>10 {{property_prefix("moz")}}<br> + {{CompatGeckoDesktop("16.0")}}</td> + <td>10, partial</td> + <td>15</td> + <td>7.1</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</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>4.4</td> + <td>{{CompatGeckoMobile("22.0")}}</td> + <td>1.0.1</td> + <td>10</td> + <td>22</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB">Using IndexedDB</a></li> + <li>Starting transactions: {{domxref("IDBDatabase")}}</li> + <li>Using transactions: {{domxref("IDBTransaction")}}</li> + <li>Setting a range of keys: {{domxref("IDBKeyRange")}}</li> + <li>Retrieving and making changes to your data: {{domxref("IDBObjectStore")}}</li> + <li>Using cursors: {{domxref("IDBCursor")}}</li> + <li>Reference example: <a class="external" href="https://github.com/mdn/to-do-notifications/tree/gh-pages">To-do Notifications</a> (<a class="external" href="http://mdn.github.io/to-do-notifications/">view example live</a>.)</li> +</ul> diff --git a/files/es/web/api/imagebitmap/index.html b/files/es/web/api/imagebitmap/index.html new file mode 100644 index 0000000000..31a33886b9 --- /dev/null +++ b/files/es/web/api/imagebitmap/index.html @@ -0,0 +1,65 @@ +--- +title: ImageBitmap +slug: Web/API/ImageBitmap +tags: + - API + - Canvas + - Imagen de mapa de bits + - Referencia +translation_of: Web/API/ImageBitmap +--- +<div>{{APIRef("Canvas API")}}</div> + +<p>The <code><strong>ImageBitmap</strong></code> interface represents a bitmap image which can be drawn to a {{HTMLElement("canvas")}} without undue latency. It can be created from a variety of source objects using the {{domxref("ImageBitmapFactories.createImageBitmap", "createImageBitmap()")}} factory method. <code>ImageBitmap</code> provides an asynchronous and resource efficient pathway to prepare textures for rendering in WebGL.</p> + +<h2 id="Properties">Properties</h2> + +<dl> + <dt>{{domxref("ImageBitmap.height")}} {{readonlyInline}}</dt> + <dd>Is an <code>unsigned</code> <code>long</code> representing the height, in CSS pixels, of the <code>ImageData</code>.</dd> + <dt>{{domxref("ImageBitmap.width")}} {{readonlyInline}}</dt> + <dd>Is an <code>unsigned</code> <code>long</code> representing the width, in CSS pixels, of the <code>ImageData</code>.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<dl> + <dt>{{domxref("ImageBitmap.close()")}}</dt> + <dd> + <p>Disposes of all graphical resources associated with an <code>ImageBitmap</code>.</p> + </dd> +</dl> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('HTML WHATWG', "webappapis.html#imagebitmap", "ImageBitmap")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("api.ImageBitmap")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{domxref("ImageBitmapFactories.createImageBitmap()")}}</li> + <li>{{domxref("CanvasRenderingContext2D.drawImage()")}}</li> + <li>{{domxref("WebGLRenderingContext.texImage2D()")}}</li> + <li>{{domxref("OffScreenCanvas.transferToImageBitmap()")}}</li> +</ul> diff --git a/files/es/web/api/imagebitmaprenderingcontext/index.html b/files/es/web/api/imagebitmaprenderingcontext/index.html new file mode 100644 index 0000000000..4fb6f8816f --- /dev/null +++ b/files/es/web/api/imagebitmaprenderingcontext/index.html @@ -0,0 +1,37 @@ +--- +title: ImageBitmapRenderingContext +slug: Web/API/ImageBitmapRenderingContext +translation_of: Web/API/ImageBitmapRenderingContext +--- +<div>{{APIRef("Canvas API")}} {{SeeCompatTable}}</div> + +<p>El interface <strong><code>ImageBitmapRenderingContext</code></strong> es un lienzo de contexto renderizado que sólo permite la funcionalidad de reemplazar el contenido del lienzo ( <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas" title="Use the HTML <canvas> element with either the canvas scripting API or the WebGL API to draw graphics and animations."><code><canvas></code></a> ) con el {{domxref("ImageBitmap")}} dado. La identificación de contenido (el primer argumento a {{domxref("HTMLCanvasElement.getContext()")}} o {{domxref("OffscreenCanvas.getContext()")}} es <code>"bitmaprenderer"</code>.</p> + +<p>Esta interface es posible en ambos , la ventana y el <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API">"worker context" </a> (contexto de tabajo).</p> + +<h2 id="Métodos">Métodos</h2> + +<dl> + <dt>{{domxref("ImageBitmapRenderingContext.transferFromImageBitmap()")}}</dt> + <dd> + <p>Muestra el <code>ImageBitmap</code> en el lienzo asociado con el contexto de renderizado. La propiedad del <code>ImageBitmap</code> se transfiere al lienzo. Este se llamaba <code>transferImageBitmap()</code>, pero se renombra en un cambio especulativo . El viejo nombre se mantiene como un alias para evitar una ruptura del código.</p> + </dd> +</dl> + +<h2 id="Especificaciones">Especificaciones</h2> + +<p>Escrito como una propuesta en la especificaación <a href="https://wiki.whatwg.org/wiki/OffscreenCanvas">OffscreenCanvas</a>.</p> + +<h2 id="Compatibilidad_del_Buscador">Compatibilidad del Buscador</h2> + +<div> +<div class="hidden">La compatibilidad de la tabla en esta página es generada de datos estructurales. Si quiere contribuir en los datos, cheque <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> y envíenos un "pull request" (requicisión).</div> + +<p>{{Compat("api.ImageBitmapRenderingContext")}}</p> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("OffScreenCanvas")}}</li> +</ul> diff --git a/files/es/web/api/index.html b/files/es/web/api/index.html new file mode 100644 index 0000000000..eb83cedc1b --- /dev/null +++ b/files/es/web/api/index.html @@ -0,0 +1,37 @@ +--- +title: Referencia de la API Web +slug: Web/API +tags: + - API + - Aterrizaje + - DOM + - Referencia + - Web +translation_of: Web/API +--- +<p><span id="result_box" lang="es"><span class="hps">Cuando escribimos código</span> <span class="hps">para la web</span> <span class="hps">utilizando</span> <span class="hps">JavaScript</span><span>, podemos usar</span><span class="hps"> gran número de</span> <span class="hps"><abbr title="Application Programming Interface">APIs</abbr></span> <span class="hps">disponibles</span><span>.</span> <span class="hps">A continuación mostramos</span> <span class="hps">una lista de todas</span> <span class="hps">las interfaces</span> <span class="atn hps">(</span><span>es decir,</span> <span class="hps">tipos de objetos</span><span>) que </span><span class="hps">puedes usar</span> <span class="hps">al desarrollar</span> <span class="hps">tu aplicación</span> <span class="hps">o sitio Web</span><span>.</span> <span class="hps">Para obtener una lista</span> <span class="hps">de</span> <span class="hps">las API que</span> <span class="hps">contiene</span> <span class="hps">cada una de</span> <span class="hps">estas interfaces</span><span>, consulta la</span> <span class="hps">referencia de la API</span> <span class="hps">Web.</span></span></p> + +<div>{{APIListAlpha}}</div> + +<div></div> + +<h2 id="Especificaciones">Especificaciones</h2> + +<p>Esta es una lista de todas las APIs que están disponibles.</p> + +<p>{{ListGroups}}</p> + +<h2 id="Interfaces">Interfaces</h2> + +<p><br> + Esta es una lista de todas las interfaces (es decir, tipos de objetos) que están disponibles</p> + +<p>{{APIListAlpha}}</p> + +<h2 id="Ve_también">Ve también</h2> + + + +<ul> + <li><a href="/es/docs/Web/Events">Referencia de la API de eventos web</a></li> +</ul> diff --git a/files/es/web/api/indexeddb_api/conceptos_basicos_detras_de_indexeddb/index.html b/files/es/web/api/indexeddb_api/conceptos_basicos_detras_de_indexeddb/index.html new file mode 100644 index 0000000000..34d4fdd438 --- /dev/null +++ b/files/es/web/api/indexeddb_api/conceptos_basicos_detras_de_indexeddb/index.html @@ -0,0 +1,216 @@ +--- +title: Conceptos Básicos +slug: Web/API/IndexedDB_API/Conceptos_Basicos_Detras_De_IndexedDB +translation_of: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +--- +<p><strong>IndexedDB</strong> es una manera de almacenar datos de manera persistente en el navegador. Dado que permite la creación de aplicaciones web con capacidades de consulta mejoradas, éstas pueden funcionar tanto en línea como fuera de línea. IndexedDB es útil para aplicaciones que almacenan una gran cantidad de datos (catálogos de DVDs en una biblioteca, por ejemplo) y para aplicaciones que no necesitan de una conexión permanente a internet para funcionar (clientes de correo, listas de tareas y blocs de notas, por ejemplo).</p> + +<h2 id="Sobre_este_documento">Sobre este documento</h2> + +<p>Esta introducción discute conceptos y terminologías fundamentales en IndexedDB. Provee una visión general y orienta sobre los conceptos clave. Para aprender más sobre los términos relacionados con IndexedDB, vea la sección de <a href="#definitions">Definiciones</a>.</p> + +<p>Para un tutorial sobre cómo usar la API, vea <a href="/es/IndexedDB/Usando_IndexedDB" title="en/IndexedDB/IndexedDB primer">Usando IndexedDB</a>. Para ver la documentación de referencia sobre la API de IndexedDB, vea el artículo <a href="/en/IndexedDB" title="https://developer.mozilla.org/en/IndexedDB">IndexedDB</a> y sus sub-páginas, que documentan los tipos de objetos utilizados por IndexedDB, así como los métodos de las API síncrona y asíncrona.</p> + +<h2 id="Visión_general_de_IndexedDB">Visión general de IndexedDB</h2> + +<p>IndexedDB le permite almacenar y obtener objetos indizados a partir de una "llave". Todos los cambios realizados a la base de datos ocurren dentro de transacciones. Como la mayoría de las soluciones de almacenamiento web, IndexedDB sigue una <a class="external" href="http://www.w3.org/Security/wiki/Same_Origin_Policy" title="http://www.w3.org/Security/wiki/Same_Origin_Policy">política de mismo origen</a>, por lo que aún cuando se puede acceder a datos almacenados en un dominio, no se pueden acceder a datos a través de distintos dominios.</p> + +<p>La API incluye una variante <a href="/en/IndexedDB#Asynchronous_API" title="https://developer.mozilla.org/en/IndexedDB#Asynchronous_API">asíncrona</a> y una <a href="/en/IndexedDB#Synchronous_API" title="https://developer.mozilla.org/en/IndexedDB#Synchronous_API">síncrona</a>. La variante asíncrona puede ser utilizada en la mayoría de los casos, incluyendo <a href="/En/DOM/Using_web_workers" title="https://developer.mozilla.org/En/Using_web_workers">WebWorkers</a>, mientras la variante síncrona está diseñada para ser utilizada solo con WebWorkers. Actualmente, ninguno de los navegadores principales soportan la API síncrona. Sin embargo, aún cuando la API síncrona sea soportada, en la mayoría de los casos de uso de IndexedDB lo más probable es que se utilice la API asíncrona.</p> + +<p>IndexedDB es una alternativa a WebSQL, que fue marcada como obsoleta por W3C el 18 de Noviembre de 2010. Aún cuando IndexedDB y WebSQL son soluciones para el almacenamiento, éstas no ofrecen las mismas funcionalidades. WebSQL es un sistema relacional de acceso a datos, mientras que IndexedDB es un sistema de tablas indizadas.</p> + +<h2 id="concepts" name="concepts">Conceptos principales</h2> + +<p>Si usted tiene alguna idea de cómo trabajan otros tipos de bases de datos, podría tener algún conflicto de conceptos al trabajar con IndexedDB. Por esta razón mantenga los siguientes conceptos importantes en mente:</p> + +<ul> + <li> + <p><strong>IndexedDB almacena pares llave-valor.</strong> Los valores pueden ser objetos con estructuras complejas, y las llaves pueden ser propiedades de esos objetos. Se pueden crear índices que usan cualquier propiedad de los objetos para realizar búsquedas rápidas o enumeraciones ordenadas.</p> + </li> + <li> + <p><strong>IndexedDB está hecho sobre un modelo de base de datos transaccional.</strong> Todo lo que usted haga en IndexedDB siempre ocurre en el contexto de una <a href="#gloss_transaction">transacción</a>. La API de IndexedDB provee una gran cantidad de objetos que representan índices, tablas, cursores, y más, pero cada uno de ellos están atados a una transacción particular. Así, usted no puede ejecutar ningún comando o abrir un cursor fuera de una transacción.</p> + + <p>Las transacciones tienen un período de vida bien definido. Por esta razón, cualquier intento de utilizar una transacción que ya se ha completado ocasionará excepciones. Igualmente, las transacciones aplican los cambios automáticamente y no se puede hacer <em>commit</em> automáticamente.</p> + + <p>Este modelo de transacciones es realmente útil cuando se considera qué podría pasar si un usuario abre dos instancias de una aplicación simultáneamente en dos pestañas. Sin operaciones transaccionales, las dos instancias podrían hacer que los cambios se <em>pisen</em> o se sobreescriban entre sí. Si no está familiarizado con el concepto de transacción en una base de datos, lea el <a class="link-https" href="https://es.wikipedia.org/wiki/Transacci%C3%B3n_%28base_de_datos%29" title="https://secure.wikimedia.org/wikipedia/en/wiki/Database_transaction">artículo correspondiente en la Wikipedia</a> y <a href="#gloss_transaction">transacción</a> en la sección de definiciones.</p> + </li> + <li> + <p><strong>La API de IndexedDB es mayormente asincrona.</strong> La API no devuelve datos regresando un valor; en cambio, es necesario pasarle una funcion como <em>callback</em>. Usted no "guarda" un valor en la base de datos, o "lee" un valor de la misma por medios síncronos. En cambio, usted "solicita" una operación a la base de datos. Un evento del DOM es utilizado para notificarle que la operación terminó, y el tipo de evento recibido le permite saber si ésta falló o si fue exitosa. Esto puede sonar complicado al comienzo, pero hay algunas medidas de sanidad incluidas por defecto. Esto no es muy distinto de cómo funciona <a href="/es/DOM/XMLHttpRequest" title="https://developer.mozilla.org/en/xmlhttprequest">XMLHttpRequest</a>.</p> + </li> + <li> + <p><strong>IndexedDB usa solicitudes en todos lados. </strong>Las solicitudes (<em>requests</em>) son objetos que reciben los eventos del DOM mencionados previamente. Éstas cuentan con las propiedades <code style="font-size: 14px;">onsuccess</code> y <code style="font-size: 14px;">onerror</code>, sobre las cuales se puede aplicar <code style="font-size: 14px;">addEventListener()</code> y <code style="font-size: 14px;">removeEventListener()</code>. Estas también tienen las propiedades <code style="font-size: 14px;">readyState</code>, <code style="font-size: 14px;">result</code>, y <code style="font-size: 14px;">errorCode</code> que permiten conocer el estado de la solicitud. La propiedad <code style="font-size: 14px;">result</code> es particularmente mágica, dado que puede ser muchas cosas distintas, dependiendo de cómo se generó la solicitud (por ejemplo, una instancia de <code>IDBCursor</code>, o la llave de un valor recién insertado en la base de datos).</p> + </li> + <li> + <p><strong>IndexedDB usa eventos DOM para notificar cuando los resultados están disponibles.</strong> Los eventos del DOM siempre tienen una propiedad <code style="font-size: 14px;">type</code> (en IndexedDB, ésta es generalmente <code style="font-size: 14px;">"success"</code> o <code style="font-size: 14px;">"error"</code>). Los eventos del DOM también tienen una propiedad <code style="font-size: 14px;">target</code> que dice a dónde apunta el evento. En la mayoría de los casos, el <code style="font-size: 14px;">target</code> de un evento es el objeto <code style="font-size: 14px;">IDBRequest</code> que se generó como resultado de una operación sobre la base de datos. Los eventos exitosos no son pasados a los padres y no pueden ser cancelados. Por otro lado, los eventos de error son pasados a los padres del target y pueden cancelarse. Esto es importante, dado que los eventos de error cancelan cualquier transacción sobre la que estén corriendo a menos que sean cancelados.</p> + </li> + <li> + <p><strong>IndexedDB es orientada a objetos.</strong> IndexedDB no es una base de datos relacional, con tablas, filas y columnas. Esta diferencia fundamental e importante afecta la manera como usted diseña e implementa sus aplicaciones.</p> + + <p>En un almacén de datos relacional, usted podría tener una tabla que almacena una colección de filas de datos y columnas de tipos de datos con un nombre. IndexedDB, por otro lado, necesita que usted cree un almacén de objetos para un tipo de datos y sencillamente almacena objetos JavaScript en ese almacén. Cada almacén de objetos puede tener una colección de índices que hacen que la iteración y la búsqueda de elementos sea más eficiente. Si usted no está familiarizado con los sistemas de manejo de datos orientados a objetos, lea el <a class="external" href="https://es.wikipedia.org/wiki/Base_de_datos_orientada_a_objetos" title="http://en.wikipedia.org/wiki/Object_database">artículo de la Wikipedia sobre bases de datos orientadas a objetos</a>.</p> + </li> + <li> + <p><strong>IndexedDB no utiliza SQL (</strong><strong>Structured Query Language).</strong> En cambio usa consultas sobre un índice que producen un cursor. Éste puede utilizarse para iterar sobre el conjunto de resultados. Si no está familiarizado con sistemas NoSQL, lea el <a class="external" href="https://es.wikipedia.org/wiki/NoSQL" title="http://en.wikipedia.org/wiki/NoSQL">artículo de Wikipedia sobre NoSQL</a>.</p> + </li> + <li> + <p><a name="origin"><strong>IndexedDB se adhiere a una política de mismo origen</strong></a>. Un orígen es el dominio, protocolo de la capa de aplicación, y el puerto de la URL del documento donde se está ejecutando la aplicación. Cada orígen tiene su propio conjunto de bases de datos asociado. Cada base de datos tiene un nombre que la identifica dentro de un orígen.</p> + + <p>El límite de seguridad impuesto en IndexedDB prevé que las aplicaciones puedan acceder a datos de un orígen diferente. Por ejemplo, mientras una aplicación en <a class="external" href="http://www.example.com/app/" rel="freelink">http://www.example.com/app/</a> puede obtener datos desde <a class="external" href="http://www.example.com/dir/" rel="freelink">http://www.example.com/dir/</a>, debido a que comparten un mismo orígen, esta no puede leer datos desde <a class="external" href="http://www.example.com:8080/dir/" rel="freelink">http://www.example.com:8080/dir/</a> (puerto distinto) o desde <a class="link-https" href="https://www.example.com/dir/" rel="freelink">https://www.example.com/dir/</a> (protocolo distinto), debido a que tienen distintos orígenes.</p> + </li> +</ul> + +<h2 id="definitions" name="definitions">Definiciones</h2> + +<p>Esta sección define y explica los términos utilizados en la API de IndexedDB.</p> + +<h3 id="database" name="database">Base de Datos</h3> + +<dl> + <dt><a name="gloss_database">base de datos</a></dt> + <dd>Un repositorio de información, típicamente compuesto de uno o más <a href="#gloss_object_store" title="#gloss_object_store"><em>almacenes de objetos</em></a>. Cada base de datos debe tener: + <ul> + <li><strong>Nombre</strong>. Identifica la base de datos dentro de un mismo origen y no cambia a lo largo de la existencia de ésta. El nombre puede ser cualquier cadena de caracteres (incluyendo una vacía).</li> + <li> + <p><strong><a href="#gloss_version"><em>Versión</em></a> actual</strong>. Cuando una base de datos se crea por primera vez, la versión es el número entero 1 si no se indica otra cosa. Cada base de datos puede tener una y sólo una versión en cualquier momento.</p> + </li> + </ul> + </dd> + <dt><a name="gloss_object_store">almacén de objetos</a></dt> + <dd> + <p>El mecanismo a través del cual los datos son almacenados en la base de datos. El almacén de objetos mantiene registros de manera persistente, que son pares de llave-valor. Los registros dentro de un almacén de objetos son ordenados de acuerdo con las <em><a href="#gloss_key">llaves</a></em> en orden ascendente.</p> + + <p>Todo almacén de objetos debe tener un nombre que es único a lo largo de su base de datos. Opcionalmente puede tener un <em><a href="#gloss_keygenerator">generador de llaves</a></em> y una <em><a href="#gloss_keypath">ruta de llaves</a></em>. Si el almacén tiene una ruta de llaves, éste utiliza <em><a href="#gloss_inline_key">llaves en línea</a></em>; si no, utiliza <em><a href="#gloss_outofline_key">llaves fuera de línea</a></em>.</p> + + <p>Para documentación de referencia sobre los almacenes de objetos, vew <a href="../../../../en/IndexedDB/IDBObjectStore" rel="internal">IDBObjectStore</a> o <a href="../../../../en/IndexedDB/IDBObjectStoreSync" rel="internal">IDBObjectStoreSync</a>.</p> + </dd> + <dt><a name="gloss_version">versión</a></dt> + <dd>Cuando una base de datos es creada por primera vez, su versión es 1. Cada base de datos tiene una versión en cualquier momento y no puede tener varias versiones al mismo tiempo. La única manera de cambiar la versión es abrir la base de datos con una versión mayor a la actual. Esto arranca una <em>transacción</em> <code>versionchang<em>e</em></code> y dispara el evento <code>upgradeneeded</code>. El único momento cuando se puede actualizar el esquema de la base de datos es dentro del manejador de este evento.</dd> + <dd>Nota: Esta definición describe la <a class="external" href="http://dvcs.w3.org/hg/IndexedDB/raw-file/tip/Overview.html">especificación más actual</a>, que solo está implementada por las versiones más nuevas de los navegadores. Los navegadores más antiguos implementaron el método <a href="/en-US/docs/IndexedDB/IDBDatabase#setVersion()" title="/en-US/docs/IndexedDB/IDBDatabase#setVersion()"><code>IDBDatabase.setVersion()</code></a>, que ya ha sido marcado obsoleto y removido.</dd> + <dt><a name="gloss_database_connection">conexión a la base de datos</a></dt> + <dd>Una operación creada al abrir una <em><a href="#gloss_database">base de datos</a></em>. Una base de datos puede tener múltiples conexiónes al mismo tiempo.</dd> + <dt><a name="gloss_transaction">transacción</a></dt> + <dd> + <p>Un conjunto atómico y durable de operaciónes de acceso y modificación de datos sobre una base de datos particular. Esta es la manera cómo se interactúa con los datos de una base de datos. De hecho, cualquier lectura o modificación de datos en la base de datos debe ocurrir dentro de una transacción.</p> + + <p>Una conexión a la base de datos puede tener varias transacciones activas, siempre que las operaciones de escrituras no tengan <a href="#scope"><em>ámbitos</em></a> que se solapen. El ámbito de las transacciones, que es definido al momento en que éstas son creadas, determina con qué almacenes de datos puede interactuar ésta y permanece constante a lo largo de su existencia. Así, por ejemplo, si una conexión tiene una transacción escribiendo con un ámbito que abarca solo el almacén <code>flyingMonkey</code>, se puede iniciar una segunda que tenga como ámbito los almacenes <code>unicornCentaur</code> y <code>unicornPegasus</code>. En el caso de las transacciones de lectura, se pueden tener varias aún cuando se solapen.</p> + + <p>Se espera que las transacciones tengan una existencia corta, de manera que el navegador puede cancelar una transacción que tome demasiado tiempo para liberar recursos que la misma tenga bloqueados. Usted puede abortar la transacción, lo que deshace los cambios hechos a la base de datos durante la misma. Ni siquiera es necesario esperar a que la transacción inicie para abortarla.</p> + + <p>Los tres modos de transacción son: <code>readwrite</code>, <code>readonly</code>, y <code>versionchange</code>. La única manera de crear y borrar almacenes es usar una transacción <code>versionchange</code>. Para aprender más sobre los tipos de transacción, vea al artículo de referencia de <a href="/en/IndexedDB" title="https://developer.mozilla.org/en/IndexedDB">IndexedDB</a>.</p> + + <p>Debido a que todo sucede dentro de una transacción, este es un concepto muy importante. Para aprender más sobre las transacciones, especialmente sobre como se relacionan con el versionado, vea <a href="../../../../en/IndexedDB/IDBTransaction" rel="internal">IDBTransaction</a>, que también cuenta con documentación de referencia. Para la documentación sobre la API asíncrona, vea <a href="../../../../en/IndexedDB/IDBTransactionSync" rel="internal">IDBTransactionSync</a>.</p> + </dd> + <dt><a name="gloss_request">solicitud</a></dt> + <dd>La operación por medio de la cual se lee o se escribe en una base de datos. Toda solicitud representa una y solo una operación de lectura o escritura.</dd> + <dt><a name="gloss_index">índice</a></dt> + <dd> + <p>Un almacén especializado para buscar registros en otro almacén, llamado <em>almacén de objetos referenciado</em>. El índice es un almacenamiento persistente llave-valor donde el valor es una llave del almacén referenciado. Los registros en un índice son rellenados automáticamente cada vez que se modifican los registros del almacén referenciado. Cada registro en un índice puede apuntar solo a un registro de su almacén referenciado, pero varios índices pueden apuntar al mismo almacén.</p> + + <p>Alternativamente, se pueden realizar búsquedas en un almacén de objetos usando la <a href="#gloss_key">llave</a><em>.</em></p> + + <p>Para aprender más sobre el uso de los índices, vea <a href="/en/IndexedDB/Using_IndexedDB#Using_an_index" title="en/IndexedDB/Using_IndexedDB#Using_an_index">Usando IndexedDB</a>. Para documentación de referencia, vea <a href="../../../../en/IndexedDB/IDBKeyRange" rel="internal">IDBKeyRange</a>.</p> + </dd> +</dl> + +<h3 id="key" name="key">Llave y valor</h3> + +<dl> + <dt><a name="gloss_key">llave</a></dt> + <dd> + <p>Es uno de los atributos del objeto a partir del cual los demás objetos son organizados y obtenidos desde el almacén de objetos. El almacén puede derivar una llave desde uno de tres orígenes: un <em><a href="#gloss_keygenerator">generador de llaves</a></em>, una <em><a href="#gloss_keypath">ruta de llave</a></em><a>, y un valor indicado de forma explícita. La llave debe ser de un tipo de datos que tenga un número creciente en relación con los objetos almacenados previamente. Cada registro en un almacén de datos debe tener una llave única en el almacén, de manera que no se pueden tener varios objetos con la misma llave en un almacén de objetos dado.</a></p> + <a> </a> + + <p><a>Una llave puede ser de uno de los siguientes tipos: </a><a href="/es/docs/Referencia_de_JavaScript_1.5/Objetos_globales/String" title="String">String</a>, <a href="/es/docs/Referencia_de_JavaScript_1.5/Objetos_globales/Date" title="Date">Date</a>, float, y <a href="/es/docs/Referencia_de_JavaScript_1.5/Objetos_globales/Array" title="Array">Array</a>. Para los arreglos, la llave puede tener un rango desde un valor vacío hasta infinito, y puede incluirse un arreglo dentro de otro. No se requiere usar solo cadenas o enteros para las llaves {{ fx_minversion_inline("11") }}.</p> + + <p>Como alternativa, se pueden realizar búsquedas de objetos usando un <em><a href="#gloss_index">índice</a>.</em></p> + </dd> + <dt><a name="gloss_keygenerator">generador de llaves</a></dt> + <dd>Es un mecanismo para producir nuevas llaves en una secuencia ordenada. Si un almacén de objetos no tiene un generador de llaves, entonces la aplicación debe proveer llaves para los registros que se almacenen. Los generadores no son compartidos entre almacenes. Esto es un detalle de implementación de los navegadores, porque en desarrollo web, realmente no se crea o se accede a un generador de llaves.</dd> + <dt><a name="gloss_inline_key">llaves en línea</a></dt> + <dd>Es una llave que se almacena como parte del valor almacenado. La manera como se determina cuál es la llave es utilizando una <em>ruta de llave</em>. Una llave en línea puede obtenerse con un generador. Después de que la llave ha sido generada, esta puede almacenarse en el valor usando la ruta del atributo o puede ser usada directamente como llave.</dd> + <dt><a name="gloss_outofline_key">llave fuera de línea</a></dt> + <dd>Una llave que se almacena separada del valor.</dd> + <dt><a name="gloss_keypath">ruta de llave</a></dt> + <dd>Define de dónde se debe extraer la llave desde un valor en el almacén o en un índice. Una ruta de llave válida puede incluir alguno de los siguientes: una cadena vacía, un identificador de JavaScript, o múltiples identificadores de JavaScript separados con puntos. No puede incluir espacios.</dd> + <dt><a name="gloss_value">valor</a></dt> + <dd> + <p>Cada registro tiene un valor, el cual puede ser cualquier cosa que pueda ser expresada en JavaScript, incluyendo: <a href="/es/docs/Referencia_de_JavaScript_1.5/Objetos_globales/Boolean" rel="internal" title="Boolean">booleanos</a>, <a href="/es/docs/Referencia_de_JavaScript_1.5/Objetos_globales/Number" rel="internal" title="Number">números</a>, <a href="/es/docs/Referencia_de_JavaScript_1.5/Objetos_globales/String" title="String">cadenas</a>, <a href="/es/docs/Referencia_de_JavaScript_1.5/Objetos_globales/Date" title="Date">fechas</a>, <a href="/es/docs/Referencia_de_JavaScript_1.5/Objetos_globales/Object" title="Object">objetos</a>, <a href="/es/docs/Referencia_de_JavaScript_1.5/Objetos_globales/Array" rel="internal" title="Array">arreglos</a>, <a href="/es/docs/Referencia_de_JavaScript_1.5/Objetos_globales/RegExp" rel="internal" title="RegExp">expresiones regulares</a>, <a href="/es/docs/Referencia_de_JavaScript_1.5/Objetos_globales/undefined" title="undefined">undefined</a>, y null.</p> + + <p>Cuando un objeto o un arreglo es almacenado, las propiedades y valores en ese objeto o arreglo pueden ser cualquier cosa que sea un valor válido.</p> + + <p>Se pueden almacenar <a href="/en/DOM/Blob" title="en/DOM/Blob">Blobs</a> y archivos. cf. <a class="external" href="http://dvcs.w3.org/hg/IndexedDB/raw-file/tip/Overview.html">especificación</a> {{ fx_minversion_inline("11") }}.</p> + </dd> +</dl> + +<h3 id="range" name="range">Rango y ámbito</h3> + +<dl> + <dt>ámbito</dt> + <dd>El conjunto de almacenes de objetos e índices en los que una transacción aplica. Los ámbitos de varias transacciones de solo lectura pueden solaparse y ejecutarse al mismo tiempo. En cambio, los ámbitos de transacciones de escritura no pueden solaparse. Aún así se pueden crear varias transacciones con el mismo ámbito al mismo tiempo, pero éstas serán manejadas por una cola y ejecutadas una detrás de otra.</dd> + <dt>cursor</dt> + <dd>Un mecanismo para iterar a través de múltiples registros con un <em>rango de llaves</em>. El cursor tiene un orígen que indica que índice o almacén de datos está iterando. El cursor tiene una posición dentro del rango, y se mueve en dirección creciente o decreciente en el orden de las llaves de cada registro. Para obtener documentación de referencia sobre cursores, vea <a href="../../../../en/IndexedDB/IDBCursor" rel="internal">IDBCursor</a> o <a href="../../../../en/IndexedDB/IDBCursorSync" rel="internal">IDBCursorSync</a>.</dd> + <dt>rango de llaves</dt> + <dd> + <p>Un intervalo continuo sobre algún tipo de datos utilizado para las llaves. Los registros pueden obtenerse desde los almacenes e índices usando llaves o un rango de llaves. Los rangos pueden limitarse o filtrarse con umbrales inferiores y superiores. Por ejemplo, se puede iterar sobre todos los valores de una llave desde x hasta y.</p> + + <p>Para documentación de referencia sobre los rangos de llaves, vea <a href="../../../../en/IndexedDB/IDBKeyRange" rel="internal">IDBKeyRange</a>.</p> + </dd> +</dl> + +<h2 id="limitations" name="limitations">Limitaciones</h2> + +<p>IndexedDB está diseñado para cubrir la mayoría de los casos en los que se necesita almacenamiento del lado del cliente. Sin embargo, no están contemplados en su diseño unos pocos casos como los siguientes:</p> + +<ul> + <li>Ordenamiento internacionalizado. No todos los idiomas ordenan las cadenas de la misma forma, por lo que el ordenamiento internacionalizado no está soportado. Aún cuando la base de datos no puede ordenar los datos respetando su idioma, usted puede ordenar los datos obtenidos de la base de datos por su cuenta.</li> + <li>Sincronización. La API no está diseñada para tomar en cuenta la sincronización con una base de datos del lado del servidor. Usted debe escribir el código de sincronización para estos casos.</li> + <li>Búsqueda de Texto Completo. La API no ofrece un equivalente al operador <span style="direction: ltr;"><code>LIKE</code> en SQL. </span></li> +</ul> + +<p>Adicionalmente, tenga en cuenta que los navegadores podrían eliminar la base de datos, como en las siguientes condiciones:</p> + +<ul> + <li>El usuario pide borrar los datos del navegador.<br> + Muchos navegadores tienen opciones que permiten al usuario eliminar todos los datos almacenados de un sitio, incluyendo cookies, marcadores, contraseñas, y datos de IndexedDB.</li> + <li>El navegador está en modo de navegación privada.<br> + Algunos navegadores tienen modos de "navegación privada" (Firefox) o "incógnito" (Chrome). Al final de la sesión, el navegador elimina la base de datos.</li> + <li>Se alcanza el límite de espacio en disco.</li> + <li>Los datos se corrompen.</li> + <li>Se realiza un cambio incompatible a ésta característica.</li> +</ul> + +<p>Las circunstancias exactas y capacidades de los navegadores cambian con el tiempo, pero la filosofía de los navegadores es, en general, hacer lo posible por conservar los datos.</p> + +<div class="warning"> +<p><strong>Advertencia:</strong> Al momento, debido a errores o a propósito, es imposible abrir una base de datos IndexedDB desde un <a href="https://developer.mozilla.org/en-US/docs/Accessibility/An_overview_of_accessible_web_applications_and_widgets" title="/en-US/docs/Accessibility/An_overview_of_accessible_web_applications_and_widgets">Web App</a>. Esto requiere mayor investigación para documentarlo.</p> +</div> + +<h2 id="next" name="next">Próximo paso</h2> + +<p>Ok, ahora con estos conceptos generales bajo nuestros cinturones, podemos seguir a cosas más concretas. Para un tutorial sobre como utilizar la API, vea <a href="/en/IndexedDB/Using_IndexedDB" title="en/IndexedDB/IndexedDB primer">Usando IndexedDB</a>.</p> + +<h2 id="Vea_también">Vea también</h2> + +<p>Especificación</p> + +<ul> + <li><a href="http://www.w3.org/TR/IndexedDB/" title="http://www.w3.org/TR/IndexedDB/"><span style="direction: ltr;">Especificación de la API de IndexedDB</span></a></li> +</ul> + +<p>Referencia</p> + +<ul> + <li><a href="/en/IndexedDB" title="https://developer.mozilla.org/en/IndexedDB">Referencia de la API de IndexedDB</a></li> +</ul> + +<p>Tutoriales</p> + +<ul> + <li><a href="/en/IndexedDB/Using_IndexedDB" title="en/IndexedDB/IndexedDB primer">Usando IndexedDB</a></li> + <li><a class="external" href="http://www.html5rocks.com/tutorials/indexeddb/todo/" title="http://www.html5rocks.com/tutorials/indexeddb/todo/">Una lista de tareas sencilla usando HTML5 e IndexedDB</a><span class="external">. </span><span class="external"> {{ Note("Este ejemplo usa una versión antigua de la especificación y no funciona en las versiones más recientes de los navegadores principales (aún utiliza el método <code>setVersion()</code>, que fue removido.") }}</span></li> +</ul> + +<p>Artículo relacionado</p> + +<ul> + <li><a class="external" href="http://msdn.microsoft.com/en-us/scriptjunkie/gg679063.aspx" title="http://msdn.microsoft.com/en-us/scriptjunkie/gg679063.aspx">IndexedDB — El almacén en su navegador</a></li> +</ul> diff --git a/files/es/web/api/indexeddb_api/index.html b/files/es/web/api/indexeddb_api/index.html new file mode 100644 index 0000000000..6ac53d75fe --- /dev/null +++ b/files/es/web/api/indexeddb_api/index.html @@ -0,0 +1,144 @@ +--- +title: IndexedDB +slug: Web/API/IndexedDB_API +translation_of: Web/API/IndexedDB_API +--- +<p>{{ SeeCompatTable() }}</p> + +<p>IndexedDB es una API de bajo nivel que ofrece almacenamiento en el cliente de cantidades significativas de datos estructurados, incluyendo archivos y blobs. Para búsquedas de alto rendimiento en esos datos usa índices. Mientras <a href="/en-US/docs/DOM/Storage" title="en-US/docs/DOM/Storage">DOM Storage</a> es útil para el almacenamiento de pequeñas cantidades de datos, no es útil para almacenar grandes cantidades de datos estructurados. IndexedDB proporciona una solución.</p> + +<p>Esta página es básicamente el punto de entrada para la descripción técnica de los objetos de la API. Si necesita algo elemental, debería consultar ;<a href="/en-US/docs/IndexedDB/Basic_Concepts_Behind_IndexedDB" title="/en-US/docs/IndexedDB/Basic_Concepts_Behind_IndexedDB">Conceptos básicos acerca de IndexedDB</a>. Para más detalles, vea <a href="https://developer.mozilla.org/en-US/docs/IndexedDB/Using_IndexedDB" title="https://developer.mozilla.org/en-US/docs/IndexedDB/Using_IndexedDB">Usando IndexedDB</a>.</p> + +<p>IndexedDB provee APIs separados para un acceso síncrono o asíncrono. El API síncrono está destinado a ser usado únicamente dentro de <a href="/en-US/docs/DOM/Worker" title="Worker">Web Workers</a>, pero no será implementado aún por cualquier navegador. El API asíncrono trabaja con o sin Web Workers.</p> + +<h2 id="API_Asíncrono">API Asíncrono</h2> + +<p>Los métodos del API Asíncrono, retornan sin bloquear el hilo de llamada. Para obtener un acceso asíncrono a la base de datos, use <code><a href="/en-US/docs/IndexedDB/IDBFactory#open" title="en-US/docs/IndexedDB/IDBFactory#open">open</a></code>() en el atributo <code><a href="/en-US/docs/IndexedDB/IDBEnvironment#attr_indexedDB" title="en-US/docs/IndexedDB/IDBEnvironment#attr indexedDB">indexedDB</a></code> de un objeto <a href="/en-US/docs/DOM/window" title="en-US/docs/DOM/window">window</a>. Este método retorna un objeto IDBRequest (IDBOpenDBRequest); operaciones asíncronas se comunicarán con la aplicación que llama, disparando eventos en los objetos IDBRequest.</p> + +<div class="note"> +<p>Nota: El objeto <code>indexedDB</code> se prefija en las versiones antiguas de los navegadores (propiedad <code>mozIndexedDB</code> para Gecko < 16, <code>webkitIndexedDB</code> en Chrome, y <code>msIndexedDB</code> en IE 10).</p> +</div> + +<ul> + <li><a href="/en-US/docs/IndexedDB/IDBFactory" title="en-US/docs/IndexedDB/IDBFactory"><code>IDBFactory</code></a> provee acceso a la base de datos. Esta es la interface implementada por el objeto global <code>indexedDB</code> y es el punto de entrada para la API.</li> + <li><a href="/en-US/docs/IndexedDB/IDBCursor" title="en-US/docs/IndexedDB/IDBCursor"><code>IDBCursor</code></a> itera sobre los objetos de almacenamiento y de índices.</li> + <li><a href="/en-US/docs/IndexedDB/IDBCursorWithValue"><code>IDBCursorWithValue</code></a> itera sobre los objetos de almacenamiento y de índices y retorna el valor actual del cursor.</li> + <li><a href="/en-US/docs/IndexedDB/IDBDatabase" title="en-US/docs/IndexedDB/IDBDatabase"><code>IDBDatabase</code></a> representa una conexión a la base de datos. Es la única manera de realizar una transacción en la base de datos.</li> + <li><a href="/en-US/docs/IndexedDB/IDBEnvironment" title="en-US/docs/IndexedDB/IDBEnvironment"><code>IDBEnvironment</code></a> provee acceso a la base de datos, desde el lado del cliente. Está implementada por el objeto <a href="/../en-US/docs/DOM/window" rel="internal" title="../en-US/docs/DOM/window">window</a>.</li> + <li><a href="/en-US/docs/IndexedDB/IDBIndex" title="en-US/docs/IndexedDB/IDBIndex"><code>IDBIndex</code></a> provee acceso a la metadata de un índice.</li> + <li><code><a href="/en-US/docs/IndexedDB/IDBKeyRange" title="en-US/docs/IndexedDB/KeyRange">IDBKeyRange</a></code> define un rango de claves.</li> + <li><a href="/en-US/docs/IndexedDB/IDBObjectStore" title="en-US/docs/IndexedDB/IDBObjectStore"><code>IDBObjectStore</code></a> representa un objeto de almacenamiento.</li> + <li><a href="/en-US/docs/IndexedDB/IDBOpenDBRequest" title="en-US/docs/IndexedDB/IDBOpenDBRequest"><code>IDBOpenDBRequest</code></a> representa un requerimiento para abrir una base de datos.</li> + <li><a href="/en-US/docs/IndexedDB/IDBRequest" title="en-US/docs/IndexedDB/IDBRequest"><code>IDBRequest</code></a> provee acceso a los resultados de los requerimientos asíncronos a la base de datos y a los objetos database. Es lo que se obtiene cuando se llama a un método asíncrono.</li> + <li><a href="/en-US/docs/IndexedDB/IDBTransaction" title="en-US/docs/IndexedDB/IDBTransaction"><code>IDBTransaction</code></a> representa una transacción. Cuando Ud. crea una transacción en la base de datos, especifica el alcance (como a que objetos store desea tener acceso), y determina la clase de acceso (sólo lectura o escritura) que desea tener.</li> + <li><a href="/en-US/docs/IndexedDB/IDBVersionChangeEvent" title="IDBVersionChangeEvent"><code>IDBVersionChangeEvent</code></a> indica que la versión de la base de datos ha cambiado.</li> +</ul> + +<p>Una versión anterior de la especificación también define estas -ahora removidas- interfaces. Éstas son documentadas todavía, en caso de que necesite actualizar código escrito previamente:</p> + +<ul> + <li><code><a href="/en-US/docs/IndexedDB/IDBVersionChangeRequest" title="https://developer.mozilla.org/en-US/docs/IndexedDB/IDBVersionChangeRequest">IDBVersionChangeRequest</a></code> representa una solicitud para cambiar la versión de una base de datos. La manera de cambiar la versión de la base de datos ahora es diferente (llamando <a href="/en-US/docs/IndexedDB/IDBFactory#open" title="en-US/docs/IndexedDB/IDBFactory#open"><code>IDBFactory.open()</code></a> sin llamar también a <a href="/en-US/docs/IndexedDB/IDBDatabase#setVersion()" title="en-US/docs/IndexedDB/IDBDatabase#setVersion()"><code>IDBDatabase.setVersion()</code></a>), y la interfaz <a href="/en-US/docs/IndexedDB/IDBOpenDBRequest" title="en-US/docs/IndexedDB/IDBOpenDBRequest"><code>IDBOpenDBRequest</code></a> tiene ahora la funcionalidad de la eliminada <code>IDBVersionChangeRequest</code>.</li> + <li><code><a href="/en-US/docs/IndexedDB/IDBDatabaseException" title="en-US/docs/IndexedDB/DatabaseException">IDBDatabaseException </a></code> {{ obsolete_inline() }} representa las condiciones de excepción que se pueden encontrar mientras se ejecutan operaciones en la base de datos.</li> +</ul> + +<p>Hay también una <a href="/en-US/docs/IndexedDB/Syncronous_API" title="/en-US/docs/IndexedDB/SyncronousAPI">versión sincrónica de la API</a>. La API síncrona no ha sido implementada en cualquier navegador. Está destinada a ser usada con <a href="/en-US/docs/DOM/Using_web_workers" title="https://developer.mozilla.org/en-US/docs/Using_web_workers">WebWorkers</a>.</p> + +<h2 id="Límites_de_almacenamiento">Límites de almacenamiento</h2> + +<p>No existe un límite de tamaño para un elemento simple de la base de datos. Sin embargo, puede haber un límite en el tamaño de cada base de datos IndexedDB. Este límite (y la forma en que la interfaz de usuario la hace valer) puede variar de una navegador a otro:</p> + +<ul> + <li> + <p>Firefox: no hay límite en el tamaño de una base de datos IndexedDB. La interfaz de usuario solicita permiso para almacenar blobs de más de 50MB. Este límite puede ser modificado mediante la preferencia dom.indexedDB.warningQuota (que está definida en <a href="http://mxr.mozilla.org/mozilla-central/source/modules/libpref/src/init/all.js" title="http://mxr.mozilla.org/mozilla-central/source/modules/libpref/src/init/all.js">http://mxr.mozilla.org/mozilla-central/source/modules/libpref/src/init/all.js</a>).</p> + </li> + <li>Google Chrome: vea <a class="link-https" href="https://developers.google.com/chrome/whitepapers/storage#temporary" rel="freelink">https://developers.google.com/chrome...rage#temporary</a></li> +</ul> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<p>Un claro ejemplo para lo que IndexedDB puede ser utilizado en la web, es el ejemplo de Marco Castelluccio, ganador del DevDerby IndexedDB Mozilla. La demostración ganadora fue <a href="/en-US/demos/detail/elibri" title="https://developer.mozilla.org/en-US/demos/detail/elibri">eLibri</a>, una biblioteca y una aplicación de lectura de libros electrónicos.</p> + +<h2 id="Browser_compatibility" name="Browser_compatibility">Compatibilidad de los navegadores</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>API asíncrono</td> + <td> + <p>24.0<br> + 11.0 {{ property_prefix("webkit") }}</p> + </td> + <td> + <p>{{ CompatGeckoDesktop("16.0") }}<br> + {{ CompatGeckoDesktop("2.0") }} {{ property_prefix("moz") }}</p> + </td> + <td>10 {{ property_prefix("ms") }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + </tr> + <tr> + <td>API síncrono<br> + (usado por <a href="/en-US/docs/DOM/Using_web_workers" title="https://developer.mozilla.org/en-US/docs/Using_web_workers">WebWorkers</a>)</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}<br> + Vea {{ bug(701634) }}</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>Característica</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>API síncrono</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatGeckoDesktop("6.0") }} {{ property_prefix("moz") }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + </tr> + </tbody> +</table> +</div> + +<p>Para otra matriz de compatibilidad, vea también: <a href="http://caniuse.com/indexeddb" title="http://caniuse.com/indexeddb">Cuándo puedo usar IndexedDB</a></p> + +<p>También existe la posibilidad de usar IndexedDB en <a href="http://caniuse.com/sql-storage" title="http://caniuse.com/sql-storage"> navegadores que soportan WebSQL</a> por el uso de <a href="https://github.com/axemclion/IndexedDBShim" title="https://github.com/axemclion/IndexedDBShim">IndexedDB Polyfill</a>.</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/IndexedDB/Basic_Concepts_Behind_IndexedDB" title="en-US/docs/IndexedDB/Basic Concepts Behind IndexedDB">Conceptos básicos acerca de IndexedDB</a></li> + <li><a href="/en-US/docs/IndexedDB/Using_IndexedDB" title="en-US/docs/IndexedDB/IndexedDB primer">Usando IndexedDB</a></li> + <li><a class="external" href="http://hacks.mozilla.org/2012/02/storing-images-and-files-in-indexeddb/" title="http://hacks.mozilla.org/2012/02/storing-images-and-files-in-indexeddb/">Almacenando imágenes y archivos en IndexedDB</a></li> + <li><a class="external" href="http://www.html5rocks.com/tutorials/indexeddb/todo/" title="http://www.html5rocks.com/tutorials/indexeddb/todo/">Una lista simple de PENDIENTES usando HTML5 IndexedDB</a>. Nota("Este tutorial está basado en una antigua versión de la especificación y no funciona en los navegadores actualizados. por ejemplo, todavía usa el método actualmente eliminado <code>setVersion()</code>.")</li> + <li><a class="external" href="http://www.w3.org/TR/IndexedDB/" title="http://www.w3.org/TR/IndexedDB/">Especificación de la API para Indexed Database </a></li> + <li><a class="external" href="http://msdn.microsoft.com/en-us/scriptjunkie/gg679063.aspx" title="http://msdn.microsoft.com/en-us/scriptjunkie/gg679063.aspx">IndexedDB — El alamcén en su navegador</a></li> + <li><a class="external" href="http://caniuse.com/indexeddb" title="http://caniuse.com/indexeddb">Soporte IndexedDB en navegadores</a></li> + <li><a class="external" href="http://nparashuram.com/IndexedDB/trialtool/index.html" title="http://nparashuram.com/IndexedDB/trialtool/index.html">Ejemplos IndexedDB</a></li> + <li><a href="https://github.com/axemclion/IndexedDBShim" title="https://github.com/axemclion/IndexedDBShim">IndexedDB Polyfill</a> para navegadores que sólo soportan WebSQL (p.e. mobile WebKit)</li> + <li><a href="http://nparashuram.com/IndexedDBShim/" title="http://nparashuram.com/IndexedDBShim/">JQuery IndexedDB plugin</a></li> +</ul> diff --git a/files/es/web/api/indexeddb_api/usando_indexeddb/index.html b/files/es/web/api/indexeddb_api/usando_indexeddb/index.html new file mode 100644 index 0000000000..ea9d2d879c --- /dev/null +++ b/files/es/web/api/indexeddb_api/usando_indexeddb/index.html @@ -0,0 +1,1308 @@ +--- +title: Usando IndexedDB +slug: Web/API/IndexedDB_API/Usando_IndexedDB +tags: + - API + - Almacenamiento + - Avanzado + - Base de datos + - Guía + - IndexedDB + - Tutorial + - jsstore +translation_of: Web/API/IndexedDB_API/Using_IndexedDB +--- +<div class="summary"> +<p>IndexedDB es una manera de almacenar datos dentro del navegador del usuario. Debido a que permite la creación de aplicaciones con habilidades de consulta enriquecidas, con independencia de la disponibilidad de la red, sus aplicaciones pueden trabajar tanto en línea como fuera de línea.</p> +</div> + +<h2 id="Acerca_de_este_documento">Acerca de este documento</h2> + +<p>Este tutorial es una guía sobre el uso de la API asíncrona de IndexedDB. Si no está familiarizado con IndexedDB, por favor consulte primero <a href="/en/IndexedDB/Basic_Concepts_Behind_IndexedDB" style="line-height: 1.5;" title="en/IndexedDB/Basic Concepts Behind IndexedDB">Conceptos Básicos Acerca de IndexedDB</a><span style="line-height: 1.5;">.</span></p> + +<p>Para la documentación de referencia sobre la API de IndexedDB, vea el artículo <a href="/es/docs/IndexedDB" style="line-height: 1.5;" title="https://developer.mozilla.org/en/IndexedDB">IndexedDB</a><span style="line-height: 1.5;"> y sus subpaginas, que documentan los tipos de objetos usados por IndexedDB, así como los métodos síncronos y asíncronos. </span></p> + +<h2 id="pattern" name="pattern">Patrones Básicos</h2> + +<p>El patrón básico que indexedDB propone es:</p> + +<ol> + <li>Abrir una base de datos.</li> + <li>Crear un objeto de almacenamiento en la base de datos.</li> + <li>Iniciar una transacción y hacer una petición para hacer alguna operación de la base de datos, tal como añadir o recuperar datos.</li> + <li> + <div><span id="result_box" lang="es"><span class="hps">Espere a que</span> <span class="hps">se complete la operación</span> <span class="hps">por</span> <span class="hps">la escucha de la</span> <span class="hps">clase correcta de</span> <span class="hps">eventos DOM</span></span> .</div> + </li> + <li> + <div>Hacer algo con el resultado (El cual puede ser encontrado en el objeto de la petición).</div> + </li> +</ol> + +<p>Con esos grandes rasgos en mente, seremos más concretos.</p> + +<h2 id="open" name="open">Creando y estructurando el almacenamiento</h2> + +<p>Como las especificaciones están todavía elaborandose, las implementaciones actuales de indexedDB dependen de los navegadores. H<span id="result_box" lang="es"><span class="hps">asta que la</span> <span class="hps">especificación</span> <span class="hps">se haya consolidado, l</span></span>os proveedores de navegadores pueden tener diferentes implementaciones de los estandares de indexedDB<span id="result_box" lang="es"><span>.</span></span> Una vez se alcance el consenso en el estandar, los proveedores implementarán la API sin prefijos. En algunas implementaciones ya fueron removidos los prefijos: Internet Explorer 10, Firefox 16, Chrome 24. Cuando utilizan un prefijo, los navegadores basados en gecko usan el prefijo <code>moz</code> , mientras que los navegadores basados en WebKit usan el prefijo <code>webkit</code>.</p> + +<h3 id="Usando_una_versión_experimental_de_IndexedDB">Usando una versión experimental de IndexedDB</h3> + +<p>En caso que usted quiera probar su código en navegadores que todavía usen un prefijo, puede usar el siguiente codigo: </p> + +<pre class="brush: js">// En la siguiente línea, puede incluir prefijos de implementación que quiera probar. +window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB; +// No use "var indexedDB = ..." Si no está en una función. +// Por otra parte, puedes necesitar referencias a algun objeto window.IDB*: +window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction; +window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange; +// (Mozilla nunca ha prefijado estos objetos, por lo tanto no necesitamos window.mozIDB*)</pre> + +<p>Hay que tener cuidado con las implementaciones que usan un prefijo ya que puede ser inestables, incompletas, o usen una versión antigua de la especificación. En producción se recomienda usar el código sin prefijos. Es preferible no tener soporte para un navegador a decir que lo tiene y fallar en ello :</p> + +<pre class="brush: js">if (!window.indexedDB) { + window.alert("Su navegador no soporta una versión estable de indexedDB. Tal y como las características no serán validas"); +} +</pre> + +<h3 id="Abriendo_una_base_de_datos">Abriendo una base de datos</h3> + +<p>Iniciamos todo el proceso así:</p> + +<pre class="brush: js">// dejamos abierta nuestra base de datos +var request = window.indexedDB.open("MyTestDatabase", 3); +</pre> + +<p>¿Lo has visto? Abrir una base de datos es igual que cualquier otra operación — solo tienes que "solicitarla" (request).</p> + +<p>La solicitud de apertura no abre la base de datos o inicia la transacción de inmediato. La llamada a la función <code>open()</code> retornan unos objetos <code><a href="/en-US/docs/IndexedDB/IDBOpenDBRequest" title="/en-US/docs/IndexedDB/IDBOpenDBRequest">IDBOpenDBRequest</a>,</code> cuyo resultado, correcto o erróneo, se maneja en un evento. Alguna otra función asincrónica en indexedDB hace lo mismo - Devolver un objeto <a href="/en-US/docs/IndexedDB/IDBRequest" title="/en-US/docs/IndexedDB/IDBRequest"><code style="font-size: 14px; color: rgb(51, 51, 51);">IDBRequest</code></a> que disparará un evento con el resultado o el error. El resultado para la función de abrir es una instancia de un <code style="font-size: 14px; color: rgb(51, 51, 51);"><a href="/en-US/docs/IndexedDB/IDBDatabase" title="/en-US/docs/IndexedDB/IDBDatabase">IDBDatabase</a>.</code></p> + +<p>El segundo parámetro para el método open es la versión de la base de datos. La versión de la base de datos determina el esquema - El almacen de objectos en la base de datos y su estructura. Si la base de datos no existe, es creada y se dispara un evento <code>onupgradeneeded</code> de inmediato, permitiéndote proveer una actualización de la estructura e índices en la función que capture dicho evento. Se verá más adelante en <a href="#Updating_the_version_of_the_database">Actualizando la versión de la base de datos</a>. </p> + +<div class="warning"> +<p><strong>Importante</strong>: El número de versión es un <code>unsigned long</code>. Por lo tanto significa que puede ser un entero muy grande. También significa que si usas un flotante será convertido en un entero más cercano y la transacción puede no ser iniciada, el evento <code>upgradeneeded </code>no se desencadenará. Por ejemplo no use 2.4 como un número de versión ya que será igual que la 2:</p> + +<pre class="brush: js">var request = indexedDB.open("MyTestDatabase", 2.4); // Esto no se hace, la versión será redondeada a 2</pre> +</div> + +<h4 id="Generando_manipuladores">Generando manipuladores</h4> + +<p>La primera cosa que usted querrá hacer con la totalidad de las peticiones que usted genera es agregar controladores de éxito y de error:</p> + +<pre class="brush: js">request.onerror = function(event) { + // Hacer algo con request.errorCode! +}; +request.onsuccess = function(event) { + // Hacer algo con request.result! +};</pre> + +<p>¿Cuál de las dos funciones, onSuccess () o onerror (), se vuelve a llamar? Si todo tiene éxito, un evento de éxito (es decir, un evento DOM cuya propiedad tipo se establece en el "éxito") se dispara con la solicitud como su objetivo. Una vez que se dispara, la función onSuccess () a petición se activa con el evento de éxito como argumento. De lo contrario, si había algún problema, un evento de error (es decir, un evento DOM cuyo tipo de propiedad se establece en "error") se dispara a petición. Esto desencadena la función onerror () con el evento de error como argumento.</p> + +<p>La API IndexedDB está diseñada para minimizar la necesidad de control de errores, por lo que no es probable que veamos muchos eventos de error (al menos, no una vez que estás acostumbrado a la API). En el caso de la apertura de una base de datos, sin embargo, hay algunas condiciones comunes que generan eventos de error. El problema más común se produce cuando el usuario ha decidido no dar, a su aplicación web, el permiso para crear una base de datos. Uno de los principales objetivos de diseño de IndexedDB es permitir que grandes cantidades de datos se almacenen para su uso sin conexión a internet. (Para obtener más información sobre la cantidad de almacenamiento que puede tener para cada navegador, consulte <a href="https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API#Storage_limits">Límites de almacenamiento</a>.) </p> + +<p>Obviamente, los navegadores no permitirán que alguna red de publicidad o sitio web malicioso pueda contaminar su ordenador, por ello los navegadores utilizan un diálogo para indicar al usuario la primera vez que cualquier aplicación web determinada intente abrir una IndexedDB para el almacenamiento. El usuario puede optar por permitir o denegar el acceso. Además, el almacenamiento IndexedDB en los modos de privacidad navegadores sólo dura en memoria hasta que la sesión de incógnito haya sido cerrada (modo de navegación privada para el modo de Firefox e Incognito para Chrome, pero en Firefox <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=781982">no está implementado</a> a partir de noviembre 2015 por lo que no puede utilizar IndexedDB en Firefox navegación privada en absoluto).</p> + +<p>Ahora, asumiendo que el usuario acepta su solicitud para crear una base de datos, y que ha recibido un evento de éxito para activar la devolución de llamada de éxito; ¿Que sigue? La solicitud aquí se generó con una llamada a indexedDB.open (), por lo request.result es una instancia de IDBDatabase, y que sin duda quieren ahorrar para más adelante. Su código podría ser algo como esto:</p> + +<pre class="brush: js">var db; +var request = indexedDB.open("MyTestDatabase"); +request.onerror = function(event) { + alert("Why didn't you allow my web app to use IndexedDB?!"); +}; +request.onsuccess = function(event) { + db = request.result; +}; +</pre> + +<h4 id="Manejando_errores">Manejando errores</h4> + +<p>Como se mencionó anteriormente, los eventos de error de burbujas. Eventos de error se dirigen a la solicitud que generó el error, entonces el evento se propaga a la operación, y finalmente con el objeto de base de datos. Si desea evitar la adición de controladores de errores a cada solicitud, en su lugar puede añadir un solo controlador de errores en el objeto de base de datos, así:</p> + +<pre class="brush: js">db.onerror = function(event) { + // Generic error handler for all errors targeted at this database's + // requests! + alert("Database error: " + event.target.errorCode); +}; +</pre> + +<p>Uno de los errores más comunes posibles al abrir una base de datos es <code>VER_ERR</code>. Indica que la versión de la base de datos almacenada en el disco es mayor que la versión que está intentando abrir. Este es un caso de error que siempre debe ser manejado por el gestor de errores.</p> + +<h3 id="Creación_o_actualización_de_la_versión_de_la_base_de_datos">Creación o actualización de la versión de la base de datos</h3> + +<p>Cuando se crea una nueva base de datos o se aumenta el número de versión de una base de datos existente (mediante la especificación de un número de versión más alto de lo que hizo antes, en {{anch ("Cómo abrir una base de datos")}}), el evento onupgradeneeded se activará y un objeto <a href="https://developer.mozilla.org/en-US/docs/Web/API/IDBVersionChangeEvent">IDBVersionChangeEvent</a> será pasado a cualquier controlador de eventos <code>onversionchange</code> establecido en <code>request.result</code> (es decir, db en el ejemplo). En el controlador para el evento <code>upgradeneeded</code>, se debe crear los almacenes de objetos necesarios para esta versión de la base de datos:</p> + +<pre class="brush:js;">// Este evento solamente está implementado en navegadores recientes +request.onupgradeneeded = function(event) { + var db = event.target.result; + + // Crea un almacén de objetos (objectStore) para esta base de datos + var objectStore = db.createObjectStore("name", { keyPath: "myKey" }); +};</pre> + +<p>En este caso, la base de datos ya tendrá los almacenes de objetos de la versión anterior de la base de datos, por lo que no tiene que crear estos almacenes de objetos de nuevo. Sólo es necesario crear nuevos almacenes de objetos, o eliminar las tiendas de objetos de la versión anterior que ya no son necesarios. Si necesita cambiar un almacén de objetos existentes (por ejemplo, para cambiar la ruta de acceso clave <code>keyPath</code>), entonces se debe eliminar el antiguo almacén de objetos y crear de nuevo con las nuevas opciones. (Tenga en cuenta que esto borrará la información en el almacén de objetos Si usted necesita guardar esa información, usted debe leerlo y guardarlo en otro lugar antes de actualizar la base de datos.)</p> + +<p>Tratar de crear un almacén de objetos con un nombre que ya existe (o tratando de eliminar un almacén de objetos con un nombre que no existe) lanzará un error.</p> + +<p>Si el evento <code>onupgradeneeded</code> retorna éxito, entonces se activará el manejador <code>onsuccess</code> de la solicitud de base de datos abierta.</p> + +<p>Blink / Webkit soportan la versión actual de la especificación, tal como fue liberado en Chrome 23+ y Opera 17+ ; IE10+ también lo soporta. Implementaciones mas viejas o distintas no implementan la versión actual de la especificación, y por lo tanto no son compatibles todavía con el <code>indexedDB.open (nombre, versión).onupgradeneeded</code> . Para obtener más información sobre cómo actualizar la versión de la base de datos en Webkit/Blink mas viejos, consulte el artículo de referencia <a href="/es/docs/Web/API/IDBDatabase" title="https://developer.mozilla.org/en/IndexedDB/IDBDatabase#setVersion()_.0A.0ADeprecated">IDBDatabase</a>.</p> + +<h3 id="Estructuración_de_la_base_de_datos">Estructuración de la base de datos</h3> + +<p>Ahora para estructurar la base de datos. IndexedDB usa almacenes de datos (object stores) en lugar de tablas, y una base de datos puede contener cualquier número de almacenes. Cuando un valor es almacenado, se le asocia con una clave. Existen diversas maneras en que una clave pude ser indicada dependiendo de si el almacén usa una <a href="https://developer.mozilla.org/en/IndexedDB/Basic_Concepts_Behind_IndexedDB#gloss_keypath">ruta de clave</a> o <a href="https://developer.mozilla.org/en/IndexedDB/Basic_Concepts_Behind_IndexedDB#gloss_keygenerator">generador</a>.</p> + +<p>La siguiente table muetra las distintas formas en que las claves pueden ser indicadas:</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Ruta de clave(<code>keyPath</code>)</th> + <th scope="col">Generador de clave (<code>autoIncrement</code>)</th> + <th scope="col">Descripción</th> + </tr> + </thead> + <tbody> + <tr> + <td>No</td> + <td>No</td> + <td>Este almacén puede contener cualquier tipo de valor, incluso valores primitivos como números y cadenas. Se debe indicar un argumento de clave distinto cada vez que se agregue un nuevo valor.</td> + </tr> + <tr> + <td>Si</td> + <td>No</td> + <td>Este almacén de objetos solo puede contener objetos de JavaScript. Los objetos deben tener una propiedad con el mismo nombre que la ruta de clave.</td> + </tr> + <tr> + <td>No</td> + <td>Si</td> + <td>Este objeto puede contener cualquier tipo de valor. La clave es generada automáticamente, o se puede indicar un argumento de clave distinto si se quiere usar una clave específica.</td> + </tr> + <tr> + <td>Si</td> + <td>Si</td> + <td> + <p>Este almacén de objetos solo puede contener objetos de JavaScript. Usualmente una clave es generada y dicho valor es almacenado en el objeto en una propiedad con el mismo nombre que la ruta de clave. Sin embargo, si dicha propiedad ya existe en el objeto, el valor de esa propuiedad es usado como clave en lugar de generar una nueva.</p> + </td> + </tr> + </tbody> +</table> + +<p>También se puede crear índices en cualquer almacén de objetos, siempre y cuando el almacén contenga objets, y no primitivos. Un índice permite buscar valores contenidos en el almacén usando el valor de una propiedad del objeto almacenado, en lugar de la clave del mismo.</p> + +<p>Adicionalmente, los índices tienen la habilidad para hacer cumplir restricciones simples en los datos almacendos. Al indicar la bandera <code>unique</code> al crear el índice, el índice asegurará que no se puedan almacenar dos objetos que tengan el mismo valor para la clave del índice. Así, por ejemplo si se tiene un almacén de objetos que contiene un set de personas, y se desea asegurar que no existan dos personas con el mismo email, se puede usar un índice con la bandera <code>unique</code> activada para forzar esto.</p> + +<p>Esto puede sonar confuso, pero un ejemplo simple debe ilustrar el concepto. Primero, definiremos alguna información de clientes para usar en nuestro ejemplo:</p> + +<pre class="brush: js">// Así se ve nuestra información de clientes. +const customerData = [ + { ssn: "444-44-4444", name: "Bill", age: 35, email: "bill@company.com" }, + { ssn: "555-55-5555", name: "Donna", age: 32, email: "donna@home.org" } +]; +</pre> + +<p>Ahora, creemos una IndexedDB para almacenar los datos:</p> + +<pre class="brush: js">const dbName = "the_name"; + +var request = indexedDB.open(dbName, 2); + +request.onerror = function(event) { + // Manejar errores. +}; +request.onupgradeneeded = function(event) { + var db = event.target.result; + + // Se crea un almacén para contener la información de nuestros cliente + // Se usará "ssn" como clave ya que es garantizado que es única + var objectStore = db.createObjectStore("customers", { keyPath: "ssn" }); + + // Se crea un índice para buscar clientes por nombre. Se podrían tener duplicados + // por lo que no se puede usar un índice único. + objectStore.createIndex("name", "name", { unique: false }); + + // Se crea un índice para buscar clientespor email. Se quiere asegurar que + // no puedan haberdos clientes con el mismo email, asi que se usa un índice único. + objectStore.createIndex("email", "email", { unique: true }); + + // Se usa transaction.oncomplete para asegurarse que la creación del almacén + // haya finalizado antes de añadir los datos en el. + objectStore.transaction.oncomplete = function(event) { + // Guarda los datos en el almacén recién creado. + var customerObjectStore = db.transaction("customers", "readwrite").objectStore("customers"); + for (var i in customerData) { + customerObjectStore.add(customerData[i]); + } + } +}; +</pre> + +<p>Como se indicó previamente, <code>onupgradeneeded</code> es el único lugar donde se puede alterar la estructura de la base de datos. En el, se puede crear y borrar almacenes de objetos y construir y remover índices.</p> + +<div>Los almacenes de datos son creados con una llamada a <code>createObjectStore()</code>. El método toma como parámetros el nombre del almacén y un objeto. A pesar de que el segundo parámetro es opcional, es muy importante, porque permite definir propiedades opcionales importantes y refinar el tipo de almacén que se desea crear. En este caso, se pregunta por un almacén llamado "customers" y se define la clave, que es la propiedad que indica que un objeto en el almacén es único. La propiedad en este ejemplo es "ssn" (Social Security Number) ya que los números de seguridad social está garantizado que sea único. "ssn" debe estar presente en cada objeto que se guarda al almacén.</div> + +<p>También se solicitó crear un índice llamado "name" que se fija en la propiedad <code>name </code>de los objetos almacenados. Así como con <code>createObjectStore()</code>, <code>createIndex()</code> toma un objeto opcional <code>options</code> que refina el tipo de índice que se desea crear. Agregar objetos que no tengan una propiedad <code>name</code> funcionará, pero los objetos no aparecerán en el índice "name"</p> + +<div>Ahora se pueden obtener los clientes almacenados usando su <code>ssn</code> directamente del almacen, o usando su nombre a través del índice. Para aprender como hacer esto, vea la sección <a href="#El_uso_de_un_índice">El uso de un índice</a></div> + +<h3 id="El_uso_de_un_generador_de_claves">El uso de un generador de claves</h3> + +<p>Indicar la bandera <code>autoIncrement </code> cuando se crea el almacén habilitará el generador de claves para dicho almacén. Por defecto esta bandera no está marcada.</p> + +<p>Con el generador de claves, la clave será generada automáticamente a medida que se agreguen valores al almacén. El número actual de un generador de claves siempre se establece en 1 cuando se creal el almacén por primera vez. Básicamente la nueva clave autogenerada es incrementada en 1 basada en la llave anterior. El numero actual para un generador de claves nunca disminuye, salvo como resultado de operaciones de base de datos que sean revertidos, por ejemplo, cuando la transacción de base de datos es abortada. Por lo tanto borrar un registro o incluso borrar todos los registros de un almacén nunca afecta al generador de claves</p> + +<p>Se puede crear otro almacén de objetos con generador de claves como se muestra abajo:</p> + +<pre class="brush: js">// Abrir la indexedDB. +var request = indexedDB.open(dbName, 3); + +request.onupgradeneeded = function (event) { + + var db = event.target.result; + + // Create another object store called "names" with the autoIncrement flag set as true. + var objStore = db.createObjectStore("names", { autoIncrement : true }); + + // Because the "names" object store has the key generator, the key for the name value is generated automatically. + // The added records would be like: + // key : 1 => value : "Bill" + // key : 2 => value : "Donna" + for (var i in customerData) { + objStore.add(customerData[i].name); + } +}</pre> + +<p>Para más detalles acerca del generador de claves, por favor ver <a href="http://www.w3.org/TR/IndexedDB/#key-generator-concept">"W3C Key Generators"</a>.</p> + +<h2 id="Añadir_recuperación_y_eliminación_de_datos">Añadir, recuperación y eliminación de datos</h2> + +<p>Antes que haga algo con su nueva base de datos , necesita comenzar una transacción. Transactions come from the database object, and you have to specify which object stores you want the transaction to span. Once you are inside the transaction, you can access the object stores that hold your data and make your requests. Next, you need to decide if you're going to make changes to the database or if you just need to read from it. Transactions have three available modes: <code>readonly</code>, <code>readwrite</code>, and <code>versionchange</code>.</p> + +<p>To change the "schema" or structure of the database—which involves creating or deleting object stores or indexes—the transaction must be in <code>versionchange</code> mode. This transaction is opened by calling the {{domxref("IDBFactory.open")}} method with a <code>version</code> specified. (In WebKit browsers, which have not implemented the latest specifcation, the {{domxref("IDBFactory.open")}} method takes only one parameter, the <code>name</code> of the database; then you must call {{domxref("IDBVersionChangeRequest.setVersion")}} to establish the <code>versionchange</code> transaction.)</p> + +<p>To read the records of an existing object store, the transaction can either be in <code>readonly</code> or <code>readwrite</code> mode. To make changes to an existing object store, the transaction must be in <code>readwrite</code> mode. You open such transactions with {{domxref("IDBDatabase.transaction")}}. The method accepts two parameters: the <code>storeNames</code> (the scope, defined as an array of object stores that you want to access) and the <code>mode</code> (<code>readonly</code> or <code>readwrite</code>) for the transaction. The method returns a transaction object containing the {{domxref("IDBIndex.objectStore")}} method, which you can use to access your object store. By default, where no mode is specified, transactions open in <code>readonly</code> mode.</p> + +<p>You can speed up data access by using the right scope and mode in the transaction. Here are a couple of tips:</p> + +<ul> + <li>When defining the scope, specify only the object stores you need. This way, you can run multiple transactions with non-overlapping scopes concurrently.</li> + <li>Only specify a <code>readwrite</code> transaction mode when necessary. You can concurrently run multiple <code>readonly</code> transactions with overlapping scopes, but you can have only one <code>readwrite</code> transaction for an object store. To learn more, see the definition for <dfn><a href="/en-US/docs/IndexedDB/Basic_Concepts_Behind_IndexedDB#Database">transactions</a></dfn> in the <a href="/en-US/docs/IndexedDB/Basic_Concepts_Behind_IndexedDB">Basic Concepts</a> article.</li> +</ul> + +<h3 id="Agregar_datos_a_la_base_de_datos">Agregar datos a la base de datos</h3> + +<p>If you've just created a database, then you probably want to write to it. Here's what that looks like:</p> + +<pre class="brush:js;">var transaction = db.transaction(["customers"], "readwrite"); +// Note: Older experimental implementations use the deprecated constant IDBTransaction.READ_WRITE instead of "readwrite". +// In case you want to support such an implementation, you can write: +// var transaction = db.transaction(["customers"], IDBTransaction.READ_WRITE);</pre> + +<p>The <code>transaction()</code> function takes two arguments (though one is optional) and returns a transaction object. The first argument is a list of object stores that the transaction will span. You can pass an empty array if you want the transaction to span all object stores, but don't do it because the spec says an empty array should generate an InvalidAccessError. If you don't specify anything for the second argument, you get a read-only transaction. Since you want to write to it here you need to pass the <code>"readwrite"</code> flag.</p> + +<p>Now that you have a transaction you need to understand its lifetime. Transactions are tied very closely to the event loop. If you make a transaction and return to the event loop without using it then the transaction will become inactive. The only way to keep the transaction active is to make a request on it. When the request is finished you'll get a DOM event and, assuming that the request succeeded, you'll have another opportunity to extend the transaction during that callback. If you return to the event loop without extending the transaction then it will become inactive, and so on. As long as there are pending requests the transaction remains active. Transaction lifetimes are really very simple but it might take a little time to get used to. A few more examples will help, too. If you start seeing <code>TRANSACTION_INACTIVE_ERR</code> error codes then you've messed something up.</p> + +<p>Transactions can receive DOM events of three different types: <code>error</code>, <code>abort</code>, and <code>complete</code>. We've talked about the way that <code>error</code> events bubble, so a transaction receives error events from any requests that are generated from it. A more subtle point here is that the default behavior of an error is to abort the transaction in which it occurred. Unless you handle the error by first calling <code>preventDefault()</code> on the error event then doing something else, the entire transaction is rolled back. This design forces you to think about and handle errors, but you can always add a catchall error handler to the database if fine-grained error handling is too cumbersome. If you don't handle an error event or if you call <code>abort()</code> on the transaction, then the transaction is rolled back and an <code>abort</code> event is fired on the transaction. Otherwise, after all pending requests have completed, you'll get a <code>complete</code> event. If you're doing lots of database operations, then tracking the transaction rather than individual requests can certainly aid your sanity.</p> + +<p>Now that you have a transaction, you'll need to get the object store from it. Transactions only let you have an object store that you specified when creating the transaction. Then you can add all the data you need.</p> + +<pre class="brush: js">// Do something when all the data is added to the database. +transaction.oncomplete = function(event) { + alert("All done!"); +}; + +transaction.onerror = function(event) { + // Don't forget to handle errors! +}; + +var objectStore = transaction.objectStore("customers"); +for (var i in customerData) { + var request = objectStore.add(customerData[i]); + request.onsuccess = function(event) { + // event.target.result == customerData[i].ssn; + }; +}</pre> + +<p>The <code>result</code> of a request generated from a call to <code>add()</code> is the key of the value that was added. So in this case, it should equal the <code>ssn</code> property of the object that was added, since the object store uses the <code>ssn</code> property for the key path. Note that the <code>add()</code> function requires that no object already be in the database with the same key. If you're trying to modify an existing entry, or you don't care if one exists already, you can use the <code>put()</code> function, as shown below in the {{ anch("Updating an entry in the database") }} section.</p> + +<h3 id="Extracción_de_datos_de_la_base_de_datos">Extracción de datos de la base de datos</h3> + +<p>Removing data is very similar:</p> + +<pre class="brush: js">var request = db.transaction(["customers"], "readwrite") + .objectStore("customers") + .delete("444-44-4444"); +request.onsuccess = function(event) { + // It's gone! +};</pre> + +<h3 id="Obtener_datos_de_la_base_de_datos">Obtener datos de la base de datos</h3> + +<p>Now that the database has some info in it, you can retrieve it in several ways. First, the simple <code>get()</code>. You need to provide the key to retrieve the value, like so:</p> + +<pre class="brush: js">var transaction = db.transaction(["customers"]); +var objectStore = transaction.objectStore("customers"); +var request = objectStore.get("444-44-4444"); +request.onerror = function(event) { + // Handle errors! +}; +request.onsuccess = function(event) { + // Do something with the request.result! + alert("Name for SSN 444-44-4444 is " + request.result.name); +};</pre> + +<p>That's a lot of code for a "simple" retrieval. Here's how you can shorten it up a bit, assuming that you handle errors at the database level:</p> + +<pre class="brush: js">db.transaction("customers").objectStore("customers").get("444-44-4444").onsuccess = function(event) { + alert("Name for SSN 444-44-4444 is " + event.target.result.name); +};</pre> + +<p>See how this works? Since there's only one object store, you can avoid passing a list of object stores you need in your transaction and just pass the name as a string. Also, you're only reading from the database, so you don't need a <code>"readwrite"</code> transaction. Calling <code>transaction()</code> with no mode specified gives you a <code>"readonly"</code> transaction. Another subtlety here is that you don't actually save the request object to a variable. Since the DOM event has the request as its target you can use the event to get to the <code>result</code> property.</p> + +<div class="note"> +<p><strong>Note</strong>: You can speed up data access by limiting the scope and mode in the transaction. Here are a couple of tips:</p> + +<ul> + <li> + <p>When defining the <a href="#scope">scope</a>, specify only the object stores you need. This way, you can run multiple transactions with non-overlapping scopes concurrently.</p> + </li> + <li> + <p>Only specify a <code>readwrite</code> transaction mode when necessary. You can concurrently run multiple <code>readonly</code> transactions with overlapping scopes, but you can have only one <code>readwrite</code> transaction for an object store. To learn more, see the definition for <a href="/en-US/docs/IndexedDB/Basic_Concepts_Behind_IndexedDB#gloss_transaction"><dfn>transactions</dfn> in the Basic Concepts article</a>.</p> + </li> +</ul> +</div> + +<h3 id="Actualización_de_una_entrada_en_la_base_de_datos">Actualización de una entrada en la base de datos</h3> + +<p>Now we've retrieved some data, updating it and inserting it back into the IndexedDB is pretty simple. Let's update the previous example somewhat:</p> + +<pre class="brush: js">var objectStore = db.transaction(["customers"], "readwrite").objectStore("customers"); +var request = objectStore.get("444-44-4444"); +request.onerror = function(event) { + // Handle errors! +}; +request.onsuccess = function(event) { + // Get the old value that we want to update + var data = request.result; + + // update the value(s) in the object that you want to change + data.age = 42; + + // Put this updated object back into the database. + var requestUpdate = objectStore.put(data); + requestUpdate.onerror = function(event) { + // Do something with the error + }; + requestUpdate.onsuccess = function(event) { + // Success - the data is updated! + }; +};</pre> + +<p>So here we're creating an <code>objectStore</code> and requesting a customer record out of it, identified by its ssn value (<code>444-44-4444</code>). We then put the result of that request in a variable (<code>data</code>), update the <code>age</code> property of this object, then create a second request (<code>requestUpdate</code>) to put the customer record back into the <code>objectStore</code>, overwriting the previous value.</p> + +<div class="note"> +<p><strong>Note</strong> that in this case we've had to specify a <code>readwrite</code> transaction because we want to write to the database, not just read out of it.</p> +</div> + +<h3 id="El_uso_de_un_cursor">El uso de un cursor</h3> + +<p>Using <code>get()</code> requires that you know which key you want to retrieve. If you want to step through all the values in your object store, then you can use a cursor. Here's what it looks like:</p> + +<pre class="brush: js">var objectStore = db.transaction("customers").objectStore("customers"); + +objectStore.openCursor().onsuccess = function(event) { + var cursor = event.target.result; + if (cursor) { + alert("Name for SSN " + cursor.key + " is " + cursor.value.name); + cursor.continue(); + } + else { + alert("No more entries!"); + } +};</pre> + +<p>The<code> openCursor()</code> function takes several arguments. First, you can limit the range of items that are retrieved by using a key range object that we'll get to in a minute. Second, you can specify the direction that you want to iterate. In the above example, we're iterating over all objects in ascending order. The success callback for cursors is a little special. The cursor object itself is the <code>result</code> of the request (above we're using the shorthand, so it's <code>event.target.result</code>). Then the actual key and value can be found on the <code>key</code> and <code>value</code> properties of the cursor object. If you want to keep going, then you have to call <code>continue()</code> on the cursor. When you've reached the end of the data (or if there were no entries that matched your <code>openCursor()</code> request) you still get a success callback, but the <code>result</code> property is <code>undefined</code>.</p> + +<p>One common pattern with cursors is to retrieve all objects in an object store and add them to an array, like this:</p> + +<pre class="brush: js">var customers = []; + +objectStore.openCursor().onsuccess = function(event) { + var cursor = event.target.result; + if (cursor) { + customers.push(cursor.value); + cursor.continue(); + } + else { + alert("Got all customers: " + customers); + } +};</pre> + +<div class="note"> +<p>Note: Mozilla has also implemented <code>getAll()</code> to handle this case (and <code>getAllKeys()</code>, which is currently hidden behind the <code>dom.indexedDB.experimental</code> preference in about:config). these aren't part of the IndexedDB standard, so may disappear in the future. We've included them because we think they're useful. The following code does precisely the same thing as above:</p> + +<pre class="brush: js">objectStore.getAll().onsuccess = function(event) { + alert("Got all customers: " + event.target.result); +};</pre> + +<p>There is a performance cost associated with looking at the <code>value</code> property of a cursor, because the object is created lazily. When you use <code>getAll()</code> for example, Gecko must create all the objects at once. If you're just interested in looking at each of the keys, for instance, it is much more efficient to use a cursor than to use <code>getAll()</code>. If you're trying to get an array of all the objects in an object store, though, use <code>getAll()</code>.</p> +</div> + +<h3 id="El_uso_de_un_índice">El uso de un índice</h3> + +<p>Storing customer data using the SSN as a key is logical since the SSN uniquely identifies an individual. (Whether this is a good idea for privacy is a different question, and outside the scope of this article.) If you need to look up a customer by name, however, you'll need to iterate over every SSN in the database until you find the right one. Searching in this fashion would be very slow, so instead you can use an index.</p> + +<pre class="brush: js">var index = objectStore.index("name"); +index.get("Donna").onsuccess = function(event) { + alert("Donna's SSN is " + event.target.result.ssn); +};</pre> + +<p>The "name" cursor isn't unique, so there could be more than one entry with the <code>name</code> set to <code>"Donna"</code>. In that case you always get the one with the lowest key value.</p> + +<p>If you need to access all the entries with a given <code>name</code> you can use a cursor. You can open two different types of cursors on indexes. A normal cursor maps the index property to the object in the object store. A key cursor maps the index property to the key used to store the object in the object store. The differences are illustrated here:</p> + +<pre class="brush: js">// Using a normal cursor to grab whole customer record objects +index.openCursor().onsuccess = function(event) { + var cursor = event.target.result; + if (cursor) { + // cursor.key is a name, like "Bill", and cursor.value is the whole object. + alert("Name: " + cursor.key + ", SSN: " + cursor.value.ssn + ", email: " + cursor.value.email); + cursor.continue(); + } +}; + +// Using a key cursor to grab customer record object keys +index.openKeyCursor().onsuccess = function(event) { + var cursor = event.target.result; + if (cursor) { + // cursor.key is a name, like "Bill", and cursor.value is the SSN. + // No way to directly get the rest of the stored object. + alert("Name: " + cursor.key + ", SSN: " + cursor.value); + cursor.continue(); + } +};</pre> + +<h3 id="Especificación_de_la_gama_y_la_dirección_de_los_cursores">Especificación de la gama y la dirección de los cursores</h3> + +<p>If you would like to limit the range of values you see in a cursor, you can use an <code>IDBKeyRange</code> object and pass it as the first argument to <code>openCursor()</code> or <code>openKeyCursor()</code>. You can make a key range that only allows a single key, or one that has a lower or upper bound, or one that has both a lower and upper bound. The bound may be "closed" (i.e., the key range includes the given value(s)) or "open" (i.e., the key range does not include the given value(s)). Here's how it works:</p> + +<pre class="brush: js">// Only match "Donna" +var singleKeyRange = IDBKeyRange.only("Donna"); + +// Match anything past "Bill", including "Bill" +var lowerBoundKeyRange = IDBKeyRange.lowerBound("Bill"); + +// Match anything past "Bill", but don't include "Bill" +var lowerBoundOpenKeyRange = IDBKeyRange.lowerBound("Bill", true); + +// Match anything up to, but not including, "Donna" +var upperBoundOpenKeyRange = IDBKeyRange.upperBound("Donna", true); + +// Match anything between "Bill" and "Donna", but not including "Donna" +var boundKeyRange = IDBKeyRange.bound("Bill", "Donna", false, true); + +// To use one of the key ranges, pass it in as the first argument of openCursor()/openKeyCursor() +index.openCursor(boundKeyRange).onsuccess = function(event) { + var cursor = event.target.result; + if (cursor) { + // Do something with the matches. + cursor.continue(); + } +};</pre> + +<p>Sometimes you may want to iterate in descending order rather than in ascending order (the default direction for all cursors). Switching direction is accomplished by passing <code>prev</code> to the <code>openCursor()</code> function as the second argument:</p> + +<pre class="brush: js">objectStore.openCursor(boundKeyRange, "prev").onsuccess = function(event) { + var cursor = event.target.result; + if (cursor) { + // Do something with the entries. + cursor.continue(); + } +};</pre> + +<p>If you just want to specify a change of direction but not constrain the results shown, you can just pass in null as the first argument:</p> + +<pre class="brush: js">objectStore.openCursor(null, "prev").onsuccess = function(event) { + var cursor = event.target.result; + if (cursor) { + // Do something with the entries. + cursor.continue(); + } +};</pre> + +<p>Since the "name" index isn't unique, there might be multiple entries where <code>name</code> is the same. Note that such a situation cannot occur with object stores since the key must always be unique. If you wish to filter out duplicates during cursor iteration over indexes, you can pass <code>nextunique</code> (or <code>prevunique</code> if you're going backwards) as the direction parameter. When <code>nextunique</code> or <code>prevunique</code> is used, the entry with the lowest key is always the one returned.</p> + +<pre class="brush: js">index.openKeyCursor(null, "nextunique").onsuccess = function(event) { + var cursor = event.target.result; + if (cursor) { + // Do something with the entries. + cursor.continue(); + } +};</pre> + +<p>Please see "<a href="https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor?redirectlocale=en-US&redirectslug=IndexedDB%2FIDBCursor#Constants">IDBCursor Constants</a>" for the valid direction arguments.</p> + +<h2 id="Cambios_Versión_mientras_que_una_aplicación_web_está_abierto_en_otra_pestaña">Cambios Versión mientras que una aplicación web está abierto en otra pestaña</h2> + +<p>When your web app changes in such a way that a version change is required for your database, you need to consider what happens if the user has the old version of your app open in one tab and then loads the new version of your app in another. When you call <code>open()</code> with a greater version than the actual version of the database, all other open databases must explicitly acknowledge the request before you can start making changes to the database (an <code>onblocked</code> event is fired until tey are closed or reloaded). Here's how it works:</p> + +<pre class="brush: js">var openReq = mozIndexedDB.open("MyTestDatabase", 2); + +openReq.onblocked = function(event) { + // If some other tab is loaded with the database, then it needs to be closed + // before we can proceed. + alert("Please close all other tabs with this site open!"); +}; + +openReq.onupgradeneeded = function(event) { + // All other databases have been closed. Set everything up. + db.createObjectStore(/* ... */); + useDatabase(db); +} + +openReq.onsuccess = function(event) { + var db = event.target.result; + useDatabase(db); + return; +} + +function useDatabase(db) { + // Make sure to add a handler to be notified if another page requests a version + // change. We must close the database. This allows the other page to upgrade the database. + // If you don't do this then the upgrade won't happen until the user closes the tab. + db.onversionchange = function(event) { + db.close(); + alert("A new version of this page is ready. Please reload!"); + }; + + // Do stuff with the database. +} +</pre> + +<h2 id="Seguridad">Seguridad</h2> + +<p>IndexedDB uses the same-origin principle, which means that it ties the store to the origin of the site that creates it (typically, this is the site domain or subdomain), so it cannot be accessed by any other origin.</p> + +<p>It's important to note that IndexedDB doesn't work for content loaded into a frame from another site (either {{ HTMLElement("frame") }} or {{ HTMLElement("iframe") }}. This is a security and privacy measure and can be considered analogous the blocking of third-party cookies. For more details, see {{ bug(595307) }}.</p> + +<h2 id="Warning_About_Browser_Shutdown">Warning About Browser Shutdown</h2> + +<p>When the browser shuts down (e.g., when the user selects Exit or clicks the Close button), any pending IndexedDB transactions are (silently) aborted — they will not complete, and they will not trigger the error handler. Since the user can exit the browser at any time, this means that you cannot rely upon any particular transaction to complete or to know that it did not complete. There are several implications of this behavior.</p> + +<p>First, you should take care to always leave your database in a consistent state at the end of every transaction. For example, suppose that you are using IndexedDB to store a list of items that you allow the user to edit. You save the list after the edit by clearing the object store and then writing out the new list. If you clear the object store in one transaction and write the new list in another transaction, there is a danger that the browser will close after the clear but before the write, leaving you with an empty database. To avoid this, you should combine the clear and the write into a single transaction. </p> + +<p>Second, you should never tie database transactions to unload events. If the unload event is triggered by the browser closing, any transactions created in the unload event handler will never complete. An intuitive approach to maintaining some information across browser sessions is to read it from the database when the browser (or a particular page) is opened, update it as the user interacts with the browser, and then save it to the database when the browser (or page) closes. However, this will not work. The database transactions will be created in the unload event handler, but because they are asynchronous they will be aborted before they can execute.</p> + +<p>In fact, there is no way to guarantee that IndexedDB transactions will complete, even with normal browser shutdown. See {{ bug(870645) }}.</p> + +<h2 id="Full_IndexedDB_example" name="Full_IndexedDB_example">Full IndexedDB example</h2> + +<h3 id="HTML_Content">HTML Content</h3> + +<pre class="brush: html"><script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> + + <h1>IndexedDB Demo: storing blobs, e-publication example</h1> + <div class="note"> + <p> + Works and tested with: + </p> + <div id="compat"> + </div> + </div> + + <div id="msg"> + </div> + + <form id="register-form"> + <table> + <tbody> + <tr> + <td> + <label for="pub-title" class="required"> + Title: + </label> + </td> + <td> + <input type="text" id="pub-title" name="pub-title" /> + </td> + </tr> + <tr> + <td> + <label for="pub-biblioid" class="required"> + Bibliographic ID:<br/> + <span class="note">(ISBN, ISSN, etc.)</span> + </label> + </td> + <td> + <input type="text" id="pub-biblioid" name="pub-biblioid"/> + </td> + </tr> + <tr> + <td> + <label for="pub-year"> + Year: + </label> + </td> + <td> + <input type="number" id="pub-year" name="pub-year" /> + </td> + </tr> + </tbody> + <tbody> + <tr> + <td> + <label for="pub-file"> + File image: + </label> + </td> + <td> + <input type="file" id="pub-file"/> + </td> + </tr> + <tr> + <td> + <label for="pub-file-url"> + Online-file image URL:<br/> + <span class="note">(same origin URL)</span> + </label> + </td> + <td> + <input type="text" id="pub-file-url" name="pub-file-url"/> + </td> + </tr> + </tbody> + </table> + + <div class="button-pane"> + <input type="button" id="add-button" value="Add Publication" /> + <input type="reset" id="register-form-reset"/> + </div> + </form> + + <form id="delete-form"> + <table> + <tbody> + <tr> + <td> + <label for="pub-biblioid-to-delete"> + Bibliographic ID:<br/> + <span class="note">(ISBN, ISSN, etc.)</span> + </label> + </td> + <td> + <input type="text" id="pub-biblioid-to-delete" + name="pub-biblioid-to-delete" /> + </td> + </tr> + <tr> + <td> + <label for="key-to-delete"> + Key:<br/> + <span class="note">(for example 1, 2, 3, etc.)</span> + </label> + </td> + <td> + <input type="text" id="key-to-delete" + name="key-to-delete" /> + </td> + </tr> + </tbody> + </table> + <div class="button-pane"> + <input type="button" id="delete-button" value="Delete Publication" /> + <input type="button" id="clear-store-button" + value="Clear the whole store" class="destructive" /> + </div> + </form> + + <form id="search-form"> + <div class="button-pane"> + <input type="button" id="search-list-button" + value="List database content" /> + </div> + </form> + + <div> + <div id="pub-msg"> + </div> + <div id="pub-viewer"> + </div> + <ul id="pub-list"> + </ul> + </div> +</pre> + +<h3 id="CSS_Content">CSS Content</h3> + +<pre class="brush: css">body { + font-size: 0.8em; + font-family: Sans-Serif; +} + +form { + background-color: #cccccc; + border-radius: 0.3em; + display: inline-block; + margin-bottom: 0.5em; + padding: 1em; +} + +table { + border-collapse: collapse; +} + +input { + padding: 0.3em; + border-color: #cccccc; + border-radius: 0.3em; +} + +.required:after { + content: "*"; + color: red; +} + +.button-pane { + margin-top: 1em; +} + +#pub-viewer { + float: right; + width: 48%; + height: 20em; + border: solid #d092ff 0.1em; +} +#pub-viewer iframe { + width: 100%; + height: 100%; +} + +#pub-list { + width: 46%; + background-color: #eeeeee; + border-radius: 0.3em; +} +#pub-list li { + padding-top: 0.5em; + padding-bottom: 0.5em; + padding-right: 0.5em; +} + +#msg { + margin-bottom: 1em; +} + +.action-success { + padding: 0.5em; + color: #00d21e; + background-color: #eeeeee; + border-radius: 0.2em; +} + +.action-failure { + padding: 0.5em; + color: #ff1408; + background-color: #eeeeee; + border-radius: 0.2em; +} + +.note { + font-size: smaller; +} + +.destructive { + background-color: orange; +} +.destructive:hover { + background-color: #ff8000; +} +.destructive:active { + background-color: red; +} +</pre> + +<p> </p> + +<h3 id="JavaScript_Content">JavaScript Content</h3> + +<pre class="brush: js">(function () { + var COMPAT_ENVS = [ + ['Firefox', ">= 16.0"], + ['Google Chrome', + ">= 24.0 (you may need to get Google Chrome Canary), NO Blob storage support"] + ]; + var compat = $('#compat'); + compat.empty(); + compat.append('<ul id="compat-list"></ul>'); + COMPAT_ENVS.forEach(function(val, idx, array) { + $('#compat-list').append('<li>' + val[0] + ': ' + val[1] + '</li>'); + }); + + const DB_NAME = 'mdn-demo-indexeddb-epublications'; + const DB_VERSION = 1; // Use a long long for this value (don't use a float) + const DB_STORE_NAME = 'publications'; + + var db; + + // Used to keep track of which view is displayed to avoid uselessly reloading it + var current_view_pub_key; + + function openDb() { + console.log("openDb ..."); + var req = indexedDB.open(DB_NAME, DB_VERSION); + req.onsuccess = function (evt) { + // Better use "this" than "req" to get the result to avoid problems with + // garbage collection. + // db = req.result; + db = this.result; + console.log("openDb DONE"); + }; + req.onerror = function (evt) { + console.error("openDb:", evt.target.errorCode); + }; + + req.onupgradeneeded = function (evt) { + console.log("openDb.onupgradeneeded"); + var store = evt.currentTarget.result.createObjectStore( + DB_STORE_NAME, { keyPath: 'id', autoIncrement: true }); + + store.createIndex('biblioid', 'biblioid', { unique: true }); + store.createIndex('title', 'title', { unique: false }); + store.createIndex('year', 'year', { unique: false }); + }; + } + + /** + * @param {string} store_name + * @param {string} mode either "readonly" or "readwrite" + */ + function getObjectStore(store_name, mode) { + var tx = db.transaction(store_name, mode); + return tx.objectStore(store_name); + } + + function clearObjectStore(store_name) { + var store = getObjectStore(DB_STORE_NAME, 'readwrite'); + var req = store.clear(); + req.onsuccess = function(evt) { + displayActionSuccess("Store cleared"); + displayPubList(store); + }; + req.onerror = function (evt) { + console.error("clearObjectStore:", evt.target.errorCode); + displayActionFailure(this.error); + }; + } + + function getBlob(key, store, success_callback) { + var req = store.get(key); + req.onsuccess = function(evt) { + var value = evt.target.result; + if (value) + success_callback(value.blob); + }; + } + + /** + * @param {IDBObjectStore=} store + */ + function displayPubList(store) { + console.log("displayPubList"); + + if (typeof store == 'undefined') + store = getObjectStore(DB_STORE_NAME, 'readonly'); + + var pub_msg = $('#pub-msg'); + pub_msg.empty(); + var pub_list = $('#pub-list'); + pub_list.empty(); + // Resetting the iframe so that it doesn't display previous content + newViewerFrame(); + + var req; + req = store.count(); + // Requests are executed in the order in which they were made against the + // transaction, and their results are returned in the same order. + // Thus the count text below will be displayed before the actual pub list + // (not that it is algorithmically important in this case). + req.onsuccess = function(evt) { + pub_msg.append('<p>There are <strong>' + evt.target.result + + '</strong> record(s) in the object store.</p>'); + }; + req.onerror = function(evt) { + console.error("add error", this.error); + displayActionFailure(this.error); + }; + + var i = 0; + req = store.openCursor(); + req.onsuccess = function(evt) { + var cursor = evt.target.result; + + // If the cursor is pointing at something, ask for the data + if (cursor) { + console.log("displayPubList cursor:", cursor); + req = store.get(cursor.key); + req.onsuccess = function (evt) { + var value = evt.target.result; + var list_item = $('<li>' + + '[' + cursor.key + '] ' + + '(biblioid: ' + value.biblioid + ') ' + + value.title + + '</li>'); + if (value.year != null) + list_item.append(' - ' + value.year); + + if (value.hasOwnProperty('blob') && + typeof value.blob != 'undefined') { + var link = $('<a href="' + cursor.key + '">File</a>'); + link.on('click', function() { return false; }); + link.on('mouseenter', function(evt) { + setInViewer(evt.target.getAttribute('href')); }); + list_item.append(' / '); + list_item.append(link); + } else { + list_item.append(" / No attached file"); + } + pub_list.append(list_item); + }; + + // Move on to the next object in store + cursor.continue(); + + // This counter serves only to create distinct ids + i++; + } else { + console.log("No more entries"); + } + }; + } + + function newViewerFrame() { + var viewer = $('#pub-viewer'); + viewer.empty(); + var iframe = $('<iframe />'); + viewer.append(iframe); + return iframe; + } + + function setInViewer(key) { + console.log("setInViewer:", arguments); + key = Number(key); + if (key == current_view_pub_key) + return; + + current_view_pub_key = key; + + var store = getObjectStore(DB_STORE_NAME, 'readonly'); + getBlob(key, store, function(blob) { + console.log("setInViewer blob:", blob); + var iframe = newViewerFrame(); + + // It is not possible to set a direct link to the + // blob to provide a mean to directly download it. + if (blob.type == 'text/html') { + var reader = new FileReader(); + reader.onload = (function(evt) { + var html = evt.target.result; + iframe.load(function() { + $(this).contents().find('html').html(html); + }); + }); + reader.readAsText(blob); + } else if (blob.type.indexOf('image/') == 0) { + iframe.load(function() { + var img_id = 'image-' + key; + var img = $('<img id="' + img_id + '"/>'); + $(this).contents().find('body').html(img); + var obj_url = window.URL.createObjectURL(blob); + $(this).contents().find('#' + img_id).attr('src', obj_url); + window.URL.revokeObjectURL(obj_url); + }); + } else if (blob.type == 'application/pdf') { + $('*').css('cursor', 'wait'); + var obj_url = window.URL.createObjectURL(blob); + iframe.load(function() { + $('*').css('cursor', 'auto'); + }); + iframe.attr('src', obj_url); + window.URL.revokeObjectURL(obj_url); + } else { + iframe.load(function() { + $(this).contents().find('body').html("No view available"); + }); + } + + }); + } + + /** + * @param {string} biblioid + * @param {string} title + * @param {number} year + * @param {string} url the URL of the image to download and store in the local + * IndexedDB database. The resource behind this URL is subjected to the + * "Same origin policy", thus for this method to work, the URL must come from + * the same origin as the web site/app this code is deployed on. + */ + function addPublicationFromUrl(biblioid, title, year, url) { + console.log("addPublicationFromUrl:", arguments); + + var xhr = new XMLHttpRequest(); + xhr.open('GET', url, true); + // Setting the wanted responseType to "blob" + // http://www.w3.org/TR/XMLHttpRequest2/#the-response-attribute + xhr.responseType = 'blob'; + xhr.onload = function (evt) { + if (xhr.status == 200) { + console.log("Blob retrieved"); + var blob = xhr.response; + console.log("Blob:", blob); + addPublication(biblioid, title, year, blob); + } else { + console.error("addPublicationFromUrl error:", + xhr.responseText, xhr.status); + } + }; + xhr.send(); + + // We can't use jQuery here because as of jQuery 1.8.3 the new "blob" + // responseType is not handled. + // http://bugs.jquery.com/ticket/11461 + // http://bugs.jquery.com/ticket/7248 + // $.ajax({ + // url: url, + // type: 'GET', + // xhrFields: { responseType: 'blob' }, + // success: function(data, textStatus, jqXHR) { + // console.log("Blob retrieved"); + // console.log("Blob:", data); + // // addPublication(biblioid, title, year, data); + // }, + // error: function(jqXHR, textStatus, errorThrown) { + // console.error(errorThrown); + // displayActionFailure("Error during blob retrieval"); + // } + // }); + } + + /** + * @param {string} biblioid + * @param {string} title + * @param {number} year + * @param {Blob=} blob + */ + function addPublication(biblioid, title, year, blob) { + console.log("addPublication arguments:", arguments); + var obj = { biblioid: biblioid, title: title, year: year }; + if (typeof blob != 'undefined') + obj.blob = blob; + + var store = getObjectStore(DB_STORE_NAME, 'readwrite'); + var req; + try { + req = store.add(obj); + } catch (e) { + if (e.name == 'DataCloneError') + displayActionFailure("This engine doesn't know how to clone a Blob, " + + "use Firefox"); + throw e; + } + req.onsuccess = function (evt) { + console.log("Insertion in DB successful"); + displayActionSuccess(); + displayPubList(store); + }; + req.onerror = function() { + console.error("addPublication error", this.error); + displayActionFailure(this.error); + }; + } + + /** + * @param {string} biblioid + */ + function deletePublicationFromBib(biblioid) { + console.log("deletePublication:", arguments); + var store = getObjectStore(DB_STORE_NAME, 'readwrite'); + var req = store.index('biblioid'); + req.get(biblioid).onsuccess = function(evt) { + if (typeof evt.target.result == 'undefined') { + displayActionFailure("No matching record found"); + return; + } + deletePublication(evt.target.result.id, store); + }; + req.onerror = function (evt) { + console.error("deletePublicationFromBib:", evt.target.errorCode); + }; + } + + /** + * @param {number} key + * @param {IDBObjectStore=} store + */ + function deletePublication(key, store) { + console.log("deletePublication:", arguments); + + if (typeof store == 'undefined') + store = getObjectStore(DB_STORE_NAME, 'readwrite'); + + // As per spec http://www.w3.org/TR/IndexedDB/#object-store-deletion-operation + // the result of the Object Store Deletion Operation algorithm is + // undefined, so it's not possible to know if some records were actually + // deleted by looking at the request result. + var req = store.get(key); + req.onsuccess = function(evt) { + var record = evt.target.result; + console.log("record:", record); + if (typeof record == 'undefined') { + displayActionFailure("No matching record found"); + return; + } + // Warning: The exact same key used for creation needs to be passed for + // the deletion. If the key was a Number for creation, then it needs to + // be a Number for deletion. + req = store.delete(key); + req.onsuccess = function(evt) { + console.log("evt:", evt); + console.log("evt.target:", evt.target); + console.log("evt.target.result:", evt.target.result); + console.log("delete successful"); + displayActionSuccess("Deletion successful"); + displayPubList(store); + }; + req.onerror = function (evt) { + console.error("deletePublication:", evt.target.errorCode); + }; + }; + req.onerror = function (evt) { + console.error("deletePublication:", evt.target.errorCode); + }; + } + + function displayActionSuccess(msg) { + msg = typeof msg != 'undefined' ? "Success: " + msg : "Success"; + $('#msg').html('<span class="action-success">' + msg + '</span>'); + } + function displayActionFailure(msg) { + msg = typeof msg != 'undefined' ? "Failure: " + msg : "Failure"; + $('#msg').html('<span class="action-failure">' + msg + '</span>'); + } + function resetActionStatus() { + console.log("resetActionStatus ..."); + $('#msg').empty(); + console.log("resetActionStatus DONE"); + } + + function addEventListeners() { + console.log("addEventListeners"); + + $('#register-form-reset').click(function(evt) { + resetActionStatus(); + }); + + $('#add-button').click(function(evt) { + console.log("add ..."); + var title = $('#pub-title').val(); + var biblioid = $('#pub-biblioid').val(); + if (!title || !biblioid) { + displayActionFailure("Required field(s) missing"); + return; + } + var year = $('#pub-year').val(); + if (year != '') { + // Better use Number.isInteger if the engine has EcmaScript 6 + if (isNaN(year)) { + displayActionFailure("Invalid year"); + return; + } + year = Number(year); + } else { + year = null; + } + + var file_input = $('#pub-file'); + var selected_file = file_input.get(0).files[0]; + console.log("selected_file:", selected_file); + // Keeping a reference on how to reset the file input in the UI once we + // have its value, but instead of doing that we rather use a "reset" type + // input in the HTML form. + //file_input.val(null); + var file_url = $('#pub-file-url').val(); + if (selected_file) { + addPublication(biblioid, title, year, selected_file); + } else if (file_url) { + addPublicationFromUrl(biblioid, title, year, file_url); + } else { + addPublication(biblioid, title, year); + } + + }); + + $('#delete-button').click(function(evt) { + console.log("delete ..."); + var biblioid = $('#pub-biblioid-to-delete').val(); + var key = $('#key-to-delete').val(); + + if (biblioid != '') { + deletePublicationFromBib(biblioid); + } else if (key != '') { + // Better use Number.isInteger if the engine has EcmaScript 6 + if (key == '' || isNaN(key)) { + displayActionFailure("Invalid key"); + return; + } + key = Number(key); + deletePublication(key); + } + }); + + $('#clear-store-button').click(function(evt) { + clearObjectStore(); + }); + + var search_button = $('#search-list-button'); + search_button.click(function(evt) { + displayPubList(); + }); + + } + + openDb(); + addEventListeners(); + +})(); // Immediately-Invoked Function Expression (IIFE) +</pre> + +<p>{{ LiveSampleLink('Full_IndexedDB_example', "Test the online live demo") }}</p> + +<h2 id="Next_step">Next step</h2> + +<p>If you want to start tinkering with the API, jump in to the <a href="/en/IndexedDB" title="https://developer.mozilla.org/en/IndexedDB">reference documentation</a> and check out the different methods.</p> + +<h2 id="See_also">See also</h2> + +<p>Reference</p> + +<ul> + <li><a href="/en/IndexedDB" title="https://developer.mozilla.org/en/IndexedDB">IndexedDB API Reference</a></li> + <li><a class="external" href="http://www.w3.org/TR/IndexedDB/" title="http://www.w3.org/TR/IndexedDB/">Indexed Database API Specification</a></li> + <li><a href="/en-US/docs/IndexedDB/Using_IndexedDB_in_chrome" title="/en-US/docs/IndexedDB/Using_IndexedDB_in_chrome">Using IndexedDB in chrome</a></li> +</ul> + +<p>Tutorials</p> + +<ul> + <li><a class="external" href="http://www.html5rocks.com/tutorials/indexeddb/todo/" title="http://www.html5rocks.com/tutorials/indexeddb/todo/">A simple TODO list using HTML5 IndexedDB</a><span class="external">. {{Note("This tutorial is based on an old version of the specification and does not work on up-to-date browsers - it still uses the removed <code>setVersion()</code> method.") }}</span></li> + <li><a href="http://www.html5rocks.com/en/tutorials/indexeddb/uidatabinding/" title="http://www.html5rocks.com/en/tutorials/indexeddb/uidatabinding/">Databinding UI Elements with IndexedDB</a></li> +</ul> + +<p>Related articles</p> + +<ul> + <li><a class="external" href="http://msdn.microsoft.com/en-us/scriptjunkie/gg679063.aspx" title="http://msdn.microsoft.com/en-us/scriptjunkie/gg679063.aspx">IndexedDB — The Store in Your Browser</a></li> +</ul> + +<p>Firefox</p> + +<ul> + <li>Mozilla <a class="link-https" href="https://mxr.mozilla.org/mozilla-central/find?text=&string=dom%2FindexedDB%2F.*%5C.idl&regexp=1" title="https://mxr.mozilla.org/mozilla-central/find?text=&string=dom/indexedDB/.*\.idl&regexp=1">interface files</a></li> +</ul> diff --git a/files/es/web/api/intersection_observer_api/index.html b/files/es/web/api/intersection_observer_api/index.html new file mode 100644 index 0000000000..d96bb02280 --- /dev/null +++ b/files/es/web/api/intersection_observer_api/index.html @@ -0,0 +1,638 @@ +--- +title: Intersection Observer API +slug: Web/API/Intersection_Observer_API +translation_of: Web/API/Intersection_Observer_API +--- +<p>{{DefaultAPISidebar("Intersection Observer API")}}</p> + +<div></div> + +<p class="summary"><span class="seoSummary">La API Observador de Intersección provee una vía asíncrona para observar cambios en la intersección de un elemento con un elemento ancestro o con el {{Glossary("viewport")}} del documento de nivel superior.</span></p> + +<p>Históricamente, detectar la visibilidad de un elemento, o la visibilidad relativa de dos elementos, uno respecto del otro, ha sido una tarea difícil para la cual las soluciones no han sido muy fiables y propensas a causar que el navegador y los sitios a los que el usuario accede lleguen a ser lentos. A medida que la web ha madurado, la necesidad para este tipo de información ha ido en aumento. La información sobre intersección es necesaria por muchas razones, tales como:</p> + +<ul> + <li>Carga en diferido de imágenes u otro contenido a medida que la página se desplaza.</li> + <li>Implementación del desplazamiento infinito en sitios web, donde más y más contenido se carga y muestra a medida que se desplaza la página, de forma que el usuario no tiene que pasar páginas.</li> + <li>Informes de visualizaciones de anuncios para calcular ingresos por publicidad.</li> + <li>Decidir si deben realizarse tareas o procesos de animación basados en si el usuario verá o no el resultado.</li> +</ul> + +<p>Implementar la detección de intersecciones en el pasado implicaba manejadores de eventos y bucles llamando a métodos como {{domxref("Element.getBoundingClientRect()")}} para reunir la información necesaria para cada elemento afectado. Dado que todo este código corre sobre el hilo principal, incluso uno de estos puede causar problemas de rendimiento. Cuando un sitio es cargado con estos tests, las cosas pueden ponerse muy feas.</p> + +<p>Considere una página web que usa scroll infinito. Usa una librería de terceros para manejar los anuncios situados periódicamente en la página, que tiene gráficos animados aquí y allá, y usa una librería personalizada que muestra cajas de notificación y similares. Cada uno de estos tiene sus propias rutinas de detección de intersecciones, todas corriendo en el hilo principal. El autor del sitio web puede no darse cuenta de que esto está pasando, ya que están usando dos librerías de las que quizás conocen muy poco acerca de su funcionamiento interno. A medida que el usuario desplaza la página, estas rutinas de detección de intersecciones están disparando código constantemente durante el scroll, lo que resulta en una experiencia que deja al usuario frustrado con el navegador, el sitio web y su ordenador.</p> + +<p>El API Intersection Observer deja al código registrar una función callback que se ejecuta si un elemento que se desea monitorizar entra o sale de otro elemento (o del {{Glossary("viewport")}}), o cuando la cantidad por la que ambos elementos se intersecan cambia en una cantidad requerida. De esta manera, los sitios no necesitan hacer nada sobre el hilo principal para mirar este tipo de intersección entre elementos, y el navegador está libre para optimizar la gestión de intersecciones como le parezca conveniente.</p> + +<p>Una cosa que el API Intersection Observer no puede decirle es: el número exacto de pixels que se solapan o específicamente cuales son; sin embargo, cubre el caso de uso mucho más común de "Si se intersecan por algún lugar alrededor del <em>N</em>%, necesito hacer algo."</p> + +<h2 id="Intersection_observer_conceptos_y_uso">Intersection observer conceptos y uso</h2> + +<p>La API Intersection Observer le permite configurar una función callback que es llamada cuando alguna de las siguientes circunstancias ocurren:</p> + +<ul> + <li>Un elemento <strong>target </strong>intersecta ya sea al viewport del dispositivo o un elemento especificado. Ese elemento especificado es llamado el <strong>elemento root</strong> o <strong>root</strong> a los propósitos de la API Intersection Observer.</li> + <li>La primera vez que se pide inicialmente al observador que observe un elemento target.</li> +</ul> + +<p>Típicamente, usted querrá observar los cambios en las intersecciones con respecto al ancestro scrollable más cercano al elemento, o, si el elemento no desciende de un ancestro scrollable, al viewport.<br> + Para observar la intersección relativa al elemento root, especifique null;</p> + +<p>Tanto si está usted usando el viewport o algún otro elemento como root, el API funciona de la misma manera, ejecutando una función callback que usted le proporciona cuando la visibilidad del elemento target cambia al cruzar en la cantidad de intersección deseada con el elemento root.</p> + +<p>El grado de intersección entre el elemento target y su elemento root es el <strong>intersection ratio</strong>. Esto es una representación del porcentaje del elemento target que es visible, indicado como un valor entre 0.0 y 1.0.</p> + +<h3 id="Creando_un_intersection_observer">Creando un intersection observer</h3> + +<p>Cree el intersection observer llamando a su constructor y pasándole una función callback para que se ejecute cuando se cruce un umbral (threshold) en una u otra dirección:</p> + +<pre class="brush: js notranslate">let options = { + root: document.querySelector('#scrollArea'), + rootMargin: '0px', + threshold: 1.0 +} + +let observer = new IntersectionObserver(callback, options);</pre> + +<p>Un umbral de 1.0 significa que cuando el 100% del elemento target está visible dentro del elemento especificado por la opción <code>root</code>, la función callback es invocada.</p> + +<h4 id="Opciones_de_Intersection_observer">Opciones de Intersection observer</h4> + +<p>El objeto <code>options</code> pasado al constructor {{domxref("IntersectionObserver.IntersectionObserver", "IntersectionObserver()")}} le deja controlar las circunstancias bajo las cuales la función callback es invocada. Tiene los siguientes campos:</p> + +<dl> + <dt><code>root</code></dt> + <dd>El elemento que es usado como viewport para comprobar la visibilidad de elemento target. Debe ser ancestro de target. Por defecto es el viewport del navegador si no se especifica o si es <code>null</code>.</dd> + <dt><code>rootMargin</code> </dt> + <dd>Margen alrededor del elemeto root. Puede tener valores similares a los de CSS {{cssxref("margin")}} property, e.g. "<code>10px 20px 30px 40px"</code> (top, right, bottom, left). Los valores pueden ser porcentajes. Este conjunto de valores sirve para aumentar o encoger cada lado del cuadro delimitador del elemento root antes de calcular las intersecciones. Por defecto son todos cero.</dd> + <dt><code>threshold</code></dt> + <dd>Es un número o un array de números que indican a que porcentaje de visibilidad del elemento target, la función callback del observer debería ser ejecutada. Si usted quiere que se detecte cuando la visibilidad pasa la marca del 50%, debería usar un valor de 0.5. Si quiere ejecutar la función callback cada vez que la visibilidad pase otro 25%, usted debería especificar el array [0, 0.25, 0.5, 0.75, 1]. El valor por defecto es 0 (lo que significa que tan pronto como un píxel sea visible, la función callback será ejecutada). Un valor de 1.0 significa que el umbral no se considera pasado hasta que todos los pixels son visibles.</dd> +</dl> + +<h4 id="Determinando_un_elemento_para_ser_observado">Determinando un elemento para ser observado</h4> + +<p>Una vez usted ha creado el observer, necesita darle un elemento target para observar:</p> + +<pre class="brush: js notranslate">var target = document.querySelector('#listItem'); +observer.observe(target); + +// el callback que indicamos al observador será ejecutado ahora por primera vez +// espera hasta que le asignemos un target a nuestro observador (aún si el target no está actualmente visible) +</pre> + +<p>Cuando el elemento target encuentra un threshold especificado por el <code>IntersectionObserver</code>, la función callback es invocada. La función callback recibe una lista de objetos {{domxref("IntersectionObserverEntry")}} y el observer:</p> + +<pre class="brush: js notranslate">var callback = function(entries, observer) { + entries.forEach(entry => { + // Cada entry describe un cambio en la intersección para + // un elemento observado + // entry.boundingClientRect + // entry.intersectionRatio + // entry.intersectionRect + // entry.isIntersecting + // entry.rootBounds + // entry.target + // entry.time + }); +}; +</pre> + +<p>Asegúrese de que su función callback se ejecute sobre el hilo principal. Debería operar tan rápidamente como sea posible; si alguna cosa necesita tiempo extra para ser realizada, use {{domxref("Window.requestIdleCallback()")}}.</p> + +<p>También, note que si especifica la opción <code>root</code>, el elemento target debe ser un descendiente del elemento root.</p> + +<h3 id="Cómo_se_calcula_la_intersección">Cómo se calcula la intersección</h3> + +<p>Todas las áreas consideradas por la API de Intersection Observer son rectángulos; los elementos que su forma es irregular se considera que están ocupando el rectángulo más pequeño que encierra todas las partes del elemento. De forma similar, si la porción visible de un elemento no es un rectángulo, entonces el rectángulo de intersección del elemento se interpreta como el rectángulo más pequeño que contiene todas las partes visibles del elemento.</p> + +<p>Es útil entender un poco sobre cómo las diferentes propiedades proporcionadas por {{domxref("IntersectionObserverEntry")}} describe una intersección.</p> + +<h4 id="La_intersección_entre_el_elemento_root_y_su_margen">La intersección entre el elemento root y su margen</h4> + +<p>Antes de poder realizar un seguimiento de la intersección de un elemento en un contenedor, necesitamos saber qué cuál es contendor. Este contenedor se le conoce como <strong>intersection root</strong>, o <strong>root element</strong>. Este puede ser un elemento del documento, que es ascendiente del elemento observado, o <code>null</code>, que usará el viewport del documento como contenedor.</p> + +<p>El rectángulo usado como los límites de la intersección del intersection root pueden ser ajustados configurando la opción <strong>root margin</strong>, <code>rootMargin</code>, cuando creamos el {{domxref("IntersectionObserver")}}. Los valores en <code>rootMargin</code> define los espacios añadidos a cada lado del cuadro delimitador que sirve de contenedor, creando los límites definitivos del contenedor, o intersection root (los cuáles están explicados en {{domxref("IntersectionObserverEntry.rootBounds")}} cuando la función callback es ejecutada).</p> + +<h4 id="Umbrales">Umbrales</h4> + +<p>En lugar de reportar cada mínimo cambio indicando cómo de visible es el elemento que observamos, la Intersection Observer API usa <strong>umbrales</strong>. Cuando creamos un observable, puedes proporcionar uno o más valores númericos representando, en porcentaje, cuán visible es el elemento observado. Entonces, la API reporta sólo los cambios de visibilidad que cruza este umbral.</p> + +<p>Por ejemplo, si te gustaría ser informado cada vez que la visibilidad del elemento pasa, hacia delante o hacía atrás, una marca de un 25%, entonces puedes especificar el array [0, 0.25, 0.5, 0.75, 1] como una lista de umbrales a la hora de crear el observable. Puedes saber incluso en qué dirección la visibilidad ha cambiado (esto es, saber si el elemento ha pasado a ser más o menos visible) comprobando el valor de la propiedad {{domxref("IntersectionObserverEntry.isIntersecting", "isIntersecting")}} disponible en el {{domxref("IntersectionObserverEntry")}} que tienes disponible en la función callback cada vez que la visibilidad cambia. Si <code>isIntersecting</code> es <code>true</code>, el elemento se ha vuelto al menos tan visibile como el umbral que pasó. Si es <code>false</code>, el elemento entonces ha dejado de ser tan visible como el umbral que sobrepasó.</p> + +<p>Para entender cómo funciona el concepto de umbral (threshold), pruebe a hacer scroll en el siguiente ejemplo. Cada caja coloreada muestra dentro de ella el porcentaje que tiene visible de cada una de las cuadro esquinas, de forma que podrá ver cómo cambian los porcentajes conforme va haciendo scroll. Cada caja tiene diferentes valores configurado de umbrales.</p> + +<ul> + <li>La primera caja tiene un umbral para cada punto del porcentaje de visibilidad posible en el array que se le pasa a {{domxref("IntersectionObserver.thresholds")}}, siendo su valor el array <code>[0.00, 0.01, 0.02, ..., 0.99, 1.00]</code>.</li> + <li>La segunda caja sólo tiene un umbral que se marca en el 50%.</li> + <li>La tercera caja tiene un umbral cada 10% de visibilidad (0%, 10%, 20%, etc.).</li> + <li>La última tiene el umbral cada 25%.</li> +</ul> + +<div class="hidden" id="threshold-example"> +<pre class="brush: html notranslate"><template id="boxTemplate"> + <div class="sampleBox"> + <div class="label topLeft"></div> + <div class="label topRight"></div> + <div class="label bottomLeft"></div> + <div class="label bottomRight"></div> + </div> +</template> + +<main> + <div class="contents"> + <div class="wrapper"> + </div> + </div> +</main></pre> + +<pre class="brush: css notranslate">.contents { + position: absolute; + width: 700px; + height: 1725px; +} + +.wrapper { + position: relative; + top: 600px; +} + +.sampleBox { + position: relative; + left: 175px; + width: 150px; + background-color: rgb(245, 170, 140); + border: 2px solid rgb(201, 126, 17); + padding: 4px; + margin-bottom: 6px; +} + +#box1 { + height: 200px; +} + +#box2 { + height: 75px; +} + +#box3 { + height: 150px; +} + +#box4 { + height: 100px; +} + +.label { + font: 14px "Open Sans", "Arial", sans-serif; + position: absolute; + margin: 0; + background-color: rgba(255, 255, 255, 0.7); + border: 1px solid rgba(0, 0, 0, 0.7); + width: 3em; + height: 18px; + padding: 2px; + text-align: center; +} + +.topLeft { + left: 2px; + top: 2px; +} + +.topRight { + right: 2px; + top: 2px; +} + +.bottomLeft { + bottom: 2px; + left: 2px; +} + +.bottomRight { + bottom: 2px; + right: 2px; +} +</pre> + +<pre class="brush: js notranslate">let observers = []; + +startup(); + +function startup() { + let wrapper = document.querySelector(".wrapper"); + + // Options for the observers + + let observerOptions = { + root: null, + rootMargin: "0px", + threshold: [] + }; + + // Un array con los umbrales para cada caje. + // El umbral de la primer caja se crea de forma programática + // ya que hay demasiados puntos. + + let thresholdSets = [ + [], + [0.5], + [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0], + [0, 0.25, 0.5, 0.75, 1.0] + ]; + + for (let i=0; i<=1.0; i+= 0.01) { + thresholdSets[0].push(i); + } + + // Añadimos cada caja y creamos un observable para cada una + for (let i=0; i<4; i++) { + let template = document.querySelector("#boxTemplate").content.cloneNode(true); + let boxID = "box" + (i+1); + template.querySelector(".sampleBox").id = boxID; + wrapper.appendChild(document.importNode(template, true)); + + // Configuramos el observable para esta caja + + observerOptions.threshold = thresholdSets[i]; + observers[i] = new IntersectionObserver(intersectionCallback, observerOptions); + observers[i].observe(document.querySelector("#" + boxID)); + } + + // Scroll a la posición inicial + + document.scrollingElement.scrollTop = wrapper.firstChild.getBoundingClientRect().top + window.scrollY; + document.scrollingElement.scrollLeft = 750; +} + +function intersectionCallback(entries) { + entries.forEach(function(entry) { + let box = entry.target; + let visiblePct = (Math.floor(entry.intersectionRatio * 100)) + "%"; + + box.querySelector(".topLeft").innerHTML = visiblePct; + box.querySelector(".topRight").innerHTML = visiblePct; + box.querySelector(".bottomLeft").innerHTML = visiblePct; + box.querySelector(".bottomRight").innerHTML = visiblePct; + }); +} +</pre> +</div> + +<p>{{EmbedLiveSample("threshold-example", 500, 500)}}</p> + +<h4 id="Acotamiento_y_el_rectángulo_de_intersección">Acotamiento y el rectángulo de intersección</h4> + +<p>El navegador computa el rectángulo de intersección final de la siguiente forma; la API hace todo esto por usted, pero puede ser útil entender estos pasos para comprender mejor cuando ocurrirán exactamente las intersecciones.</p> + +<ol> + <li>El rectangulo delimitador del elemento target (el rectangulo mas pequeño, que encierra por completo los componentes que conforman el elemento) es obtenido llamando {{domxref("Element.getBoundingClientRect", "getBoundingClientRect()")}} en el target. Este es el rectangulo de intersección mas grande que puede ser. Los pasos restantes removeran las porciones que no intersectan.</li> + <li>Starting at the target's immediate parent block and moving outward, each containing block's clipping (if any) is applied to the intersection rectangle. A block's clipping is determined based on the intersection of the two blocks and the clipping mode (if any) specified by the {{cssxref("overflow")}} property. Setting <code>overflow</code> to anything but <code>visible</code> causes clipping to occur.</li> + <li>If one of the containing elements is the root of a nested browsing context (such as the document contained in an {{HTMLElement("iframe")}}, the intersection rectangle is clipped to the containing context's viewport, and recursion upward through the containers continues with the container's containing block. So if the top level of an <code><iframe></code> is reached, the intersection rectangle is clipped to the frame's viewport, then the frame's parent element is the next block recursed through toward the intersection root.</li> + <li>When recursion upward reaches the intersection root, the resulting rectangle is mapped to the intersection root's coordinate space.</li> + <li>The resulting rectangle is then updated by intersecting it with the <a href="https://wiki.developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API#root-intersection-rectangle">root intersection rectangle</a>.</li> + <li>This rectangle is, finally, mapped to the coordinate space of the target's {{domxref("document")}}.</li> +</ol> + +<h3 id="Callbacks_de_cambio_de_intersección">Callbacks de cambio de intersección</h3> + +<p>Cuando la cantidad del elemento target que es visible dentro del elemento root cruza uno de los umbrales de visibilidad, el callback del objeto {{domxref("IntersectionObserver")}} es ejecutado. El callback recibe como input un array de todos los objetos {{domxref("IntersectionObserverEntry")}}, uno por cada umbral que haya sido cruzado, y una referencia al objeto <code>IntersectionObserver</code> mismo.</p> + +<p>Cada entrada en la lista de umbrales es un objeto {{domxref("IntersectionObserverEntry")}} que describe un umbral que ha sido cruzado; esto es, cada entrada describe qué porción de un elemento dado se está intersectando con el elemento root, sea que el elemento se considere en intersección o no, y la dirección en la cual ocurrió la transición.</p> + +<p>The code snippet below shows a callback which keeps a counter of how many times elements transition from not intersecting the root to intersecting by at least 75%. For a threshold value of 0.0 (default) the callback is called <a href="https://www.w3.org/TR/intersection-observer/#dom-intersectionobserverentry-isintersecting">approximately</a> upon transition of the boolean value of {{domxref("IntersectionObserverEntry.isIntersecting", "isIntersecting")}}. The snippet thus first checks that the transition is a positive one, then determines whether {{domxref("IntersectionObserverEntry.intersectionRatio", "intersectionRatio")}} is above 75%, in which case it increments the counter.</p> + +<pre class="notranslate">intersectionCallback(entries) => { + entries.forEach(entry => { + if (entry.isIntersecting) { + let elem = entry.target; + + if (entry.intersectionRatio >= 0.75) { + intersectionCounter++; + } + } + }); +} +</pre> + +<h2 id="Interfaces">Interfaces</h2> + +<dl> + <dt>{{domxref("IntersectionObserver")}}</dt> + <dd>The primary interface for the Intersection Observer API. Provides methods for creating and managing an observer which can watch any number of target elements for the same intersection configuration. Each observer can asynchronously observe changes in the intersection between one or more target elements and a shared ancestor element or with their top-level {{domxref("Document")}}'s {{Glossary('viewport')}}. The ancestor or viewport is referred to as the <strong>root</strong>.</dd> + <dt>{{domxref("IntersectionObserverEntry")}}</dt> + <dd>Describes the intersection between the target element and its root container at a specific moment of transition. Objects of this type can only be obtained in two ways: as an input to your <code>IntersectionObserver</code> callback, or by calling {{domxref("IntersectionObserver.takeRecords()")}}.</dd> +</dl> + +<h2 id="Un_ejemplo_sencillo">Un ejemplo sencillo</h2> + +<p>Este ejemplo causa que el elemento que queremos observar cambia de color y transparencia conforme se va haciendo más o menos visible. En la página <a href="/en-US/docs/Web/API/Intersection_Observer_API/Timing_element_visibility">Timing element visibility with the Intersection Observer API</a>, puedes encontrar un ejemplo más extenso que muestra cómo calcular cuanto tiempo que una serie de elementos, como anuncios, son visibles para el usuario y reaccionar a esa información guardando estadísticas.</p> + +<h3 id="HTML">HTML</h3> + +<p>El HTML para este ejemplo es muy simple, con un elemento primario que será la caja que querremos observar (con la creativa ID de <code>"box"</code>) y algo de contenido para dentro de la caja.</p> + +<pre class="brush: html notranslate"><div id="box"> + <div class="vertical"> + Welcome to <strong>The Box!</strong> + </div> +</div></pre> + +<h3 id="CSS">CSS</h3> + +<p>El CSS del ejemplo no es muy importante para el propósito de este ejemplo: pinta el elemento y establece que los atributos {{cssxref("background-color")}} y {{cssxref("border")}} puedan participar en las <a href="/en-US/docs/Web/CSS/CSS_Transitions">CSS transitions</a>, los cuáles usaremos para afectar los cambios al elemento conforme este es más o menos visible.</p> + +<pre class="brush: css notranslate">#box { + background-color: rgba(40, 40, 190, 255); + border: 4px solid rgb(20, 20, 120); + transition: background-color 1s, border 1s; + width: 350px; + height: 350px; + display: flex; + align-items: center; + justify-content: center; + padding: 20px; +} + +.vertical { + color: white; + font: 32px "Arial"; +} + +.extra { + width: 350px; + height: 350px; + margin-top: 10px; + border: 4px solid rgb(20, 20, 120); + text-align: center; + padding: 20px; +}</pre> + +<h3 id="JavaScript">JavaScript</h3> + +<p>Finalmente, vamos a mirar el código JavaScript que usa la API Intersection Observer API para hacer que las cosas ocurran.</p> + +<h4 id="Preparación">Preparación</h4> + +<p>Primero, necesitamos preparar algunas variables e instalar el observador.</p> + +<pre class="brush: js notranslate">var numSteps = 20.0; + +var boxElement; +var prevRatio = 0.0; +var increasingColor = "rgba(40, 40, 190, ratio)"; +var decreasingColor = "rgba(190, 40, 40, ratio)"; + +// Set things up. + +window.addEventListener("load", function(event) { + boxElement = document.querySelector("#box"); + + createObserver(); +}, false);</pre> + +<p>Las constantes y variables que establecimos aquí son:</p> + +<dl> + <dt><code>numSteps</code></dt> + <dd>A constant which indicates how many thresholds we want to have between a visibility ratio of 0.0 and 1.0.</dd> + <dt><code>prevRatio</code></dt> + <dd>This variable will be used to record what the visibility ratio was the last time a threshold was crossed; this will let us figure out whether the target element is becoming more or less visible.</dd> + <dt><code>increasingColor</code></dt> + <dd>A string defining a color we'll apply to the target element when the visibility ratio is increasing. The word "ratio" in this string will be replaced with the target's current visibility ratio, so that the element not only changes color but also becomes increasingly opaque as it becomes less obscured.</dd> + <dt><code>decreasingColor</code></dt> + <dd>Similarly, this is a string defining a color we'll apply when the visibility ratio is decreasing.</dd> +</dl> + +<p>We call {{domxref("EventTarget.addEventListener", "Window.addEventListener()")}} to start listening for the {{event("load")}} event; once the page has finished loading, we get a reference to the element with the ID <code>"box"</code> using {{domxref("Document.querySelector", "querySelector()")}}, then call the <code>createObserver()</code> method we'll create in a moment to handle building and installing the intersection observer.</p> + +<h4 id="Creating_the_intersection_observer">Creating the intersection observer</h4> + +<p>The <code>createObserver()</code> method is called once page load is complete to handle actually creating the new {{domxref("IntersectionObserver")}} and starting the process of observing the target element.</p> + +<pre class="brush: js notranslate">function createObserver() { + var observer; + + var options = { + root: null, + rootMargin: "0px", + threshold: buildThresholdList() + }; + + observer = new IntersectionObserver(handleIntersect, options); + observer.observe(boxElement); +}</pre> + +<p>This begins by setting up an <code>options</code> object containing the settings for the observer. We want to watch for changes in visibility of the target element relative to the document's viewport, so <code>root</code> is <code>null</code>. We need no margin, so the margin offset, <code>rootMargin</code>, is specified as "0px". This causes the observer to watch for changes in the intersection between the target element's bounds and those of the viewport, without any added (or subtracted) space.</p> + +<p>The list of visibility ratio thresholds, <code>threshold</code>, is constructed by the function <code>buildThresholdList()</code>. The threshold list is built programmatically in this example since there are a number of them and the number is intended to be adjustable.</p> + +<p>Once <code>options</code> is ready, we create the new observer, calling the {{domxref("IntersectionObserver.IntersectionObserver", "IntersectionObserver()")}} constructor, specifying a function to be called when intersection crosses one of our thresholds, <code>handleIntersect()</code>, and our set of options. We then call {{domxref("IntersectionObserver.observe", "observe()")}} on the returned observer, passing into it the desired target element.</p> + +<p>We could opt to monitor multiple elements for visibility intersection changes with respect to the viewport by calling <code>observer.observe()</code> for each of those elements, if we wanted to do so.</p> + +<h4 id="Building_the_array_of_threshold_ratios">Building the array of threshold ratios</h4> + +<p>The <code>buildThresholdList()</code> function, which builds the list of thresholds, looks like this:</p> + +<pre class="brush: js notranslate">function buildThresholdList() { + var thresholds = []; + + for (var i=1.0; i<=numSteps; i++) { + var ratio = i/numSteps; + thresholds.push(ratio); + } + + thresholds.push(0); + return thresholds; +}</pre> + +<p>This builds the array of thresholds—each of which is a ratio between 0.0 and 1.0, by pushing the value <code>i/numSteps</code> onto the <code>thresholds</code> array for each integer <code>i</code> between 1 and <code>numSteps</code>. It also pushes 0 to include that value. The result, given the default value of <code>numSteps</code> (20), is the following list of thresholds:</p> + +<table class="standard-table"> + <tbody> + <tr> + <th>#</th> + <th>Ratio</th> + <th>#</th> + <th>Ratio</th> + </tr> + <tr> + <th>1</th> + <td>0.05</td> + <th>11</th> + <td>0.55</td> + </tr> + <tr> + <th>2</th> + <td>0.1</td> + <th>12</th> + <td>0.6</td> + </tr> + <tr> + <th>3</th> + <td>0.15</td> + <th>13</th> + <td>0.65</td> + </tr> + <tr> + <th>4</th> + <td>0.2</td> + <th>14</th> + <td>0.7</td> + </tr> + <tr> + <th>5</th> + <td>0.25</td> + <th>15</th> + <td>0.75</td> + </tr> + <tr> + <th>6</th> + <td>0.3</td> + <th>16</th> + <td>0.8</td> + </tr> + <tr> + <th>7</th> + <td>0.35</td> + <th>17</th> + <td>0.85</td> + </tr> + <tr> + <th>8</th> + <td>0.4</td> + <th>18</th> + <td>0.9</td> + </tr> + <tr> + <th>9</th> + <td>0.45</td> + <th>19</th> + <td>0.95</td> + </tr> + <tr> + <th>10</th> + <td>0.5</td> + <th>20</th> + <td>1.0</td> + </tr> + </tbody> +</table> + +<p>We could, of course, hard-code the array of thresholds into our code, and often that's what you'll end up doing. But this example leaves room for adding configuration controls to adjust the granularity, for example.</p> + +<h4 id="Handling_intersection_changes">Handling intersection changes</h4> + +<p>When the browser detects that the target element (in our case, the one with the ID <code>"box"</code>) has been unveiled or obscured such that its visibility ratio crosses one of the thresholds in our list, it calls our handler function, <code>handleIntersect()</code>:</p> + +<pre class="brush: js notranslate">function handleIntersect(entries, observer) { + entries.forEach(function(entry) { + if (entry.intersectionRatio > prevRatio) { + entry.target.style.backgroundColor = increasingColor.replace("ratio", entry.intersectionRatio); + } else { + entry.target.style.backgroundColor = decreasingColor.replace("ratio", entry.intersectionRatio); + } + + prevRatio = entry.intersectionRatio; + }); +}</pre> + +<p>For each {{domxref("IntersectionObserverEntry")}} in the list <code>entries</code>, we look to see if the entry's {{domxref("IntersectionObserverEntry.intersectionRatio", "intersectionRatio")}} is going up; if it is, we set the target's {{cssxref("background-color")}} to the string in <code>increasingColor</code> (remember, it's <code>"rgba(40, 40, 190, ratio)"</code>), replaces the word "ratio" with the entry's <code>intersectionRatio</code>. The result: not only does the color get changed, but the transparency of the target element changes, too; as the intersection ratio goes down, the background color's alpha value goes down with it, resulting in an element that's more transparent.</p> + +<p>Similarly, if the <code>intersectionRatio</code> is going up, we use the string <code>decreasingColor</code> and replace the word "ratio" in that with the <code>intersectionRatio</code> before setting the target element's <code>background-color</code>.</p> + +<p>Finally, in order to track whether the intersection ratio is going up or down, we remember the current ratio in the variable <code>prevRatio</code>.</p> + +<h3 id="Resultado">Resultado</h3> + +<p>Abajo se encuentra el contenido resultante. Desplace ésta página hacia arriba y abajo y note como la apariencia de la caja cambia mientras lo hace.</p> + +<p>{{EmbedLiveSample('A_simple_example', 400, 400)}}</p> + +<p>Hay un ejemplo aún más extensivo en <a href="/en-US/docs/Web/API/Intersection_Observer_API/Timing_element_visibility">Cronometrando la visibilidad de un elemento con la API Intersection Observer</a>.</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('IntersectionObserver')}}</td> + <td>{{Spec2('IntersectionObserver')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome(51)}}</td> + <td>15</td> + <td>{{CompatGeckoDesktop(55)}}<sup>[1][2]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatOpera(38)}}</td> + <td>{{WebKitBug(159475)}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android Webview</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome(51)}}</td> + <td>{{CompatChrome(51)}}</td> + <td>{{CompatGeckoMobile(55)}}<sup>[1][2]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatOperaMobile(38)}}</td> + <td>{{WebKitBug(159475)}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] This feature has been implemented since Gecko 53.0 {{geckoRelease("53.0")}} behind the preference <code>dom.IntersectionObserver.enabled</code>, which was <code>false</code> by default. Enabled by default beginning in Firefox 55. See {{bug(1243846)}}.</p> + +<p>[2] Firefox doesn't currently take the {{cssxref("clip-path")}} of ancestor elements into account when computing the visibility of an element within its root. See {{bug(1319140)}} for the status of this issue.</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="https://github.com/w3c/IntersectionObserver">Intersection Observer polyfill</a></li> + <li><a href="/en-US/docs/Web/API/Intersection_Observer_API/Timing_element_visibility">Timing element visibility with the Intersection Observer API</a></li> + <li>{{domxref("IntersectionObserver")}} and {{domxref("IntersectionObserverEntry")}}</li> +</ul> diff --git a/files/es/web/api/keyboardevent/getmodifierstate/index.html b/files/es/web/api/keyboardevent/getmodifierstate/index.html new file mode 100644 index 0000000000..b44ecc6da3 --- /dev/null +++ b/files/es/web/api/keyboardevent/getmodifierstate/index.html @@ -0,0 +1,253 @@ +--- +title: KeyboardEvent.getModifierState() +slug: Web/API/KeyboardEvent/getModifierState +tags: + - API + - DOM + - KeyboardEvent + - Referencia + - getModifierState + - metodo +translation_of: Web/API/KeyboardEvent/getModifierState +--- +<p>{{APIRef("DOM Events")}}</p> + +<p>El método <code><strong>KeyboardEvent.getModifierState()</strong></code> retorna <code>true</code> respecto al estado actual de la tecla modificadora especificada si la misma está presionada o bloqueada, en caso contrario devuelve <code>false</code>.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var <code><em>active</em> = <em>event</em>.getModifierState(<em>keyArg</em>);</code></pre> + +<h3 id="Retorna">Retorna</h3> + +<p>A {{jsxref("Boolean")}}</p> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><em><code>keyArg</code></em></dt> + <dd>El valor de la tecla modificadora. El valor debe ser uno de los valores {{domxref("KeyboardEvent.key")}} que representan las teclas modificadoras, o el string <code>"Accel"</code> {{deprecated_inline}}, el cual es case-sensitive.</dd> +</dl> + +<h2 id="Teclas_modificadoras_en_Internet_Explorer">Teclas modificadoras en Internet Explorer</h2> + +<p>IE9 usa <code>"Scroll"</code> para <code>"ScrollLock"</code> y <code>"Win"</code> para <code>"OS"</code>.</p> + +<h2 id="Teclas_modificadoras_en_Gecko">Teclas modificadoras en Gecko</h2> + +<table style="width: 100%;"> + <caption>When getModifierState() returns true on Gecko?</caption> + <thead> + <tr> + <th scope="row"> </th> + <th scope="col">Windows</th> + <th scope="col">Linux (GTK)</th> + <th scope="col">Mac</th> + <th scope="col">Android 2.3</th> + <th scope="col">Android 3.0 or latter</th> + </tr> + </thead> + <tbody> + <tr> + <th scope="row"><code>"Alt"</code></th> + <td>Either <kbd>Alt</kbd> key or <kbd>AltGr</kbd> key pressed</td> + <td><kbd>Alt</kbd> key pressed</td> + <td><kbd>⌥ Option</kbd> key pressed</td> + <td colspan="2" rowspan="1"><kbd>Alt</kbd> key or <kbd>option</kbd> key pressed</td> + </tr> + <tr> + <th scope="row"><code>"AltGraph"</code></th> + <td> + <p>Both <kbd>Alt</kbd> and <kbd>Ctrl</kbd> keys are pressed, or <kbd>AltGr</kbd> key is pressed</p> + </td> + <td><kbd>Level 3 Shift</kbd> key (or <kbd>Level 5 Shift</kbd> key {{gecko_minversion_inline("20.0")}}) pressed</td> + <td><kbd>⌥ Option</kbd> key pressed</td> + <td colspan="2" rowspan="1" style="background-color: rgb(204, 204, 204); text-align: center;"><em>Not supported</em></td> + </tr> + <tr> + <th scope="row"><code>"CapsLock"</code></th> + <td colspan="3" style="text-align: center;">During LED for <kbd>⇪ Caps Lock</kbd> turned on</td> + <td style="text-align: center; background-color: rgb(204, 204, 204);"><em>Not supported</em></td> + <td>While <kbd>CapsLock</kbd> is locked {{gecko_minversion_inline("29.0")}}</td> + </tr> + <tr> + <th scope="row"><code>"Control"</code></th> + <td>Either <kbd>Ctrl</kbd> key or <kbd>AltGr</kbd> key pressed</td> + <td><kbd>Ctrl</kbd> key pressed</td> + <td><kbd>control</kbd> key pressed</td> + <td><kbd>menu</kbd> key pressed.</td> + <td><kbd>Ctrl</kbd> key, <kbd>control</kbd> key or <kbd>menu</kbd> key pressed.</td> + </tr> + <tr> + <th scope="row"><code>"Fn"</code></th> + <td colspan="4" style="background-color: rgb(204, 204, 204); text-align: center;"><em>Not supported</em></td> + <td><kbd>Function</kbd> key is pressed, but we're not sure what key makes the modifier state active. <kbd>Fn</kbd> key on Mac keyboard doesn't cause this active. {{gecko_minversion_inline("29.0")}}</td> + </tr> + <tr> + <th scope="row"><code>"FnLock"</code></th> + <td colspan="5" rowspan="1" style="background-color: rgb(204, 204, 204); text-align: center;"><em>Not supported</em></td> + </tr> + <tr> + <th scope="row"><code>"Hyper"</code></th> + <td colspan="5" style="background-color: rgb(204, 204, 204); text-align: center;"><em>Not supported</em></td> + </tr> + <tr> + <th scope="row"><code>"Meta"</code></th> + <td style="background-color: rgb(204, 204, 204); text-align: center;"><em>Not supported</em></td> + <td style="text-align: center;"><kbd>Meta</kbd> key pressed {{gecko_minversion_inline("17.0")}}</td> + <td><kbd>⌘ Command</kbd> key pressed</td> + <td style="text-align: center; background-color: rgb(204, 204, 204);"><em>Not supported</em></td> + <td><kbd>⊞ Windows Logo</kbd> key or <kbd>command</kbd> key pressed</td> + </tr> + <tr> + <th scope="row"><code>"NumLock"</code></th> + <td colspan="2" style="text-align: center;">During LED for <kbd>Num Lock</kbd> turned on</td> + <td>A key on numpad pressed</td> + <td style="text-align: center; background-color: rgb(204, 204, 204);"><em>Not supported</em></td> + <td>While <kbd>NumLock</kbd> is locked {{gecko_minversion_inline("29.0")}}</td> + </tr> + <tr> + <th scope="row"><code>"OS"</code></th> + <td><kbd>⊞ Windows Logo</kbd> key pressed</td> + <td><kbd>Super</kbd> key or <kbd>Hyper</kbd> key pressed (typically, mapped to <kbd>⊞ Windows Logo</kbd> key)</td> + <td colspan="3" rowspan="1" style="background-color: rgb(204, 204, 204); text-align: center;"><em>Not supported</em></td> + </tr> + <tr> + <th scope="row"><code>"ScrollLock"</code></th> + <td>During LED for <kbd>Scroll Lock</kbd> turned on</td> + <td>During LED for <kbd>Scroll Lock</kbd> turned on, but typically this isn't supported by platform</td> + <td colspan="2" style="background-color: rgb(204, 204, 204); text-align: center;"><em>Not supported</em></td> + <td>While <kbd>ScrollLock</kbd> is locked {{gecko_minversion_inline("29.0")}}</td> + </tr> + <tr> + <th scope="row"><code>"Shift"</code></th> + <td colspan="5" rowspan="1" style="text-align: center;"><kbd>⇧ Shift</kbd> key pressed</td> + </tr> + <tr> + <th scope="row"><code>"Super"</code></th> + <td colspan="5" style="background-color: rgb(204, 204, 204); text-align: center;"><em>Not supported</em></td> + </tr> + <tr> + <th scope="row"><code>"Symbol"</code></th> + <td colspan="5" style="background-color: rgb(204, 204, 204); text-align: center;"><em>Not supported</em></td> + </tr> + <tr> + <th scope="row"><code>"SymbolLock"</code></th> + <td colspan="5" style="background-color: rgb(204, 204, 204); text-align: center;"><em>Not supported</em></td> + </tr> + </tbody> +</table> + +<ul> + <li>On the other platforms, "Alt", "Control" and "Shift" may be supported.</li> + <li>All modifiers (except <code>"FnLock"</code>, <code>"Hyper"</code>, <code>"Super"</code> and <code>"Symbol"</code> which are defined after Gecko implements this) are always supported for untrusted events on Gecko. This doesn't depend on the platform.</li> +</ul> + +<h2 id="El_modificador_virtual_Accel"> El modificador virtual <code>"Accel"</code></h2> + +<div class="note"><strong>Note:</strong> The <code>"Accel"</code> virtual modifier has been effectively <strong>deprecated</strong> in current drafts of the DOM3 Events specification.</div> + +<p><code>getModifierState()</code> also accepts a deprecated virtual modifier named <code>"Accel"</code>. <code>event.getModifierState("Accel")</code> returns <code>true</code> when at least one of {{domxref("KeyboardEvent.ctrlKey")}} or {{domxref("KeyboardEvent.metaKey")}} is <code>true</code>.</p> + +<p>In old implementations and outdated specifications, it returned <code>true</code> when a modifier which is the typical modifier key for the shortcut key is pressed. For example, on Windows, pressing <kbd>Ctrl</kbd> key may make it return <code>true</code>. However, on Mac, pressing <kbd>⌘ Command</kbd> key may make it return <code>true</code>. Note that which modifier key makes it return true depends on platforms, browsers, and user settings. For example, Firefox users can customize this with a pref, <code>"ui.key.accelKey"</code>.</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush: js">// Ignore if following modifier is active. +if (event.getModifierState("Fn") || + event.getModifierState("Hyper") || + event.getModifierState("OS") || + event.getModifierState("Super") || + event.getModifierState("Win") /* hack for IE */) { + return; +} + +// Also ignore if two or more modifiers except Shift are active. +if (event.getModifierState("Control") + + event.getModifierState("Alt") + + event.getModifierState("Meta") > 1) { + return; +} + +// Handle shortcut key with standard modifier +if (event.getModifierState("Accel")) { + switch (event.key.toLowerCase()) { + case "c": + if (event.getModifierState("Shift")) { + // Handle Accel + Shift + C + event.preventDefault(); // consume the key event + } + break; + case "k": + if (!event.getModifierState("Shift")) { + // Handle Accel + K + event.preventDefault(); // consume the key event + } + break; + } + return; +} + +// Do somethig different for arrow keys if ScrollLock is locked. +if ((event.getModifierState("ScrollLock") || + event.getModifierState("Scroll") /* hack for IE */) && + !event.getModifierState("Control") && + !event.getModifierState("Alt") && + !event.getModifierState("Meta")) { + switch (event.key) { + case "ArrowDown": + case "Down": // hack for IE and old Gecko + event.preventDefault(); // consume the key event + break; + case "ArrowLeft": + case "Left": // hack for IE and old Gecko + // Do something different if ScrollLock is locked. + event.preventDefault(); // consume the key event + break; + case "ArrowRight": + case "Right": // hack for IE and old Gecko + // Do something different if ScrollLock is locked. + event.preventDefault(); // consume the key event + break; + case "ArrowUp": + case "Up": // hack for IE and old Gecko + // Do something different if ScrollLock is locked. + event.preventDefault(); // consume the key event + break; + } +} +</pre> + +<div class="note"> +<p>Although, this example uses<code> .getModifierState()</code> with <code>"Alt"</code>, <code>"Control"</code>, <code>"Meta"</code> and <code>"Shift"</code>, perhaps it's better for you to use <code>altKey</code>, <code>ctrlKey</code>, <code>metaKey</code> and <code>shiftKey</code> because they are shorter and may be faster.</p> +</div> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificaciones</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('DOM3 Events', '#widl-KeyboardEvent-getModifierState', 'getModifierState()')}}</td> + <td>{{Spec2('DOM3 Events')}}</td> + <td>Initial definition (<a href="https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3Events-key.html#keys-modifier">Modifier Keys spec</a>)</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_Browsers">Compatibilidad con Browsers</h2> + + + +<p>{{Compat("api.KeyboardEvent.getModifierState")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>The {{domxref("KeyboardEvent")}} this method belongs to.</li> + <li>{{domxref("MouseEvent.getModifierState")}}</li> +</ul> diff --git a/files/es/web/api/keyboardevent/index.html b/files/es/web/api/keyboardevent/index.html new file mode 100644 index 0000000000..bcb27d00b6 --- /dev/null +++ b/files/es/web/api/keyboardevent/index.html @@ -0,0 +1,441 @@ +--- +title: KeyboardEvent +slug: Web/API/KeyboardEvent +tags: + - API +translation_of: Web/API/KeyboardEvent +--- +<p>{{APIRef("DOM Events")}}</p> + +<p>Los objetos <strong><code>KeyboardEvent</code></strong> describen una interacción del usuario con el teclado. Cada evento describe una tecla; el tipo de evento(<code>keydown</code>, <code>keypress</code>, o <code>keyup</code>) identifica el tipo de acción realizada.</p> + +<div class="note"><strong>Nota:</strong> El <code>KeyboardEvent</code> solo indica qué está pasando en una tecla. Cuando necesite manejar la entrada de texto, use el evento <code><a href="/en-US/docs/DOM/DOM_event_reference/input" rel="custom">input</a></code> de HTML5 en su lugar. Por ejemplo, si el usuario introduce texto desde un sistema de tipo manuscrito como una tableta, los eventos para teclas no podrán ser lanzados.</div> + +<h2 id="Constructor">Constructor</h2> + +<dl> + <dt>{{domxref("KeyboardEvent.KeyboardEvent", "KeyboardEvent()")}}</dt> + <dd>Crea un objeto <code>KeyboardEvent</code>.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<p><em>Esta interfaz también hereda métodos de sus padres, {{domxref("UIEvent")}} and {{domxref("Event")}}.</em></p> + +<dl> + <dt>{{domxref("KeyboardEvent.getModifierState()")}}</dt> + <dd>Devuelve un {{jsxref("Boolean")}} indicando si una tecla modificadora, como <kbd>Alt</kbd>, <kbd>Shift</kbd>, <kbd>Ctrl</kbd>, o <kbd>Meta</kbd>, fue pulsada cuando el evento fue creado.</dd> + <dt>{{domxref("KeyboardEvent.initKeyEvent()")}}{{deprecated_inline}}</dt> + <dd>Inicializa un objeto <code>KeyboardEvent</code>. Este método solo ha sido implementado por Gecko (otros usados {{domxref("KeyboardEvent.initKeyboardEvent()")}}) y nunca más será usado. El modo estándar moderno es usar el constructor {{domxref("KeyboardEvent.KeyboardEvent", "KeyboardEvent()")}}.</dd> + <dt>{{domxref("KeyboardEvent.initKeyboardEvent()")}}{{deprecated_inline}}</dt> + <dd>Inicializa un objeto <code>KeyboardEvent</code>. Este método nunca fue implementado por Gecko (quien usa {{domxref("KeyboardEvent.initKeyEvent()")}}) y no debe ser utilizado más. El modo estándar moderno es usar el constructor {{domxref("KeyboardEvent.KeyboardEvent", "KeyboardEvent()")}}.</dd> +</dl> + +<h2 id="Propiedades">Propiedades</h2> + +<p><em>Esta interfaz también hereda propiedades de sus padres {{domxref("UIEvent")}} y {{domxref("Event")}}.</em></p> + +<dl> + <dt>{{domxref("KeyboardEvent.altKey")}} {{Readonlyinline}}</dt> + <dd>Devuelve un {{jsxref("Boolean")}} que será <code>true</code> si la tecla <kbd>Alt</kbd> ( <kbd>Option</kbd> or <kbd>⌥</kbd> on OS X) fue activada cuando el evento fue generado.</dd> + <dt>{{domxref("KeyboardEvent.char")}} {{Non-standard_inline()}}{{Deprecated_inline}}{{Readonlyinline}}</dt> + <dd>Devuelve un {{domxref("DOMString")}} representando el valor del carácter de la tecla. Si la tecla corresponde con un carácter imprimible, este valor es una cadena Unicode no vacía que contiene este carácter. Si la tecla no tiene una representación imprimible, esta es una cadena vacía.</dd> + <dd> + <div class="note"><strong>Nota:</strong> Si la tecla es usada como una macro que inserta múltiples caracteres, If the key is used as a macro that inserts multiple characters, el valor de este atributo es la cadena completa, no solo el primer carácter.</div> + + <div class="warning"><strong>Advertencia:</strong> Esta propiedad ha sido eliminada de los eventos del DOM de nivel 3. Esta es únicamente soportada en IE.</div> + </dd> + <dt>{{domxref("KeyboardEvent.charCode")}} {{Deprecated_inline}}{{Readonlyinline}}</dt> + <dd>Returns an <code>unsigned<code> </code>long</code> representing the Unicode reference number of the key; this attribute is used only by the <code>keypress</code> event. For keys whose <code>char</code> attribute contains multiple characters, this is the Unicode value of the first character in that attribute. In Firefox 26 this returns codes for printable characters. + <div class="warning"><strong>Warning:</strong> This attribute is deprecated; you should use <code>key</code> instead, if available.</div> + </dd> + <dt>{{domxref("KeyboardEvent.code")}} {{Readonlyinline}}</dt> + <dd>Returns a {{domxref("DOMString")}} with the code value of the key represented by the event.</dd> + <dt>{{domxref("KeyboardEvent.ctrlKey")}} {{Readonlyinline}}</dt> + <dd>Returns a {{jsxref("Boolean")}} that is <code>true</code> if the <kbd>Ctrl</kbd> key was active when the key event was generated.</dd> + <dt>{{domxref("KeyboardEvent.isComposing")}} {{Readonlyinline}}</dt> + <dd>Returns a {{jsxref("Boolean")}} that is <code>true</code> if the event is fired between after <code>compositionstart</code> and before <code>compositionend</code>.</dd> + <dt>{{domxref("KeyboardEvent.key")}} {{Readonlyinline}}</dt> + <dd>Returns a {{domxref("DOMString")}} representing the key value of the key represented by the event.</dd> + <dt>{{domxref("KeyboardEvent.keyCode")}} {{deprecated_inline()}}{{Readonlyinline}}</dt> + <dd>Returns an <code>unsigned long</code> representing a system and implementation dependent numerical code identifying the unmodified value of the pressed key. + <div class="warning"><strong>Warning:</strong> This attribute is deprecated; you should use <code>key</code> instead, if available.</div> + </dd> + <dt>{{domxref("KeyboardEvent.locale")}} {{Readonlyinline}}</dt> + <dd>Returns a {{domxref("DOMString")}} representing a locale string indicating the locale the keyboard is configured for. This may be the empty string if the browser or device doesn't know the keyboard's locale. + <div class="note"><strong>Note:</strong> This does not describe the locale of the data being entered. A user may be using one keyboard layout while typing text in a different language.</div> + </dd> + <dt>{{domxref("KeyboardEvent.location")}}<a name="Attributes_location"> {{Readonlyinline}}</a></dt> + <dd>Returns an <code>unsigned long</code> representing the location of the key on the keyboard or other input device.</dd> + <dt>{{domxref("KeyboardEvent.metaKey")}} {{Readonlyinline}}</dt> + <dd>Returns a {{jsxref("Boolean")}} that is <code>true</code> if the <kbd>Meta</kbd> (or <kbd>Command</kbd> on OS X) key was active when the key event was generated.</dd> + <dt>{{domxref("KeyboardEvent.repeat")}} {{Readonlyinline}}</dt> + <dd>Returns a {{jsxref("Boolean")}} that is <code>true</code> if the key is being held down such that it is automatically repeating.</dd> + <dt>{{domxref("KeyboardEvent.shiftKey")}} {{Readonlyinline}}</dt> + <dd>Returns a {{jsxref("Boolean")}} that is <code>true</code> if the <kbd>Shift</kbd> key was active when the key event was generated.</dd> + <dt>{{domxref("KeyboardEvent.which")}} {{deprecated_inline}}{{Readonlyinline}}</dt> + <dd>Returns an <code>unsigned long</code> representing a system and implementation dependent numeric code identifying the unmodified value of the pressed key; this is usually the same as <code>keyCode</code>. + <div class="warning"><strong>Warning:</strong> This attribute is deprecated; you should use <code>key</code> instead, if available.</div> + </dd> +</dl> + +<h2 id="Notes">Notes</h2> + +<p>There are <code>keydown</code>, <code>keypress</code>, and <code>keyup</code> events. For most keys, Gecko dispatches a sequence of key events like this:</p> + +<ol> + <li>When the key is first depressed, the <code>keydown</code> event is sent.</li> + <li>If the key is not a modifier key, the <code>keypress</code> event is sent.</li> + <li>When the user releases the key, the <code>keyup</code> event is sent.</li> +</ol> + +<h3 id="Special_cases">Special cases</h3> + +<p>Certain keys toggle the state of an LED indicator, such as Caps Lock, Num Lock, and Scroll Lock. On Windows and Linux, these keys dispatch only the <code>keydown</code> and <code>keyup</code> events. Note that on Linux, Firefox 12 and earlier also dispatched the <code>keypress</code> event for these keys.</p> + +<p>On Mac, however, Caps Lock dispatches only the <code>keydown</code> event due to a platform event model limitation. Num Lock had been supported on old MacBook (2007 model and older) but Mac hasn't supported Num Lock feature even on external keyboards in these days. On the old MacBook which has Num Lock key, Num Lock doesn't cause any key events. And Gecko supports Scroll Lock key if an external keyboard which has F14 is connected. However, it generates <code>keypress</code> event. This inconsistent behavior is a bug; see {{bug(602812)}}.</p> + +<h3 id="Auto-repeat_handling">Auto-repeat handling</h3> + +<p>When a key is pressed and held down, it begins to auto-repeat. This results in a sequence of events similar to the following being dispatched:</p> + +<ol> + <li><code>keydown</code></li> + <li><code>keypress</code></li> + <li><code>keydown</code></li> + <li><code>keypress</code></li> + <li><<repeating until the user releases the key>></li> + <li><code>keyup</code></li> +</ol> + +<p>This is what the DOM Level 3 specification says should happen. There are some caveats, however, as described below.</p> + +<h4 id="Auto-repeat_on_some_GTK_environments_such_as_Ubuntu_9.4">Auto-repeat on some GTK environments such as Ubuntu 9.4</h4> + +<p>In some GTK-based environments, auto-repeat dispatches a native key-up event automatically during auto-repeat, and there's no way for Gecko to know the difference between a repeated series of keypresses and an auto-repeat. On those platforms, then, an auto-repeat key will generate the following sequence of events:</p> + +<ol> + <li><code>keydown</code></li> + <li><code>keypress</code></li> + <li><code>keyup</code></li> + <li><code>keydown</code></li> + <li><code>keypress</code></li> + <li><code>keyup</code></li> + <li><<repeating until the user releases the key>></li> + <li><code>keyup</code></li> +</ol> + +<p>In these environments, unfortunately, there's no way for web content to tell the difference between auto-repeating keys and keys that are just being pressed repeatedly.</p> + +<h4 id="Auto-repeat_handling_prior_to_Gecko_4.0">Auto-repeat handling prior to Gecko 4.0</h4> + +<p>Before Gecko 4.0 {{geckoRelease('4.0')}}, keyboard handling was less consistent across platforms.</p> + +<dl> + <dt>Windows</dt> + <dd>Auto-repeat behavior is the same as in Gecko 4.0 and later.</dd> + <dt>Mac</dt> + <dd>After the initial keydown event, only keypress events are sent until the keyup event occurs; the inter-spaced keydown events are not sent.</dd> + <dt>Linux</dt> + <dd>The event behavior depends on the specific platform. It will either behave like Windows or Mac depending on what the native event model does.</dd> +</dl> + +<h2 id="Example">Example</h2> + +<pre class="brush: js"><!DOCTYPE html> +<html> +<head> +<script> +var metaChar = false; +var exampleKey = 16; + +function keyEvent(event) { + var key = event.keyCode || event.which; + var keychar = String.fromCharCode(key); + if (key == exampleKey) { + metaChar = true; + } + if (key != exampleKey) { + if (metaChar) { + alert("Combination of metaKey + " + keychar); + metaChar = false; + } else { + alert("Key pressed " + key); + } + } +} + +function metaKeyUp (event) { + var key = event.keyCode || event.which; + + if (key == exampleKey) { + metaChar = false; + } +} +</script> +</head> + +<body onkeydown="keyEvent(event)" onkeyup="metaKeyUp(event)"> +</body> +</html> +</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('DOM3 Events', '#interface-KeyboardEvent', 'KeyboardEvent')}}</td> + <td>{{Spec2('DOM3 Events')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<p>The <code>KeyboardEvent</code> interface specification went through numerous draft versions, first under DOM Events Level 2 where it was dropped as no consensus arose, then under DOM Events Level 3. This led to the implementation of non-standard initialization methods, the early DOM Events Level 2 version, {{domxref("KeyboardEvent.initKeyEvent()")}} by Gecko browsers and the early DOM Events Level 3 version, {{domxref("KeyboardEvent.initKeyboardEvent()")}} by others. Both have been superseded by the modern usage of a constructor: {{domxref("KeyboardEvent.KeyboardEvent", "KeyboardEvent()")}}.</p> + +<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 (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + <tr> + <td>constructor</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatGeckoDesktop("31.0") }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + </tr> + <tr> + <td><code>.char</code></td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + </tr> + <tr> + <td><code>.charCode</code></td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + <tr> + <td><code>.code</code></td> + <td colspan="5" rowspan="1">See Browser compatibility of {{domxref("KeyboardEvent.code")}}.</td> + </tr> + <tr> + <td><code>.isComposing</code></td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatGeckoDesktop("31.0") }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + </tr> + <tr> + <td><code>.key</code></td> + <td colspan="5" rowspan="1">See Browser compatibility of {{domxref("KeyboardEvent.key")}}.</td> + </tr> + <tr> + <td><code>.keyCode</code></td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + <tr> + <td><code>.locale</code></td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + </tr> + <tr> + <td><code>.location</code></td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatGeckoDesktop("15.0") }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + </tr> + <tr> + <td><code>.repeat</code></td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatGeckoDesktop("28.0") }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + </tr> + <tr> + <td><code>.which</code></td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + <tr> + <td><code>.getModifierState()</code></td> + <td colspan="5" rowspan="1">See Browser compatibility of {{domxref("KeyboardEvent.getModifierState")}}</td> + </tr> + <tr> + <td><code>.initKeyboardEvent()</code></td> + <td>{{ CompatVersionUnknown() }} *1</td> + <td>{{ CompatNo() }} *2</td> + <td>{{ CompatIE("9.0") }} *3</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatVersionUnknown() }} *1</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 Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + </tr> + <tr> + <td>constructor</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatGeckoMobile("31.0") }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + </tr> + <tr> + <td><code>.char</code></td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + </tr> + <tr> + <td><code>.charCode</code></td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + </tr> + <tr> + <td><code>.code</code></td> + <td colspan="5" rowspan="1">See Browser compatibility of {{domxref("KeyboardEvent.code")}}.</td> + </tr> + <tr> + <td><code>.isComposing</code></td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatGeckoMobile("31.0") }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + </tr> + <tr> + <td><code>.key</code></td> + <td colspan="6">See Browser compatibility table of {{domxref("KeyboardEvent.key")}}.</td> + </tr> + <tr> + <td><code>.keyCode</code></td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + </tr> + <tr> + <td><code>.locale</code></td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + </tr> + <tr> + <td><code>.location</code></td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatGeckoMobile("15.0") }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + </tr> + <tr> + <td><code>.repeat</code></td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatGeckoMobile("28.0") }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + </tr> + <tr> + <td><code>.which</code></td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + </tr> + <tr> + <td><code>.getModifierState()</code></td> + <td colspan="5" rowspan="1">See Browser compatibility of {{domxref("KeyboardEvent.getModifierState")}}</td> + </tr> + <tr> + <td><code>.initKeyboardEvent()</code></td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<p><br> + *1 The arguments of <code>initKeyboardEvent()</code> of WebKit and Blink's are different from the definition in DOM Level 3 Events. The method is: <code>initKeyboardEvent(in DOMString typeArg, in boolean canBubbleArg, in boolean cancelableArg, in views::AbstractView viewArg, in DOMString keyIndentifierArg, in unsigned long locationArg, in boolean ctrlKeyArg, in boolean altKeyArg, in boolean shiftKeyArg, in boolean metaKeyArg, in boolean altGraphKeyArg)</code></p> + +<p><code>*2</code> Gecko won't support <code>initKeyboardEvent()</code> because supporting it completely breaks feature detection of web applications. See {{Bug(999645)}}.</p> + +<p>*3 The argument of initKeyboardEvent() of IE is different from the definition in DOM Level 3 Events. The method is: <code>initKeyboardEvent(in DOMString typeArg, in boolean canBubbleArg, in boolean cancelableArg, in views::AbstractView viewArg, in DOMString keyArg, in unsigned long locationArg, in DOMString modifierListArg, in boolean repeatArt, in DOMString locationArg)</code>. See <a href="http://msdn.microsoft.com/en-us/library/ie/ff975297%28v=vs.85%29.aspx">document of <code>initKeyboardEvent()</code> in MSDN</a>.</p> diff --git a/files/es/web/api/keyboardevent/key/index.html b/files/es/web/api/keyboardevent/key/index.html new file mode 100644 index 0000000000..ed765b38b3 --- /dev/null +++ b/files/es/web/api/keyboardevent/key/index.html @@ -0,0 +1,212 @@ +--- +title: KeyboardEvent.key +slug: Web/API/KeyboardEvent/key +translation_of: Web/API/KeyboardEvent/key +--- +<p>{{APIRef("DOM Events")}}</p> + +<p><span class="seoSummary">La propiedad de solo lectura<strong> </strong><code><strong>KeyboardEvent.key</strong></code> retorna el valor de la tecla presionada por el usuario while taking into considerations the state of modifier keys such as the <code>shiftKey</code> as well as the keyboard locale/layout.</span> Its value is determined as follows:</p> + +<div class="pull-aside"> +<p class="moreinfo">See a full list of <a href="/docs/Web/API/KeyboardEvent/key/Key_Values">key values</a>.</p> +</div> + +<ul> + <li>Si la tecla presionada tiene una representación impresa, el valor devuelto es una cadena de caracteres Unicode no-vacía que contiene la representación imprimible de la tecla.</li> + <li>Si la tecla presionada es un control o un carácter especial, el valor devuelto es uno de los <a href="/docs/Web/API/KeyboardEvent/key/Key_Values">valores clave definidos</a>.</li> + <li>If the <code>KeyboardEvent</code> represents the press of a dead key, the key value must be "<code>Dead</code>".</li> + <li>Some specialty keyboard keys (such as the extended keys for controlling media on multimedia keyboards) don't generate key codes on Windows; instead, they trigger <code>WM_APPCOMMAND</code> events. These events get mapped to DOM keyboard events, and are listed among the "Virtual key codes" for Windows, even though they aren't actually key codes.</li> + <li>If the key cannot be identified, the returned value is <code>"Unidentified"</code>.</li> +</ul> + +<h2 id="KeyboardEvent_Sequence">KeyboardEvent Sequence</h2> + +<p><code>KeyboardEvent</code>s are fired in a pre-determined sequence and understanding this will go a long way into understanding the <code>key</code> property value for a particular <code>KeyboardEvent</code>. For a given key press, the sequence of <code>KeyboardEvent</code>s fired is as follows assuming that {{domxref("Event.preventDefault")}} is not called:</p> + +<ol> + <li>A {{event("keydown")}} event is first fired. If the key is held down further and the key produces a character key, then the event continues to be emitted in a platform implementation dependent interval and the {{domxref("KeyboardEvent.repeat")}} read only property is set to <code>true</code>.</li> + <li>If the key produces a character key that would result in a character being inserted into possibly an {{HTMLElement("input")}}, {{HTMLElement("textarea")}} or an element with {{domxref("HTMLElement.contentEditable")}} set to true, the {{event("beforeinput")}} and {{event("input")}} event types are fired in that order. Note that some other implementations may fire {{event("keypress")}} event if supported. The events will be fired repeatedly while the key is held down.</li> + <li>A {{event("keyup")}} event is fired once the key is released. This completes the process.</li> +</ol> + +<p>In sequence 1 & 3, the <code>KeyboardEvent.key</code> attribute is defined and is set appropriately to a value according to the rules defined ealier.</p> + +<h2 id="KeyboardEvent_Sequence_Sample">KeyboardEvent Sequence Sample</h2> + +<p>Consider the event sequence generated when we interact with the <code>ShiftKey</code> and the legend <code>key 2</code> using a U.S keyboard layout and a UK keyboard layout.</p> + +<p>Try experimenting using the following two test cases:</p> + +<ol> + <li>Press and hold the <code>shift</code> key, then press <code>key 2</code> and release it. Next, release the <code>shift</code> key.</li> + <li>Press and hold the <code>shift</code> key, then press and hold <code>key 2</code>. Release the <code>shift</code> key. Finally, release <code>key 2</code>.</li> +</ol> + +<h3 id="HTML">HTML</h3> + +<pre class="brush: html"><div class="fx"> + <div> + <textarea rows="5" name="test-target" id="test-target"></textarea> + <button type="button" name="btn-clear-console" id="btn-clear-console">clear console</button> + </div> + <div class="flex"> + <div id="console-log"></div> + </div> +</div> +</pre> + +<h3 id="CSS">CSS</h3> + +<pre class="brush: css">.fx { + -webkit-display: flex; + display: flex; + margin-left: -20px; + margin-right: -20px; +} + +.fx > div { + padding-left: 20px; + padding-right: 20px; +} + +.fx > div:first-child { + width: 30%; +} + +.flex { + -webkit-flex: 1; + flex: 1; +} + +#test-target { + display: block; + width: 100%; + margin-bottom: 10px; +}</pre> + +<h3 id="JavaScript">JavaScript</h3> + +<pre class="brush: js">let textarea = document.getElementById('test-target'), +consoleLog = document.getElementById('console-log'), +btnClearConsole = document.getElementById('btn-clear-console'); + +function logMessage(message) { + let p = document.createElement('p'); + p.appendChild(document.createTextNode(message)); + consoleLog.appendChild(p); +} + +textarea.addEventListener('keydown', (e) => { + if (!e.repeat) + logMessage(`first keydown event. key property value is "${e.key}"`); + else + logMessage(`keydown event repeats. key property value is "${e.key}"`); +}); + +textarea.addEventListener('beforeinput', (e) => { + logMessage(`beforeinput event. you are about inputing "${e.data}"`); +}); + +textarea.addEventListener('input', (e) => { + logMessage(`input event. you have just inputed "${e.data}"`); +}); + +textarea.addEventListener('keyup', (e) => { + logMessage(`keyup event. key property value is "${e.key}"`); +}); + +btnClearConsole.addEventListener('click', (e) => { + let child = consoleLog.firstChild; + while (child) { + consoleLog.removeChild(child); + child = consoleLog.firstChild; + } +});</pre> + +<h3 id="Result">Result</h3> + +<p>{{EmbedLiveSample('KeyboardEvent_Sequence_Sample')}}</p> + +<h3 id="Case_1">Case 1</h3> + +<p>When the shift key is pressed, a {{event("keydown")}} event is first fired, and the <code>key</code> property value is set to the string <code>"Shift"</code>. As we keep holding this key, the {{event("keydown")}} event does not continue to fire repeatedly because it does not produce a character key.</p> + +<p>When <code>key 2</code> is pressed, another {{event("keydown")}} event is fired for this new key press, and the <code>key</code> property value for the event is set to the string <code>"@"</code> for the U.S keyboard type and <code>"""</code> for the UK keyboard type, because of the active modifier <code>shift</code> key. The {{event("beforeinput")}} and {{event("input")}} events are fired next because a character key has been produced.</p> + +<p>As we release the <code>key 2</code>, a {{event("keyup")}} event is fired and the <code>key</code> property will maintain the string values <code>"@"</code> and <code>"""</code> for the different keyboard layouts respectively.</p> + +<p>As we finally release the <code>shift</code> key, another {{event("keyup")}} event is fired for it, and the key attribute value remains <code>"Shift"</code>.</p> + +<h3 id="Case_2">Case 2</h3> + +<p>When the shift key is pressed, a {{event("keydown")}} event is first fired, and the <code>key</code> property value is set to be the string <code>"Shift"</code>. As we keep holding this key, the keydown event does not continue to fire repeatedly because it produced no character key.</p> + +<p>When <code>key 2</code> is pressed, another {{event("keydown")}} event is fired for this new key press, and the <code>key</code> property value for the event is set to be the string <code>"@"</code> for the U.S keyboard type and <code>"""</code> for the UK keyboard type, because of the active modifier <code>shift</code> key. The {{event("beforeinput")}} and {{event("input")}} events are fired next because a character key has been produced. As we keep holding the key, the {{event("keydown")}} event continues to fire repeatedly and the {{domxref("KeyboardEvent.repeat")}} property is set to <code>true</code>. The {{event("beforeinput")}} and {{event("input")}} events are fired repeatedly as well.</p> + +<p>As we release the <code>shift</code> key, a {{event("keyup")}} event is fired for it, and the key attribute value remains <code>"Shift"</code>. At this point, notice that the <code>key</code> property value for the repeating keydown event of the <code>key 2</code> key press is now "2" because the modifier <code>shift</code> key is no longer active. The same goes for the {{domxref("InputEvent.data")}} property of the {{event("beforeinput")}} and {{event("input")}} events.</p> + +<p>As we finally release the <code>key 2</code>, a {{event("keyup")}} event is fired but the <code>key</code> property will be set to the string value <code>"2"</code> for both keyboard layouts because the modifier <code>shift</code> key is no longer active.</p> + +<h2 id="Example">Example</h2> + +<p>This example uses {{domxref("EventTarget.addEventListener()")}} to listen for {{event("keydown")}} events. When they occur, the key's value is checked to see if it's one of the keys the code is interested in, and if it is, it gets processed in some way (possibly by steering a spacecraft, perhaps by changing the selected cell in a spreadsheet).</p> + +<pre class="brush: js">window.addEventListener("keydown", function (event) { + if (event.defaultPrevented) { + return; // Do nothing if the event was already processed + } + + switch (event.key) { + case "Down": // IE specific value + case "ArrowDown": + // Do something for "down arrow" key press. + break; + case "Up": // IE specific value + case "ArrowUp": + // Do something for "up arrow" key press. + break; + case "Left": // IE specific value + case "ArrowLeft": + // Do something for "left arrow" key press. + break; + case "Right": // IE specific value + case "ArrowRight": + // Do something for "right arrow" key press. + break; + case "Enter": + // Do something for "enter" or "return" key press. + break; + case "Escape": + // Do something for "esc" key press. + break; + default: + return; // Quit when this doesn't handle the key event. + } + + // Cancel the default action to avoid it being handled twice + event.preventDefault(); +}, true); +</pre> + +<h2 id="Specification">Specification</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('DOM3 Events', '#widl-KeyboardEvent-key', 'KeyboardEvent.key')}}</td> + <td>{{Spec2('DOM3 Events')}}</td> + <td>Initial definition, included key values.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("api.KeyboardEvent.key")}}</p> diff --git a/files/es/web/api/keyboardevent/metakey/index.html b/files/es/web/api/keyboardevent/metakey/index.html new file mode 100644 index 0000000000..7a83c5c0b2 --- /dev/null +++ b/files/es/web/api/keyboardevent/metakey/index.html @@ -0,0 +1,131 @@ +--- +title: KeyboardEvent.metaKey +slug: Web/API/KeyboardEvent/metaKey +tags: + - Evento + - Referencia +translation_of: Web/API/KeyboardEvent/metaKey +--- +<p>{{APIRef("DOM Events")}}</p> + +<p>La propiedad <strong><code>KeyboardEvent.metaKey</code></strong> es de solo lectura y regresa un valor {{jsxref("Boolean")}} que indica si la tecla <kbd>Meta</kbd> estaba presionada (true) o no (false) cuando el evento ocurrio.</p> + +<div class="note"> +<p><strong>Nota:</strong> En teclados Macintosh es la tecla comando (<kbd>⌘</kbd>). En teclados Windows la tecla es lla tecla window (<kbd>⊞</kbd>).</p> +</div> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox">var metaKeyPressed = <em>instanceOfKeyboardEvent</em>.metaKey +</pre> + +<h3 id="Valor_de_retorno">Valor de retorno</h3> + +<p>{{jsxref("Boolean")}}</p> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre class="brush: js"> function goInput(e) { + // Revisa si estaba presionada la tecla meta y + if (e.metaKey) { + // realiza esto en caso de cierto + superSizeOutput(e); + } else { + //Realiz esto en caso de falso + doOutput(e); + } + } +</pre> + +<h2 id="metaKey" name="metaKey">metaKey</h2> + +<h3 id="Contenido_HTML">Contenido HTML</h3> + +<pre class="brush: html"><div id="example" onmousedown="ismetaKey(event);">¡Presiona la tecla meta y dame click!<div> +</pre> + +<h3 id="Contenido_Javascript">Contenido Javascript</h3> + +<pre class="brush: js">function ismetaKey(e){ + var el=document.getElementById("example");//Toma el control del div example + var mK=e.metaKey;//Obtiene el valor de metaKey y lo almacena + el.innerHTML="¡Presiona la tecla meta y dame click!</br>metaKey:"+mK;//Muestra el valor de metaKey +} +</pre> + +<p> </p> + +<p>{{ EmbedLiveSample('metaKey') }}</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Status</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('DOM3 Events','#widl-KeyboardEvent-metaKey','KeyboardEvent.metaKey')}}</td> + <td>{{Spec2('DOM3 Events')}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">Compatibilidad de Navegadores</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Firefox (Gecko)</th> + <th>Chrome</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>{{CompatVersionUnknown()}}</td> + <td>{{CompatVersionUnknown()}}</td> + <td>{{CompatVersionUnknown()}}</td> + <td>{{CompatVersionUnknown()}}</td> + <td>{{CompatVersionUnknown()}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Firefox Mobile (Gecko)</th> + <th>Android</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also" name="See_also">Ver también</h2> + +<ul> + <li>{{ domxref("KeyboardEvent") }}</li> +</ul> diff --git a/files/es/web/api/keyboardevent/which/index.html b/files/es/web/api/keyboardevent/which/index.html new file mode 100644 index 0000000000..11e1e3e48e --- /dev/null +++ b/files/es/web/api/keyboardevent/which/index.html @@ -0,0 +1,62 @@ +--- +title: event.which +slug: Web/API/KeyboardEvent/which +tags: + - DOM + - events + - metodo + - which +translation_of: Web/API/KeyboardEvent/which +--- +<p>{{ ApiRef() }}</p> +<h3 id="Summary" name="Summary">Resumen</h3> +<p>Devuelve el <code>keyCode</code> de la tecla presionada, o el codigo del caracter (<code>charCode</code>) de la tecla alfanumerica presionada.</p> +<h3 id="Syntax" name="Syntax">Sintaxis</h3> +<pre class="eval"><em>var keyResult</em> = event.which; +</pre> +<p><code>keyResult</code> contiene el codigo numerico para una tecla en particular, dependiendo si la tecla presionada es alfanumerica o no-alfanumerica. Por favor mire <code><a href="/en/DOM/event.charCode" title="en/DOM/event.charCode">charCode</a></code> y <code><a href="/en/DOM/event.keyCode" title="en/DOM/event.keyCode">keyCode</a></code> para mas informacion.</p> +<h3 id="Example" name="Example">Ejemplo</h3> +<pre><html> +<head> +<title>charCode/keyCode/which example</title> + +<script type="text/javascript"> + +function showKeyPress(evt) +{ +alert("onkeypress handler: \n" + + "keyCode property: " + evt.keyCode + "\n" + + "which property: " + evt.which + "\n" + + "charCode property: " + evt.charCode + "\n" + + "Character Key Pressed: " + + String.fromCharCode(evt.charCode) + "\n" + ); +} + + +function keyDown(evt) +{ +alert("onkeydown handler: \n" + + "keyCode property: " + evt.keyCode + "\n" + + "which property: " + evt.which + "\n" + ); +} + + +</script> +</head> + +<body + onkeypress="showKeyPress(event);" + onkeydown="keyDown(event);" +> + +<p>Por favor presione cualquier tecla.</p> + +</body> +</html> +</pre> +<div class="note"> + <strong>Nota:</strong> El codigo de arriba falla en Firefox 9 debido al <a class="link-https" href="https://bugzilla.mozilla.org/show_bug.cgi?id=696020" title="onkeypress attribute on body no longer gets events happening on the window">bug 696020</a>.</div> +<h3 id="Specification" name="Specification">Especificacion</h3> +<p>No es parte de ninguna especificacion.</p> diff --git a/files/es/web/api/location/index.html b/files/es/web/api/location/index.html new file mode 100644 index 0000000000..9276724542 --- /dev/null +++ b/files/es/web/api/location/index.html @@ -0,0 +1,212 @@ +--- +title: Location +slug: Web/API/Location +tags: + - API + - HTML DOM + - Interface + - Location + - Referencia +translation_of: Web/API/Location +--- +<p>{{APIRef("HTML DOM")}}</p> + +<p>La interface <strong><code>Location</code></strong> representa la ubicación (URL) del objeto al que esta vinculado. Los cambios hechos en ella son reflejados en el objeto al cual está relacionado. Ambas interfaces, {{domxref("Document")}} y {{domxref("Window")}} tienen una interface <code>Location</code> asignada, accessible desde {{domxref("Document.location")}} y {{domxref("Window.location")}} respectivamente.</p> + +<h2 id="Propiedades">Propiedades</h2> + +<p><em>La interface <code>Location</code></em><em> no hereda ninguna propiedad, pero las implementa desde {{domxref("URLUtils")}}.</em></p> + +<dl> + <dt>{{domxref("Location.href")}}</dt> + <dd>Es un {{domxref("DOMString")}} que contiene la URL completa. Si es cambiada, el documento asociado navegará a la nueva pagina. Puede ser cambiada desde un origen diferente que el asociado al documento.</dd> + <dt>{{domxref("Location.protocol")}}</dt> + <dd>Es un {{domxref("DOMString")}} que contiene el esquema del protocolo de la URL, incluyendo el <code>':'</code> final.</dd> + <dt>{{domxref("Location.host")}}</dt> + <dd>Es un {{domxref("DOMString")}} que contiene el host, el cual esta compuesta por: <em>hostname</em>, <code>':'</code>, y el <em>port</em> de la URL.</dd> + <dt>{{domxref("Location.hostname")}}</dt> + <dd>Es un {{domxref("DOMString")}} que contiene el dominio de la URL.</dd> + <dt>{{domxref("Location.port")}}</dt> + <dd>Es un {{domxref("DOMString")}} que contiene el numero del puerto de la URL.</dd> + <dt>{{domxref("Location.pathname")}}</dt> + <dd>Es un {{domxref("DOMString")}} que contiene el <code>'/'</code> inicial, seguido por la ruta de la URL.</dd> + <dt>{{domxref("Location.search")}}</dt> + <dd>Es un {{domxref("DOMString")}} que contiene un <code>'?'</code> seguido por los parametros o el "querystring" de la URL. Navegadores modernos proveen <a href="/en-US/docs/Web/API/URLSearchParams/get#Example">URLSearchParams</a> y <a href="/en-US/docs/Web/API/URL/searchParams#Example">URL.searchParams</a> para hacer mas facil de obtener los parametros desde el querystring.</dd> + <dt>{{domxref("Location.hash")}}</dt> + <dd>Es un {{domxref("DOMString")}} que contiene un <code>'#'</code> seguido por el fragmento identificador de la URL.</dd> + <dt>{{domxref("Location.username")}}</dt> + <dd>Es un {{domxref("DOMString")}} que contiene el <em>username</em> (usuario) especificado antes del dominio.</dd> + <dt>{{domxref("Location.password")}}</dt> + <dd>Es un {{domxref("DOMString")}} que contiene el <em>password</em> (contraseña) especificado antes del dominio.</dd> + <dt>{{domxref("Location.origin")}} {{readOnlyInline}}</dt> + <dd>Es un {{domxref("DOMString")}} que contiene la forma canonica del <em>origin</em> (origen) de la URL.</dd> +</dl> + +<h2 id="Metodos">Metodos</h2> + +<p><em>La interface <code>Location</code></em><em> no hereda ningun metodo<em>, pero los implementa desde {{domxref("URLUtils")}}</em>.</em></p> + +<dl> + <dt>{{domxref("Location.assign()")}}</dt> + <dd>Carga el recurso en la URL proporcionada en el parámetro.</dd> + <dt>{{domxref("Location.reload()")}}</dt> + <dd>Recarga el recurso desde la URL actual. Si unico y opcional parametro es {{domxref("Boolean")}}, el cual, cuando es <code>true</code>, hace que la pagina siempre sea recargada desde el servidor. Si es <code>false</code> o no es especificado, el navegador puede recargar la pagina desde su cache.</dd> + <dt>{{domxref("Location.replace()")}}</dt> + <dd>Reemplaza el recurso actual por el recibido como URL. La diferencia con el metodo <code>assign()</code> es que luego de usar <code>replace()</code> la pagina actual no va a ser guardada en la sesión {{domxref("History")}}, esto significa que el usuario no podrá usar el boton <em>Atras</em> para navegar a esta.</dd> + <dt>{{domxref("Location.toString()")}}</dt> + <dd>Retorna un {{domxref("DOMString")}} que contiene la URL completa. Es un sinonimo de {{domxref("URLUtils.href")}}, aunque este no puede ser utilizado para modificar el valor.</dd> +</dl> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush: js">// Crear un elemento <a> y usar la propiedad href para el proposito de este ejemplo. +// Una alternativa mas correcta es navegar a la URL y usar document.location o window.location +var url = document.createElement('a'); +url.href = 'https://developer.mozilla.org:8080/en-US/search?q=URL#search-results-close-container'; +console.log(url.href); // https://developer.mozilla.org/en-US/search?q=URL#search-results-close-container +console.log(url.protocol); // https: +console.log(url.host); // developer.mozilla.org:8080 +console.log(url.hostname); // developer.mozilla.org +console.log(url.port); // 8080 +console.log(url.pathname); // /en-US/search +console.log(url.search); // ?q=URL +console.log(url.hash); // #search-results-close-container +console.log(url.origin); // https://developer.mozilla.org +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificacion</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', "browsers.html#the-location-interface", "Location")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>No change from {{SpecName("HTML5 W3C")}}.</td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', "browsers.html#the-location-interface", "Location")}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>Definicion inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Caracteristica</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Soporte basico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>origin</code> en <code>Windows.location</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("21")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>origin</code> en todos los objetos <code>location</code> (pero en Workes, usa {{domxref("WorkerLocation")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("26")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>username</code> and <code>password</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("26")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Caracteristica</th> + <th>Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte basico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>origin</code> en <code>Windows.location</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("21")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>origin</code> en todos los objetos <code>location</code> (pero en Workers, usa {{domxref("WorkerLocation")}})</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("26")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>username</code> y <code>password</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("26")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Vea_también">Vea también</h2> + +<ul> + <li>Dos metodos que crean tal objeto: {{domxref("Window.location")}} y {{domxref("Document.location")}}.</li> + <li>URL relacionadas a interfaces: {{domxref("URL")}}, {{domxref("URLSearchParams")}} y {{domxref("HTMLHyperlinkElementUtils")}}</li> +</ul> diff --git a/files/es/web/api/location/origin/index.html b/files/es/web/api/location/origin/index.html new file mode 100644 index 0000000000..4e019a68f0 --- /dev/null +++ b/files/es/web/api/location/origin/index.html @@ -0,0 +1,56 @@ +--- +title: 'Location: origin' +slug: Web/API/Location/origin +tags: + - API + - Location + - Propiedad + - Referencia + - Ubicación +translation_of: Web/API/Location/origin +--- +<p>{{APIRef("Location")}}</p> + +<p><span class="seoSummary">La propiedad de sólo-lectura <strong><code>origin</code></strong> de la interfaz {{domxref("Location")}} es una {{domxref("USVString")}} que contiene la serialización Unicode del origen de la URL que representa</span>; que es:</p> + +<ul> + <li>para una URL que usa <code>http</code> o <code>https</code>, el esquema seguido de <code>'://'</code>, seguido del dominio, seguido de <code>':'</code>, seguido del puerto (el puerto por defecto, <code>80</code> y <code>443</code> respectivamente, si se indica de forma explícita);</li> + <li>para una URL que usa <code>file:</code> esquema, el valor es independiente del navegador;</li> + <li>para una URL que usa <code>blob:</code> esquema, el origen de la URL seguido de <code>blob:</code>. Ej. <code>"blob:https://mozilla.org"</code> tendrá <code>"https://mozilla.org".</code></li> +</ul> + +<p>{{AvailableInWorkers}}</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox notranslate"><em>string</em> = <em>object</em>.origin; +</pre> + +<h2 id="Ejemplos">Ejemplos</h2> + +<pre class="brush: js notranslate">// En esta página, devuelve el origen +var result = window.location.origin; // Devuelve:'https://developer.mozilla.org' +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', '#dom-location-origin', 'origin')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_navegadores">Compatibilidad en navegadores</h2> + + + +<p>{{Compat("api.Location.origin")}}</p> diff --git a/files/es/web/api/location/reload/index.html b/files/es/web/api/location/reload/index.html new file mode 100644 index 0000000000..2c7cedccab --- /dev/null +++ b/files/es/web/api/location/reload/index.html @@ -0,0 +1,75 @@ +--- +title: 'Location: reload()' +slug: Web/API/Location/reload +tags: + - API + - HTML + - HTML DOM + - Location + - Method + - Referencia + - metodo +translation_of: Web/API/Location/reload +--- +<div>{{ APIRef("HTML DOM") }}</div> + +<p>El metodo <code><strong>location.reload()</strong></code> carga de nuevo la URL actual, como lo hace el boton de Refresh de los navegadores.</p> + +<p>La recarga puede estar bloqueada y arrojar un <code>SECURITY_ERROR</code> {{domxref("DOMException")}} . Esto sucede si el {{Glossary("origin")}} de la llamada <code>location.reload()</code> difiere del origen de la página que posee el objeto { {domxref("Location")}}. Consulta <a href="/en-US/docs/Web/Security/Same-origin_policy">Same-origin policy</a> para mayor información.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox notranslate"><em>location</em>.reload(); +</pre> + +<h2 id="Ejemplo">Ejemplo</h2> + +<h3 id="HTML">HTML</h3> + +<pre class="brush: html notranslate"><button id="reload">Click para recargar</button> +</pre> + +<h3 id="JavaScript">JavaScript</h3> + +<pre class="brush: js notranslate">const reload = document.getElementById('reload'); + +reload.addEventListener('click', _ => { // el _ es para indicar la ausencia de parametros + location.reload(); +});</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('HTML WHATWG', "history.html#dom-location-reload", "Location.reload()")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>No change from {{SpecName("HTML5 W3C")}}.</td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', "browsers.html#dom-location-reload", "Location.reload()")}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_del_navegador">Compatibilidad del navegador</h2> + +<div class="hidden">La tabla de compatibilidad en esta página se genera a partir de datos estructurados. Si desea contribuir con los datos, consulte <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> y envíenos una solicitud de extracción.</div> + +<p>{{Compat("api.Location.reload")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>The {{domxref("Location")}} interface it belongs to.</li> + <li>Similar methods: {{domxref("Location.assign()")}} and {{domxref("Location.replace()")}}.</li> +</ul> diff --git a/files/es/web/api/mediadevices/getusermedia/index.html b/files/es/web/api/mediadevices/getusermedia/index.html new file mode 100644 index 0000000000..1466aecd36 --- /dev/null +++ b/files/es/web/api/mediadevices/getusermedia/index.html @@ -0,0 +1,300 @@ +--- +title: MediaDevices.getUserMedia() +slug: Web/API/MediaDevices/getUserMedia +translation_of: Web/API/MediaDevices/getUserMedia +--- +<div>{{APIRef("WebRTC")}}{{SeeCompatTable}}</div> + +<p>El método <code><strong>MediaDevices.getUserMedia()</strong></code> solicita al usuario permisos para usar un dispositivo de entrada de vídeo y/o uno de audio como una cámara o compartir la pantalla y/o micrófono. Si el usuario proporciona los permisos, entonces le retornará un {{domxref("Promise")}} que es resuelto por el resultado del objeto <code><a href="/en-US/docs/WebRTC/MediaStream_API#LocalMediaStream">MediaStream</a></code>. Si el usuario niega el permiso, o si el recurso multimedia no es válido, entonces el promise es rechazado con <code>PermissionDeniedError</code> o <code>NotFoundError</code> respectivamente. Nótese que es posible que el promise retornado no sea ni resuelto ni rechazado, ya que no se requiere que el usuario tome una decisión.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var <em>gumPromise</em> = <em>MediaDevices</em>.getUserMedia(<em>constraints</em>);</pre> + +<p>Generalmente, accederás al objeto singleton {{domxref("MediaDevices")}} usando {{domxref("navigator.mediaDevices")}}, de esta forma:</p> + +<pre><code>navigator.mediaDevices.getUserMedia(myConstraints).then(function(mediaStream) { + /* usar el flujo de datos */ +}).catch(function(err) { + /* manejar el error */ +});</code></pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code>constraints</code></dt> + <dd> + <p>Es un objeto {{domxref("MediaStreamConstraints")}} que especifica los tipos de recursos a solicitar, junto con cualquier requerimiento para cada tipo.</p> + + <p>El parámetro constraints es un objeto <code>MediaStreamConstaints</code> con dos miembros: <code>video</code> y <code>audio</code>, que describen los tipos de recurso solicitados. Debe especificarse uno o ambos. Si el navegador no puede encontrar todas las pistas de recursos con los tipos especificados que reúnan las restricciones dadas, entonces el promise retornado es rechazado con <code>NotFoundError</code>.</p> + + <p>Lo siguiente realiza la petición de tanto audio como vídeo sin requerimientos específicos:</p> + + <pre class="brush: js">{ audio: true, video: true }</pre> + + <p>Mientras que la información acerca de las cámaras y micrófonos de los usuarios se encuentran inaccesibles por razones de privacidad, una aplicación puede solicitar la cámara y las capacidades del micrófono que este requiera, usando restricciones adicionales. El siguiente código es para mosrtar una resolución de una cámara de 1280x720.</p> + + <pre class="brush: js">{ + audio: true, + video: { width: 1280, height: 720 } +}</pre> + + <p>El navegador tratará de respetar esto, pero puede devolver otras resoluciones si una coincidencia exacta no está disponible o si el usuario la reemplaza.</p> + + <p>Para <em>conseguir </em>otras resoluciones, puede utilizar las propiedaes <code>min</code>, <code>max</code>, or <code>exact</code> (también conocido como min == max). El siguiente ejemplo le muestra cómo solicitar una resolución mínima de 1280x720.</p> + + <pre class="brush: js">{ + audio: true, + video: { + width: { min: 1280 }, + height: { min: 720 } + } +}</pre> + + <p>Si no existe una cámara con una resolución mínima para trabajar, entonces la promesa devuelta será rechazada con NotFoundError, y no se le pedirá al usuario.</p> + + <p>La razón de esto es debido a que las propiedades <code>min</code>, <code>max</code>, y <code>exact </code>son inherentemente obligatorias, mientras que los valores planos y una propiedad llamada <em>ideal </em>no lo son. He aquí un ejemplo más completo:</p> + + <pre class="brush: js">{ + audio: true, + video: { + width: { min: 1024, ideal: 1280, max: 1920 }, + height: { min: 776, ideal: 720, max: 1080 } + } +}</pre> + + <p>Un valor perteneciente a la propiedad <code>ideal, </code>cuando es usada, tiene gravedad, lo que significa que el navegador tratará de encontrar la configuración (una cámara, si tienes más de una), con la distancia de aptitud más pequeña (<a href="http://w3c.github.io/mediacapture-main/#methods-5">fitness distance</a>) de los valores ideales dados.</p> + + <p>Los valores planos son inherentemente ideales, lo que significa que de los ejemplos mostrados anteriormente, podrían haberse escrito de la siguiente manera:</p> + + <pre class="brush: js">{ + audio: true, + video: { + width: { ideal: 1280 }, + height: { ideal: 720 } + } +}</pre> + + <p>No todas las restricciones son números. Por ejemplo, en dispositivos móviles, los siguientes preferirán la cámara frontal (si está disponible) sobre la posterior:</p> + + <pre class="brush: js">{ audio: true, video: { facingMode: "user" } }</pre> + + <p>Para <em>solicitar </em>la cámara frontal, use:</p> + + <pre class="brush: js">{ audio: true, video: { facingMode: { exact: "environment" } } }</pre> + </dd> +</dl> + +<h3 id="Valor_de_retorno">Valor de retorno</h3> + +<p>Un {{jsxref("Promise")}} que resuelve a un objeto {{domxref("MediaStream")}}.</p> + +<h3 id="Errores">Errores</h3> + +<p>Los rechazos de la promesa devuelta se realizan con un objeto {{domxref ("MediaStreamError")}} que está modelado en {{domxref ("DOMException")}}. Los errores más relevantes son:</p> + +<dl> + <dt><code>SecurityError</code></dt> + <dd>Permiso para usar un dispositivo fue denegado por el usuario o por el sistema.</dd> + <dt><code>NotFoundError</code></dt> + <dd>No se encontraron pistas multimedia del tipo especificado que satisfagan las restricciones especificadas.</dd> +</dl> + +<h2 id="Ejemplos"><strong>Ejemplos</strong></h2> + +<h3 id="Usando_la_Promesa_(Promise)">Usando la Promesa (Promise)</h3> + +<p>Este ejemplo asigna el objeto {{domxref("MediaStream")}} al elemento apropiado.</p> + +<pre>var p = navigator.mediaDevices.getUserMedia({ audio: true, video: true }); + +p.then(function(mediaStream) { + var video = document.querySelector('video'); + video.src = window.URL.createObjectURL(mediaStream); + video.onloadedmetadata = function(e) { + // Do something with the video here. + }; +}); + +p.catch(function(err) { console.log(err.name); }); // always check for errors at the end.</pre> + +<h3 id="Ancho_y_alto">Ancho y alto</h3> + +<p>He aquí un ejemplo del uso de <code>mediaDevices.getUserMedia(), </code>incluyendo un polyfill para hacer frente a los navegadores más antiguos.</p> + +<pre class="brush: js">var promisifiedOldGUM = function(constraints, successCallback, errorCallback) { + + // First get ahold of getUserMedia, if present + var getUserMedia = (navigator.getUserMedia || + navigator.webkitGetUserMedia || + navigator.mozGetUserMedia); + + // Some browsers just don't implement it - return a rejected promise with an error + // to keep a consistent interface + if(!getUserMedia) { + return Promise.reject(new Error('getUserMedia is not implemented in this browser')); + } + + // Otherwise, wrap the call to the old navigator.getUserMedia with a Promise + return new Promise(function(successCallback, errorCallback) { + getUserMedia.call(navigator, constraints, successCallback, errorCallback); + }); + +} + +// Older browsers might not implement mediaDevices at all, so we set an empty object first +if(navigator.mediaDevices === undefined) { + navigator.mediaDevices = {}; +} + +// Some browsers partially implement mediaDevices. We can't just assign an object +// with getUserMedia as it would overwrite existing properties. +// Here, we will just add the getUserMedia property if it's missing. +if(navigator.mediaDevices.getUserMedia === undefined) { + navigator.mediaDevices.getUserMedia = promisifiedOldGUM; +} + + +// Prefer camera resolution nearest to 1280x720. +var constraints = { audio: true, video: { width: 1280, height: 720 } }; + +navigator.mediaDevices.getUserMedia(constraints) +.then(function(stream) { + var video = document.querySelector('video'); + video.src = window.URL.createObjectURL(stream); + video.onloadedmetadata = function(e) { + video.play(); + }; +}) +.catch(function(err) { + console.log(err.name + ": " + err.message); +}); +</pre> + +<h3 id="Cuadros_por_segundo">Cuadros por segundo</h3> + +<p>Pocos frame-rates ó cuadros por segundo pueden ser deseables en algunos casos, como transmisiones WebRTC con restricciones de ancho de banda.</p> + +<pre class="brush: js">var constraints = { video: { frameRate: { ideal: 10, max: 15 } } }; +</pre> + +<h3 id="Camara_frontal_y_camara_trasera">Camara frontal y camara trasera</h3> + +<p>En telefonos moviles.</p> + +<pre class="brush: js">var front = false; +document.getElementById('flip-button').onclick = function() { front = !front; }; + +var constraints = { video: { facingMode: (front? "user" : "environment") } }; +</pre> + +<h2 id="Permisos">Permisos</h2> + +<p>Para usar <code>getUserMedia()</code> en una app instalable (por ejemplo, una <a href="/en-US/Apps/Build/Building_apps_for_Firefox_OS/Firefox_OS_app_beginners_tutorial">Firefox OS app</a>), necesitas especificar uno o ambos de los siguientes campos dentro de tu archivo manifest:</p> + +<pre class="brush: js">"permissions": { + "audio-capture": { + "description": "Required to capture audio using getUserMedia()" + }, + "video-capture": { + "description": "Required to capture video using getUserMedia()" + } +}</pre> + +<p>Ver <a href="/en-US/Apps/Developing/App_permissions#audio-capture">permission: audio-capture</a> y <a href="/en-US/Apps/Developing/App_permissions#video-capture">permission: video-capture</a> para más información.</p> + +<h2 id="Especificaciones">Especificaciones</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 Capture', '#dom-mediadevices-getusermedia', 'MediaDevices.getUserMedia()')}}</td> + <td>{{Spec2('Media Capture')}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</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>Stream API</td> + <td>{{CompatVersionUnknown}}<sup>[1][3]</sup><br> + 47</td> + <td>36<sup>[2]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}<sup>[1]</sup></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>Android Webview</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android </th> + </tr> + <tr> + <td>Stream API</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>36<sup>[2]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Viejas versiones de Chrome y Opera implementan <code>navigator.webkitGetUserMedia</code>, la versión prefijada {{domxref("navigator.getUserMedia")}} del metodo.</p> + +<p>En Chrome, esta promise-based interfaz esta unicamente disponible mediante el <a href="https://github.com/webrtc/adapter">adapter.js</a> polyfill, o usando la bandera <a>chrome://flags/#enable-experimental-web-platform-features</a>.</p> + +<p>Chrome usa una sintaxis de restricciones desactualizada, pero la sintaxis descrita aquí esta disponible mediante el <a href="https://github.com/webrtc/adapter">adapter.js</a> polyfill.</p> + +<p>[2] Viejas versiones de Firefox implementan <code>navigator.mozGetUserMedia</code>, la versión prefijada {{domxref("navigator.getUserMedia")}} del método.</p> + +<p>Esta promise-based interfaz y la sintaxis de restricciones descrita aquí esta disponible en Firefox 38. Versiones anteriores (32-37) usaban una sitaxis de restriciones desactualizada, pero la sintaxis descrita aquí, tanto como la promise-based interfaz, esta disponible mediante <a href="https://github.com/webrtc/adapter">adapter.js</a> polyfill.</p> + +<p>Opera usa una sintaxis de restricciones desactualizada, pero la sintaxis descrita aquí esta disponible mediante <a href="https://github.com/webrtc/adapter">adapter.js</a> polyfill.</p> + +<p>[3] Chrome lanza un error si la página que sirve el script es cargada desde un origen inseguro (i.e. HTTP).</p> + +<h2 id="Ver_También">Ver También</h2> + +<ul> + <li>The older <a href="/en-US/docs/Web/API/Navigator/getUserMedia">navigator.getUserMedia</a> legacy API.</li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/enumerateDevices">navigator.enumerateDevices</a> - learn the types and number of devices the user has available.</li> + <li><a href="/en-US/docs/WebRTC">WebRTC</a> - the introductory page to the API</li> + <li><a href="/en-US/docs/WebRTC/MediaStream_API">MediaStream API</a> - the API for the media stream objects</li> + <li><a href="/en-US/docs/WebRTC/taking_webcam_photos">Taking webcam photos</a> - a tutorial on using <code>getUserMedia() for taking photos rather than video.</code></li> +</ul> diff --git a/files/es/web/api/mediadevices/index.html b/files/es/web/api/mediadevices/index.html new file mode 100644 index 0000000000..9c02a60cea --- /dev/null +++ b/files/es/web/api/mediadevices/index.html @@ -0,0 +1,172 @@ +--- +title: MediaDevices +slug: Web/API/MediaDevices +tags: + - API + - Experimental + - Interface + - Media + - MediaDevices + - NeedsTranslation + - TopicStub +translation_of: Web/API/MediaDevices +--- +<div>{{APIRef("WebRTC")}}{{SeeCompatTable}}</div> + +<p><span class="seoSummary">The <strong><code>MediaDevices</code></strong> interface provides access to connected media input devices like cameras and microphones, as well as screensharing.</span></p> + +<h2 id="Properties">Properties</h2> + +<p><em>None.</em></p> + +<h2 id="Methods">Methods</h2> + +<dl> + <dt>{{ domxref("MediaDevices.getUserMedia()") }}</dt> + <dd>With the user's permission through a prompt, turns on a camera or screensharing and/or a microphone on the system and provides a {{domxref("MediaStream")}} containing a video track and/or an audio track with the input.</dd> + <dt>{{ domxref("MediaDevices.enumerateDevices()") }}</dt> + <dd>Obtains an array of information about the media input and output devices available on the system.</dd> +</dl> + +<h2 id="Example">Example</h2> + +<pre class="brush:js">'use strict'; + +// Put variables in global scope to make them available to the browser console. +var video = document.querySelector('video'); +var constraints = window.constraints = { + audio: false, + video: true +}; +var errorElement = document.querySelector('#errorMsg'); + +navigator.mediaDevices.getUserMedia(constraints) +.then(function(stream) { + var videoTracks = stream.getVideoTracks(); + console.log('Got stream with constraints:', constraints); + console.log('Using video device: ' + videoTracks[0].label); + stream.onended = function() { + console.log('Stream ended'); + }; + window.stream = stream; // make variable available to browser console + video.srcObject = stream; +}) +.catch(function(error) { + if (error.name === 'ConstraintNotSatisfiedError') { + errorMsg('The resolution ' + constraints.video.width.exact + 'x' + + constraints.video.width.exact + ' px is not supported by your device.'); + } else if (error.name === 'PermissionDeniedError') { + errorMsg('Permissions have not been granted to use your camera and ' + + 'microphone, you need to allow the page access to your devices in ' + + 'order for the demo to work.'); + } + errorMsg('getUserMedia error: ' + error.name, error); +}); + +function errorMsg(msg, error) { + errorElement.innerHTML += '<p>' + msg + '</p>'; + if (typeof error !== 'undefined') { + console.error(error); + } +}</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 Capture', '#mediadevices', 'MediaDevices')}}</td> + <td>{{Spec2('Media Capture')}}</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>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop("36.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>enumerateDevices()</code></td> + <td>{{CompatChrome(45.0)}}<sup>[1]</sup></td> + <td>{{CompatUnknown}}</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>Android Webview</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoMobile("36.0")}}</td> + <td>2.2</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>enumerateDevices()</code></td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Behind a flag.</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/WebRTC" title="/en-US/docs/WebRTC">WebRTC</a> - the introductory page to the API</li> + <li><a href="/en-US/docs/WebRTC/navigator.getUserMedia" title="/en-US/docs/WebRTC/navigator.getUserMedia">Navigator.getUserMedia()</a></li> +</ul> diff --git a/files/es/web/api/mediaquerylist/addlistener/index.html b/files/es/web/api/mediaquerylist/addlistener/index.html new file mode 100644 index 0000000000..e52d1b8b33 --- /dev/null +++ b/files/es/web/api/mediaquerylist/addlistener/index.html @@ -0,0 +1,148 @@ +--- +title: MediaQueryList.addListener() +slug: Web/API/MediaQueryList/addListener +translation_of: Web/API/MediaQueryList/addListener +--- +<div>{{APIRef("CSSOM View")}}</div> + +<div>El método <code><strong>addListener()</strong></code> de la interfaz {{domxref ("MediaQueryList")}} añade un escucha al <code>MediaQueryListener</code> que ejecutará una función de devolución de llamada personalizada en respuesta al cambio de estado de consulta de medios.<br> + </div> + +<div> +<p>Esto es básicamente un alias para {{domxref("EventTarget.addEventListener()")}}, para propósitos de compatibilidad con versiones anteriores: en los navegadores antiguos se puede usar <code>addEventListener.</code></p> +</div> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><em>MediaQueryList.addListener(func)</em></pre> + +<h3 id="Parametros">Parametros</h3> + +<dl> + <dt>func</dt> + <dd>A function or function reference representing the callback function you want to run when the media query status changes. In the original implementation, the callback was a non-standard {{domxref("MediaQueryListListener")}} object. In the new implementation the standard event mechanism is used, the callback is a standard function, and the event object is a {{domxref("MediaQueryListEvent")}}, which inherits from {{domxref("Event")}}.</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>Void.</p> + +<h2 id="Examples">Examples</h2> + +<pre class="brush: js">var mql = window.matchMedia('(max-width: 600px)'); + +function screenTest(e) { + if (e.matches) { + /* the viewport is 600 pixels wide or less */ + para.textContent = 'This is a narrow screen — less than 600px wide.'; + document.body.style.backgroundColor = 'red'; + } else { + /* the viewport is more than than 600 pixels wide */ + para.textContent = 'This is a wide screen — more than 600px wide.'; + document.body.style.backgroundColor = 'blue'; + } +} + +mql.addListener(screenTest);</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th>Specification</th> + <th>Status</th> + <th>Comment</th> + </tr> + <tr> + <td>{{SpecName("CSSOM View", "#dom-mediaquerylist-addlistener", "addListener")}}</td> + <td>{{Spec2("CSSOM View")}}</td> + <td>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>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>9</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("6.0")}}</td> + <td>10</td> + <td>12.1</td> + <td>5</td> + </tr> + <tr> + <td>New version spec update</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("55")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>New version spec update</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("55")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/CSS/Media_queries">Media queries</a></li> + <li><a href="/en-US/docs/CSS/Using_media_queries_from_code">Using media queries from code</a></li> + <li>{{domxref("window.matchMedia()")}}</li> + <li>{{domxref("MediaQueryList")}}</li> + <li>{{domxref("MediaQueryListEvent")}}</li> +</ul> diff --git a/files/es/web/api/mediaquerylist/index.html b/files/es/web/api/mediaquerylist/index.html new file mode 100644 index 0000000000..a13b29cdbb --- /dev/null +++ b/files/es/web/api/mediaquerylist/index.html @@ -0,0 +1,178 @@ +--- +title: MediaQueryList +slug: Web/API/MediaQueryList +tags: + - API + - CSSOM Vista + - CompatibilidadDeNavegadores + - Interface + - MediaQueryList + - Refetencia +translation_of: Web/API/MediaQueryList +--- +<div>{{APIRef("CSSOM View")}}{{SeeCompatTable}}</div> + +<p>Un objeto <code>MediaQueryList</code> almacena información en un <a href="/en-US/docs/Web/CSS/Media_Queries">media query</a> aplicada a un documento y se encarga de enviar notificaciones a los oyentes cuando cambia el estado de consulta de medios (es decir, cuando la prueba de consulta de medios comienza o deja de evaluarse a <code>true</code>).</p> + +<p>Esto hace posible observar un documento para detectar cuando sus consultas de medios cambian, en lugar de sondear los valores periódicamente y le permite programar cambios en un documento basado en el estado de consulta de medios.</p> + +<h2 id="Propiedades">Propiedades</h2> + +<p>La nueva versión de la interfaz de <em><code>MediaQueryList</code> </em> hereda las propiedades de su interfaz principal, <em>{{domxref("EventTarget")}}.</em></p> + +<dl> + <dt>{{domxref("MediaQueryList.matches")}} {{readonlyInline}}</dt> + <dd> Un {{domxref("Boolean")}} que devuelve <code>true</code> si el<br> + {{domxref("document")}} actualmente coincide con la lista de consultas de medios, o <code>false</code> si no.</dd> + <dt>{{domxref("MediaQueryList.media")}} {{readonlyInline}}</dt> + <dd> Un {{domxref("DOMString")}} representa una consulta de medios serializada.</dd> +</dl> + +<h3 id="Controladores_de_eventos">Controladores de eventos</h3> + +<dl> + <dt>{{domxref("MediaQueryList.onchange")}}</dt> + <dd>Una propiedad de controlador de eventos que representa una función que se invoca cuando se desencadena el evento {{event("change")}}, es decir, cuando cambia el estado del soporte de consulta de medios. El objeto de evento es una instancia {{domxref("MediaQueryListEvent")}}, que se reconoce como una instancia de <code>MediaListQuery</code> en navegadores antiguos, para propósitos de compatibilidad con versiones anteriores.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<p><em>La nueva versión de la interfaz de <code>MediaQueryList</code> hereda métodos de su interfaz principal, {{domxref("EventTarget")}}.</em></p> + +<dl> + <dt>{{domxref("MediaQueryList.addListener()")}}</dt> + <dd> Agrega un escucha al <code>MediaQueryListener</code> que ejecutará una función de devolución de llamada personalizada en respuesta al cambio de estado de consulta de medios. Esto es básicamente un alias para {{domxref("EventTarget.addEventListener()")}}, para propósitos de compatibilidad con versiones anteriores. </dd> + <dt>{{domxref("MediaQueryList.removeListener()")}}</dt> + <dd> Elimina un escucha de <code>MediaQueryListener</code>. Esto es básicamente un alias para {{domxref ("EventTarget.removeEventListener ()")}}, para propósitos de compatibilidad con versiones anteriores.</dd> +</dl> + +<dl> +</dl> + +<h2 id="Ejemplos">Ejemplos</h2> + +<p>Este ejemplo sencillo crea una <code>MediaQueryList</code> y, a continuación, establece un detector para detectar cuándo cambia el estado de la consulta de medios, ejecutando una función personalizada cuando cambia la apariencia de la página.</p> + +<pre class="brush: js">var para = document.querySelector('p'); + +var mql = window.matchMedia('(max-width: 600px)'); + +function screenTest(e) { + if (e.matches) { + /* el ventana tiene 600 píxeles de ancho o menos*/ + para.textContent = 'This is a narrow screen — less than 600px wide.'; + document.body.style.backgroundColor = 'red'; + } else { + /* la ventana tiene más de 600 píxeles de ancho */ + para.textContent = 'This is a wide screen — more than 600px wide.'; + document.body.style.backgroundColor = 'blue'; + } +} + +mql.addListener(screenTest);</pre> + +<div class="note"> +<p><strong>Nota</strong>: Puedes encontrar este ejemplo en GitHub (ver el <a href="https://github.com/mdn/dom-examples/blob/master/mediaquerylist/index.html">codigo fuente</a>, y también verlo en <a href="https://mdn.github.io/dom-examples/mediaquerylist/index.html">ejecución</a>).</p> +</div> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th>Especificaciones</th> + <th>Estado</th> + <th>Comentario</th> + </tr> + <tr> + <td>{{SpecName("CSSOM View", "#the-mediaquerylist-interface", "MediaQueryList")}}</td> + <td>{{Spec2("CSSOM View")}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_del_navegador">Compatibilidad del navegador</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>9</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("6.0")}}</td> + <td>10</td> + <td>12.1</td> + <td>5</td> + </tr> + <tr> + <td>New version spec update</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("55")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>New version spec update</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("55")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/CSS/Media_queries">Media queries</a></li> + <li><a href="/en-US/docs/CSS/Using_media_queries_from_code">Uso de media queries desde el código</a></li> + <li>{{domxref("window.matchMedia()")}}</li> + <li>{{domxref("MediaQueryListListener")}}</li> + <li>{{domxref("MediaQueryListEvent")}}</li> +</ul> diff --git a/files/es/web/api/mediaquerylist/matches/index.html b/files/es/web/api/mediaquerylist/matches/index.html new file mode 100644 index 0000000000..c31f6fa707 --- /dev/null +++ b/files/es/web/api/mediaquerylist/matches/index.html @@ -0,0 +1,108 @@ +--- +title: MediaQueryList.matches +slug: Web/API/MediaQueryList/matches +translation_of: Web/API/MediaQueryList/matches +--- +<div>{{APIRef("CSSOM View")}}</div> + +<p>La propiedad <strong><code>matches</code> </strong>de sólo lectura de la interfaz {{domxref ("MediaQueryList")}} es {{domxref ("Boolean")}} que devuelve <code>true</code> si el {{domxref ("document")}} coincide actualmente con el medio lista de consultas, o <code>false</code> si no.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var <em>matches</em> = <em>MediaQueryList.matches;</em></pre> + +<h3 id="Value">Value</h3> + +<p>A {{domxref("Boolean")}}; returns <code>true</code> if the {{domxref("document")}} currently matches the media query list, <code>false</code> if not.</p> + +<h2 id="Examples">Examples</h2> + +<pre class="brush: js">var mql = window.matchMedia('(max-width: 600px)'); + +if(mql.matches) { + // media query test returning true +} +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th>Specification</th> + <th>Status</th> + <th>Comment</th> + </tr> + <tr> + <td>{{SpecName("CSSOM View", "#dom-mediaquerylist-matches", "matches")}}</td> + <td>{{Spec2("CSSOM View")}}</td> + <td>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>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>9</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("6.0")}}</td> + <td>10</td> + <td>12.1</td> + <td>5</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/CSS/Media_queries">Media queries</a></li> + <li><a href="/en-US/docs/CSS/Using_media_queries_from_code">Using media queries from code</a></li> + <li>{{domxref("window.matchMedia()")}}</li> + <li>{{domxref("MediaQueryList")}}</li> + <li>{{domxref("MediaQueryListEvent")}}</li> +</ul> diff --git a/files/es/web/api/mediaquerylist/removelistener/index.html b/files/es/web/api/mediaquerylist/removelistener/index.html new file mode 100644 index 0000000000..2689dde854 --- /dev/null +++ b/files/es/web/api/mediaquerylist/removelistener/index.html @@ -0,0 +1,149 @@ +--- +title: MediaQueryList.removeListener() +slug: Web/API/MediaQueryList/removeListener +translation_of: Web/API/MediaQueryList/removeListener +--- +<div>{{APIRef("CSSOM View")}}</div> + +<p>El método <code><strong>removeListener()</strong></code> de la interfaz {{domxref ("MediaQueryList")}} elimina un escucha de <code>MediaQueryListener</code>.</p> + +<p>Esto es básicamente un alias para {{domxref("EventTarget.removeEventListener()")}}, para propósitos de compatibilidad con versiones anteriores: en los navegadores antiguos puede usar <code>removeEventListener()</code>.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><em>MediaQueryList.removeListener(func)</em></pre> + +<h3 id="Parametros">Parametros</h3> + +<dl> + <dt>func</dt> + <dd>Una función o referencia de función que representa la función de devolución de llamada que desea eliminar. En la implementación original, la devolución de llamada era un objeto {{domxref ("MediaQueryListListener")}} no estándar. En la nueva implementación se utiliza el mecanismo de eventos estándar y la devolución de llamada es una función estándar.</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>Void.</p> + +<h2 id="Ejemplos">Ejemplos</h2> + +<pre class="brush: js">var mql = window.matchMedia('(max-width: 600px)'); + +function screenTest(e) { + if (e.matches) { + /* the viewport is 600 pixels wide or less */ + para.textContent = 'This is a narrow screen — less than 600px wide.'; + document.body.style.backgroundColor = 'red'; + } else { + /* the viewport is more than than 600 pixels wide */ + para.textContent = 'This is a wide screen — more than 600px wide.'; + document.body.style.backgroundColor = 'blue'; + } +} + +mql.addListener(screenTest); + +// Later on, when it is no longer needed +mql.removeListener(screenTest); +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th>Especificaciones</th> + <th>Estado</th> + <th>Comentario</th> + </tr> + <tr> + <td>{{SpecName("CSSOM View", "#dom-mediaquerylist-removelistener", "removeListener")}}</td> + <td>{{Spec2("CSSOM View")}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_del_navegador">Compatibilidad del navegador</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>9</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("6.0")}}</td> + <td>10</td> + <td>12.1</td> + <td>5</td> + </tr> + <tr> + <td>New version spec update</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("55")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>New version spec update</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("55")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/CSS/Media_queries">Media queries</a></li> + <li><a href="/en-US/docs/CSS/Using_media_queries_from_code">Using media queries from code</a></li> + <li>{{domxref("window.matchMedia()")}}</li> + <li>{{domxref("MediaQueryList")}}</li> + <li>{{domxref("MediaQueryListEvent")}}</li> +</ul> diff --git a/files/es/web/api/mediasource/index.html b/files/es/web/api/mediasource/index.html new file mode 100644 index 0000000000..2f5ff914c9 --- /dev/null +++ b/files/es/web/api/mediasource/index.html @@ -0,0 +1,182 @@ +--- +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/mediastreamaudiosourcenode/index.html b/files/es/web/api/mediastreamaudiosourcenode/index.html new file mode 100644 index 0000000000..7e620ac305 --- /dev/null +++ b/files/es/web/api/mediastreamaudiosourcenode/index.html @@ -0,0 +1,129 @@ +--- +title: MediaStreamAudioSourceNode +slug: Web/API/MediaStreamAudioSourceNode +tags: + - API + - MediaStreamAudioSourceNode + - Web Audio API +translation_of: Web/API/MediaStreamAudioSourceNode +--- +<p>{{APIRef("Web Audio API")}}</p> + +<div> +<p>La interfaz <code>MediaStreamAudioSourceNode</code> representa una fuente de audio compuesta por un <a href="/en-US/docs/WebRTC" title="/en-US/docs/WebRTC">WebRTC</a> {{domxref("MediaStream")}} (tal como una cámara web o un micrófono.) Es un {{domxref("AudioNode")}} que actúa como una fuente de audio.</p> +</div> + +<p>El <code>MediaElementSourceNode</code> no tiene entradas y una y sólo una salida, y es creado usando el método {{domxref("AudioContext.createMediaStreamSource")}}.</p> + +<p>La cantidad de canales en la salida es igual al número de canales en {{domxref("AudioMediaStreamTrack")}}. Si no existe un flujo de media válido, entonces el número de canales de salida será un canal silencioso.</p> + +<div class="blockIndicator note"> +<p><strong>Nota:</strong> <code>MediaStreamAudioSourceNode</code> selecciona la pista de audio automáticamente, y puede que no siempre sea predecible. Usted debería considerar seriamente usar el {{domxref("MediaStreamTrackAudioSourceNode")}} en su lugar, que se crea especificando la pista exacta que desea utilizar.</p> +</div> + +<table class="properties"> + <tbody> + <tr> + <th scope="row">Número de entradas</th> + <td><code>0</code></td> + </tr> + <tr> + <th scope="row">Número de salidas</th> + <td><code>1</code></td> + </tr> + <tr> + <th scope="row">Cantidad de canales</th> + <td>definido por {{domxref("AudioMediaStreamTrack")}} pasado al método {{domxref("AudioContext.createMediaStreamSource")}} que lo creó.</td> + </tr> + </tbody> +</table> + +<h2 id="Propiedades">Propiedades</h2> + +<p><em>Heredadas de su padre, </em><em>{{domxref("AudioNode")}}</em>.</p> + +<h2 id="Métodos">Métodos</h2> + +<p><em>Heredadas de su padre, {{domxref("AudioNode")}}</em>.</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>{{page("/en-US/docs/Web/API/AudioContext.createMediaStreamSource","Example")}}</p> + +<h2 id="Especificación">Especificación</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('Web Audio API', '#the-mediastreamaudiosourcenode-interface', 'MediaStreamAudioSourceNode')}}</td> + <td>{{Spec2('Web Audio API')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Caracterísitica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>14 {{property_prefix("webkit")}}</td> + <td>{{CompatGeckoDesktop("25")}}</td> + <td>{{CompatNo}}</td> + <td>15 {{property_prefix("webkit")}}<br> + 22 (unprefixed)</td> + <td>6 {{property_prefix("webkit")}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Caracterísitica</th> + <th>Android</th> + <th>Chrome</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatNo}}</td> + <td>28 {{property_prefix("webkit")}}</td> + <td>{{CompatGeckoMobile("25")}}</td> + <td>1.2</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>6 {{property_prefix("webkit")}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_también">Ver también</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/mediastreamtrack/index.html b/files/es/web/api/mediastreamtrack/index.html new file mode 100644 index 0000000000..3bc2159332 --- /dev/null +++ b/files/es/web/api/mediastreamtrack/index.html @@ -0,0 +1,181 @@ +--- +title: MediaStreamTrack +slug: Web/API/MediaStreamTrack +translation_of: Web/API/MediaStreamTrack +--- +<div>{{APIRef("WebRTC")}}</div> + +<h2 id="Sumario">Sumario</h2> + +<p>La interfaz <strong><code>MediaStream</code></strong><strong> </strong> representa un flujo de contenido de los medios. Un flujo consiste en gran cantidad de <em>tracks</em>, como pistas de audio o video.</p> + +<h2 id="Propiedades">Propiedades</h2> + +<dl> + <dt>{{domxref("MediaStreamTrack.enabled")}}</dt> + <dd>Es un valor Booleano con un valor de <code>true</code> <span class="short_text" id="result_box" lang="es"><span class="hps">si la pista</span> <span class="hps">está habilitada</span></span>, que se permite para renderizar el fujo fuente del medio; <span class="short_text" id="result_box" lang="es"><span class="hps">o </span></span><code>false</code><span class="short_text" lang="es"> <span class="hps">si está desactivado, ue no </span></span><span id="result_box" lang="es"><span class="hps">está rederizando el flujo de la fuente de medios que el silencio y la oscuridad.</span></span> <span id="result_box" lang="es"><span class="hps">Si la pista</span> <span class="hps">se ha desconectado</span><span>,</span> <span class="hps">este valor puede ser</span> <span class="hps">cambiado</span><span>, pero no tiene</span> <span class="hps">más</span> <span class="hps">efecto</span><span>.</span></span></dd> + <dt>{{domxref("MediaStreamTrack.id")}} {{readonlyInline}}</dt> + <dd>Retorna un {{domxref("DOMString")}}<span class="short_text" id="result_box" lang="es"><span class="hps"> que contiene</span> <span class="hps">un identificador único</span></span> (GUID) para la pista; que es generado por le navegador.</dd> + <dt>{{domxref("MediaStreamTrack.kind")}} {{readonlyInline}}</dt> + <dd>Retorna un {{domxref("DOMString")}} se establece en <code>"audio"</code> si la pista es un audio y para <code>"video"</code>, si es una pista de video. Este no cambia si la pista se disociada de su fuente.</dd> + <dt>{{domxref("MediaStreamTrack.label")}} {{readonlyInline}}</dt> + <dd>Retorna un {{domxref("DOMString")}} que contiene una etiqueta agente-asignado por el usuario que identifica la fuente de la pista, como en <code>"internal microphone"</code>. <span id="result_box" lang="es"><span class="hps">La cadena puede</span> <span class="hps">dejarse vacío</span> <span class="hps">y</span> <span class="hps">está vacía</span><span>, siempre y cuando</span> <span class="hps">ninguna fuente</span> <span class="hps">haya sido conectada.</span></span> Cuando la pista está disociada de la fuente, la etiqueta no cambia.</dd> + <dt>{{domxref("MediaStreamTrack.muted")}} {{readonlyInline}}</dt> + <dd>Retorna un valor booleano con un valor de <code>true</code> si la pista esta silenciada, de lo contrario <code>false</code>.</dd> + <dt>{{domxref("MediaStreamTrack.readonly")}} {{readonlyInline}}</dt> + <dd>Retona un valor Booleano con un valor de <code>true</code> si la pista es de solo lectura ( una fuente de archivo de vídeo o una cámara que los ajustes no puedan ser modificados),<code> </code>de lo contrario<code> false</code>.</dd> + <dt>{{domxref("MediaStreamTrack.readyState")}} {{readonlyInline}}</dt> + <dd>Retorna un valor enumerado dando el estado de la pista. Este toma uno de los siguientes valores: + <ul> + <li><code>"live"</code> el cual indica que una entrada es conectada y hace de esta el mejor esfuerzo en proveer datos en tiempo real. En este caso, la salida de datos puede ser cambiada a on u off usando el atributo <code>MediaStreamTrack.enabled</code>.</li> + <li><code>"ended"</code> este indica que la entrada no esta obteniendo algun dato mas y negará proporcionar nuevos datos.</li> + </ul> + </dd> + <dt>{{domxref("MediaStreamTrack.remote")}} {{readonlyInline}}</dt> + <dd>retorna un booleano con un valor de verdadero si la pista es originada por {{domxref("RTCPeerConnection")}}, falso a cualquier otro.</dd> +</dl> + +<h3 id="Disparador_de_eventos">Disparador de eventos</h3> + +<dl> + <dt>{{domxref("MediaStreamTrack.onstarted")}}</dt> + <dd>Es un contenedor {{domxref("EventHandler")}} de la acción a realizar cuando el evento {{event("started")}} es disparado sobre el objeto, que es cuando un objeto {{domxref("MediaStreamTrack")}} es añadido.</dd> + <dt>{{domxref("MediaStreamTrack.onmute")}}</dt> + <dd>Es un contenedor {{domxref("EventHandler")}} de la acción ha realizar cuando un evento {{event("mute")}} es disparado sobre el objeto, que es cuando la transmición es terminada.</dd> + <dt>{{domxref("MediaStreamTrack.onunmute")}}</dt> + <dd>Es un contenedor {{domxref("EventHandler")}} de la acción ha realizar cuando un evento {{event("unmute")}} es disparado sobre el objeto, que es cuando un objeto {{domxref("MediaStreamTrack")}} es removido por este.</dd> + <dt>{{domxref("MediaStreamTrack.onoverconstrained")}}</dt> + <dd>Es un contenedor {{domxref("EventHandler")}} de la acción ha realizar cuando un objeto {{event("overconstrained")}} es disparado sobre el objeto, que es cuando un objeto {{domxref("MediaStreamTrack")}} es removido por este.</dd> + <dt>{{domxref("MediaStreamTrack.oneended")}}</dt> + <dd>Es un contenedor {{domxref("EventHandler")}} de la acción ha realizar cuando un evento {{event("ended_(MediaStream)", "ended")}} es disparado sobre el objeto, que es cuando un objeto {{domxref("MediaStreamTrack")}} es removido por este.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<dl> + <dt>{{domxref("MediaStreamTrack.getConstraints()")}}</dt> + <dd> </dd> + <dt>{{domxref("MediaStreamTrack.applyConstraints()")}}</dt> + <dd> </dd> + <dt>{{domxref("MediaStreamTrack.getSettings()")}}</dt> + <dd> </dd> + <dt>{{domxref("MediaStreamTrack.getCapabilities()")}}</dt> + <dd> </dd> + <dt>{{domxref("MediaStreamTrack.clone()")}}</dt> + <dd> </dd> + <dt>{{domxref("MediaStreamTrack.stop()")}}</dt> + <dd>Detiene la reproducción del origen asociado a la pista, pero el origen y la pista son desasociados. El estado de la pista es un conjunto de <code>ended</code>.</dd> +</dl> + +<h2 id="Especificaciones">Especificaciones</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 Capture', '#mediastreamtrack', 'MediaStreamTrack')}}</td> + <td>{{Spec2('Media Capture')}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_los_navegadores">Compatibilidad de los navegadores</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>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>stop()</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop(34)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>muted</code>, <code>onmuted</code>, <code>onunmuted</code>, <code>readonly</code>, <code>readyState</code>, <code>remote</code>, <code>onstarted</code>, <code>onended</code>, <code>onoverconstrained</code>, <code>appendConstraint()</code>, <code>applyConstraints()</code>, <code>constraints()</code>, <code>getConstraints()</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</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 Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td> + <table class="compat-table"> + <tbody> + <tr> + <td><code>stop()</code></td> + </tr> + </tbody> + </table> + </td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop(34)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>muted</code>, <code>onmuted</code>, <code>onunmuted</code>, <code>readonly</code>, <code>readyState</code>, <code>remote</code>, <code>onstarted</code>, <code>onended</code>, <code>onoverconstrained</code>, <code>appendConstraint()</code>, <code>applyConstraints()</code>, <code>constraints()</code>, <code>getConstraints()</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_támbien">Ver támbien</h2> + +<ul> + <li><a href="/en-US/docs/WebRTC/MediaStream_API" title="/en-US/docs/WebRTC/MediaStream_API">Using the MediaStream API</a></li> +</ul> diff --git a/files/es/web/api/messageevent/index.html b/files/es/web/api/messageevent/index.html new file mode 100644 index 0000000000..1d1e898be5 --- /dev/null +++ b/files/es/web/api/messageevent/index.html @@ -0,0 +1,195 @@ +--- +title: MessageEvent +slug: Web/API/MessageEvent +translation_of: Web/API/MessageEvent +--- +<div>{{APIRef("HTML DOM")}}</div> + +<p>La interface <code><strong>MessageEvent</strong></code> representa un mensaje recibido por un objeto de destino.</p> + +<p>Este es usado para representar mensajes en : </p> + +<ul> + <li><a href="/en-US/docs/Web/API/Server-sent_events">Eventos enviados por el servidor </a>(ver {{domxref("EventSource.onmessage")}}).</li> + <li><a href="/en-US/docs/Web/API/WebSockets_API">Web sockets</a> (ver la propiedad <code>onmessage</code> de la interface <a href="/en-US/docs/Web/API/WebSocket">WebSocket</a> ).</li> + <li>Mensajeria cruzada(ver {{domxref("Window.postMessage()")}} y {{domxref("Window.onmessage")}}).</li> + <li><a href="/en-US/docs/Web/API/Channel_Messaging_API">Mensajes de canal </a>(ver {{domxref("MessagePort.postMessage()")}} y {{domxref("MessagePort.onmessage")}}).</li> + <li>Trabajo cruzado / Mensajes de texto (vea las dos entradas anteriores, pero también {{domxref("Worker.postMessage()")}}, {{domxref("Worker.onmessage")}}, {{domxref("ServiceWorkerGlobalScope.onmessage")}}, etc.)</li> + <li><a href="/en-US/docs/Web/API/Broadcast_Channel_API">Canales de Transmisión</a>(ver{{domxref("Broadcastchannel.postMessage()")}}) y {{domxref("BroadcastChannel.onmessage")}}).</li> + <li>Canal de datos WebRTC (ver {{domxref("RTCDataChannel.onmessage")}}).</li> +</ul> + +<p>La acción desencadenada por este evento es definida en una función establecida como el controlador de eventos para el evento pertinente {{event("message")}} ( es decir : Usando un manejador de <code>onmessage</code> como se lista arriba).</p> + +<p>{{AvailableInWorkers}}</p> + +<h2 id="Constructor">Constructor</h2> + +<dl> + <dt>{{domxref("MessageEvent.MessageEvent", "MessageEvent()")}}</dt> + <dd>Crear un nuevo <code>MessageEvent</code>.</dd> +</dl> + +<h2 id="Propiedades">Propiedades</h2> + +<p><em>Esta interface tambien herada propiedadesde desde su padre {{domxref("Evento")}}.</em></p> + +<dl> + <dt>{{domxref("MessageEvent.data")}} {{readonlyInline}}</dt> + <dd>La información enviada por el emisor del mensaje.</dd> + <dt>{{domxref("MessageEvent.origin")}} {{readonlyInline}}</dt> + <dd>{{domxref("USVString")}} es una representacion del origen del emisor del mensaje. </dd> + <dt>{{domxref("MessageEvent.lastEventId")}} {{readonlyInline}}</dt> + <dd>{{domxref("DOMString")}} es una representación de una ID unico para el evento.</dd> + <dt>{{domxref("MessageEvent.source")}} {{readonlyInline}}</dt> + <dd>El <code>MessageEventSource</code> (El cual puede ser un {{domxref("WindowProxy")}}, {{domxref("MessagePort")}}, or {{domxref("ServiceWorker")}} object) es ima representación del mensaje emitido.</dd> + <dt>{{domxref("MessageEvent.ports")}} {{readonlyInline}}</dt> + <dd>Un array de objetos {{domxref("MessagePort")}} representa los puertos asociados al canal, el mensaje se esta enviado a traves de (donde sea apropiado, por ejemplo, en mensajes de canal o al enviar un mensaje a un trabajador compartido).</dd> +</dl> + +<h2 id="Metodos">Metodos</h2> + +<p><em>Esta interface tambien herada propiedadesde desde su padre, {{domxref("Evento")}}.</em></p> + +<dl> + <dt>{{domxref("MessageEvent.initMessageEvent()")}} {{deprecated_inline}}</dt> + <dd>Inicializar un vento de mensaje. <strong>No use esto mas </strong>— en vez de eso use el constructor <strong>{{domxref("MessageEvent.MessageEvent", "MessageEvent()")}} .</strong></dd> +</dl> + +<h2 id="Ejemplos">Ejemplos</h2> + +<p>En nuestro <a class="external external-icon" href="https://github.com/mdn/simple-shared-worker">Ejemplo basico de trabajador compartido</a>(<a class="external external-icon" href="http://mdn.github.io/simple-shared-worker/">Ejecutar trabajador compartdo </a>), Tenemos dos paginas HTML, cada una de las cuales usa algo de JavaScript para mejorar un calculo simple. Los diferentes scripts estan usando el mismo archivo de trabajo para mejorar el calculo — Ambos pueden accederlo, Incluso si sus paginas esta corriendo n diferentes ventanas. </p> + +<p>The following code snippet shows creation of a <code>SharedWorker</code> object using the {{domxref("SharedWorker.SharedWorker", "SharedWorker()")}} constructor. Both scripts contain this:</p> + +<pre class="brush: js">var myWorker = new SharedWorker('worker.js'); +</pre> + +<p>Both scripts then access the worker through a {{domxref("MessagePort")}} object created using the {{domxref("SharedWorker.port")}} property. If the onmessage event is attached using addEventListener, the port is manually started using its <code>start()</code> method:</p> + +<pre class="brush: js">myWorker.port.start();</pre> + +<p>When the port is started, both scripts post messages to the worker and handle messages sent from it using <code>port.postMessage()</code> and <code>port.onmessage</code>, respectively:</p> + +<pre class="brush: js">first.onchange = function() { + myWorker.port.postMessage([first.value,second.value]); + console.log('Message posted to worker'); +} + +second.onchange = function() { + myWorker.port.postMessage([first.value,second.value]); + console.log('Message posted to worker'); +} + +myWorker.port.onmessage = function(e) { + result1.textContent = e.data; + console.log('Message received from worker'); +}</pre> + +<p>Inside the worker we use the {{domxref("SharedWorkerGlobalScope.onconnect")}} handler to connect to the same port discussed above. The ports associated with that worker are accessible in the {{event("connect")}} event's <code>ports</code> property — we then use {{domxref("MessagePort")}} <code>start()</code> method to start the port, and the <code>onmessage</code> handler to deal with messages sent from the main threads.</p> + +<pre class="brush: js">onconnect = function(e) { + var port = e.ports[0]; + + port.addEventListener('message', function(e) { + var workerResult = 'Result: ' + (e.data[0] * e.data[1]); + port.postMessage(workerResult); + }); + + port.start(); // Required when using addEventListener. Otherwise called implicitly by onmessage setter. +}</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', "#messageevent", "MessageEvent")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_entre_navegadores">Compatibilidad entre navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Caracteristica</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>1</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("2.0")}}</td> + <td>9</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatSafari('10.0+')}}</td> + </tr> + <tr> + <td><code>origin</code> as {{domxref("USVString")}} and <code>source</code> as <code>MessageEventSource</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("55.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Edge</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>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>3.0+</td> + </tr> + <tr> + <td><code>origin</code> as {{domxref("USVString")}} and <code>source</code> as <code>MessageEventSource</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("55.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_tambien">Ver tambien</h2> + +<ul> + <li>{{domxref("ExtendableMessageEvent")}} — similar to this interface but used in interfaces that needs to give more flexibility to authors.</li> +</ul> diff --git a/files/es/web/api/mimetype/index.html b/files/es/web/api/mimetype/index.html new file mode 100644 index 0000000000..0594c0c5eb --- /dev/null +++ b/files/es/web/api/mimetype/index.html @@ -0,0 +1,97 @@ +--- +title: MimeType +slug: Web/API/MimeType +tags: + - API + - Interface + - Plugins + - Referencia +translation_of: Web/API/MimeType +--- +<p>{{SeeCompatTable}}{{APIRef("HTML DOM")}}</p> + +<p>La interfaz <strong><code>MimeType</code></strong> provee información acerca de un tipo MIME asociado con un plugin en particular. {{domxref("NavigatorPlugins.mimeTypes")}} retorna un arreglo de estos objetos.</p> + +<h2 id="Propiedades">Propiedades</h2> + +<dl> + <dt>{{domxref("MimeType.type")}}</dt> + <dd>Retorna el tipo MIME del plugin asociado.</dd> + <dt>{{domxref("MimeType.description")}}</dt> + <dd>Retorna la descripción del plugin asociado o un string vacío en caso de no haberla.</dd> + <dt>{{domxref("MimeType.suffixes")}}</dt> + <dd>Un string que contiene las extensiones de archivo válidas para los datos mostrados por el plugin, o un string vacío si una extensión de archivo no es válida para el módulo en particular. Por ejemplo, un módulo de decriptación de contenido del navegador podría aparecer en la lista de plugins, pero soportar más extensiones de archivo de las que se pueden anticipar. Por lo tanto, podría retornar un string vacío.</dd> + <dt>{{domxref("MimeType.enabledPlugin")}}</dt> + <dd>Retorna una instancia de {{domxref("Plugin")}} que contiene la información acerca del plugin en sí mismo.</dd> +</dl> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG','#mimetype','MimeType')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>Definición Inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_Navegadores">Compatibilidad de Navegadores</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android Webview</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> diff --git a/files/es/web/api/mouseevent/index.html b/files/es/web/api/mouseevent/index.html new file mode 100644 index 0000000000..74aabe922e --- /dev/null +++ b/files/es/web/api/mouseevent/index.html @@ -0,0 +1,298 @@ +--- +title: MouseEvent +slug: Web/API/MouseEvent +tags: + - API +translation_of: Web/API/MouseEvent +--- +<p id="Summary">{{APIRef("DOM Events")}}</p> + +<p>The <code><strong>MouseEvent</strong></code> interface represents events that occur due to the user interacting with a pointing device (such as a mouse). Common events using this interface include {{event("click")}}, {{event("dblclick")}}, {{event("mouseup")}}, {{event("mousedown")}}.</p> + +<p><code>MouseEvent</code> derives from {{domxref("UIEvent")}}, which in turn derives from {{domxref("Event")}}. Though the {{domxref("MouseEvent.initMouseEvent()")}} method is kept for backward compatibility, creating of a <code>MouseEvent</code> object should be done using the {{domxref("MouseEvent.MouseEvent", "MouseEvent()")}} constructor.</p> + +<p>Several more specific events derivate from <code>MouseEvent</code>: {{domxref("WheelEvent")}} and {{domxref("DragEvent")}}.</p> + +<h2 id="Constructor">Constructor</h2> + +<dl> + <dt>{{domxref("MouseEvent.MouseEvent", "MouseEvent()")}}</dt> + <dd>Creates a <code>MouseEvent</code> object.</dd> +</dl> + +<h2 id="Properties">Properties</h2> + +<p><em>This interface also inherits properties of its parents, {{domxref("UIEvent")}} and {{domxref("Event")}}.</em></p> + +<dl> + <dt>{{domxref("MouseEvent.altKey")}} {{readonlyinline}}</dt> + <dd>Returns <code>true</code> if the <kbd>alt</kbd> key was down when the mouse event was fired.</dd> + <dt>{{domxref("MouseEvent.button")}} {{readonlyinline}}</dt> + <dd>The button number that was pressed when the mouse event was fired. </dd> + <dt>{{domxref("MouseEvent.buttons")}} {{readonlyinline}} {{gecko_minversion_inline("15.0")}}</dt> + <dd> + <p>The buttons being pressed when the mouse event was fired</p> + </dd> + <dt>{{domxref("MouseEvent.clientX")}} {{readonlyinline}}</dt> + <dd>The X coordinate of the mouse pointer in local (DOM content) coordinates.</dd> + <dt>{{domxref("MouseEvent.clientY")}} {{readonlyinline}}</dt> + <dd>The Y coordinate of the mouse pointer in local (DOM content) coordinates.</dd> + <dt>{{domxref("MouseEvent.ctrlKey")}} {{readonlyinline}}</dt> + <dd>Returns <code>true</code> if the <kbd>control</kbd> key was down when the mouse event was fired.</dd> + <dt>{{domxref("MouseEvent.metaKey")}} {{readonlyinline}}</dt> + <dd>Returns <code>true</code> if the <kbd>meta</kbd> key was down when the mouse event was fired.</dd> + <dt>{{domxref("MouseEvent.movementX")}} {{readonlyinline}}</dt> + <dd>The X coordinate of the mouse pointer relative to the position of the last {{event("mousemove")}} event.</dd> + <dt>{{domxref("MouseEvent.movementY")}} {{readonlyinline}}</dt> + <dd>The Y coordinate of the mouse pointer relative to the position of the last {{event("mousemove")}} event.</dd> + <dt>{{domxref("MouseEvent.region")}} {{readonlyinline}}</dt> + <dd>Returns the id of the hit region affected by the event. If no hit region is affected, <code>null</code> is returned.</dd> + <dt>{{domxref("MouseEvent.relatedTarget")}} {{readonlyinline}}</dt> + <dd> + <p>The secondary target for the event, if there is one.</p> + </dd> + <dt>{{domxref("MouseEvent.screenX")}} {{readonlyinline}}</dt> + <dd>The X coordinate of the mouse pointer in global (screen) coordinates.</dd> + <dt>{{domxref("MouseEvent.screenY")}} {{readonlyinline}}</dt> + <dd>The Y coordinate of the mouse pointer in global (screen) coordinates.</dd> + <dt>{{domxref("MouseEvent.shiftKey")}} {{readonlyinline}}</dt> + <dd>Returns <code>true</code> if the <kbd>shift</kbd> key was down when the mouse event was fired.</dd> + <dt>{{domxref("MouseEvent.which")}} {{non-standard_inline}} {{readonlyinline}}</dt> + <dd>The button being pressed when the mouse event was fired.</dd> + <dt>{{domxref("MouseEvent.mozPressure")}} {{non-standard_inline()}} {{readonlyinline}}</dt> + <dd>The amount of pressure applied to a touch or tablet device when generating the event; this value ranges between <code>0.0</code> (minimum pressure) and <code>1.0</code> (maximum pressure).</dd> + <dt>{{domxref("MouseEvent.mozInputSource")}} {{non-standard_inline()}} {{readonlyinline}}</dt> + <dd> + <p>The type of device that generated the event (one of the <code>MOZ_SOURCE_*</code> constants listed below). This lets you, for example, determine whether a mouse event was generated by an actual mouse or by a touch event (which might affect the degree of accuracy with which you interpret the coordinates associated with the event). The possible values are:</p> + + <table class="standard-table"> + <tbody> + <tr> + <th>Constant name</th> + <th>Value</th> + <th>Desription</th> + </tr> + <tr> + <td><code>MouseEvent.MOZ_SOURCE_UNKNOWN</code></td> + <td>0</td> + <td>The input device is unknown.</td> + </tr> + <tr> + <td><code><code>MouseEvent.</code>MOZ_SOURCE_MOUSE</code></td> + <td>1</td> + <td>The event was generated by a mouse (or mouse-like device).</td> + </tr> + <tr> + <td><code><code>MouseEvent.</code>MOZ_SOURCE_PEN</code></td> + <td>2</td> + <td>The event was generated by a pen on a tablet.</td> + </tr> + <tr> + <td><code><code>MouseEvent.</code>MOZ_SOURCE_ERASER</code></td> + <td>3</td> + <td>The event was generated by an eraser on a tablet.</td> + </tr> + <tr> + <td><code><code>MouseEvent.</code>MOZ_SOURCE_CURSOR</code></td> + <td>4</td> + <td>The event was generated by a cursor.</td> + </tr> + <tr> + <td><code><code>MouseEvent.</code>MOZ_SOURCE_TOUCH</code></td> + <td>5</td> + <td>The event was generated on a touch interface.</td> + </tr> + <tr> + <td><code><code>MouseEvent.</code>MOZ_SOURCE_KEYBOARD</code></td> + <td>6</td> + <td>The event was generated by a keyboard.</td> + </tr> + </tbody> + </table> + </dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<p><em>This interface also inherits methods of its parents, {{domxref("UIEvent")}} and {{domxref("Event")}}.</em></p> + +<dl> + <dt>{{domxref("MouseEvent.getModifierState()")}}</dt> + <dd>Returns the current state of the specified modifier key. See the {{domxref("KeyboardEvent.getModifierState")}}() for details.</dd> + <dt>{{domxref("MouseEvent.initMouseEvent()")}} {{deprecated_inline}}</dt> + <dd>Initializes the value of a <code>MouseEvent</code> created. If the event has already being dispatched, this method does nothing.</dd> +</dl> + +<h2 id="Example">Example</h2> + +<p>This example demonstrates simulating a click (that is programmatically generating a click event) on a checkbox using DOM methods. </p> + +<pre class="brush: js">function simulateClick() { + var evt = new <a href="/en-US/docs/Web/API/MouseEvent">MouseEvent</a>("click", { + bubbles: true, + cancelable: true, + view: window, + }); + var cb = document.getElementById("checkbox"); //element to click on + var canceled = !cb.<a href="/en-US/docs/Web/API/EventTarget.dispatchEvent" rel="internal" title="en/DOM/element.dispatchEvent">dispatchEvent</a>(evt); + if(canceled) { + // A handler called preventDefault + alert("canceled"); + } else { + // None of the handlers called preventDefault + alert("not canceled"); + } +} +document.getElementById("button").addEventListener('click', simulateClick);</pre> + +<pre class="brush: html"><p><label><input type="checkbox" id="checkbox"> Checked</label> +<p><button id="button">Click me</button></pre> + +<p>Click on the button to see how the sample works:</p> + +<p>{{ EmbedLiveSample('Example', '', '', '') }}</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-mouseevent-region", "MouseEvent.region")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>From {{SpecName('DOM3 Events')}}, added the <code>region</code> property.</td> + </tr> + <tr> + <td>{{SpecName('Pointer Lock','#extensions-to-the-mouseevent-interface','MouseEvent')}}</td> + <td>{{Spec2('Pointer Lock')}}</td> + <td>From {{SpecName('DOM3 Events')}}, added <code>movementX</code> and <code>movementY</code> properties.</td> + </tr> + <tr> + <td>{{SpecName('DOM3 Events','#events-mouseevents','MouseEvent')}}</td> + <td>{{Spec2('DOM3 Events')}}</td> + <td>From {{SpecName('DOM2 Events')}}, added the <code>MouseEvent()</code> constructor, the <code>getModifierState()</code> method and the <code>buttons</code> property.</td> + </tr> + <tr> + <td>{{SpecName('DOM2 Events','#Events-MouseEvent','MouseEvent')}}</td> + <td>{{Spec2('DOM2 Events')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">Browser compatibility</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Firefox (Gecko)</th> + <th>Chrome</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown()}}</td> + <td>{{CompatVersionUnknown()}}</td> + <td>{{CompatVersionUnknown()}}</td> + <td>{{CompatVersionUnknown()}}</td> + <td>{{CompatVersionUnknown()}}</td> + </tr> + <tr> + <td>{{domxref("MouseEvent.movementX","movementX")}}<br> + {{domxref("MouseEvent.movementY","movementY")}}</td> + <td>{{CompatVersionUnknown()}} {{property_prefix("moz")}}</td> + <td>{{CompatVersionUnknown()}} {{property_prefix("webkit")}}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + </tr> + <tr> + <td>{{ domxref("MouseEvent.buttons", "buttons") }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + </tr> + <tr> + <td>{{ domxref("MouseEvent.which", "which") }}</td> + <td>1.0</td> + <td>1.0</td> + <td>9.0</td> + <td>5.0</td> + <td>1.0</td> + </tr> + <tr> + <td>{{domxref("MouseEvent.getModifierState()", "getModifierState()")}}</td> + <td>{{CompatGeckoDesktop(15)}}</td> + <td>{{CompatVersionUnknown()}}</td> + <td>{{CompatVersionUnknown()}}</td> + <td>{{CompatVersionUnknown()}}</td> + <td>{{CompatVersionUnknown()}}</td> + </tr> + <tr> + <td>{{domxref("MouseEvent.mozPressure", "mozPressure")}} and {{domxref("MouseEvent.mozInputSource", "mozInputSource")}} {{non-standard_inline}}</td> + <td>{{CompatGeckoDesktop(2)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>{{domxref("MouseEvent.MouseEvent", "MouseEvent()")}}</td> + <td>{{CompatGeckoDesktop(11)}}</td> + <td>{{CompatVersionUnknown()}}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{CompatVersionUnknown()}}</td> + <td>{{ CompatUnknown() }}</td> + </tr> + <tr> + <td>{{domxref("MouseEvent.region")}}</td> + <td>{{CompatGeckoDesktop(32)}}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Firefox Mobile (Gecko)</th> + <th>Android</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>Its direct parent, {{domxref("UIEvent")}}.</li> +</ul> diff --git a/files/es/web/api/mouseevent/initmouseevent/index.html b/files/es/web/api/mouseevent/initmouseevent/index.html new file mode 100644 index 0000000000..0e5a795b27 --- /dev/null +++ b/files/es/web/api/mouseevent/initmouseevent/index.html @@ -0,0 +1,60 @@ +--- +title: event.initMouseEvent +slug: Web/API/MouseEvent/initMouseEvent +tags: + - Referencia_DOM_de_Gecko +translation_of: Web/API/MouseEvent/initMouseEvent +--- +<p>{{ApiRef("DOM Events")}}{{deprecated_header}}</p> + +<div class="note"> +<p><strong>No utilize este método porque está obsoleto.</strong></p> + +<p>Usa constructores de eventos específicos, como {{domxref("MouseEvent.MouseEvent", "MouseEvent()")}}. La página <a href="/en-US/docs/Web/Guide/Events/Creating_and_triggering_events">Creando y disparando eventos</a> da más información sobre cómo usarlos.</p> +</div> + +<h3 id="Resumen" name="Resumen">Resumen</h3> + +<p>Asigna el valor inicial de un evento de ratón una vez creado (normalmente usando el método <a href="/es/docs/Web/API/Document/createEvent">document.createEvent</a>).</p> + +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> + +<pre class="eval"><em>event</em>.initMouseEvent(<em>type</em>,<em>canBubble</em>,<em>cancelable</em>,<em>view</em>,<em>detail</em>,<em>screenX</em>,<em>screenY</em>,<em>clientX</em>,<em>clientY</em>,<em>ctrlKey</em>,<em>altKey</em>,<em>shiftKey</em>,<em>metaKey</em>,<em>button</em>,<em>relatedTarget</em>); +</pre> + +<dl> + <dt><code>type</code></dt> + <dd>la cadena del <a href="es/DOM/event.type">type</a>. Los tipos posibles para un evento de ratón incluyen: <code>click</code>, <code>mousedown</code>, <code>mouseup</code>, <code>mouseover</code>, <code>mousemove</code>, <code>mouseout</code>.</dd> + <dt><code>canBubble</code></dt> + <dd>si el elemento puede ser recurrente. Pone el valor de <a href="es/DOM/event.bubbles">event.bubbles</a>.</dd> + <dt><code>cancelable</code></dt> + <dd>si la acción inicial del evento puede o no ser cancelada. Pone el valor de <a href="es/DOM/event.cancelable">event.cancelable</a>.</dd> + <dt><code>view</code></dt> + <dd>el valor AbstractView del evento. Aquí debes pasar el objeto <a href="es/DOM/window">window</a>. Pone el valor de <a href="es/DOM/event.view">event.view</a>.</dd> + <dt><code>detail</code></dt> + <dd>el contador de clic del evento. Pone el valor de <a href="es/DOM/event.detail">event.detail</a>.</dd> + <dt><code>screenX</code></dt> + <dd>la coordenada x en pantalla donde ha ocurrido el evento. Pone el valor de <a href="es/DOM/event.screenX">event.screenX</a>.</dd> + <dt><code>screenY</code></dt> + <dd>la coordenada y en pantalla donde ha ocurrido el evento. Pone el valor de <a href="es/DOM/event.screenY">event.screenY</a>.</dd> + <dt><code>clientX</code></dt> + <dd>la coordenada client x donde ha ocurrido el evento. Pone el valor de <a href="es/DOM/event.clientX">event.clientX</a>.</dd> + <dt><code>clientY</code></dt> + <dd>la coordenada client y donde ha ocurrido el evento. Pone el valor de <a href="es/DOM/event.clientY">event.clientY</a>.</dd> + <dt><code>ctrlKey</code></dt> + <dd>si se ha pulsado o no la tecla Control mientras ha ocurrido el evento. Pone el valor de <a href="es/DOM/event.ctrlKey">event.ctrlKey</a>.</dd> + <dt><code>altKey</code></dt> + <dd>si se ha pulsado o no la tecla Alt mientras ha ocurrido el evento. Pone el valor de <a href="es/DOM/event.altKey">event.altKey</a>.</dd> + <dt><code>shiftKey</code></dt> + <dd>si se ha pulsado o no la tecla Mayúsculas mientras ha ocurrido el evento. Pone el valor de <a href="es/DOM/event.shiftKey">event.shiftKey</a>.</dd> + <dt><code>metaKey</code></dt> + <dd>si se ha pulsado o no una meta tecla mientras ha ocurrido el evento. Pone el valor de <a href="es/DOM/event.metaKey">event.metaKey</a>.</dd> + <dt><code>button</code></dt> + <dd>el ratón del evento <a href="es/DOM/event.button">event.button</a>.</dd> + <dt><code>relatedTarget</code></dt> + <dd>el destino del evento <a href="es/DOM/event.relatedTarget">related EventTarget</a>. Sólo se usa con algún tipo de evento (ejemplo: <code>mouseover</code> y <code>mouseout</code>). En otros casos, devuelve <code>null</code>.</dd> +</dl> + +<h3 id="Especificaci.C3.B3n" name="Especificaci.C3.B3n">Especificación</h3> + +<p><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-Event-initMouseEvent">DOM Level 2 Events: initMouseEvent</a></p> diff --git a/files/es/web/api/mouseevent/shiftkey/index.html b/files/es/web/api/mouseevent/shiftkey/index.html new file mode 100644 index 0000000000..7f2fc25d61 --- /dev/null +++ b/files/es/web/api/mouseevent/shiftkey/index.html @@ -0,0 +1,126 @@ +--- +title: MouseEvent.shiftKey +slug: Web/API/MouseEvent/shiftKey +translation_of: Web/API/MouseEvent/shiftKey +--- +<p>{{APIRef("DOM Events")}}</p> + +<p>El evento de <strong><code>MouseEvent.shiftKey</code></strong> es una propiedad de solo lectura que indica si la tecla de <kbd>shift</kbd> se presionó (<code>true</code>) o no (<code>false</code>).</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var <em>shiftKeyPressed</em> = <em>instanceOfMouseEvent</em>.shiftKey +</pre> + +<h3 id="Valor_que_retorna">Valor que retorna</h3> + +<p>Un valor booleano</p> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre class="brush: js"><html> +<head> +<title>Ejemplo de shiftKey</title> + +<script type="text/javascript"> + +function showChar(e){ + alert( + "Tecla presionada: " + String.fromCharCode(e.charCode) + "\n" + + "charCode: " + e.charCode + "\n" + + "SHIFT presionada: " + e.shiftKey + "\n" + + "ALT presionado: " + e.altKey + "\n" + ); +} + +</script> +</head> + +<body onkeypress="showChar(event);"> +<p>Presione cualquier tecla, con o sin la tecla SHIFT.<br /> +También puede utilizar SHIFT junto a la tecla ALT.</p> +</body> +</html> +</pre> + +<h2 id="Especificación">Especificación</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('DOM3 Events','#widl-MouseEvent-shiftKey','MouseEvent.shiftKey')}}</td> + <td>{{Spec2('DOM3 Events')}}</td> + <td>Sin cambios desde {{SpecName('DOM2 Events')}}.</td> + </tr> + <tr> + <td>{{SpecName('DOM2 Events','#Events-MouseEvent','MouseEvent.shiftKey')}}</td> + <td>{{Spec2('DOM2 Events')}}</td> + <td>Primera definición.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">Compatibilidad con navegadores</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Chrome</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown()}}</td> + <td>{{CompatVersionUnknown()}}</td> + <td>{{CompatVersionUnknown()}}</td> + <td>{{CompatVersionUnknown()}}</td> + <td>{{CompatVersionUnknown()}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>Android</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also" name="See_also">Ver más</h2> + +<ul> + <li>{{ domxref("MouseEvent") }}</li> +</ul> diff --git a/files/es/web/api/mozsocial/closepanel/index.html b/files/es/web/api/mozsocial/closepanel/index.html new file mode 100644 index 0000000000..1b2305967f --- /dev/null +++ b/files/es/web/api/mozsocial/closepanel/index.html @@ -0,0 +1,19 @@ +--- +title: MozSocial.closePanel +slug: Web/API/MozSocial/closePanel +tags: + - Social +translation_of: Archive/Social_API/MozSocial/closePanel +--- +<p>{{ ApiRef() }}</p> +<p>{{non-standard_header()}}</p> +<p>{{fx_minversion_header("17.0")}}</p> +<h3 id="Summary" name="Summary">Resumen</h3> +<p>Cierra el panel social que está actualmente abierto en el panel del proveedor de servicios sociales de nivel superior.</p> +<h3 id="Syntax" name="Syntax">Sintaxis</h3> +<pre class="eval">MozSocial.closePanel(); +</pre> +<h3 id="Parametros">Parametros</h3> +<p>Ninguno.</p> +<h3 id="Specification" name="Specification">Especificación</h3> +<p>No es parte de ninguna especificación.</p> diff --git a/files/es/web/api/mozsocial/getattention/index.html b/files/es/web/api/mozsocial/getattention/index.html new file mode 100644 index 0000000000..e362749b56 --- /dev/null +++ b/files/es/web/api/mozsocial/getattention/index.html @@ -0,0 +1,19 @@ +--- +title: MozSocial.getAttention +slug: Web/API/MozSocial/getAttention +tags: + - Social +translation_of: Archive/Social_API/MozSocial/getAttention +--- +<p>{{ ApiRef() }}</p> +<p>{{non-standard_header()}}</p> +<p>{{fx_minversion_header("17.0")}}</p> +<h3 id="Summary" name="Summary">Resumen</h3> +<p>Ejecuta algunas acciones, posiblemente específicas de la plataforma, diseñadas para obtener la atención del usuario. Esto puede involucrar la reproducción de un efecto de sonido, parpadeo en la pantalla, o mostrando alguna otra forma de efecto.</p> +<h3 id="Syntax" name="Syntax">Sintaxis</h3> +<pre class="eval">MozSocial.getAttention(); +</pre> +<h3 id="Parámetros">Parámetros</h3> +<p>Ninguno.</p> +<h3 id="Specification" name="Specification">Especificación</h3> +<p>No es parte de ninguna especificación.</p> diff --git a/files/es/web/api/mozsocial/getworker/index.html b/files/es/web/api/mozsocial/getworker/index.html new file mode 100644 index 0000000000..e32cc7b240 --- /dev/null +++ b/files/es/web/api/mozsocial/getworker/index.html @@ -0,0 +1,19 @@ +--- +title: MozSocial.getWorker +slug: Web/API/MozSocial/getWorker +translation_of: Archive/Social_API/MozSocial/getWorker +--- +<p>{{ ApiRef() }}</p> +<p>{{non-standard_header()}}</p> +<p>{{fx_minversion_header("17.0")}}</p> +<h3 id="Summary" name="Summary">Resumen</h3> +<p>Devuelve una referencia al <a href="/en-US/docs/Social_API/Service_worker_API_reference" title="/en-US/docs/Social_API/Service_worker_API_reference">worker del servicio</a> de contenidos de redes sociales. Una vez obtenido, puedes llamar a su método <code>postMessage()</code> para comunicarte con él. Puedes usar uno de los <span style="color: #ffff00;"><span style="background-color: rgb(255, 0, 0);">mensajes estándares para redes sociales</span></span>, o mensajes específicos de ese servicio.</p> +<h3 id="Syntax" name="Syntax">Sintaxis</h3> +<pre class="eval">var <em>socialWorker</em> = MozSocial.getWorker(); +</pre> +<h3 id="Parámetros">Parámetros</h3> +<p>Ninguno.</p> +<h3 id="Valor_devuelto">Valor devuelto</h3> +<p>Una referencia al <a href="/en-US/docs/Social_API/Service_worker_API_reference" title="/en-US/docs/Social_API/Service_worker_API_reference">worker del servicio</a>.</p> +<h3 id="Specification" name="Specification">Especificación</h3> +<p>No forma parte de ninguna especificación.</p> diff --git a/files/es/web/api/mozsocial/index.html b/files/es/web/api/mozsocial/index.html new file mode 100644 index 0000000000..a2f559a9df --- /dev/null +++ b/files/es/web/api/mozsocial/index.html @@ -0,0 +1,44 @@ +--- +title: MozSocial +slug: Web/API/MozSocial +tags: + - API +translation_of: Archive/Social_API/MozSocial +--- +<div>{{ ApiRef("Social API") }} {{non-standard_header}}{{fx_minversion_header("17.0")}}</div> + +<p>The <code>MozSocial</code> object, returned by the <code>navigator.mozSocial</code> property, is available within the social media provider's panel to provide functionality it may need.</p> + +<div class="note"> +<p><strong>Note:</strong> Although Mozilla hopes to submit this API for standardization eventually, it has not yet done so.</p> +</div> + +<h2 id="Attributes" name="Attributes">Properties</h2> + +<dl> + <dt>{{domxref("MozSocial.isVisible")}}</dt> + <dd>Returns a Boolean value; the result is <code>true</code> if the content is visible, otherwise it's <code>false</code>.</dd> +</dl> + +<h2 id="Methods" name="Methods">Methods</h2> + +<dl> + <dt>{{domxref("MozSocial.closePanel()")}}</dt> + <dd>Closes the currently open flyout panel.</dd> + <dt>{{domxref("MozSocial.getAttention()")}}</dt> + <dd>Performs some action designed to get the user's attention; the exact behavior may vary from platform to platform. This might display a visual effect, play an audible notification, flash the screen, or use some other technique.</dd> + <dt>{{domxref("MozSocial.getWorker()")}}</dt> + <dd>Returns a reference to the service worker; once content has this reference, it can call <code>worker.port.postMessage()</code> method to communicate with the service.</dd> + <dt>{{domxref("MozSocial.openChatWindow()")}}</dt> + <dd>Opens a chat window that is anchored to the bottom of the browser window. Each chat window is expected to be a singular chat, but functionality may vary by provider.</dd> + <dt>{{domxref("MozSocial.openPanel()")}}</dt> + <dd>Opens a flyout panel attached to the sidebar at a given vertical offset. This might be, for example, used to display the actual conversation corresponding to a notification in the sidebar.</dd> + <dt>{{domxref("MozSocial.share()")}}</dt> + <dd>Initiates a share action via the SocialAPI Share panel. One argument is passed, an object containing "url", "title", "description", "source" and "image".</dd> +</dl> + +<h2 id="See_also" name="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Social_API" title="Social_API">Social API</a></li> +</ul> diff --git a/files/es/web/api/mozsocial/isvisible/index.html b/files/es/web/api/mozsocial/isvisible/index.html new file mode 100644 index 0000000000..7bc90e47da --- /dev/null +++ b/files/es/web/api/mozsocial/isvisible/index.html @@ -0,0 +1,22 @@ +--- +title: MozSocial.isVisible +slug: Web/API/MozSocial/isVisible +tags: + - Social +translation_of: Archive/Social_API/MozSocial/isVisible +--- +<p>{{non-standard_header()}}</p> +<p>{{fx_minversion_header("17.0")}}</p> +<p>{{ ApiRef() }}</p> +<h2 id="Summary" name="Summary">Resumen</h2> +<p>Indica si la barra lateral del contenido del proveedor de social media está o no visible actualmente.</p> +<h2 id="Syntax" name="Syntax">Sintaxis</h2> +<pre class="eval">var <em>visible</em> = navigator.MozSocial.isVisible +</pre> +<p>Al retornar, <code>visible</code> es <code>true</code> si la barra lateral es visible actualmente; de otro modo es <code>false</code>.</p> +<h2 id="Especificación">Especificación</h2> +<p>No es parte de ninguna especificación.</p> +<h2 id="Ver_también">Ver también</h2> +<ul> + <li><a href="/en-US/docs/Social_API" title="/en-US/docs/Social_API">Social API</a></li> +</ul> diff --git a/files/es/web/api/mozsocial/openchatwindow/index.html b/files/es/web/api/mozsocial/openchatwindow/index.html new file mode 100644 index 0000000000..26f6b97643 --- /dev/null +++ b/files/es/web/api/mozsocial/openchatwindow/index.html @@ -0,0 +1,26 @@ +--- +title: MozSocial.openChatWindow +slug: Web/API/MozSocial/openChatWindow +translation_of: Archive/Social_API/MozSocial/openChatWindow +--- +<p>{{ ApiRef() }}</p> +<p>{{non-standard_header()}}</p> +<p>{{fx_minversion_header("17.0")}}</p> +<h3 id="Summary" name="Summary">Resumen</h3> +<p>Abre una ventana de chat, anclada en la parte inferior de la ventana del navegador. Cada ventana de chat suele ser un one-on-one chat, pero esta funcionalidad puede variar dependiendo del proveedor.</p> +<h3 id="Syntax" name="Syntax">Sintaxis</h3> +<pre class="eval">MozSocial.openChatWindow(<em>toUrl</em>, <em>callback</em>); +</pre> +<h3 id="Parametros">Parametros</h3> +<dl> + <dt> + <code>toUrl</code></dt> + <dd> + URL a la que se abre la conexión de chat.</dd> + <dt> + <code>callback</code></dt> + <dd> + Un objeto para recibir notificaciones de devolución de llamada en la conexión. La devolución de llamada recibe como entrada una referencia a la ventana de chat. Vease <a href="/en-US/docs/Social_API/Implementing_chat_functionality" title="/en-US/docs/Social_API/Implementing_chat_functionality">Implementing chat functionality</a> para más detalles.</dd> +</dl> +<h3 id="Specification" name="Specification">Especificaciones</h3> +<p>No es parte de ninguna especificación.</p> diff --git a/files/es/web/api/mozsocial/openpanel/index.html b/files/es/web/api/mozsocial/openpanel/index.html new file mode 100644 index 0000000000..9ea96cd5bd --- /dev/null +++ b/files/es/web/api/mozsocial/openpanel/index.html @@ -0,0 +1,30 @@ +--- +title: MozSocial.openPanel +slug: Web/API/MozSocial/openPanel +translation_of: Archive/Social_API/MozSocial/openPanel +--- +<p>{{ ApiRef() }}</p> +<p>{{non-standard_header()}}</p> +<p>{{fx_minversion_header("17.0")}}</p> +<h3 id="Summary" name="Summary">Resumen</h3> +<p>Abre un panel desplegable sujeto a la barra lateral del proveedor de medios sociales con una distancia vertical dada.</p> +<h3 id="Syntax" name="Syntax">Sintaxis</h3> +<pre class="eval">MozSocial.openPanel(<em>toUrl</em>, <em>offset</em>, <em>callback</em>); +</pre> +<h3 id="Parámetros">Parámetros</h3> +<dl> + <dt> + <code>toUrl</code></dt> + <dd> + La URL al contenido a presentar en el panel.</dd> + <dt> + <code>offset</code></dt> + <dd> + La distancia vertical, en pixeles, a la cual posicionar el panel desplegable.</dd> + <dt> + <code>callback</code></dt> + <dd> + Un objeto para recibir notificaciones devueltas por la conexión. La llamada de vuelta recibe como entrada una referencia al panel desplegable. <<<OCUPA ENLACE A DETALLES>>></dd> +</dl> +<h3 id="Specification" name="Specification">Especificación</h3> +<p>No es parte de ninguna especificación.</p> diff --git a/files/es/web/api/mutationobserver/index.html b/files/es/web/api/mutationobserver/index.html new file mode 100644 index 0000000000..f0fe2a4b01 --- /dev/null +++ b/files/es/web/api/mutationobserver/index.html @@ -0,0 +1,330 @@ +--- +title: MutationObserver +slug: Web/API/MutationObserver +translation_of: Web/API/MutationObserver +--- +<p>{{APIRef("DOM")}}</p> + +<p><code>MutationObserver</code> establece un mecanismo para reaccionar ante cambios en el <a href="/en-US/docs/DOM">DOM</a>. Ha sido diseñado como un sustituto de los <a href="/en-US/docs/DOM/Mutation_events">Mutation Events</a> definidos en las especificaciones de <em>DOM3 Events</em>.</p> + +<h2 id="Constructor" name="Constructor">Constructor</h2> + +<h3 id="MutationObserver()" name="MutationObserver()"><code>MutationObserver()</code></h3> + +<p>Constructor para la instaciación de nuevos <em>DOM mutation observers</em>.</p> + +<pre class="eval">MutationObserver( + function callback +); +</pre> + +<h6 id="Parameters" name="Parameters">Parámetros</h6> + +<dl> + <dt><code>callback</code></dt> + <dd>La función que será llamada en cada mutación del DOM. El <em>observer</em> llamará a esta función con dos argumentos. El primero es un array de objetos, cada uno del tipo <a href="#MutationRecord"><code>MutationRecord</code></a>. El segundo es la propia instancia del <code>MutationObserver</code>.</dd> +</dl> + +<h2 id="Instance_methods" name="Instance_methods">Métodos</h2> + +<table class="standard-table"> + <tbody> + <tr> + <td><code>void <a href="#observe()">observe</a>( {{domxref("Node")}} target, <a href="#MutationObserverInit">MutationObserverInit</a> options );</code></td> + </tr> + <tr> + <td><code>void <a href="#disconnect()">disconnect</a>();</code></td> + </tr> + <tr> + <td><code>Array <a href="#takeRecords()">takeRecords</a>();</code></td> + </tr> + </tbody> +</table> + +<h3 id="observe()" name="observe()"><code>observe()</code></h3> + +<p>Registra la instancia del <code>MutationObserver</code> para recibir notificaciones de las mutaciones del DOM sobre el nodo especificado.</p> + +<pre class="eval">void observe( + {{domxref("Node")}} target, + <a href="#MutationObserverInit"><code>MutationObserverInit</code></a> options +); +</pre> + +<h6 id="Parameters" name="Parameters">Parámetros</h6> + +<dl> + <dt><code>target</code></dt> + <dd>El {{domxref("Node")}} sobre el que observar las mutaciones del DOM.</dd> + <dt><code>options</code></dt> + <dd><code>Un objeto <a href="#MutationObserverInit">MutationObserverInit</a></code>, que especifica que mutaciones del DOM deben ser informadas.</dd> +</dl> + +<div class="note">NOTA: Añadir un observador a un elemento es igual que addEventListener, si usted observa el elemento múltiples veces no hace ninguna diferencia. Si se observa dos veces un elemento, el observe callback no se ejecutará dos veces, ni tampoco tendrá que ejecutar disconnect() dos veces. En otras palabras, una vez el elemento es observado, observarlo de nuevo con la misma instancia del observador no hará nada. Sin embargo, si el callback es diferente por supuesto se le añadirá otro observador.</div> + +<h3 id="disconnect()" name="disconnect()"><code>disconnect()</code></h3> + +<p>Evita que la instancia <code>de MutationObserver</code> continue recibiendo notificaciones de modificaciones del DOM. Hasta que el método <a href="#observe()"><code>observe()</code></a> sea usado de nuevo, la función callback no será invocada.</p> + +<pre class="eval">void disconnect(); +</pre> + +<h3 id="takeRecords()" name="takeRecords()"><code>takeRecords()</code></h3> + +<p>Vacía la cola de registros de la instancia de <code>MutationObserver</code> devolviendo su contenido.</p> + +<pre class="eval">Array takeRecords(); +</pre> + +<h6 id="Return_value" name="Return_value">Return value</h6> + +<p>Returns an Array of <a href="#MutationRecord"><code>MutationRecord</code>s</a>.</p> + +<h2 id="MutationObserverInit" name="MutationObserverInit"><code>MutationObserverInit</code></h2> + +<p><code>MutationObserverInit</code> es un objeto para el que se pueden especificar las siguientes propiedades:</p> + +<div class="note">NOTA: Como mínimo las propiedades <code>childList</code>, <code>attributes</code>, o <code>characterData </code>deben ser <code>true</code>. En caso contrario, se producirá un error "An invalid or illegal string was specified"</div> + +<table class="standard-table"> + <tbody> + <tr> + <td class="header">Propiedad</td> + <td class="header">Descripción</td> + </tr> + <tr> + <td><code>childList</code></td> + <td> + <p>Establecer a <code>true</code> si la adición y/o eliminación de elementos hijo del nodo (incluso los nodos <code>text</code>) han se ser observados.</p> + </td> + </tr> + <tr> + <td><code>attributes</code></td> + <td> + <p>Establecer a <code>true</code> si los cambios en los atributos deben ser observados</p> + </td> + </tr> + <tr> + <td><code>characterData</code></td> + <td> + <p>Establecer a <code>true</code> si los cambios en los datos deben ser observados</p> + </td> + </tr> + <tr> + <td><code>subtree</code></td> + <td> + <p>Establecer a <code>true</code> si los cambios tambien deben ser observados en los descendientes.</p> + </td> + </tr> + <tr> + <td><code>attributeOldValue</code></td> + <td> + <p>Establecer a <code>true</code> si <code>attributes</code> es <code>true</code> y el valor anterior al cambio debe ser guardado.</p> + </td> + </tr> + <tr> + <td><code>characterDataOldValue</code></td> + <td> + <p>Establecer a <code>true</code> si <code>characterData</code> vale <code>true</code> y el dato anterior al cambio de be ser guardado.</p> + </td> + </tr> + <tr> + <td><code>attributeFilter</code></td> + <td> + <p>Asigne un array de nombres de atributos locales (sin su espacio de nombres) si no necesita observar los cambios en todos los atributos</p> + </td> + </tr> + </tbody> +</table> + +<h2 id="MutationRecord" name="MutationRecord"><code>MutationRecord</code></h2> + +<p><code>MutationRecord</code> es el objeto que será pasado a la funcion "callback" del observador. Tiene las siguientes propiedades:</p> + +<table class="standard-table"> + <tbody> + <tr> + <td class="header">Propiedad</td> + <td class="header">Tipo</td> + <td class="header">Descripción</td> + </tr> + <tr> + <td><code>type</code></td> + <td><code>String</code></td> + <td> + <p>Devuelve:</p> + + <ul> + <li><code>attributes </code>si el cambio fué en un atributo</li> + <li><code>characterData</code> si se produjo en un nodo.</li> + <li><code>childList</code> si se produjo en los nodos del árbol.</li> + </ul> + + <dl> + </dl> + </td> + </tr> + <tr> + <td><code>target</code></td> + <td><code>{{domxref("Node")}}</code></td> + <td> + <p>Devuelve el<strong> nodo</strong> afectado por el cambio, dependiendo del <code>type</code>:</p> + + <ul> + <li>Para <code>attributes</code>, el elemento cuyos atributos han cambiado.</li> + <li>Para <code>characterData</code>, el nodo <code>CharacterData</code>.</li> + <li>Para <code>childList</code>, El nodo padre cuyos hijos han cambiado.</li> + </ul> + </td> + </tr> + <tr> + <td><code>addedNodes</code></td> + <td><code>{{domxref("NodeList")}}</code></td> + <td> + <p>Devuelve los nodos añadidos. Si no tiene nodos añadidos devuelve un <span style="font-family: courier new,andale mono,monospace;">NodeList</span> vacio.</p> + </td> + </tr> + <tr> + <td><code>removedNodes</code></td> + <td><code>{{domxref("NodeList")}}</code></td> + <td> + <p>Devuelve los nodos eliminados. Si no tiene nodos eliminados devuelve un <span style="font-family: courier new,andale mono,monospace;">NodeList</span> vacio.</p> + </td> + </tr> + <tr> + <td><code>previousSibling</code></td> + <td><code>{{domxref("Node")}}</code></td> + <td> + <p>Devuelve el nodo hermano <strong>anterior</strong> añadido o eliminado, o el valor <code>null</code>.</p> + </td> + </tr> + <tr> + <td><code>nextSibling</code></td> + <td><code>{{domxref("Node")}}</code></td> + <td> + <p>Devuelve el <strong>siguiente</strong> nodo hermano añadido o eliminado, o el valor <code>null</code>.</p> + </td> + </tr> + <tr> + <td><code>attributeName</code></td> + <td><code>String</code></td> + <td> + <p>Devuelve el nombre local del atributo cambiado, o el valor <code>null</code>.</p> + </td> + </tr> + <tr> + <td><code>attributeNamespace</code></td> + <td><code>String</code></td> + <td> + <p>Devuelve espacio de nombres (namespace) del atributo cambiado, o el valor <code>null</code>.</p> + </td> + </tr> + <tr> + <td><code>oldValue</code></td> + <td><code>String</code></td> + <td> + <p>El valor devuelto depende del <code>type</code>:</p> + + <ul> + <li>Para <code>attributes</code>,el valor anterior del atributo.</li> + <li>Para <code>characterData</code>,los datos antes del cambio</li> + <li>Para <code>childList</code>,devuelve <code>null</code>.</li> + </ul> + </td> + </tr> + </tbody> +</table> + +<h2 id="Example_usage" name="Example_usage">Ejemplo de uso</h2> + +<p>El siguiente ejemplo fué tomado de: <a class="external" href="http://hacks.mozilla.org/2012/05/dom-mutationobserver-reacting-to-dom-changes-without-killing-browser-performance/" rel="freelink">this blog post</a>.</p> + +<pre class="brush: js">// selecciona el nodo target +var target = document.querySelector('#some-id'); + +// Crea una instancia de observer +var observer = new MutationObserver(function(mutations) { + mutations.forEach(function(mutation) { + console.log(mutation.type); + }); +}); + +// Configura el observer: +var config = { attributes: true, childList: true, characterData: true }; + +// pasa al observer el nodo y la configuracion +observer.observe(target, config); + +// Posteriormente, puede detener la observacion +observer.disconnect(); +</pre> + +<h2 id="Additional_reading" name="Additional_reading">Lectura adicional</h2> + +<ul> + <li><a class="external" href="http://updates.html5rocks.com/2012/02/Detect-DOM-changes-with-Mutation-Observers" rel="freelink">A brief overview</a></li> + <li><a class="external" href="http://hacks.mozilla.org/2012/05/dom-mutationobserver-reacting-to-dom-changes-without-killing-browser-performance/" rel="freelink">A more in-depth discussion</a></li> + <li><a class="external" href="http://www.youtube.com/watch?v=eRZ4pO0gVWw" rel="freelink">A screencast by Chromium developer Rafael Weinstein</a></li> + <li><a class="external" href="http://code.google.com/p/mutation-summary/" rel="freelink">The mutation summary library</a></li> + <li><a href="http://dom.spec.whatwg.org/#mutation-observers">The DOM standard</a> which defines the <code>MutationObserver</code> interface</li> +</ul> + +<h2 id="Compatibilidad_en_navegadores">Compatibilidad en navegadores</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>18 {{ property_prefix("-webkit") }}<br> + 26</td> + <td>{{ CompatGeckoDesktop(14) }}</td> + <td>11</td> + <td>15</td> + <td>6.0 {{ property_prefix("-webkit") }}</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 (Windows Phone) </th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatUnknown() }}</td> + <td>18 {{ property_prefix("-webkit") }}<br> + 26</td> + <td>{{ CompatGeckoMobile(14) }}</td> + <td><span style="font-size: 12px; line-height: 18px;">11 (8.1)</span></td> + <td>15</td> + <td> + <p>6 {{ property_prefix("-webkit")}}</p> + + <p>7</p> + </td> + </tr> + </tbody> +</table> +</div> + +<p> </p> diff --git a/files/es/web/api/mutationobserver/mutationobserver/index.html b/files/es/web/api/mutationobserver/mutationobserver/index.html new file mode 100644 index 0000000000..faf72f1db3 --- /dev/null +++ b/files/es/web/api/mutationobserver/mutationobserver/index.html @@ -0,0 +1,98 @@ +--- +title: MutationObserver.MutationObserver() +slug: Web/API/MutationObserver/MutationObserver +translation_of: Web/API/MutationObserver/MutationObserver +--- +<div>{{APIRef("DOM WHATWG")}}</div> + +<p><span class="seoSummary">El constructor DOM <code><strong>MutationObserver()</strong></code> — parte del interface {{domxref("MutationObserver")}} — </span>crea y devuelve un nuevo objeto <strong>observer </strong>que llamará a la función especificada (callback), cuando tengan lugar cambios sobre el DOM. Estos observadores no se inician inmediatamente; en primer lugar debemos llamar al método {{domxref("MutationObserver.observe", "observe()")}} para establecer qué parte del DOM observar y que tipo de cambios comunicar.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var <em>observer</em> = new MutationObserver(<em>callback</em>);</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>La función que será llamada con cada cambio en el DOM, determinado por el nodo, subárbol y opciones. Esta función toma dos parámetros de entrada: un array de objetos {{domxref("MutationRecord")}}, con los cambios producidos, y el <code>MutationObserver</code> que llamó a la función. Para mas detalles vea {{anch("Example", "example")}}</dd> + <dt> </dt> +</dl> + +<h3 id="Valor_devuelto">Valor devuelto</h3> + +<p>Un nuevo objeto {{domxref("MutationObserver")}}, configurado para llamar a una determinada función cuando se producca un cambio en el DOM.</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>Este ejemplo crea un nuevo <code>MutationObserver</code> configurado para <em>observar </em>a un nodo y a sus hijos (subárbol), cuando se añadan o eliminen elementos al mismo; tambien observa cualquier cambio en los atributos de los elementos del árbol.</p> + +<h3 id="La_función_callback">La función callback</h3> + +<pre class="brush: js">function callback(mutationList, observer) { + mutationList.forEach((mutation) => { + switch(mutation.type) { + case 'childList': + /* Uno o mas hijos han sido añadidos y/o eliminados del árbol; + vea mutation.addedNodes y mutation.removedNodes */ + break; + case 'attributes': + /* El valor de un atributo en mutation.target ha cambiado; + El nombre del atributo esta en mutation.attributeName y + su valor anterior en mutation.oldValue */ + break; + } + }); +} +</pre> + +<p>La función <code>callback()</code> es llamada cuando el <strong>observer </strong>detecta cambios que coinciden con la configuración de consulta especificada cuando llamamos a {{domxref("MutationObserver.observe", "observe()")}} para que inicie la observación.</p> + +<p>El tipo de cambio que se produjo (tanto en la lista de hijos como en los atributos) es detectado observando la propiedad {{domxref("MutationRecord.type", "mutation.type")}}</p> + +<h3 id="Crear_e_iniciar_un_observer">Crear e iniciar un "observer"</h3> + +<p>Este código establece el proceso de observación</p> + +<pre class="brush: js">var targetNode = document.querySelector("#someElement"); +var observerOptions = { + childList: true, + attributes: true, + subtree: true //Omita o ponga false si no quiere controlar los cambios en los hijos +} + +var observer = new MutationObserver(callback); +observer.observe(targetNode, observerOptions);</pre> + +<p>El subárbol deseado se localiza buscando un elemento cuyo ID es "someElement". Un conjunto de opciones para el "observer" es establecido en el registro <code>observerOptions</code>. En él, especificamos los valores <code>true </code>tanto para <code>childList</code> como <code>attributes</code>, para obtener la información deseada.</p> + +<p>Posteriormente instanciamos el objeto observer, especificando la función <code>callback()</code>, e iniciamos la observación de los nodos del DOM llamando al método <code>observe()</code>, pasandole el nodo y las opciones.</p> + +<p>Desde este momento y hasta que se llame al método {{domxref("MutationObserver.disconnect", "disconnect()")}}, la funcion <code>callback()</code> será llamada cada vez que un elemento sea añadido o eliminado del árbol del DOM, cuya raiz es <code>targetNode</code>, o uno de sus atributos sea cambiado.</p> + +<p> </p> + +<h2 id="Specifications" name="Specifications">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('DOM WHATWG', '#dom-mutationobserver-mutationobserver', 'MutationObserver()')}}</td> + <td>{{ Spec2('DOM WHATWG') }}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad">Compatibilidad</h2> + +<div class="hidden">La tabla de compatibilidad de esta página ha sido generada utilizando datos estructurados. Si desea contribuir, compruebe nuestra <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data </a>y envienos una petición de actualizacion</div> + +<p>{{Compat("api.MutationObserver.MutationObserver")}}</p> diff --git a/files/es/web/api/mutationobserver/observe/index.html b/files/es/web/api/mutationobserver/observe/index.html new file mode 100644 index 0000000000..607af27cd0 --- /dev/null +++ b/files/es/web/api/mutationobserver/observe/index.html @@ -0,0 +1,95 @@ +--- +title: MutationObserver.observe() +slug: Web/API/MutationObserver/observe +translation_of: Web/API/MutationObserver/observe +--- +<div>{{APIRef("DOM WHATWG")}}</div> + +<p><span class="seoSummary">El método {{domxref("MutationObserver")}} <code><strong>observe()</strong></code><strong> </strong>configura la funcion <code>MutationObserver</code> para que inicie la recepción de cambios en el DOM que coincidan con las opciones dadas.</span></p> + +<p>Según la configuración, el <em>observador </em>verá un solo {{domxref("Node")}} del árbol del DOM, o ese nodo y alguno o todos los nodos descendientes.</p> + +<p>Para detener al <code>MutationObserver</code> (de modo que la funcion no sea llamada), llame al método {{domxref("MutationObserver.disconnect()")}}.</p> + +<ul> +</ul> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><em>mutationObserver</em>.observe(<em>target</em>[, <em>options</em>]) +</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code>target</code></dt> + <dd> Un {{domxref("Node")}} del DOM (que puede ser un {{domxref("Element")}}) perteneciente al árbol DOM, o la raiz de un subárbol de nodos, donde observar cambios.</dd> + <dt><code>options</code> {{optional_inline}}</dt> + <dd>Un objeto {{domxref("MutationObserverInit")}} opcional, que decribe qué cambios en el DOM deben ser enviados a la función <code>callback </code>del observador.</dd> +</dl> + +<h3 id="Valor_devuelto">Valor devuelto</h3> + +<p><code>undefined</code>.</p> + +<h3 id="Excepciones">Excepciones</h3> + +<dl> + <dt><code>TypeError</code></dt> + <dd>llamado en cualquiera de las siguientes circunstancias</dd> + <dd> + <ul> + <li>Las opciones han sido configuradas de tal modo que no existe nada que monitorizar (por ejemplo, si {{domxref("MutationObserverInit.childList")}}, {{domxref("MutationObserverInit.attributes")}}, y {{domxref("MutationObserverInit.characterData")}} son <strong>false</strong>)</li> + <li>La opcion <code>attributes</code> es <code>false</code> (indicando que los cambios en los atributos no son monitorizados) y <code>attributeOldValue</code> es <code>true</code> y/o <code>attributeFilter</code> está presente.</li> + <li>Las opciones {{domxref("MutaitonObserverInit.characterDataOldValue", "characterDataOldValue")}} son <code>true </code>pero {{domxref("MutationObserverInit.characterData")}} es <code>false</code> (indicando que los cambios en los caracteres no se guardan).</li> + </ul> + </dd> +</dl> + +<h2 id="Notas_de_uso">Notas de uso</h2> + +<h3 id="Reutilizar_MutationObservers">Reutilizar MutationObservers</h3> + +<p>Puede llamar varias veces al método <code>observe()</code> del mismo objeto <code>MutationObserver</code> para ver los cambios en diferentes partes del árbol del DOM y/o diferentes tipos de cambios. Sin embargo ha de tener en cuenta:</p> + +<ul> + <li>Si llama a <code>observe()</code> en un nodo que ya estaba siendo observado por el mísmo <code>MutationObserver</code>, todos los observadores serán automáticamente eliminados de todos los elementos observados antes de que el nuevo observador sea activado.</li> + <li>Si el mismo <code>MutationObserver</code> no estaba siendo usado sobre ese nodo, entonces los observadores existentes se quedarán solos y se agregará el nuevo.</li> +</ul> + +<h3 id="La_observación_sigue_a_los_nodos_cuando_se_desconecta">La observación sigue a los nodos cuando se desconecta</h3> + +<p>Los observadores de cambios tienen como objetivo permitirle ver un conjunto de nodos a lo largo del tiempo, incluso si la conexion entre estos nodos desaparece. Si esta observando un subárbol de nodos, y una parte del subárbol es desconectado y llevado a otra parte del DOM, continuará viendo ese mismo segmento de nodos, recibiendo las mismas llamadas a la función que antes de ser desconectado.</p> + +<p>En otras palabras, hasta que se le haya notificado que los nodos se están separando de su subárbol monitoreado, recibirá notificaciones de los cambios en ese subárbol y sus nodos. Esto evita que pierda los cambios producidos despues de que la conexion se corte y antes de que tenga la oportunidad de especificar un nuevo monitoreo sobre los cambios en el nodo o subárbol movido.</p> + +<p>De manera que en teoria si mantiene la pista de los objetos {{domxref("MutationRecord")}} que describen los cambios, podrá "deshacer" los mismos, devolviendo el DOM a su estado inicial.</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p> </p> + +<h2 id="Specifications" name="Specifications">Especificaciones</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('DOM WHATWG', '#dom-mutationobserver-observe', 'MutationObserver.observe()')}}</td> + <td>{{ Spec2('DOM WHATWG') }}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad">Compatibilidad</h2> + + + +<p>{{Compat("api.MutationObserver.observe")}}</p> diff --git a/files/es/web/api/navigator/donottrack/index.html b/files/es/web/api/navigator/donottrack/index.html new file mode 100644 index 0000000000..fbc7c54b32 --- /dev/null +++ b/files/es/web/api/navigator/donottrack/index.html @@ -0,0 +1,111 @@ +--- +title: Navigator.doNotTrack +slug: Web/API/Navigator/doNotTrack +tags: + - API + - DOM + - Experimental + - Propiedad + - Referencia +translation_of: Web/API/Navigator/doNotTrack +--- +<div>{{ApiRef("HTML DOM")}}{{SeeCompatTable}}</div> + +<p>Devuelve los ajustes de do-not-track del usuario. Esto es <code>"1"</code> si el usuario ha solicitado no ser rastreado por sitios web, contenidos, o anuncios.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><em>dnt</em> = <em>navigator</em>.doNotTrack; +</pre> + +<p>El valor refleja el de la cabecera do-not-track, ej. valores de {"1", "0", "unspecified" }. Nota: Antes de Gecko 32, Gecko empleaba los valores { "yes", "no", "unspecified"} (<a href="https://bugzilla.mozilla.org/show_bug.cgi?id=887703">bug 887703</a>).</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush: js">console.log(navigator.doNotTrack); +// imprime "1" si DNT está habilitado; "0" si el usuario ha aceptado el rastreo; en caso contrario es "unspecified" +</pre> + +<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("Tracking", "#widl-Navigator-doNotTrack", "Navigator.doNotTrack")}}</td> + <td>{{Spec2("Tracking")}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>23</td> + <td>{{CompatGeckoDesktop("9.0")}}<sup>[1]</sup></td> + <td>9<sup>[2]</sup><br> + 11[3]</td> + <td>12</td> + <td>5.1<sup>[4]</sup></td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("9.0")}}<sup>[1]</sup></td> + <td>{{CompatUnknown}}<sup>[2]</sup></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Antes de Gecko 32 Firefox reporta <code>navigator.doNotTrack</code> con valores de <code>yes</code> y <code>no</code> en lugar de <code>1</code> y <code>0</code>.</p> + +<p>[2] Internet Explorer 9 y 10 utilizan un prefijo, ej. <code>navigator.msDoNotTrack</code>.</p> + +<p>[3] Internet Explorer 11 y Edge utilizan <code>window.doNotTrack</code> en lugar de <code>navigator.doNotTrack</code>.</p> + +<p>[4] Safari 7.1.3+ utiliza <code>window.doNotTrack</code> en lugar de <code>navigator.doNotTrack</code>.</p> + +<h2 id="Vea_también">Vea también</h2> + +<ul> + <li><a href="/en-US/docs/Web/Security/Do_not_track_field_guide">Guía sobre el campo Do Not Track</a></li> +</ul> diff --git a/files/es/web/api/navigator/getusermedia/index.html b/files/es/web/api/navigator/getusermedia/index.html new file mode 100644 index 0000000000..e3fd046743 --- /dev/null +++ b/files/es/web/api/navigator/getusermedia/index.html @@ -0,0 +1,184 @@ +--- +title: Navigator.getUserMedia +slug: Web/API/Navigator/getUserMedia +translation_of: Web/API/Navigator/getUserMedia +--- +<p>Pide al usuario permiso para usar un dispositivo multimedia como una cámara o micrófono. Si el usuario concede este permiso, el successCallback es invocado en la aplicación llamada con un objeto <a href="/en-US/docs/WebRTC/MediaStream_API#LocalMediaStream" title="WebRTC/MediaStream_API#LocalMediaStream">LocalMediaStream</a> como argumento.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">navigator.getUserMedia ( constraints, successCallback, errorCallback );</pre> + +<p><strong>Ejemplo</strong></p> + +<p>Aquí hay un ejemplo usando getUserMedia() con los prefijos del navegador.</p> + +<pre class="brush: js">navigator.getMedia = ( navigator.getUserMedia || + navigator.webkitGetUserMedia || + navigator.mozGetUserMedia); + +navigator.getMedia ( + + // Restricciones (contraints) *Requerido + { + video: true, + audio: true + }, + + // Funcion de finalizacion (Succes-Callback) *Requerido + function(localMediaStream) { + var video = document.querySelector('video'); + video.src = window.URL.createObjectURL(localMediaStream); + video.onloadedmetadata = function(e) { + // Haz algo con el video aquí. + }; + }, + + // errorCallback *Opcional + function(err) { + console.log("Ocurrió el siguiente error: " + err); + } + +);</pre> + +<h2 id="Parámetros">Parámetros</h2> + +<table> + <thead> + <tr> + <th scope="col">Parámetro</th> + <th scope="col"> + <p>Requerido/Opcional</p> + </th> + <th scope="col">Descripción</th> + </tr> + </thead> + <tbody> + <tr> + <td>constraints</td> + <td>Requerido</td> + <td>El tipo de multimedia que soporta el objeto LocalMediaStream devuelto en el successCallback.</td> + </tr> + <tr> + <td>successCallback </td> + <td>Requerido</td> + <td>La función a invocar cuando se pasa el objeto LocalMediaStream.</td> + </tr> + <tr> + <td>errorCallback</td> + <td>Opcional</td> + <td>La función que se invoca en la aplicación si falla la llamada.</td> + </tr> + </tbody> +</table> + +<h3 id="constraints">constraints</h3> + +<p>El parámetro <code>constraints</code> es un objeto <code>MediaStreamConstraints</code> con dos miembros booleanos: <code>video</code> y <code>audio</code>. Estos describen el los tipos de multimedia soportados por el objeto <a href="/en-US/docs/WebRTC/MediaStream_API#LocalMediaStream" title="WebRTC/MediaStream_API#LocalMediaStream">LocalMediaStream</a>. Uno o ambos deben ser especificados para validar el argumento del parametro constraint. Si un constraint especificado no es soportado por el navegador, <code>getUserMedia </code>llama a la función <code>errorCallback </code>con el error <code>NOT_SUPPORTED_ERROR</code>. Si el navegador no puede encontrar ninguna fuente multimedia con el tipo especificado, <code>getUserMedia </code>llama a la función <code>errorCallback </code>con el error <code>MANDATORY_UNSATISFIED_ERR</code>.</p> + +<p>Si el valor o el miembro no es especificado en el objeto, el valor del miembro por defecto será falso. El siguiente ejemplo muestra como definir el constraints para audio y video:</p> + +<pre>{ video: true, audio: true }</pre> + +<h3 id="successCallback">successCallback</h3> + +<p>La función getUserMedia llamará a la función especificada en el <code>successCallback </code>con el objeto <a href="/en-US/docs/WebRTC/MediaStream_API#LocalMediaStream" title="WebRTC/MediaStream_API#LocalMediaStream">LocalMediaStream</a> que contenga la secuencia multimedia. Puedes asignar el objeto al elemento apropiado y trabajar con él, como se muestra en el siguiente ejemplo:</p> + +<pre>function(localMediaStream) { + var video = document.querySelector('video'); + video.src = window.URL.createObjectURL(localMediaStream); + video.onloadedmetadata = function(e) { + // Haz algo aquí con el video. + }; +},</pre> + +<h3 id="errorCallback">errorCallback</h3> + +<p>La función <code>getUserMedia </code>llama a la función indicada en el errorCallback con un <code>código</code> como argumento. Los códigos de error se describen a continuación:</p> + +<table> + <thead> + <tr> + <th scope="col">Error </th> + <th scope="col">Descripción </th> + </tr> + </thead> + <tbody> + <tr> + <td>PERMISSION_DENIED </td> + <td>El usuario denegó el permiso para usar el dispositivo multimadia requerido para esta operación. </td> + </tr> + <tr> + <td>NOT_SUPPORTED_ERROR </td> + <td>Un constraint especificado no es soportado por el navegador.</td> + </tr> + <tr> + <td>MANDATORY_UNSATISFIED_ERROR </td> + <td>No se encontraron fuentes multimedia del tipo especificado en el constraints.</td> + </tr> + <tr> + <td>NO_DEVICES_FOUND</td> + <td>No se encontró ninguna webcam instalada.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_los_navegadores">Compatibilidad con los navegadores</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Stream API </td> + <td>21{{property_prefix("webkit")}} </td> + <td>20{{property_prefix("moz")}} </td> + <td>{{CompatNo}} </td> + <td>12</td> + <td>{{CompatUnknown}} </td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Stream API </td> + <td>{{CompatNo}} </td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}} </td> + <td>12</td> + <td>{{CompatNo}} </td> + </tr> + </tbody> +</table> +</div> + +<p><span style="line-height: 1.5em;">Actualmente el uso de WebRTC para acceder a la cámara esta soportado en Chrome, Opera y Firefox 20.</span></p> + +<h2 id="Vease_también">Vease también</h2> + +<ul> + <li><a href="/en-US/docs/WebRTC" title="WebRTC">WebRTC</a> - la página introductoria a la API</li> + <li><a href="/en-US/docs/WebRTC/MediaStream_API" title="WebRTC/MediaStream_API">MediaStream API</a> - la API para los objetos multimedia</li> + <li><a href="/en-US/docs/WebRTC/taking_webcam_photos" title="WebRTC/taking_webcam_photos">Taking webcam photos</a> - un tutorial acerca del uso de getUserMedia()</li> +</ul> diff --git a/files/es/web/api/navigator/id/index.html b/files/es/web/api/navigator/id/index.html new file mode 100644 index 0000000000..707d9a6255 --- /dev/null +++ b/files/es/web/api/navigator/id/index.html @@ -0,0 +1,16 @@ +--- +title: navigator.id +slug: Web/API/Navigator/id +translation_of: Archive/Navigator-id +--- +<div>{{ ApiRef("Persona") }}</div> + +<h2 id="Summary" name="Summary">Summary</h2> + +<p>The <a href="/en-US/docs/Persona" title="BrowserID">BrowserID protocol</a> defines a new <code>id</code> property on the {{ domxref ("window.navigator")}} object, through which it exposes the BrowserID API, that is the {{domxref("IdentityManager")}} intreface. This API has gone through several significant revisions. Each generation is listed separately below.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre>var id = navigator.id</pre> + +<p> </p> diff --git a/files/es/web/api/navigator/index.html b/files/es/web/api/navigator/index.html new file mode 100644 index 0000000000..6c38d2ca6b --- /dev/null +++ b/files/es/web/api/navigator/index.html @@ -0,0 +1,141 @@ +--- +title: Navigator +slug: Web/API/Navigator +tags: + - API + - HTML-DOM +translation_of: Web/API/Navigator +--- +<p>{{Apiref}}</p> + +<p>La interfaz <code><strong>Navigator</strong></code> representa el estado y la identidad del <em>user agent</em>. Es completamente consultable y es posible registrar scripts para que ejecuten diversas actividades.</p> + +<p>Un objeto <code>Navigator</code> puede ser obtenido usando la propiedad de sólo lectura {{domxref("Window.navigator")}}.</p> + +<h2 id="Propiedades">Propiedades</h2> + +<p><em>No hereda ninguna propiedad, pero implementa las definidas en {{domxref("NavigatorID")}}, {{domxref("NavigatorLanguage")}}, {{domxref("NavigatorOnLine")}}, {{domxref("NavigatorContentUtils")}}, {{domxref("NavigatorStorageUtils")}}, {{domxref("NavigatorCookies")}}, {{domxref("NavigatorConcurrentHardware")}}, {{domxref("NavigatorPlugins")}}, y {{domxref("NavigatorUserMedia")}}.</em></p> + +<h3 id="Estándar">Estándar</h3> + +<dl> + <dt>{{domxref("Navigator.activeVRDisplays")}} {{readonlyInline}}{{experimental_inline}}</dt> + <dd>Devuelve un arreglo que contiene cada objeto {{domxref("VRDisplay")}} que está siendo presentado en el momento ({{domxref("VRDisplay.ispresenting")}} es <code>true</code>).</dd> + <dt>{{domxref("NavigatorID.appCodeName")}} {{readonlyInline}}{{experimental_inline}}</dt> + <dd>Devuelve el nombre código interno del navegador actual. No confie en que esta propiedad devuelva siempre el valor correcto.</dd> + <dt>{{domxref("NavigatorID.appName")}} {{readonlyInline}}{{experimental_inline}}</dt> + <dd>Devuelve un {{domxref("DOMString")}} con el nombre oficial del navegador. No confie en que esta propiedad devuelva siempre el valor correcto. </dd> + <dt>{{domxref("NavigatorID.appVersion")}} {{readonlyInline}}{{experimental_inline}}</dt> + <dd>Devuelve la versión del navegador como un {{domxref("DOMString")}}. No confie en que esta propiedad devuelva siempre el valor correcto.</dd> + <dt>{{domxref("Navigator.battery")}} {{readonlyInline}}</dt> + <dd>Devuelve un objeto de tipo {{domxref("BatteryManager")}} que puede utilizar para obtener la información del estado de carga de la batería.</dd> + <dt>{{domxref("NetworkInformation.connection")}} {{readonlyInline}}{{experimental_inline}}</dt> + <dd>Provee un objeto {{domxref("NetworkInformation")}} con la información sobre la conexión a la red de un dispositivo.</dd> + <dt>{{domxref("NavigatorGeolocation.geolocation")}} {{readonlyInline}}</dt> + <dd>Devuelve un objeto {{domxref("Geolocation")}} que permite el acceso a la ubicación del dispositivo.</dd> + <dt>{{domxref("NavigatorConcurrentHardware.hardwareConcurrency")}} {{readOnlyInline}}</dt> + <dd>Devuelve el número de núcleos de procesador lógicos disponibles.</dd> + <dt>{{domxref("NavigatorPlugins.javaEnabled")}} {{readonlyInline}}{{experimental_inline}}</dt> + <dd>Devuelve un valor {{domxref("Boolean")}} que indica si el navegador tiene o no habilitado Java.</dd> + <dt>{{domxref("NavigatorLanguage.language")}} {{readonlyInline}}</dt> + <dd>Devuelve un valor {{domxref("DOMString")}} que representa el idioma elegido por el usuario, generalmente el idioma de la interfaz del navegador. Si no se puede identificar el idioma, devuelve un valor <code>null</code>.</dd> + <dt>{{domxref("NavigatorLanguage.languages")}} {{readonlyInline}}</dt> + <dd>Devuelve un arreglo de {{domxref("DOMString")}} que representan los idiomas conocidos por el usuario, en orden de preferencia.</dd> + <dt>{{domxref("NavigatorPlugins.mimeTypes")}} {{readonlyInline}}{{experimental_inline}}</dt> + <dd>Devieñve im {{domxref("MimeTypeArray")}} que enlista los tipos MIME soportados por el navegador.</dd> + <dt>{{domxref("NavigatorOnLine.onLine")}} {{readonlyInline}}</dt> + <dd>Devuelve un valor {{domxref("Boolean")}} que indica si el navegador está trabajando en línea.</dd> + <dt>{{domxref("Navigator.oscpu")}}</dt> + <dd>Devuelve una cadena de texto que representa al sistema operativo actual.</dd> + <dt>{{domxref("Navigator.permissions")}} {{readonlyinline}}{{experimental_inline}}</dt> + <dd>;</dd> + <dd>Devuelve un objeto {{domxref("Permissions")}} que puede ser usado para consultar y actualizar estatus de permisos de las APIs, acorde a la <a href="https://developer.mozilla.org/en-US/docs/Web/API/Permissions_API">API Permissions</a>.</dd> + <dt>{{domxref("NavigatorID.platform")}} {{readonlyInline}}{{experimental_inline}}</dt> + <dd>Devuelve una cadena de texto que representa la plataforma del navegador. No confíe en que esta función devuelva un valor significativo.</dd> + <dt>{{domxref("NavigatorPlugins.plugins")}} {{readonlyInline}}{{experimental_inline}}</dt> + <dd>Devuelve un {{domxref("PluginArray")}} que enlista los plugins instalados en el navegador.</dd> + <dt>{{domxref("NavigatorID.product")}} {{readonlyInline}} {{experimental_inline}}</dt> + <dd>Siempre devuelve <code>'Gecko'</code>, en cualquier navegador. Esta propiedad es mantenido únicamente por razones de compatibilidad.</dd> + <dt>{{domxref("NavigatorID.userAgent")}} {{readonlyInline}}</dt> + <dd>Devuelve la cadena de agente usuario del navegador actual.</dd> + <dt>{{domxref("Navigator.serviceWorker")}} {{readonlyInline}}</dt> + <dd>Devuelve un objeto {{domxref("ServiceWorkerContainer")}}, el cual provee acceso a registro, eliminación, actualización y comunicación con los objetos {{domxref("ServiceWorker")}} para <a href="https://html.spec.whatwg.org/multipage/browsers.html#concept-document-window">documentos asociados</a>.</dd> +</dl> + +<h3 id="Methods" name="Methods">No Estándar</h3> + +<div class="note"> +<p>Dispositivos con Firefox OS añaden más propiedades no estándares. Puede consultarlas en el <a href="/en-US/docs/Mozilla/Firefox_OS/API/Navigator">artículo de extensiones de Navigator de Firefox OS</a>.</p> +</div> + +<dl> + <dt>{{domxref("Navigator.buildID")}} {{non-standard_inline}}</dt> + <dd>Devuelve el identificador de la compilación del navegador(p.ej., "2006090803").</dd> + <dt>{{domxref("Navigator.cookieEnabled")}} {{non-standard_inline}}</dt> + <dd>Devuelve un booleano que indica si el navegador tiene activadas las cookies.</dd> + <dt>{{domxref("Navigator.credentials")}} {{non-standard_inline}}</dt> + <dd>Devuelve la interfaz {{domxref("CredentialsContainer")}}, la cual expone métodos para solicitar credenciales y notificar al agente usuario cuando ocurran eventos de interés, como inicios o cierres de sesión.</dd> + <dt>{{domxref("Navigator.doNotTrack")}} {{non-standard_inline}}</dt> + <dd>Reporta el valor de la preferencia <em>do-not-track</em>. Cuando su valor es positivo ("yes", "1"), el sitio o aplicación web no debe rastrear al usuario.</dd> + <dt>{{domxref("Navigator.id")}} {{non-standard_inline}}</dt> + <dd>Devuelve el objeto {{domxref("window.navigator.id", "id")}}, el cual se puede usar para añadir soporte a <a href="/es/docs/Mozilla/Persona" title="BrowserID">BrowserID</a> en el sitio web.</dd> + <dt>{{domxref("Navigator.mediaDevices")}} {{non-standard_inline}}</dt> + <dd>Devuelve una referencia a la interfaz {{domxref("MediaDevices")}}.</dd> + <dt>{{domxref("Navigator.mozNotification")}} {{deprecated_inline("22")}} {{non-standard_inline}}<br> + {{domxref("Navigator.webkitNotification")}}</dt> + <dd>Devuelve un objeto {{domxref("navigator.mozNotification", "notification")}} que puede ser usado para enviar notificaciones al usuario desde la aplicación web.</dd> + <dt>{{domxref("Navigator.mozSocial")}} {{non-standard_inline}}</dt> + <dd>El objeto devuelto por la propiedad <code>navigator.mozSocial</code>, está disponible en el panel de proveedor de medios sociales para proporcionar funcionalidad la que se necesite.</dd> + <dt>{{domxref("Navigator.presentation")}} {{non-standard_inline}}</dt> + <dd>Devuelve una referencia a la API {{domxref("Presentation")}}.</dd> + <dt>{{domxref("Navigator.productSub")}} {{non-standard_inline}}</dt> + <dd>Devuelve el número de compilación del navegador actual (p.ej., "20060909").</dd> + <dt>{{domxref("Navigator.securitypolicy")}} {{non-standard_inline}}</dt> + <dd>Devuelve una cadena de texto vacía. En Netscape 4.7x, devuelve "US & CA domestic policy" o "Export policy".</dd> + <dt>{{domxref("Navigator.standalone")}} {{non-standard_inline}}</dt> + <dd>Devuelve un booleano que indica si el navegador está ejecutándose en modo <em>standalone</em>. Disponible sólo para Safari de iOS de Apple.</dd> + <dt>{{domxref("Navigator.vendor")}} {{non-standard_inline}}</dt> + <dd>Devuelve el nombre del fabricante del navegador actual (p.ej., "Netscape6").</dd> + <dt>{{domxref("Navigator.vendorSub")}} {{non-standard_inline}}</dt> + <dd>Devuelve la versión de fabricante (p.ej. "6.1").</dd> + <dt>{{domxref("Navigator.webkitPointer")}} {{non-standard_inline}}</dt> + <dd>Devuelve un objeto PointerLock para la API <a href="https://developer.mozilla.org/en-US/docs/API/Pointer_Lock_API" title="Mouse Lock API">Mouse Lock</a>.</dd> +</dl> + +<h2 id="Methods" name="Methods">Métodos</h2> + +<p><em>No hereda ninguna propiedad, pero implementa las definidas en </em><em>{{domxref("NavigatorID")}}, {{domxref("NavigatorContentUtils")}}, <em>{{domxref("NavigatorUserMedia")}}, </em>y {{domxref("NavigatorStorageUtils")}}.</em></p> + +<h3 id="Estándar_2">Estándar</h3> + +<dl> + <dt>{{domxref("Navigator.getVRDisplays()")}} {{experimental_inline}}</dt> + <dd>Devuelve una promesa que se resuelve en un arreglo de objetos {{domxref("VRDisplay")}} que representan cualquier dispositivo VR conectado a la computadora que esté disponible.</dd> + <dt>{{domxref("Navigator.getUserMedia", "NavigatorUserMedia.getUserMedia()")}}</dt> + <dd>Después de solicitar permiso al usuario, devuelve el stream de audio o video asociado a la cámara o micrófono de la computadora local.</dd> + <dt>{{domxref("Navigator.registerContentHandler()")}}</dt> + <dd>Permite a los web sites registrarse como posibles controladores de un tipo MIME determinado.</dd> + <dt>{{domxref("Navigator.registerProtocolHandler()")}}</dt> + <dd>Permite a los sitios webs registrarse como posibles controladores de un protocolo determinado.</dd> + <dt>{{domxref("Navigator.requestMediaKeySystemAccess()")}} {{experimental_inline}}</dt> + <dd>Devuelve un objeto {{jsxref("Promise")}} para un objeto MediaKeySystemAccess.</dd> + <dt>{{domxref("Navigator.sendBeacon()")}}{{experimental_inline}}</dt> + <dd>Usado para transferir, de forma asíncrona, conjuntos pequeños de datos HTTP del agente usuario al servidor.</dd> + <dt>{{domxref("NavigatorID.taintEnabled()")}} {{deprecated_inline("1.7.8")}} {{obsolete_inline("9.0")}} {{experimental_inline}}</dt> + <dd>Devuelve <code>false</code>. Las funciones <code>taint</code>/<code>untaint</code> de JavaScript fueron desaprobadas en JavaScript 1.2.</dd> + <dt>{{domxref("Navigator.vibrate()")}} {{gecko_minversion_inline("11.0")}}</dt> + <dd>Causa vibración en el dispositivo que la soporta. No hace nada si el soporte para vibración no está disponible.</dd> +</dl> + +<h3 id="Specification" name="Specification">No Estándar</h3> + +<div class="note"> +<p>Dispositivos con Firefox OS añaden más métodos no estándares. Puede consultarlas en el <a href="/en-US/docs/Mozilla/Firefox_OS/API/Navigator">artículo de extensiones de Navigator de Firefox OS</a>.</p> +</div> + +<dl> + <dt>{{domxref("Navigator.mozIsLocallyAvailable()")}} {{non-standard_inline}}</dt> + <dd>Permite al código verificar si el documento en una URI determinada está disponible sin usar la red.</dd> + <dt>{{domxref("Navigator.mozPay()")}} {{non-standard_inline}}</dt> + <dd>Permite pagos dentro de la aplicación.</dd> +</dl> diff --git a/files/es/web/api/navigator/mozsocial/index.html b/files/es/web/api/navigator/mozsocial/index.html new file mode 100644 index 0000000000..cf5dd808f8 --- /dev/null +++ b/files/es/web/api/navigator/mozsocial/index.html @@ -0,0 +1,48 @@ +--- +title: navigator.mozSocial +slug: Web/API/Navigator/mozSocial +translation_of: Archive/mozSocial +--- +<p>{{non-standard_header()}}</p> +<p>{{fx_minversion_header("17.0")}}</p> +<p>{{ ApiRef() }}</p> +<p>El objeto <code>MozSocial</code> , regresado por la propiedad <code>navigator.mozSocial</code> , esta disponible dentro del tablero del proveedor de medios de comunicación para proporcionar la funcionalidad que pueda necesitar.</p> +<div class="note"> + <p><strong>Nota:</strong> Aunque mozilla espera enviar eventualmente este API para su estandarización, aun no se ha hecho.</p> +</div> +<h2 id="Atributos">Atributos</h2> +<dl> + <dt> + {{domxref("MozSocial.isVisible")}}</dt> + <dd> + Regresa un valor Booleano; el resultado es <code>true</code> si el contenido es visible, de otra manera es <code>false</code>.</dd> +</dl> +<h2 id="Métodos">Métodos</h2> +<dl> + <dt> + {{domxref("MozSocial.closePanel()")}}</dt> + <dd> + Cierra el tablero flotante abierto actualmente.</dd> + <dt> + {{domxref("MozSocial.getAttention()")}}</dt> + <dd> + Realiza algunas acciones diseñadas para obtener la atención del usuario; el mismo comportamiento puede variar de plataforma a plataforma. Esto puede mostrar un efecto visual, reproducir una notificación audible, parpadear la pantalla, o utilizar alguna otra técnica.</dd> + <dt> + {{ domxref("MozSocial.getWorker()") }}</dt> + <dd> + Regresa una referencia al trabajador de servicios; una vez el contenido tiene esta referencia, puede llamar a su método <code>postMessage()</code> para comunicarse con el servicio.</dd> + <dt> + {{domxref("MozSocial.openChatWindow()")}}</dt> + <dd> + Abre una ventana de chat que es anclada al pie de la ventana del navegador. Se espera que cada ventana de chat sea un chat singular, pero su funcionalidad va a variar dependiento del proveedor.</dd> + <dt> + {{domxref("MozSocial.openPanel()")}}</dt> + <dd> + Abre un tablero flotante adjunto a la barra lateral en una vertical dada para compensar. Esto puede ser, por ejemplo, utilizado para mostrar la conversación actual correspondiente a una notificación en la barra lateral.</dd> + <dd> + </dd> + <dt> + Vease Tambien</dt> + <dd> + Social API</dd> +</dl> diff --git a/files/es/web/api/navigator/registerprotocolhandler/index.html b/files/es/web/api/navigator/registerprotocolhandler/index.html new file mode 100644 index 0000000000..a2a57f7ae3 --- /dev/null +++ b/files/es/web/api/navigator/registerprotocolhandler/index.html @@ -0,0 +1,33 @@ +--- +title: window.navigator.registerProtocolHandler +slug: Web/API/Navigator/registerProtocolHandler +tags: + - Firefox 3 + - Referencia_DOM_de_Gecko +translation_of: Web/API/Navigator/registerProtocolHandler +--- +<p> </p> +<p>{{ ApiRef() }} {{ Fx_minversion_header(3) }}</p> +<h3 id="Resumen" name="Resumen">Resumen</h3> +<p>Permite que las páginas web se registren por si mismas como posibles manejadores para protocolos concretos.</p> +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> +<pre class="eval">window.navigator.registerProtocolHandler(<i>protocol</i>,<i>uri</i>,<i>title</i>); +</pre> +<ul> + <li><code>protocol</code> es el protocolo que el sitio quiere manejar, especificado como una cadena.</li> + <li><code>uri</code> es la URI del manejador en forma de cadena. Puedes incluir "%s" para indicar dónde debe insertarse la URI (en formato escaped) del documento a manejar.</li> + <li><code>title</code> es el título del manejador presentado al usuario como una cadena.</li> +</ul> +<h3 id="Ejemplo" name="Ejemplo">Ejemplo</h3> +<pre class="eval">navigator.registerProtocolHandler("mailto", + "<span class="nowiki">https://mail.google.com/mail?view=cm&tf=0&to=%s</span>", + "Google Mail"); +</pre> +<p>Esto crea un nuevo manejador que permite a los enlaces de tipo "mailto:" dirigir al usuario a Google Mail, insertando la dirección de correo especificada en el enlace, en la URL.</p> +<h3 id="Especificaci.C3.B3n" name="Especificaci.C3.B3n">Especificación</h3> +<p>Especificado en el documento del WHATWG: <a class="external" href="http://whatwg.org/specs/web-apps/current-work/#custom-handlers">Web Applications 1.0 working draft</a>.</p> +<p> </p> +<p> </p> +<div class="noinclude"> + </div> +<p>{{ languages( { "en": "en/DOM/window.navigator.registerProtocolHandler", "fr": "fr/DOM/window.navigator.registerProtocolHandler", "ja": "ja/DOM/window.navigator.registerProtocolHandler", "ko": "ko/DOM/window.navigator.registerProtocolHandler", "pl": "pl/DOM/window.navigator.registerProtocolHandler" } ) }}</p> diff --git a/files/es/web/api/navigator/registerprotocolhandler/web-based_protocol_handlers/index.html b/files/es/web/api/navigator/registerprotocolhandler/web-based_protocol_handlers/index.html new file mode 100644 index 0000000000..2f72c52dc9 --- /dev/null +++ b/files/es/web/api/navigator/registerprotocolhandler/web-based_protocol_handlers/index.html @@ -0,0 +1,132 @@ +--- +title: Controladores de protocolos basados en web +slug: Web/API/Navigator/registerProtocolHandler/Web-based_protocol_handlers +tags: + - Avanzado + - Controladores de Protocolos Basados en Web + - HTML5 +translation_of: Web/API/Navigator/registerProtocolHandler/Web-based_protocol_handlers +--- +<div>{{Fx_minversion_header(3)}}</div> + +<h2 id="Background" name="Background">Antecedentes</h2> + +<p>Es bastante común encontrar enlaces de páginas web a recursos que no usan protocolos <code>http</code>. Un ejemplo es el protocolo <code>mailto:</code>:</p> + +<div style="overflow: hidden;"> +<pre class="brush:html"><a href="mailto:webmaster@example.com">Web Master</a></pre> +</div> + +<p>Los autores de la Web pueden usar un enlace <code>mailto:</code> cuando quieren proporcionar una forma conveniente para que los usuarios envién un correo electrónico, directamente desde la página web. Cuando el enlace está activo, el navegador debería lanzar la aplicación de escritorio predeterminada para gestionar correos electrónicos. Se puede pensar en esto como un controlador de protocolos <em>basados en escritorio</em>.</p> + +<p>Los controladores de protocolos basados en web permiten a las aplicaciones basadas en web participar en el proceso también. <span id="result_box" lang="es"><span>Esto es cada vez más importante a medida que más tipos de aplicaciones migren a la web</span></span>. De hecho, hay muchas aplicaciones basadas en web que gestionan correo electrónicos podrían procesar un enlace <code>mailto</code>.</p> + +<h2 id="Registering" name="Registering">Registro</h2> + +<p>Configurar una aplicación web como un controlador de protocolo no es un proceso difícil. Básicamente la aplicación web usa <code><a href="/en-US/docs/Web/API/navigator.registerProtocolHandler" title="DOM/window.navigator.registerProtocolHandler">registerProtocolHandler()</a></code> para registrarse a sí mismo con el navegador como un controlador potencial para un protocolo dado. Por ejemplo:</p> + +<pre class="brush: js">navigator.registerProtocolHandler("burger", + "http://www.google.co.uk/?uri=%s", + "Burger handler");</pre> + +<p>En donde los parámetros son:</p> + +<ul> + <li>El protocolo.</li> + <li>La plantilla de la URL, usada como el controlador. El "%s" es reemplazado con el <code>href</code> del enlace y una petición GET es ejecutada en la URL resultante.</li> + <li>El nombre fácil de usar para el controlador del protocolo.</li> +</ul> + +<p>Cuando un navegador ejecuta este código, se le mostrará un mensaje al usuario, pidiendo permiso para permitir a la aplicación web registrase como controlador para el protocolo. Firefox muestra un mensaje en el área de la barra de notificaciones:</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/9683/protocolregister.png" style="display: block; height: 401px; margin: 0px auto; width: 700px;"></p> + +<div class="note"><strong>Nota:</strong> La plantila de la URL proporcionada al registrar <strong>debe</strong> ser del mismo dominio que el de la página que intenta realizar el registro o el registro fallará. Por ejemplo, <code class="plain">http://example.com/homepage.html</code> puede registrar un controlador de protocolo para <code class="plain">http://example.com/handle_mailto/%s</code>, pero no para <code class="plain">http://example.<em><strong>org</strong></em>/handle_mailto/%s</code>.</div> + +<p>Al registrar el mismo controlador de protocolo más de una vez aparecerá una notifiación diferente, indicando que el controlador del protocolo ya ha está registrado. Por lo tanto, es una buena idea cuidar el registro del controlador de protocolo con una verificación para saber si ya está registrado, como con el siguiente ejemplo.</p> + +<h3 id="Example" name="Example">Ejemplo</h3> + +<pre class="brush: js"><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> +<html lang="en"> +<head> + <title>Ejemplo de Controlador de Protocolo Web - Registro</title> + <script type="text/javascript"> + navigator.registerProtocolHandler("burger", + "http://www.google.co.uk/?uri=%s", + "Burger handler"); + </script> +</head> +<body> + <h1>Ejemplo de Controlador de Protocolo Web</h1> + <p>Esta página web instalará un controlador de protocolo web para el protocolo <code>burger:</code>.</p> +</body> +</html> +</pre> + +<h2 id="Activating" name="Activating">Activando</h2> + +<p>Ahora, cada vez que el usuario active un enlace que usa el protocolo registrado, el navegador enrutará la acción a la URL suministrada cuando la aplicación web se haya registrado. Firefox, de manera predeterminada, alertará al usaurio antes de controlar la acción.</p> + +<h3 id="Example_2" name="Example_2">Ejemplo</h3> + +<pre class="brush: html"><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> +<html lang="en"> +<head> + <title>Ejemplo de Controlador de Protocolo Web - Prueba</title> +</head> +<body> + <p>Oye ¿Has visto <a href="burger:cheeseburger">esto</a> antes?</p> +</body> +</html> +</pre> + +<h2 id="Handling" name="Handling">Controlando</h2> + +<p>La siguiente fase es controlar la acción. El navgador extrae el <code>href</code> desde el enlace activado, lo combina con la plantilla de la URL suministrada durante el registro del controlador y realzia una petición HTTP GET sobre la URL. Luego, usando los ejemplos anteriores, el navegador realizará una petición GET sobre esta URL:</p> + +<pre>http://www.google.co.uk/?uri=burger:cheeseburger +</pre> + +<p>El código del lado del servidor puede extraer los parámetros de la cadena de petición y realizar la acción deseada.</p> + +<div class="note"><strong>Nota:</strong> Al código del lado del servidor se le pasa todo el contenido del <code>href</code>. Esto significa que el código del lado del servidor tendrá que analizar el protocolo desde los datos.</div> + +<h3 id="Example_3" name="Example_3">Example</h3> + +<pre class="brush: php"><?php +$value = ""; +if ( isset ( $_GET["value"] ) ) { + $value = $_GET["value"]; +} +?> + +<!DOCTYPE html> +<html lang="en"> +<head> + <title>Ejemplo de Controlador de Protocolo Web</title> +</head> +<body> + <h1>Ejemplo de Controlador de Protocolo Web - Controlador</h1> + <p>Esta página es llamada al controlar una acción del protocolo <code>burger:</code>. Datos enviados:</p> + <textarea> +<?php echo(htmlspecialchars($value, ENT_QUOTES, 'UTF-8')); ?> + </textarea> +</body> +</html> +</pre> + +<h2 id="References" name="References">Referencias</h2> + +<ul> + <li><a href="http://www.w3.org/TR/2011/WD-html5-20110525/timers.html#custom-handlers">http://www.w3.org/TR/2011/WD-html5-20110525/timers.html#custom-handlers</a></li> +</ul> + +<h2 id="See_also" name="See_also">Véase también</h2> + +<ul> + <li><a href="/en-US/docs/DOM/window.navigator.registerContentHandler" title="DOM/window.navigator.registerContentHandler">window.navigator.registerContentHandler</a></li> + <li><a href="/en-US/docs/XPCOM_Interface_Reference/nsIProtocolHandler" title="nsIProtocolHandler">nsIProtocolHandler</a> (solamente XUL)</li> + <li><a class="external" href="http://blog.mozilla.com/webdev/2010/07/26/registerprotocolhandler-enhancing-the-federated-web/" title="http://blog.mozilla.com/webdev/2010/07/26/registerprotocolhandler-enhancing-the-federated-web/">RegisterProtocolHandler, la mejora a la Web federada</a> en Mozilla Webdev</li> + <li><a href="https://developers.google.com/web/updates/2011/06/Registering-a-custom-protocol-handler">Registrar un protocolHandler personalizado</a> en Google Developers.</li> +</ul> diff --git a/files/es/web/api/navigator/vibrate/index.html b/files/es/web/api/navigator/vibrate/index.html new file mode 100644 index 0000000000..39969f4cfc --- /dev/null +++ b/files/es/web/api/navigator/vibrate/index.html @@ -0,0 +1,82 @@ +--- +title: window.navigator.vibrate +slug: Web/API/Navigator/vibrate +translation_of: Web/API/Navigator/vibrate +--- +<div> + {{ApiRef}}{{SeeCompatTable}}</div> +<h2 id="Summary" name="Summary">Resumen</h2> +<p>Ejecuta la vibración por hardware en el dispositivo, si existe dicho hardware. Si el dispositivo no soporta vibración, este método no tendrá efecto. Si un patrón de vibración ya estaba en progreso cuando este método es ejecutado, el patrón anterior se detiene y en su lugar se iniciará el último patrón ejecutado.</p> +<h2 id="Syntax" name="Syntax">Sintaxis</h2> +<pre class="syntaxbox">window.navigator.vibrate(<var>pattern</var>); +</pre> +<ul> + <li><code>pattern</code> proporciona un patrón de intervalos de vibración y pausas, como se describe a continuación.</li> +</ul> +<dl> + <dt> + pattern</dt> + <dd> + Proporciona un patrón de intervalos de vibraciones y pausas. Cada valor indica el número de milisegundos que durará la vibración y la pausa, respectivamente. Se puede porporcionar un valor único (en cuyo caso la vibración se ejecutará una vez, con la duración especificada en milisegundos) o un arreglo de valores (array) para alternar vibraciones y pausas. Ver <a href="/en-US/docs/WebAPI/Vibration" title="/en-US/docs/WebAPI/Vibration">Vibration API</a> para más detalles.</dd> +</dl> +<p>Si se especifica el valor 0, un array vacío o un array que contenga todos los valores en 0, se cancelarán todos los patrones de vibración que se estén ejecutando.</p> +<h2 id="Excepciones">Excepciones</h2> +<p>Podrá producirse una excepción si el patrón de vibración especificado es demasiado largo o si cualquiera de sus elementos son demasiado grandes.</p> +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> +<div> + {{CompatibilityTable}}</div> +<div id="compat-desktop"> + <table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatVersionUnknown}} {{property_prefix("webkit")}}</td> + <td> + <p>11.0 {{property_prefix("moz")}}</p> + <p>16 (no prefix)</p> + </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>Característica</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatVersionUnknown}} {{property_prefix("webkit")}}</td> + <td>11.0 {{property_prefix("moz")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> + </table> +</div> +<h2 id="Specification" name="Specification">Especificación</h2> +<ul> + <li>{{spec("http://www.w3.org/TR/vibration/", "Vibration API Specification", "WD")}}</li> +</ul> +<h2 id="Véase_también">Véase también</h2> +<ul> + <li><a href="/en-US/docs/WebAPI/Vibration" title="/en-US/docs/WebAPI/Vibration">Vibration API</a></li> +</ul> diff --git a/files/es/web/api/navigatorconcurrenthardware/hardwareconcurrency/index.html b/files/es/web/api/navigatorconcurrenthardware/hardwareconcurrency/index.html new file mode 100644 index 0000000000..ed2116fa94 --- /dev/null +++ b/files/es/web/api/navigatorconcurrenthardware/hardwareconcurrency/index.html @@ -0,0 +1,69 @@ +--- +title: navigator.hardwareConcurrency +slug: Web/API/NavigatorConcurrentHardware/hardwareConcurrency +translation_of: Web/API/NavigatorConcurrentHardware/hardwareConcurrency +--- +<p>{{APIRef("HTML DOM")}}</p> + +<p>{{AvailableInWorkers}}</p> + +<p>La propiedad <code><strong>navigator.hardwareConcurrency </strong></code>es de solo lectura navigator.hardwareConcurrency devuelve el número de procesadores lógicos disponibles para ejecutar subprocesos en la computadora del usuario.</p> + +<h2 id="Sintaxi">Sintaxi</h2> + +<pre class="syntaxbox"><em>logicalProcessors</em> = window.navigator.hardwareConcurrency +</pre> + +<h2 id="Valor">Valor</h2> + +<p>{{jsxref("Number")}} <span class="tlid-translation translation" lang="es"><span title="">indica el número de núcleos de procesadores lógicos.</span></span></p> + +<p><span class="tlid-translation translation" lang="es"><span title="">Las computadoras modernas tienen múltiples núcleos de procesadores físicos en su CPU (dos o cuatro núcleos son típicos), pero cada núcleo físico también puede ejecutar más de un subproceso a la vez utilizando técnicas avanzadas de programación.</span> <span title="">Por lo tanto, una CPU de cuatro núcleos puede ofrecer ocho núcleos de procesador lógico, por ejemplo.</span> <span title="">El número de núcleos de procesador lógico se puede utilizar para medir el número de subprocesos que se pueden ejecutar de manera efectiva a la vez sin que tengan que cambiar de contexto.</span></span></p> + +<p> <span class="tlid-translation translation" lang="es"><span title="">Sin embargo, el navegador puede optar por informar un número menor de núcleos lógicos para representar con mayor precisión el número de </span></span>{{domxref("Worker")}}s<span class="tlid-translation translation" lang="es"><span title=""> que pueden ejecutarse a la vez, así que no trate esto como una medida absoluta del número de núcleos en el sistema del usuario</span> <span title="">.</span></span></p> + +<h2 id="Ejemplos">Ejemplos</h2> + +<p>En este ejemplo, se crea un {{domxref ("Worker")}} para cada procesador lógico informado por el navegador y se crea un registro que incluye una referencia al nuevo worker, así como un valor booleano que indica si nosotros ' estoy usando ese worker todavía; Estos objetos, a su vez, se almacenan en una matriz para su uso posterior. Esto crea un grupo de workers que podemos usar para procesar solicitudes más adelante.</p> + +<pre class="brush: js">let workerList = []; + +for (let i = 0; i < window.navigator.hardwareConcurrency; i++) { + let newWorker = { + worker: new Worker('cpuworker.js'), + inUse: false + }; + workerList.push(newWorker); +}</pre> + +<h2 id="Specification">Specification</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-navigator-hardwareconcurrency', 'navigator.hardwareConcurrency')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("api.NavigatorConcurrentHardware.hardwareConcurrency")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{domxref("Navigator")}}</li> + <li>{{domxref("WorkerNavigator")}}</li> +</ul> diff --git a/files/es/web/api/navigatorconcurrenthardware/index.html b/files/es/web/api/navigatorconcurrenthardware/index.html new file mode 100644 index 0000000000..d7cee835c0 --- /dev/null +++ b/files/es/web/api/navigatorconcurrenthardware/index.html @@ -0,0 +1,71 @@ +--- +title: NavigatorConcurrentHardware +slug: Web/API/NavigatorConcurrentHardware +tags: + - API + - Concurrency + - HTML DOM + - Interface + - Navigator + - NavigatorCPU + - NavigatorConcurrentHardware + - NeedsBrowserCompatibility + - NeedsTranslation + - Reference + - Threading + - Threads + - TopicStub + - WorkerNavigator + - Workers +translation_of: Web/API/NavigatorConcurrentHardware +--- +<p>{{APIRef("HTML DOM")}}</p> + +<p>The <strong><code>NavigatorConcurrentHardware</code></strong> {{Glossary("mixin")}} adds to the {{domxref("Navigator")}} interface features which allow Web content to determine how many logical processors the user has available, in order to let content and Web apps optimize their operations to best take advantage of the user's CPU.</p> + +<p>{{AvailableInWorkers}}</p> + +<p>The number of <strong>logical processor cores</strong> is a way to measure the number of threads which can effectively be run at once without them having to share CPUs. Modern computers have multiple physical cores in their CPU (two or four cores is typical), but each physical core is also usually able to run more than one thread at a time using advanced scheduling techniques. So a four-core CPU may return 8. The browser may, however, choose to reduce the number in order to represent more accurately the number of {{domxref("Worker")}}s that can run at once</p> + +<h2 id="Properties">Properties</h2> + +<dl> + <dt>{{domxref("NavigatorConcurrentHardware.hardwareConcurrency")}} {{readonlyinline}}</dt> + <dd>Returns the number of logical processors which may be available to the user agent. This value is always at least 1, and will be 1 if the actual number of logical processors can't be determined.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<p><em>The <code>NavigatorConcurrentHardware</code></em><em> mixin has no methods.</em></p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('HTML WHATWG', '#navigatorconcurrenthardware', 'NavigatorConcurrentHardware')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("api.NavigatorConcurrentHardware")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{domxref("Navigator")}}</li> + <li>{{domxref("WorkerNavigator")}}</li> +</ul> diff --git a/files/es/web/api/navigatorgeolocation/geolocation/index.html b/files/es/web/api/navigatorgeolocation/geolocation/index.html new file mode 100644 index 0000000000..94c22ef6b0 --- /dev/null +++ b/files/es/web/api/navigatorgeolocation/geolocation/index.html @@ -0,0 +1,106 @@ +--- +title: window.navigator.geolocation +slug: Web/API/NavigatorGeolocation/geolocation +translation_of: Web/API/Navigator/geolocation +--- +<p>{{APIRef("Geolocation API")}}<br> + La propiedad de sólo lectura <strong><code>Navigator.geolocation</code></strong> devuelve un objeto <a href="https://developer.mozilla.org/es/docs/Web/API/Geolocation" title="La interfaz Geolocalización representa un objeto capaz de obtener mediante programación la posición del dispositivo. Se da acceso Web de la ubicación del dispositivo. Esto permite a un sitio Web o aplicación ofrecer resultados personalizados basados en la ubicación del usuario."><code>Geolocation</code></a> que proporciona acceso web a la ubicación de un dispositivo. Esto permite ofrecer al sitio web o aplicación resultados personalizados basados en la ubicación del usuario.</p> + +<div class="note"> +<p><strong>Nota:</strong> Por motivos de seguridad, cuando una página web trata de acceder a la información de ubicación, se solicita permiso al usuario. Cada navegador tiene sus propias reglas sobre cómo y cuándo obtener dicho permiso.</p> +</div> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><var>geo</var> = <var>navigator</var>.geolocation +</pre> + +<h2 id="Métodos">Métodos</h2> + +<dl> + <dt>{{domxref("geolocation.getCurrentPosition", "geolocation.getCurrentPosition()")}}</dt> + <dd>Utilizado para obtener la posición actual.</dd> + <dt>{{domxref("geolocation.watchPosition", "geolocation.watchPosition()")}}</dt> + <dd>Utilizado para asignar un manejador para dar seguimiento a cualquier cambio de ubicación.</dd> + <dt>{{domxref("geolocation.clearWatch", "geolocation.clearWatch()")}}</dt> + <dd>Utilizado para eliminar un manejador asignado a los cambios de ubicación.</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('Geolocation')}}</td> + <td>{{Spec2('Geolocation')}}</td> + <td>Especificación inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_navegadores">Compatibilidad en navegadores</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>5</td> + <td>{{CompatGeckoDesktop("1.9.1")}}</td> + <td>9</td> + <td>10.60<br> + {{CompatNo}} 15.0<br> + 16.0</td> + <td>5</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Chrome para Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>2.1</td> + <td>50</td> + <td>{{CompatGeckoMobile("4")}}</td> + <td>10</td> + <td>10.60</td> + <td>3.2</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="/docs/WebAPI/Using_geolocation" title="/en-US/docs/WebAPI/Using_geolocation">Utilizando la geolocalización</a></li> +</ul> diff --git a/files/es/web/api/navigatorgeolocation/index.html b/files/es/web/api/navigatorgeolocation/index.html new file mode 100644 index 0000000000..f9e540d902 --- /dev/null +++ b/files/es/web/api/navigatorgeolocation/index.html @@ -0,0 +1,106 @@ +--- +title: NavigatorGeolocation +slug: Web/API/NavigatorGeolocation +tags: + - API +translation_of: Web/API/Geolocation +--- +<p>{{APIRef("Geolocation API")}}</p> + +<p><code><strong>NavigatorGeolocation</strong></code> contains a creation method allowing objects implementing it to obtain a {{domxref("Geolocation")}} instance.</p> + +<p>There is no object of type <code>NavigatorGeolocation</code>, but some interfaces, like {{domxref("Navigator")}} implements it.</p> + +<h2 id="Properties">Properties</h2> + +<p><em>The <code>NavigatorGeolocation</code></em><em> interface doesn't inherit any property.</em></p> + +<dl> + <dt>{{domxref("NavigatorGeolocation.geolocation")}} {{readonlyInline}}</dt> + <dd>Returns a {{domxref("Geolocation")}} object allowing accessing the location of the device.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<p><em>The </em><em><code>NavigatorGeolocation</code></em><em> interface neither implements, nor inherit any method.</em></p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('Geolocation', '#navi-geo', 'NavigatorGeolocation')}}</td> + <td>{{Spec2('Geolocation')}}</td> + <td>Initial specification.</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>5</td> + <td>{{CompatGeckoDesktop("1.9.1")}}</td> + <td>9</td> + <td>10.60<br> + Removed in 15.0<br> + Reintroduced in 16.0</td> + <td>5</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>{{CompatUnknown()}}</td> + <td>{{CompatUnknown()}}</td> + <td>{{CompatGeckoMobile("4")}}</td> + <td>{{CompatUnknown()}}</td> + <td>10.60</td> + <td>{{CompatUnknown()}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/WebAPI/Using_geolocation" title="/en-US/docs/WebAPI/Using_geolocation">Using geolocation.</a></li> +</ul> + +<p> </p> diff --git a/files/es/web/api/navigatorlanguage/index.html b/files/es/web/api/navigatorlanguage/index.html new file mode 100644 index 0000000000..7d6b0751e7 --- /dev/null +++ b/files/es/web/api/navigatorlanguage/index.html @@ -0,0 +1,148 @@ +--- +title: NavigatorLanguage +slug: Web/API/NavigatorLanguage +tags: + - API + - HTML-DOM + - NeedsTranslation + - No Interface + - Reference + - TopicStub +translation_of: Web/API/NavigatorLanguage +--- +<p>{{APIRef("HTML DOM")}}</p> + +<p><code><strong>NavigatorLanguage</strong></code> contains methods and properties related to the language of the navigator.</p> + +<p>There is no object of type <code>NavigatorLanguage</code>, but other interfaces, like {{domxref("Navigator")}} or {{domxref("WorkerNavigator")}}, implement it.</p> + +<h2 id="Properties">Properties</h2> + +<p><em>The <code>NavigatorLanguage</code></em><em> interface doesn't inherit any property.</em></p> + +<dl> + <dt>{{domxref("NavigatorLanguage.language")}} {{readonlyInline}}</dt> + <dd>Returns a {{domxref("DOMString")}} representing the preferred language of the user, usually the language of the browser UI. The <code>null</code> value is returned when this is unknown.</dd> + <dt>{{domxref("NavigatorLanguage.languages")}} {{readonlyInline}}</dt> + <dd>Returns an array of {{domxref("DOMString")}} representing the languages known to the user, by order of preference.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<p><em>The </em><em><code>NavigatorLanguage</code></em><em> interface neither implements, nor inherit any method.</em></p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('HTML WHATWG', '#navigatorlanguage', 'NavigatorLanguage')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>Since the {{SpecName('HTML5 W3C')}} snapshot, the <code>languages</code> property has been added.</td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', '#navigatorlanguage', 'NavigatorLanguage')}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>Initial specification; snapshot of an early version{{SpecName('HTML WHATWG')}}.</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>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>languages</code></td> + <td>37</td> + <td>{{CompatGeckoDesktop("32")}}</td> + <td>{{CompatNo}}</td> + <td>24</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>on {{domxref("WorkerNavigator")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("35")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</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>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>languages</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}} </td> + <td>{{CompatGeckoMobile("32")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>on {{domxref("WorkerNavigator")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("35")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>The {{domxref("Navigator")}} interface that implements it.</li> +</ul> diff --git a/files/es/web/api/navigatorlanguage/language/index.html b/files/es/web/api/navigatorlanguage/language/index.html new file mode 100644 index 0000000000..a8c388b631 --- /dev/null +++ b/files/es/web/api/navigatorlanguage/language/index.html @@ -0,0 +1,133 @@ +--- +title: NavigatorLanguage.language +slug: Web/API/NavigatorLanguage/language +tags: + - API + - Gecko + - Idioma + - Lenguaje + - NavigatorLanguage + - Propiedad + - Referencia + - Referencia DOM de Gecko + - Solo lectura +translation_of: Web/API/NavigatorLanguage/language +--- +<div>{{APIRef("HTML DOM")}}</div> + +<p>La propiedad de solo lectura <strong><code>NavigatorLanguage.language</code></strong> devuelve un string representando el lenguaje predefinido del usuario, generalmente es el lenguaje configurado para la interfaz del navegador.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">lang = globalObj.navigator.language +</pre> + +<h3 id="Valores">Valores</h3> + +<p><code>Un string que representa el código del lenguaje standard como se define en la</code> <a class="external" href="http://www.ietf.org/rfc/bcp/bcp47.txt">BCP 47</a>. Ejemplos de códigos válidos de lenguaje incluyen: "en", "en-US", "fr", "es-ES", etc.</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush: js">if (window.navigator.language != "en") { + doLangSelect(window.navigator.language); +} +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{ SpecName('HTML5.1', '#dom-navigator-language', 'NavigatorLanguage.language') }}</td> + <td>{{ Spec2('HTML5.1') }}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_navegadores">Compatibilidad en navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatVersionUnknown}}<sup>[1]</sup></td> + <td>{{CompatGeckoDesktop("1.0")}}<sup>[2]</sup><br> + {{CompatGeckoDesktop("5.0")}}<sup>[3]</sup></td> + <td>11.0<sup>[4]</sup></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>sobre {{domxref("WorkerNavigator")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("35")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile(1.0)}}</td> + <td>{{CompatNo}}<sup>[4]</sup></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>sobre {{domxref("WorkerNavigator")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("35")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Devuelve el lenguaje configurado para la interfaz del navegador, no el valor de la <strong><code>Accept-Language</code></strong> <a href="/en-US/docs/Web/HTTP/Headers">HTTP header</a>.</p> + +<p>[2] Antes de Gecko 2.0 {{geckoRelease("2.0")}}, el valor de esta propiedad fue también parte de la cadena de <strong>user agent</strong>, como se informa en {{domxref("window.navigator.userAgent", "navigator.userAgent")}}.</p> + +<p>[3] A partir de Gecko 5.0 {{geckoRelease("5.0")}}, el valor de esta propiedad está basada en el valor de la <strong><code>Accept-Language</code></strong> <a href="en-US/docs/Web/HTTP/Headers">HTTP header</a>.</p> + +<p>[4] Otras propiedades disponibles (no estandarizadas) son: <code><a href="http://msdn.microsoft.com/en-us/library/ie/ms534713.aspx">userLanguage</a></code> y <code><a href="http://msdn.microsoft.com/en-us/library/ie/ms533542.aspx">browserLanguage</a></code>.</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("NavigatorLanguage.languages", "navigator.languages")}}</li> + <li>{{domxref("navigator")}}</li> +</ul> diff --git a/files/es/web/api/navigatoronline/eventos_online_y_offline/index.html b/files/es/web/api/navigatoronline/eventos_online_y_offline/index.html new file mode 100644 index 0000000000..d4f8a77824 --- /dev/null +++ b/files/es/web/api/navigatoronline/eventos_online_y_offline/index.html @@ -0,0 +1,91 @@ +--- +title: Eventos online y offline +slug: Web/API/NavigatorOnLine/Eventos_online_y_offline +tags: + - AJAX + - DOM + - Desarrollo_Web + - Todas_las_Categorías +translation_of: Web/API/NavigatorOnLine/Online_and_offline_events +--- +<p>{{ Fx_minversion_header(3) }} +<a href="es/Firefox_3_para_desarrolladores">Firefox 3</a> implementa <a class="external" href="http://www.whatwg.org/specs/web-apps/current-work/#offline">eventos Online/Offline</a> de la <a class="external" href="http://www.whatwg.org/specs/web-apps/current-work/">especificacióbn WHATWG Web Applications 1.0</a>. +</p> +<h3 id="Descripci.C3.B3n" name="Descripci.C3.B3n"> Descripción </h3> +<p>Para poder construir una aplicación web offline-funcional, necesitas conocer cuándo está tu aplicación realmente offline. Además, también necesitas conocer cuándo vuelve la aplicación al estado 'online' nuevamente. A efectos prácticos, los requisitos son los siguientes: +</p> +<ol><li> Necesitas conocer cuándo el usuario vuelve a estar online, para que puedas re-sincronizar con el servidor. +</li><li> Necesitas conocer cuándo el usuario está offline, para así estar seguro de poner en cola las peticiones al servidor para más tarde. +</li></ol> +<p>Es este proceso el que los eventos online/offline ayudan a trivializar. +</p><p>Tu aplicación web quizás necesite establecer que ciertos documentos se mantengan en la caché de recursos offline. Para hacerlo, incluye elementos <code>LINK</code> en tu sección <code>HEAD</code> de la siguiente manera: +</p> +<pre class="eval"><span class="nowiki"><link rel="offline-resource" href="mi_recurso></span> +</pre> +<p>Cuando Firefox 3 o superiores procesan el HTML, esto causará que el recurso referenciado se mantenga en caché para su uso offline en un recurso especial de la caché. +</p> +<h3 id="API" name="API"> API </h3> +<h4 id="navigator.onLine" name="navigator.onLine"> <code>navigator.onLine</code> </h4> +<p><code><a href="es/DOM/window.navigator.onLine">navigator.onLine</a></code> es una propiedad que mantiene un valor <code>true</code>/<code>false</code> (<code>true</code> para online, <code>false</code> para offline). Esta propiedad se actualiza siempre que el usuario cambia hacia "Modo sin conexión" seleccionando el menú correspondiente (Archivo -> Trabajar sin conexión en Firefox). +</p><p>Además, esta propiedad se debería actualizar siempre que el navegador no sea capaz de conectarse a la red. De acuerdo con la especificación: +</p> +<blockquote> +El atributo <code>navigator.onLine</code> debe devolver false si el agente de usuario no contactará con la red cuando el usuario siga los enlaces o cuando un script solicite una página remota (o sepa que intentarlo fallaría)... +</blockquote> +<p>Firefox 2 actualiza esta propiedad cuando cambia desde/hacia el modo offline del navegador, y cuando pierde/recupera la conectividad de la red en Windows y Linux. +</p><p>Esta propiedad existía en versiones más antiguas de Firefox e Internet Explorer (la especificación surgió a partir estas implementaciones previas), así que puedes comenzar a usarla inmediatamente. La detección automática del estado de la red se implementó en Firefox 2. +</p> +<h4 id="eventos_.22online.22_y_.22offline.22" name="eventos_.22online.22_y_.22offline.22"> eventos "<code>online</code>" y "<code>offline</code>" </h4> +<p><a href="es/Firefox_3_para_desarrolladores">Firefox 3</a> introduce dos nuevos eventos: "<code>online</code>" y "<code>offline</code>". Estos dos eventos son iniciados en el <code><body></code> de cada página cuando el usuario cambia de modo online a offline. Además, los eventos emergen desde <code>document.body</code> a <code>document</code>, terminando en <code>window</code>. Ambos eventos son no-cancelables (no se puede evitar que el usuario pase a modo online u offline). +</p><p>Puedes registrar <i>listeners</i> para estos eventos de varias maneras habituales: +</p> +<ul><li> Usando <code><a href="es/DOM/element.addEventListener">addEventListener</a></code> en <code>window</code>, <code>document</code> o <code>document.body</code> +</li><li> estableciendo las propiedades <code>.ononline</code> u <code>.onoffline</code> en <code>document</code> o <code>document.body</code> para que apunten a un objeto JavaScript <code>Function</code> (<b>Nota:</b> usar <code>window.ononline</code> o <code>window.onoffline</code> no funcionará por razones de compatibilidad). +</li><li> especificando los atributos <code>ononline="..."</code> u <code>onoffline="..."</code> en la etiqueta <code><body></code> en el código HTML. +</li></ul> +<h3 id="Ejemplo:" name="Ejemplo:"> Ejemplo: </h3> +<p>Hay una <a class="link-https" href="https://bugzilla.mozilla.org/attachment.cgi?id=220609">prueba sencilla</a> que puedes ejecutar para verificar que los eventos están funcionando. +</p><p><span class="comment"> +</span></p> +<pre class="eval"> <!doctype html> + <html> + <head> + <script> + function updateOnlineStatus(msg) { + var status = document.getElementById("status"); + var condition = navigator.onLine ? "ONLINE" : "OFFLINE"; + status.setAttribute("class", condition); + var state = document.getElementById("state"); + state.innerHTML = condition; + var log = document.getElementById("log"); + log.appendChild(document.createTextNode("Event: " + msg + "; status=" + condition + "\n")); + } + function loaded() { + updateOnlineStatus("load"); + document.body.addEventListener("offline", function () { + updateOnlineStatus("offline") + }, false); + document.body.addEventListener("online", function () { + updateOnlineStatus("online") + }, false); + } + </script> + <style>...</style> + </head> + <body onload="loaded()"> + <div id="status"><p id="state"></p></div> + <div id="log"></div> + </body> + </html> +</pre> +<h3 id="Referencias" name="Referencias"> Referencias </h3> +<ul><li> <a class="external" href="http://www.whatwg.org/specs/web-apps/current-work/#offline">Sección 'Eventos Online/Offline ' de la especificación WHATWG Web Applications 1.0 </a> +</li><li> <a class="link-https" href="https://bugzilla.mozilla.org/show_bug.cgi?id=336359">El bug que documenta la implementación de los eventos online/offline en Firefox </a> y un enlace <a class="link-https" href="https://bugzilla.mozilla.org/show_bug.cgi?id=336682">con una modificación posterior</a> +</li><li> <a class="link-https" href="https://bugzilla.mozilla.org/attachment.cgi?id=220609">Un ejemplo sencillo</a> +</li><li> <a class="external" href="http://ejohn.org/blog/offline-events/">Una explicación de los eventos Online/Offline</a> +</li></ul> +<p><br> +</p> +<div class="noinclude"> +</div> +{{ languages( { "en": "en/Online_and_offline_events", "fr": "fr/\u00c9v\u00e8nements_online_et_offline", "ja": "ja/Online_and_offline_events", "pl": "pl/Zdarzenia_online_i_offline", "pt": "pt/Eventos_online_e_offline" } ) }} diff --git a/files/es/web/api/navigatoronline/index.html b/files/es/web/api/navigatoronline/index.html new file mode 100644 index 0000000000..7aa4d6c0e1 --- /dev/null +++ b/files/es/web/api/navigatoronline/index.html @@ -0,0 +1,133 @@ +--- +title: NavigatorOnLine +slug: Web/API/NavigatorOnLine +tags: + - API + - HTML-DOM + - NeedsTranslation + - TopicStub +translation_of: Web/API/NavigatorOnLine +--- +<p>{{APIRef("HTML DOM")}}</p> + +<p>The <code><strong>NavigatorOnLine</strong></code> interface contains methods and properties related to the connectivity status of the browser.</p> + +<p>There is no object of type <code>NavigatorOnLine</code>, but other interfaces, like {{domxref("Navigator")}} or {{domxref("WorkerNavigator")}}, implement it.</p> + +<h2 id="Properties">Properties</h2> + +<p><em>The <code>NavigatorOnLine</code></em><em> interface doesn't inherit any property.</em></p> + +<dl> + <dt>{{domxref("NavigatorOnLine.onLine")}} {{readonlyInline}}</dt> + <dd>Returns a {{domxref("Boolean")}} indicating whether the browser is working online.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<p><em>The </em><em><code>NavigatorOnLine</code></em><em> interface neither implements, nor inherit any method.</em></p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('HTML WHATWG', '#navigatoronline', 'NavigatorOnLine')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>No change from the latest snapshot, {{SpecName('HTML5 W3C')}}</td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', '#navigatoronline', 'NavigatorOnLine')}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>Snapshot of {{SpecName('HTML WHATWG')}} with its initial specification.</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>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>on {{domxref("WorkerNavigator")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop(29)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</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>Edge</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}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>on {{domxref("WorkerNavigator")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile(29)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>The {{domxref("Navigator")}} interface that implements it.</li> +</ul> diff --git a/files/es/web/api/navigatoronline/online/index.html b/files/es/web/api/navigatoronline/online/index.html new file mode 100644 index 0000000000..cc74bdbb8b --- /dev/null +++ b/files/es/web/api/navigatoronline/online/index.html @@ -0,0 +1,166 @@ +--- +title: Navigator.onLine +slug: Web/API/NavigatorOnLine/onLine +translation_of: Web/API/NavigatorOnLine/onLine +--- +<div>{{ApiRef("HTML DOM")}}</div> + +<p>Retorna el estado en línea del navegador. La propiedad retorna un valor booleano, <code>true</code> significa <strong>en línea</strong> y <code>false</code> significa <strong>desconectado</strong>. La propiedad envía actualizaciones siempre que el navegador tenga la capacidad de conectarse a los cambios de red. La actualización se produce cuando un usuario sigue un enlace o cuando un script pide una pagina remota. Por ejemplo, la propiedad debe retornar <code>false</code> cuando los usuarios hacen clic en un enlace poco después de perder la conexión a internet.</p> + +<p>Los navegadores implementan esta propiedad de forma diferente.</p> + +<p>En Chrome y Safari, si el navegador no puede conectarse a la red de area local (LAN) o al router, está <code>desconectado</code>; todas las otras condiciones retornan <code>true</code>. Así que puedes suponer que el navegador esta desconectado cuando retorna un valor <code>false</code>, no puedes suponer que un valor <code>true</code> signifique que el navegador puede acceder a internet. Podrías estar recibiendo falsos positivos, como en los casos en el que el ordenador este ejecutando un software de virtualización que tiene los adaptadores ethernet virtuales siempre "conectados". Por lo tanto, si tu quieres determinar el estado en linea de el navegador, tu debes desarrollar medios adicionales para comprobarlo. Para más información, consulte el artículo HTML5 Rocks article, <a href="http://www.html5rocks.com/en/mobile/workingoffthegrid.html"> Working Off the Grid</a>.</p> + +<p>En Firefox e Internet Explorer, cambiando el navegador al modo desconectado envía un valor <code>false</code>. Hasta Firefox 41, todas las demás condiciones retornaban un valor <code>true</code>; desde Firefox 41, en OS X y Windows, el valor sigue la actual conectividad de red.</p> + +<p>Puedes ver los cambios en el estado de red escuchando los eventos <code><a href="/en-US/docs/Web/API/document.ononline">window.ononline</a> y </code><code><a href="https://developer.mozilla.org/en-US/docs/Web/API/document.onoffline">window.onoffline</a>.</code></p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><em>online</em> = <em>window</em>.navigator.onLine; +</pre> + +<h3 id="Valor">Valor</h3> + +<p><code>online</code> es booleano <code>true</code> o <code>false</code>.</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>Ver <a href="http://html5-demos.appspot.com/static/navigator.onLine.html">ejemplo en linea</a>.</p> + +<p>Para comprobar que estas es linea, consulte <code>window.navigator.onLine</code>, como en el siguiente ejemplo: </p> + +<pre class="brush: js">if (navigator.onLine) { + console.log('online'); +} else { + console.log('offline'); +}</pre> + +<p>Si el navegador no soporta <code>navigator.onLine</code> el ejemplo anterior siempre devolvera <code>false</code>/<code>undefined</code>.</p> + +<p>Para ver los cambios en el estado de la red, use <code><a href="/es/docs/Web/API/EventTarget/addEventListener">addEventListener</a></code> para escuchar los eventos <code>window.ononline</code> y <code>window.onoffline</code>, como en el siguiente ejemplo:</p> + +<pre class="brush: js">window.addEventListener('offline', function(e) { console.log('offline'); }); + +window.addEventListener('online', function(e) { console.log('online'); }); +</pre> + +<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("HTML WHATWG", "browsers.html#navigator.online", "navigator.onLine")}}</td> + <td>{{Spec2("HTML WHATWG")}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}<sup>[1]</sup></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(1.9.1)}}<sup>[2]</sup><br> + {{CompatGeckoDesktop(2.0)}}<sup>[4]</sup></td> + <td>8<sup>[3]</sup></td> + <td>{{CompatNo}}<sup>[2]</sup></td> + <td>5.0.4</td> + </tr> + <tr> + <td>on {{domxref("WorkerNavigator")}}</td> + <td>Yes</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop(29)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>BlackBerry</th> + </tr> + <tr> + <td>Basic support</td> + <td>2.2<sup>[5]</sup></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile(1.9.1)}}<sup>[2]</sup></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td> + <p>7<br> + 10</p> + </td> + </tr> + <tr> + <td>on {{domxref("WorkerNavigator")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile(29)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Earlier versions of Chrome incorrectly return <code>true</code> when a tab is first opened, but it starts reporting the correct connectivity status after the first network event. Windows: 11, Mac: 14, Chrome OS: 13, Linux: Always returns <code>true</code>. For history, see <a href="http://crbug.com/7469">crbug.com/7469</a>.</p> + +<p>[2] Since Firefox 4, and Opera 11.10, the browser returns <code>true</code> when "Work Offline" mode is disabled and <code>false</code> when it is enabled, regardless of actual connectivity.</p> + +<p>[3] in Internet Explorer 8 "online" and "offline" events are raised on the <code>document.body</code>; under IE 9 they are raised on both <code>document.body</code> and <code>window</code>.</p> + +<p>[4] Since Firefox 41, on OS X and Windows, the returned values follow the actual network connectivity, unless "Work offline" mode is selected (where it will always return <code>false</code>).</p> + +<p>[5] Faulty in a WebView component, see Issue <a href="http://code.google.com/p/android/issues/detail?id=16760">bug 16760</a>.</p> + +<h2 id="Notas">Notas</h2> + +<p>See <a href="/en-US/docs/Online_and_offline_events">Online/Offline Events</a> for a more detailed description of this property as well as new offline-related features introduced in Firefox 3.</p> + +<h2 id="Véase_también">Véase también</h2> + +<ul> + <li><a href="http://www.html5rocks.com/en/mobile/workingoffthegrid.html">HTML5 Rocks: Working Off the Grid With HTML5 Offline</a></li> + <li><a href="http://www.html5rocks.com/en/tutorials/offline/whats-offline/">HTML5 Rocks: "Offline": What does it mean and why should I care?</a></li> + <li><a href="http://hacks.mozilla.org/2010/01/offline-web-applications/">Mozilla Blog: Offline Web Applications</a></li> +</ul> diff --git a/files/es/web/api/network_information_api/index.html b/files/es/web/api/network_information_api/index.html new file mode 100644 index 0000000000..07b3d3e3a7 --- /dev/null +++ b/files/es/web/api/network_information_api/index.html @@ -0,0 +1,93 @@ +--- +title: Network Information API +slug: Web/API/Network_Information_API +tags: + - API + - Experimental + - JSAPI Reference + - Referencia +translation_of: Web/API/Network_Information_API +--- +<p>{{DefaultAPISidebar("Network Information API")}}{{SeeCompatTable}}</p> + +<p>La Network Information (Información de red) API provee información sobre el sistema de conexión en términos genéricos de tipos de conexión (ej., 'wifi', 'cellular', etc.). Esta puede ser usada para elegir contenido en alta definición o contenido baja definición basándose en la conexión del usuario. Toda la API consiste en la adición de la {{domxref("NetworkInformation")}} interfaz y una única propiedad para la {{domxref("Navigator")}} interfaz: {{domxref("Navigator.connection")}}.</p> + +<p>{{AvailableInWorkers}}</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Detectar_cambios_de_conexiónThis_example_watches_for_changes_to_the_users_connection."><span style="">Detectar cambios de conexión</span><span style="">This example watches for changes to the user's connection.</span></h3> + +<pre class="brush: js notranslate">var conexion = navigator.connection || navigator.mozConnection || navigator.webkitConnection; +var tipo = connection.effectiveType; + +function updateConnectionStatus() { + console.log("Connection type changed from " + tipo + " to " + conexion.effectiveType); + tipo = conexion.effectiveType; +} + +conexion.addEventListener('change', updateConnectionStatus); +</pre> + +<h3 id="Precargar_recursos_grandes"><span style="">Precargar recursos grandes</span></h3> + +<p><span style="">El objeto de conexión es muy útil por ir decidiendo entre precargar recursos que ocupan mucho ancho de banda o memoria. Este ejemplo puede ser llamado justo después de que la página cargue para verificar el tipo de conexión donde precargar un video tal vez no sea lo deseado.Si se detecta la conexión de un celular, entonces el </span><code style="">preloadVideo</code><span style=""> flag está seteado en </span><code style="">false</code><span style="">. Para simplificación y claridad, este ejemplo sólo testea un tipo de conexión. Una real-word usa case probablemente una declaración de switch o otro método para verificar todos los posibles valores de</span> {{domxref("NetworkInformation.type")}}.<span style=""> <br> + <br> + en caso usaría una declaración de switch o algún otro método para verificar todos los valores posibles de<br> + use case would likely use a switch statement or some other method to check all of the possible values of {{domxref("NetworkInformation.type")}}. </span>Independientemente del valor de tipo, puede obtener una estimación de la velocidad de conexión a través de la propiedad<span style=""> {{domxref("NetworkInformation.effectiveType")}}.</span></p> + +<pre class="brush: js notranslate">let precargarVideo = true; +var connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection; +if (connection) { + if (connection.effectiveType === 'slow-2g') { + precargarVideo = false; + } +}</pre> + +<h2 id="Interfaces">Interfaces</h2> + +<dl> + <dt>{{domxref("NetworkInformation")}}</dt> + <dd>Provee información sobre la conexión de un dispositivo si está usándose para cominicarse con la red y proveer un tipo de scripts para ser notificado si el tipo de conexión cambia. La intefaz de <code>NetworkInformation</code> no puede ser inicializada. En lugar de esto, se accede a través de la interfaz {{domxref("Navigator")}}.</dd> +</dl> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especifiación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('Network Information', '', 'Network Information API')}}</td> + <td>{{Spec2('Network Information')}}</td> + <td>Initial specification</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_Navegadores">Compatibilidad en Navegadores</h2> + +<h3 id="NetworkInformation">NetworkInformation</h3> + +<div class="hidden">La tabla de compatibilidad de esta página se genera a partir de datos estructurados. Si usted desea contribuir con datos, por favor acceda a <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> y envíenos una solicitud de pull.</div> + +<p>{{Compat("api.NetworkInformation")}}</p> + +<h3 id="Navigator.connection">Navigator.connection</h3> + +<div class="hidden">La tabla de compatibilidad de esta página se genera a partir de datos estructurados. Si usted desea contribuir con datos, por favor acceda a <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> y envíenos una solicitud de pull.</div> + +<p>{{Compat("api.Navigator.connection")}}</p> + +<h2 id="Véase_también">Véase también</h2> + +<ul> + <li>{{spec("http://w3c.github.io/netinfo/", "Network Information API Specification", "ED")}}</li> + <li><a href="/en-US/docs/Online_and_offline_events">Online and offline events</a></li> + <li>{{domxref("Navigator.connection", "window.navigator.connection")}}</li> +</ul> diff --git a/files/es/web/api/node/appendchild/index.html b/files/es/web/api/node/appendchild/index.html new file mode 100644 index 0000000000..a72eb7d6c3 --- /dev/null +++ b/files/es/web/api/node/appendchild/index.html @@ -0,0 +1,113 @@ +--- +title: Nodo appendChild +slug: Web/API/Node/appendChild +tags: + - API + - DOM + - Node + - Referencia + - metodo +translation_of: Web/API/Node/appendChild +--- +<div>{{APIRef("DOM")}}</div> + +<p>Agrega un nuevo nodo al final de la lista de un elemento hijo de un elemento padre especificado.</p> + +<p>Si el hijo(Child) <strong>es una referencia</strong>(hace referencia) hacia un nodo existente en el documento actual, este es quitado del padre actual para ser puesto en el nodo padre nuevo. La clave está en <strong>si el (Child) es una referencia a un nodo existente en el documento</strong>.</p> + +<div class="blockIndicator note"> +<p><strong>Nueva API disponible </strong><br> + El método {{domxref("ParentNode.append()")}} soporta varios argumentos y cadenas para adjuntar.</p> +</div> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><em>element</em>.appendChild(<em>aChild</em>);</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><strong>aChild</strong></dt> + <dd>El nodo a adjuntar al nodo padre proporcionado (normalmente un elemento).</dd> +</dl> + +<h3 id="Valor_de_retorno">Valor de retorno</h3> + +<p>El valor devuelto es el hijo adjunto excepto cuando el hijo proporcionado es un {{domxref("DocumentFragment")}}, en cuyo caso el {{domxref("DocumentFragment")}} vacío es devuelto.</p> + +<h2 id="Notas">Notas</h2> + +<p>El encadenamiento podría no funcionar como se espera debido a que <code>appendChild()</code> devuelve un elemento hijo:</p> + +<pre class="brush: js">var aBlock = doc.createElement('block').appendChild(doc.createElement('b'));</pre> + +<p>Establece <code>aBlock</code> como <code><b></b></code> sólo, que no es probablemente lo que quieras.</p> + +<p>Si el <code>child</code> hace una referencia a un nodo existente en el documento, el método <code>appendChild</code> se mueve de su posición actual a su nueva posición (ej. no existen requerimientos para eliminar el nodo desde su nodo padre antes de añadirlo a cualquier otro nodo).</p> + +<p>Ésto significa también que el nodo no puede estar en dos puntos del documento de manera simultánea. Así que si el nodo ya contiene un padre, primero es eliminado, y después se añade a la nueva posición.</p> + +<p>Se puede usar {{domxref("Node.cloneNode")}} para hacer una copia del nodo antes de añadirlo debajo de su nuevo elemento padre. (Nota: las copias echas con <code>cloneNode</code> no serán guardadas automáticamente en sincronía.)</p> + +<p>Éste método no es permitido para mover nodos entre distintos documentos. Si se quiere añadir un nodo desde un documento diferente (por ejemplo para mostrar los resultados de una petición AJAX) se debe usar primero:<br> + {{domxref("document.importNode")}}.</p> + +<p><code>appendChild()</code> Es uno de los métodos fundamentales de la programación web usando el DOM. El método <code>appendChild()</code> inserta un nuevo nodo dentro de la estructura DOM de un documento, y es la segunda parte del proceso central uno-dos, crear-y-añadir para construir páginas web a base de programación.</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush:js">// Crea un nuevo elemento párrafo, y lo agrega al final del cuerpo del documento +var p = document.createElement("p"); +document.body.appendChild(p);</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especifación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('DOM WHATWG', '#dom-node-appendchild', 'Node.appendChild()')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Sin cambio desde {{SpecName("DOM3 Core")}}.</td> + </tr> + <tr> + <td>{{SpecName('DOM3 Core', 'core.html#ID-184E7107', 'Node.appendChild()')}}</td> + <td>{{Spec2('DOM3 Core')}}</td> + <td>Sin cambio desde {{SpecName("DOM2 Core")}}.</td> + </tr> + <tr> + <td>{{SpecName('DOM2 Core', 'core.html#ID-184E7107', 'Node.appendChild()')}}</td> + <td>{{Spec2('DOM2 Core')}}</td> + <td>Sin cambio desde {{SpecName("DOM1")}}.</td> + </tr> + <tr> + <td>{{SpecName('DOM1', 'level-one-core.html#ID-184E7107', 'Node.appendChild()')}}</td> + <td>{{Spec2('DOM1')}}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<div> + + +<p>{{Compat("api.Node.appendChild")}}</p> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("Node.removeChild")}}</li> + <li>{{domxref("Node.replaceChild")}}</li> + <li>{{domxref("Node.insertBefore")}}</li> + <li>{{domxref("Node.hasChildNodes")}}</li> + <li>{{domxref("ParentNode.append()")}}</li> +</ul> diff --git a/files/es/web/api/node/childnodes/index.html b/files/es/web/api/node/childnodes/index.html new file mode 100644 index 0000000000..567cd9fd08 --- /dev/null +++ b/files/es/web/api/node/childnodes/index.html @@ -0,0 +1,103 @@ +--- +title: Node.childNodes +slug: Web/API/Node/childNodes +tags: + - API + - DOM + - Propiedad + - Referencia + - Referência DOM +translation_of: Web/API/Node/childNodes +--- +<div> +<div>{{APIRef("DOM")}}</div> +</div> + +<p>La propiedad de solo lectura <code><strong>Node.childNodes</strong></code> devuelve una colección de hijos {{domxref("Node","nodes")}} del elemento dado donde el primer nodo hijo es asignado un índice 0.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var <var>nodeList</var> = <var>elementNodeReference</var>.childNodes; +</pre> + +<h2 id="Ejemplos">Ejemplos</h2> + +<h3 id="Uso_simple">Uso simple</h3> + +<pre class="brush:js">// parg is an object reference to a <p> element + +// First check that the element has child nodes +if (parg.hasChildNodes()) { + var children = parg.childNodes; + + for (var i = 0; i < children.length; i++) { + // do something with each child as children[i] + // NOTE: List is live, adding or removing children will change the list + } +}</pre> + +<h3 id="Eliminar_todos_los_hijos_de_un_nodo">Eliminar todos los hijos de un nodo</h3> + +<pre class="brush:js">// This is one way to remove all children from a node +// box is an object reference to an element + +while (box.firstChild) { + //The list is LIVE so it will re-index each call + box.removeChild(box.firstChild); +}</pre> + +<h2 id="Notas">Notas</h2> + +<p>Los items en una colección de nodos son objetos y no cadenas de caracteres. Para obtener los datos de los objetos del nodo, use sus propiedades (ej. <code>elementNodeReference.childNodes[1].nodeName</code> para obtener el nombre, etc.).</p> + +<p>El objeto <code>document</code> contiene 2 hijos: la declaración del Doctype y el elemento raíz, generalmente referido como <code>documentElement</code>. (En documentos (X)HTML es el elemento <code>HTML</code>)</p> + +<p><code>childNodes</code> incluye todos los nodos hijos, incluidos los nodos no elementos, como nodos de tipo textos y comentarios. Para obtener una colección de solo elementos, use {{domxref("ParentNode.children")}}.</p> + +<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">Comentarios</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('DOM WHATWG', '#dom-node-childnodes', 'Node.childNodes')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Sin cambios</td> + </tr> + <tr> + <td>{{SpecName('DOM3 Core', 'core.html#ID-1451460987', 'Node.childNodes')}}</td> + <td>{{Spec2('DOM3 Core')}}</td> + <td>Sin cambios</td> + </tr> + <tr> + <td>{{SpecName('DOM2 Core', 'core.html#ID-1451460987', 'Node.childNodes')}}</td> + <td>{{Spec2('DOM2 Core')}}</td> + <td>Sin cambios</td> + </tr> + <tr> + <td>{{SpecName('DOM1', 'level-one-core.html#ID-1451460987', 'Node.childNodes')}}</td> + <td>{{Spec2('DOM1')}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<p>{{Compat("api.Node.childNodes")}}</p> + +<h2 id="Vea_también">Vea también</h2> + +<ul> + <li>{{domxref("Node.firstChild")}}</li> + <li>{{domxref("Node.lastChild")}}</li> + <li>{{domxref("Node.nextSibling")}}</li> + <li>{{domxref("Node.previousSibling")}}</li> + <li>{{domxref("ParentNode.children")}}</li> +</ul> diff --git a/files/es/web/api/node/clonenode/index.html b/files/es/web/api/node/clonenode/index.html new file mode 100644 index 0000000000..0fb78af5dd --- /dev/null +++ b/files/es/web/api/node/clonenode/index.html @@ -0,0 +1,91 @@ +--- +title: Node.cloneNode() +slug: Web/API/Node/cloneNode +tags: + - API + - DOM + - Referencia + - Referência DOM + - metodo +translation_of: Web/API/Node/cloneNode +--- +<div>{{APIRef("DOM")}}</div> + +<p>El método <strong><code>Node.cloneNode()</code></strong> devuelve un duplicado del nodo en el que este método fue llamado.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var <em><var>dupNode</var></em> = <em><var>node</var></em>.cloneNode(<em><var>deep</var></em>); +</pre> + +<dl> + <dt><em>node</em></dt> + <dd>El nodo que se desea clonar.</dd> + <dt><em>dupNode</em></dt> + <dd>El nuevo nodo que será un clon de <code>node</code></dd> + <dt><em>deep {{optional_inline}}</em></dt> + <dd><code>true</code> si los hijos del nodo también deben ser clonados, o <code>false</code> para clonar únicamente al nodo.</dd> +</dl> + +<div class="note"> +<p><strong>Nota:</strong> En la especificación DOM4 (como se implementó en Gecko 13.0 {{geckoRelease(13)}}), <code>deep</code> es un argumento opcional. Si éste se omite, el método actua como si el valor se estableciera en <strong><code>true</code></strong>, estableciendo el uso de la clonación profunda como el comportamiento por defecto. Para crear un clon superficial, <code>deep</code> debe establecerse en <code>false</code>.</p> + +<p>Este comportamiento ha sido modificado en la última especificación, si es omitido, el método se comportará como si <code>deep</code> fuera <strong><code>false</code></strong>. Aunque sigue siendo opcional, usted siempre debería proporcionar el argumento <code>deep</code> tanto para la compatibilidad con las nuevas y anteriores especificaciones. Con Gecko 28.0 {{geckoRelease(28)}}), la consola advierte a los desarrolladores a no omitir el argumento. Desde Gecko 29.0 {{geckoRelease(29)}}), una copia superficial, es el comportamiento por defecto en lugar de una copia profunda.</p> +</div> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush: js">var p = document.getElementById("para1"); +var p_prime = p.cloneNode(true); +</pre> + +<h2 id="Notas">Notas</h2> + +<p id="not-event-listeners">Al clonar un nodo se copian todos sus atributos y valores, incluyendo escuchadores intrínsecos (en–línea). No copia los escuchadores de evento añadidos utilizando <a href="/en-US/docs/DOM/element.addEventListener"><code>addEventListener()</code></a> o aquellos asignados a las propiedades de un elemento. (ej. <code>node.onclick = fn</code>). Además, para un elemento <code><canvas></code>, la imagen pintada no se copia.</p> + +<p>El nodo duplicado devuelto por <code>cloneNode()</code> no formará parte del documento hasta que sea añadido a otro nodo que sea parte del documento utilizando {{domxref("Node.appendChild()")}} o un método similar. Tampoco tiene padre hasta que sea añadido a otro nodo.</p> + +<p>Si <code>deep</code> se establece a <code>false</code>, los elementos hijos no se clonan. Tampoco se clona ningún texto que contenga el nodo, ya que está contenido en uno o más nodos {{domxref("Text")}}.</p> + +<p>Si <code>deep</code> se evalúa a <code>true</code>, el subárbol completo (incluyendo texto que pueda estar en nodos {{domxref("Text")}} hijos) también se copian. En los nodos vacíos (por ejemplo, los elementos {{HTMLElement("img")}} y {{HTMLElement("input")}}) no importa si <code>deep</code> es <code>true</code> o <code>false</code>.</p> + +<div class="warning"><strong>Advertencia:</strong> <code>cloneNode()</code> puede conducir a elementos con ID's duplicados en el documento.</div> + +<p>Si el nodo original tiene un ID el elemento clonado se ubicará en el mismo documento, el ID del clon debería ser modificado para ser único. Los atributos name pueden necesitar ser modificados también, dependiendo de si se esperan nombres duplicados.</p> + +<p>Para clonar un nodo con el fin de agregarlo a un domento distinto, utiliza {{domxref("Document.importNode()")}}.</p> + +<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("DOM WHATWG", "#dom-node-clonenode", "Node.cloneNode()")}}</td> + <td>{{Spec2("DOM WHATWG")}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName("DOM3 Core", "core.html#ID-3A0ED0A4", "Node.cloneNode()")}}</td> + <td>{{Spec2("DOM3 Core")}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName("DOM2 Core", "core.html#ID-3A0ED0A4", "Node.cloneNode()")}}</td> + <td>{{Spec2("DOM2 Core")}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_navegadores">Compatibilidad en navegadores</h2> + +<div> +<p>{{Compat("api.Node.cloneNode")}}</p> +</div> diff --git a/files/es/web/api/node/contains/index.html b/files/es/web/api/node/contains/index.html new file mode 100644 index 0000000000..be0f8848d9 --- /dev/null +++ b/files/es/web/api/node/contains/index.html @@ -0,0 +1,56 @@ +--- +title: Node.contains() +slug: Web/API/Node/contains +tags: + - API + - DOM + - Nodo + - metodo +translation_of: Web/API/Node/contains +--- +<div>{{APIRef("DOM")}}</div> + +<p>El método <strong><code>Node.contains()</code></strong> devuelve un valor {{jsxref("Boolean")}} indicando si un nodo es descendiente de un nodo dado o no, por ejemplo, el propio nodo, uno de sus hijos directos (({{domxref("Node.childNodes", "childNodes")}})), uno de los hijos directos de su nodo hijo, etc.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">node.contains( otroNodo ) +</pre> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>Esta función verifica si un un elemento esté en el cuerpo de la página. Como <code>contains</code> es inclusivo y determinar si el cuerpo se contiene a sí mismo no es la intención de <code>isInPage</code> este caso explícitamente devuelve <code>false</code>.</p> + +<pre class="brush:js">function isInPage(node) { + return (node === document.body) ? false : document.body.contains(node); +}</pre> + +<h2 id="Specifications" name="Specifications">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("DOM WHATWG", "#dom-node-contains", "Node.contains()")}}</td> + <td>{{Spec2("DOM WHATWG")}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_navegadores">Compatibilidad en navegadores</h2> + +<p>{{Compat("api.Node.contains")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("Node.compareDocumentPosition")}}</li> + <li>{{domxref("Node.hasChildNodes")}}</li> +</ul> diff --git a/files/es/web/api/node/elementopadre/index.html b/files/es/web/api/node/elementopadre/index.html new file mode 100644 index 0000000000..2a2e947a8d --- /dev/null +++ b/files/es/web/api/node/elementopadre/index.html @@ -0,0 +1,46 @@ +--- +title: Node.parentElement +slug: Web/API/Node/elementoPadre +tags: + - API + - DOM + - NecesitaCompatiblidadNavegador + - Nodo + - Propiedad +translation_of: Web/API/Node/parentElement +--- +<div> +<div>{{APIRef("DOM")}}</div> +</div> + +<p>La propiedad de sólo lectura de <code><strong>Nodo.parentElement</strong></code> devuelve el nodo padre del DOM {{domxref("Element")}}, o <code>null</code>, si el nodo no tiene padre o si el padre no es un {{domxref("Element")}} DOM .</p> + +<h2 id="Sintaxis" name="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><em>elementoPadre</em> = <em>node</em>.parentElement</pre> + +<p>El <code>elementoPadre</code> es el padre del nodo actual. Esto es siempre un objecto {{domxref("Element")}} DOM, o <code>null</code>.</p> + +<h2 id="Ejemplo" name="Ejemplo">Ejemplo</h2> + +<pre class="brush:js">if (node.parentElement) { + node.parentElement.style.color = "red"; +}</pre> + +<h2 id="Compatibilidad_en_navegadores">Compatibilidad en navegadores</h2> + +<p>En algunos navegadores, la propiedad <code>elementoPadre</code> es solo definida en nodos que ellos mismos son {{domxref("Element")}}. En particular, esto no está definido en nodos de texto.</p> + +<p>{{Compat("api.Node.parentElement")}}</p> + +<h2 id="Especificación" name="Especificación">Especificación</h2> + +<ul> + <li>{{spec("http://dvcs.w3.org/hg/domcore/raw-file/tip/Overview.html#parent-element", "DOM Level 4: Node.parentElement", "WD")}}</li> +</ul> + +<h2 id="Ver_también" name="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("Node.parentNode")}}</li> +</ul> diff --git a/files/es/web/api/node/haschildnodes/index.html b/files/es/web/api/node/haschildnodes/index.html new file mode 100644 index 0000000000..b5b3bc58b2 --- /dev/null +++ b/files/es/web/api/node/haschildnodes/index.html @@ -0,0 +1,73 @@ +--- +title: Node.hasChildNodes() +slug: Web/API/Node/hasChildNodes +tags: + - API + - DOM + - Nodo + - metodo +translation_of: Web/API/Node/hasChildNodes +--- +<div> +<div>{{APIRef("DOM")}}</div> +</div> + +<p>El método <code><strong>Node.hasChildNodes()</strong></code> devuelve un valor <strong>Boolean</strong> indicando si el {{domxref("Node")}} (nodo) actual tiene <a href="/es/docs/Web/API/Node/childNodes" title="DOM/Node.childNodes">nodos hijos</a> o no.</p> + +<h2 id="Sintaxis" name="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><code><em>resultado</em> = <em>node</em>.hasChildNodes();</code></pre> + +<dl> + <dt><code>resultado</code></dt> + <dd>almacena el valor devuelto <code>true</code> o <code>false</code>.</dd> +</dl> + +<h2 id="Ejemplos" name="Ejemplos">Ejemplos</h2> + +<p>El siguiente ejemplo elimina el primer nodo dentro del elemento con id <code>"foo"</code> si <em>foo</em> tiene nodos hijos.</p> + +<pre class="brush:js">var foo = document.getElementById("foo"); +if (foo.hasChildNodes()) { + // do something with 'foo.childNodes' +} +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<pre class="brush:js">;(function(prototype) { + prototype.hasChildNodes = prototype.hasChildNodes || function() { + return !!this.firstChild; + } +})(Node.prototype); +</pre> + +<h2 id="Resumen">Resumen</h2> + +<p>Hay varias maneras de determinar si el nodo tiene nodos hijos.</p> + +<ul> + <li>node.hasChildNodes()</li> + <li>node.firstChild != null (o sólo node.firstChild)</li> + <li>node.childNodes && node.childNodes.length (o node.childNodes.length > 0)</li> +</ul> + +<h2 id="Especificación" name="Especificación">Especificación</h2> + +<ul> + <li><a href="https://dom.spec.whatwg.org/#dom-node-haschildnodes">WHATWG: hasChildNodes</a></li> + <li><a class="external" href="http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-810594187">hasChildNodes</a></li> +</ul> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + + + +<p>{{Compat("api.Node.hasChildNodes")}}</p> + +<h2 id="Ver_también" name="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("Node.childNodes")}}</li> + <li>{{domxref("Node.hasAttributes")}}</li> +</ul> diff --git a/files/es/web/api/node/index.html b/files/es/web/api/node/index.html new file mode 100644 index 0000000000..6511274333 --- /dev/null +++ b/files/es/web/api/node/index.html @@ -0,0 +1,371 @@ +--- +title: Node +slug: Web/API/Node +tags: + - API + - DOM + - Interfaz + - Nodo + - Referencia +translation_of: Web/API/Node +--- +<div>{{APIRef("DOM")}}</div> + +<p><strong><code>Node</code></strong> es una interfaz en la cuál un número de objetos de tipo DOM API heredan. Esta interfaz permite que esos objetos sean tratados similarmente.</p> + +<p>Las siguientes interfaces todas heredan de los metodos y propiedades de <code>Node</code>: {{domxref("Document")}}, {{domxref("Element")}}, {{domxref("CharacterData")}} (heredan el {{domxref("Text")}}, el {{domxref("Comment")}}, y {{domxref("CDATASection")}}), {{domxref("ProcessingInstruction")}}, {{domxref("DocumentFragment")}}, {{domxref("DocumentType")}}, {{domxref("Notation")}}, {{domxref("Entity")}}, {{domxref("EntityReference")}}</p> + +<p>Estas interfaces pueden retornar null en casos particulares donde los métodos y las propiedades no son relevantes. Pueden retornar una excepción - por ejemplo cuando se agregan hijos a un tipo de node del cuál no puede existir hijos.</p> + +<h2 id="Propiedades">Propiedades</h2> + +<p><em>herendan propiedades de sus padres {{domxref("EventTarget")}}</em>.<sup>[1]</sup></p> + +<dl> + <dt>{{domxref("Node.baseURI")}} {{readonlyInline}}</dt> + <dd>Retorna un {{domxref("DOMString")}} representando la base de la URL. El concepto de la base de la URL cambia de un lenguaje a otro; en HTML, le corresponde al protocolo, el nombre del dominio y la estructura del directorio, eso es todo hasta el último <code>'/'</code>.</dd> + <dt>{{domxref("Node.baseURIObject")}} {{Non-standard_inline()}} {{ Fx_minversion_inline("3") }}</dt> + <dd>(Not available to web content.) The read-only {{ Interface("nsIURI") }} object representing the base URI for the element.</dd> + <dt>{{domxref("Node.childNodes")}} {{readonlyInline}}</dt> + <dd>Returns a live {{domxref("NodeList")}} containing all the children of this node. {{domxref("NodeList")}} being live means that if the children of the <code>Node</code> change, the {{domxref("NodeList")}} object is automatically updated.</dd> + <dt>{{domxref("Node.firstChild")}} {{readonlyInline}}</dt> + <dd>Returns a {{domxref("Node")}} representing the first direct child node of the node, or <code>null</code> if the node has no child.</dd> + <dt>{{domxref("Node.lastChild")}} {{readonlyInline}}</dt> + <dd>Returns a {{domxref("Node")}} representing the last direct child node of the node, or <code>null</code> if the node has no child.</dd> + <dt>{{domxref("Node.localName")}} {{obsolete_inline}}{{readonlyInline}}</dt> + <dd>Returns a {{domxref("DOMString")}} representing the local part of the qualified name of an element. In Firefox 3.5 and earlier, the property upper-cases the local name for HTML elements (but not XHTML elements). In later versions, this does not happen, so the property is in lower case for both HTML and XHTML. {{ gecko_minversion_inline("1.9.2") }}<br> + Though recent specifications require <code>localName</code> to be defined on the {{domxref("Element")}} interface, Gecko-based browsers still implement it on the {{domxref("Node")}} interface.</dd> + <dt>{{domxref("Node.namespaceURI")}} {{obsolete_inline}}{{readonlyInline}}</dt> + <dd>The namespace URI of this node, or <code>null</code> if it is no namespace. In Firefox 3.5 and earlier, HTML elements are in no namespace. In later versions, HTML elements are in the <code><a class="linkification-ext external" href="http://www.w3.org/1999/xhtml" title="Linkification: http://www.w3.org/1999/xhtml">http://www.w3.org/1999/xhtml</a></code> namespace in both HTML and XML trees. {{ gecko_minversion_inline("1.9.2") }}<br> + Though recent specifications require <code>namespaceURI</code> to be defined on the {{domxref("Element")}} interface, Gecko-based browsers still implement it on the {{domxref("Node")}} interface.</dd> + <dt>{{domxref("Node.nextSibling")}} {{readonlyInline}}</dt> + <dd>Returns a {{domxref("Node")}} representing the next node in the tree, or <code>null</code> if there isn't such node.</dd> + <dt>{{domxref("Node.nodeName")}} {{readonlyInline}}</dt> + <dd>Returns a {{domxref("DOMString")}} containing the name of the <code>Node</code>. The structure of the name will differ with the name type. E.g. An {{domxref("HTMLElement")}} will contain the name of the corresponding tag, like <code>'audio'</code> for an {{domxref("HTMLAudioElement")}}, a {{domxref("Text")}} node will have the <code>'#text'</code> string, or a {{domxref("Document")}} node will have the <code>'#document'</code> string.</dd> + <dt>{{domxref("Node.nodePrincipal")}} {{Non-standard_inline()}}{{ Fx_minversion_inline("3") }}</dt> + <dd>A {{ Interface("nsIPrincipal") }} representing the node principal.</dd> + <dt>{{domxref("Node.nodeType")}}{{readonlyInline}}</dt> + <dd>Returns an <code>unsigned short</code> representing the type of the node. Possible values are: + <table class="standard-table"> + <tbody> + <tr> + <th scope="col">Name</th> + <th scope="col">Value</th> + </tr> + <tr> + <td><code>ELEMENT_NODE</code></td> + <td><code>1</code></td> + </tr> + <tr> + <td><code>ATTRIBUTE_NODE</code> {{deprecated_inline()}}</td> + <td><code>2</code></td> + </tr> + <tr> + <td><code>TEXT_NODE</code></td> + <td><code>3</code></td> + </tr> + <tr> + <td><code>CDATA_SECTION_NODE</code> {{deprecated_inline()}}</td> + <td><code>4</code></td> + </tr> + <tr> + <td><code>ENTITY_REFERENCE_NODE</code> {{deprecated_inline()}}</td> + <td><code>5</code></td> + </tr> + <tr> + <td><code>ENTITY_NODE</code> {{deprecated_inline()}}</td> + <td><code>6</code></td> + </tr> + <tr> + <td><code>PROCESSING_INSTRUCTION_NODE</code></td> + <td><code>7</code></td> + </tr> + <tr> + <td><code>COMMENT_NODE</code></td> + <td><code>8</code></td> + </tr> + <tr> + <td><code>DOCUMENT_NODE</code></td> + <td><code>9</code></td> + </tr> + <tr> + <td><code>DOCUMENT_TYPE_NODE</code></td> + <td><code>10</code></td> + </tr> + <tr> + <td><code>DOCUMENT_FRAGMENT_NODE</code></td> + <td><code>11</code></td> + </tr> + <tr> + <td><code>NOTATION_NODE</code> {{deprecated_inline()}}</td> + <td><code>12</code></td> + </tr> + </tbody> + </table> + </dd> + <dt>{{domxref("Node.nodeValue")}}</dt> + <dd>Is a {{domxref("DOMString")}} representing the value of an object. For most <code>Node</code> type, this returns <code>null</code> and any set operation is ignored. For nodes of type <code>TEXT_NODE</code> ({{domxref("Text")}} objects), <code>COMMENT_NODE</code> ({{domxref("Comment")}} objects), and <code>PROCESSING_INSTRUCTION_NODE</code> ({{domxref("ProcessingInstruction")}} objects), the value corresponds to the text data contained in the object.</dd> + <dt>{{domxref("Node.ownerDocument")}} {{readonlyInline}}</dt> + <dd>Returns the {{domxref("Document")}} that this node belongs to. If no document is associated with it, returns <code>null</code>.</dd> + <dt>{{domxref("Node.parentNode")}} {{readonlyInline}}</dt> + <dd>Returns a {{domxref("Node")}} that is the parent of this node. If there is no such node, like if this node is the top of the tree or if doesn't participate in a tree, this property returns <code>null</code>.</dd> + <dt>{{domxref("Node.parentElement")}} {{readonlyInline}}</dt> + <dd>Returns an {{domxref("Element")}} that is the parent of this node. If the node has no parent, or if that parent is not an {{domxref("Element")}}, this property returns <code>null</code>.</dd> + <dt>{{domxref("Node.prefix")}} {{obsolete_inline}}{{readonlyInline}}</dt> + <dd>Is a {{domxref("DOMString")}} representing the namespace prefix of the node, or <code>null</code> if no prefix is specified.<br> + Though recent specifications require <code>prefix</code> to be defined on the {{domxref("Element")}} interface, Gecko-based browsers still implement it on the {{domxref("Node")}} interface.</dd> + <dt>{{domxref("Node.previousSibling")}} {{readonlyInline}}</dt> + <dd>Returns a {{domxref("Node")}} representing the previous node in the tree, or <code>null</code> if there isn't such node.</dd> + <dt>{{domxref("Node.textContent")}}</dt> + <dd>Is a {{domxref("DOMString")}} representing the textual content of an element and all its descendants.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<p><em>Inherits methods from its parents {{domxref("EventTarget")}}</em>.<sup>[1]</sup></p> + +<dl> + <dt>{{domxref("Node.appendChild()")}}</dt> + <dd>Insert a {{domxref("Node")}} as the last child node of this element.</dd> + <dt>{{domxref("Node.cloneNode()")}}</dt> + <dd>Clone a {{domxref("Node")}}, and optionally, all of its contents. By default, it clones the content of the node.</dd> + <dt>{{domxref("Node.compareDocumentPosition()")}}</dt> + <dd> </dd> + <dt>{{domxref("Node.contains()")}}</dt> + <dd> </dd> + <dt>{{domxref("Node.getFeature()")}} {{obsolete_inline}}</dt> + <dd>...</dd> + <dt>{{domxref("Node.getUserData()")}} {{obsolete_inline}}</dt> + <dd>Allows a user to get some {{domxref("DOMUserData")}} from the node.</dd> + <dt>{{domxref("Node.hasAttributes()")}} {{obsolete_inline}}</dt> + <dd>Returns a {{domxref("Boolean")}} indicating if the element has any attributes, or not.</dd> + <dt>{{domxref("Node.hasChildNodes()")}}</dt> + <dd>Returns a {{domxref("Boolean")}} indicating if the element has any child nodes, or not.</dd> + <dt>{{domxref("Node.insertBefore()")}}</dt> + <dd>Inserts the first {{domxref("Node")}} given in a parameter immediately before the second, child of this element, {{domxref("Node")}}.</dd> + <dt>{{domxref("Node.isDefaultNamespace()")}}</dt> + <dd> </dd> + <dt>{{domxref("Node.isEqualNode()")}}</dt> + <dd> </dd> + <dt>{{domxref("Node.isSameNode()")}} {{obsolete_inline}}</dt> + <dd> </dd> + <dt>{{domxref("Node.isSupported()")}} {{obsolete_inline}}</dt> + <dd>Returns a <a href="https://developer.mozilla.org/en-US/docs/Web/API/Boolean" title="The Boolean object is an object wrapper for a boolean value."><code>Boolean</code></a> flag containing the result of a test whether the DOM implementation implements a specific feature and this feature is supported by the specific node.</dd> + <dt>{{domxref("Node.lookupPrefix()")}}</dt> + <dd> </dd> + <dt>{{domxref("Node.lookupNamespaceURI()")}}</dt> + <dd> </dd> + <dt>{{domxref("Node.normalize()")}}</dt> + <dd>Clean up all the text nodes under this element (merge adjacent, remove empty).</dd> + <dt>{{domxref("Node.removeChild()")}}</dt> + <dd>Removes a child node from the current element, which must be a child of the current node.</dd> + <dt>{{domxref("Node.replaceChild()")}}</dt> + <dd>Replaces one child {{domxref("Node")}} of the current one with the second one given in parameter.</dd> + <dt>{{domxref("Node.setUserData()")}} {{obsolete_inline}}</dt> + <dd>Allows a user to attach, or remove, {{domxref("DOMUserData")}} to the node.</dd> + <dd> </dd> +</dl> + +<h2 id="Examples">Examples</h2> + +<h3 id="Browse_all_child_nodes">Browse all child nodes</h3> + +<p>The following function recursively cycles all child nodes of a node and executes a callback function upon them (and upon the parent node itself).</p> + +<pre class="brush: js">function DOMComb (oParent, oCallback) { + if (oParent.hasChildNodes()) { + for (var oNode = oParent.firstChild; oNode; oNode = oNode.nextSibling) { + DOMComb(oNode, oCallback); + } + } + oCallback.call(oParent); +}</pre> + +<h4 id="Syntax">Syntax</h4> + +<pre>DOMComb(parentNode, callbackFunction);</pre> + +<h4 id="Description">Description</h4> + +<p>Recursively cycle all child nodes of <code>parentNode</code> and <code>parentNode</code> itself and execute the <code>callbackFunction</code> upon them as <a href="/en-US/docs/JavaScript/Reference/Operators/this" title="en-US/docs/JavaScript/Reference/Operators/this"><code>this</code></a> objects.</p> + +<h4 id="Parameters">Parameters</h4> + +<dl> + <dt><code>parentNode</code></dt> + <dd>The parent node (<code><strong>Node</strong> <a href="/en-US/docs/JavaScript/Reference/Global_Objects/Object" title="en-US/docs/JavaScript/Reference/Global_Objects/Object">Object</a></code>).</dd> + <dt><code>callbackFunction</code></dt> + <dd>The callback function (<a href="/en-US/docs/JavaScript/Reference/Global_Objects/Function" title="en-US/docs/JavaScript/Reference/Global_Objects/Function"><code>Function</code></a>).</dd> +</dl> + +<h4 id="Sample_usage">Sample usage</h4> + +<p>The following example send to the <code>console.log</code> the text content of the body:</p> + +<pre class="brush: js">function printContent () { + if (this.nodeValue) { console.log(this.nodeValue); } +} + +onload = function () { + DOMComb(document.body, printContent); +};</pre> + +<h3 id="Remove_all_children_nested_within_a_node">Remove all children nested within a node</h3> + +<pre class="brush: js">Element.prototype.removeAll = function () { + while (this.firstChild) { this.removeChild(this.firstChild); } + return this; +};</pre> + +<h4 id="Sample_usage_2">Sample usage</h4> + +<pre class="brush: js">/* ... an alternative to document.body.innerHTML = "" ... */ +document.body.removeAll();</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('DOM WHATWG', '#interface-node', 'Node')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Removed the following properties: <code>attributes</code>, <code>namespaceURI</code>, <code>prefix</code>, and <code>localName</code>.<br> + Removed the following methods: <code>isSupported()</code>, <code>hasAttributes()</code>, <code>isSameNode()</code>, <code>getFeature()</code>, <code>setUserData()</code>, and <code>getUserData()</code>.</td> + </tr> + <tr> + <td>{{SpecName('DOM3 Core', 'core.html#ID-1950641247', 'Node')}}</td> + <td>{{Spec2('DOM3 Core')}}</td> + <td>The methods <code>insertBefore()</code>, <code>replaceChild()</code>, <code>removeChild()</code>, and <code>appendChild()</code> returns one more kind of error (<code>NOT_SUPPORTED_ERR</code>) if called on a {{domxref("Document")}}.<br> + The <code>normalize()</code> method has been modified so that {{domxref("Text")}} node can also be normalized if the proper {{domxref("DOMConfiguration")}} flag is set.<br> + Added the following methods: <code>compareDocumentPosition()</code>, <code>isSameNode()</code>, <code>lookupPrefix()</code>, <code>isDefaultNamespace()</code>, <code>lookupNamespaceURI()</code>, <code>isEqualNode()</code>, <code>getFeature()</code>, <code>setUserData()</code>, and <code>getUserData().</code><br> + Added the following properties: <code>baseURI</code> and <code>textContent</code>.</td> + </tr> + <tr> + <td>{{SpecName('DOM2 Core', 'core.html#ID-1950641247', 'Node')}}</td> + <td>{{Spec2('DOM2 Core')}}</td> + <td>The <code>ownerDocument</code> property was slightly modified so that {{domxref("DocumentFragment")}} also returns <code>null</code>.<br> + Added the following properties: <code>namespaceURI</code>, <code>prefix</code>, and <code>localName</code>.<br> + Added the following methods: <code>normalize()</code>, <code>isSupported()</code> and <code>hasAttributes()</code>.</td> + </tr> + <tr> + <td>{{SpecName('DOM1', 'level-one-core.html#ID-1950641247', 'Node')}}</td> + <td>{{Spec2('DOM1')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<p> </p> + +<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>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("1.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>getFeature()</code>{{obsolete_inline}}</td> + <td>{{CompatNo}}</td> + <td>Supported from {{CompatGeckoDesktop("1.0")}} to {{CompatGeckoDesktop("6.0")}}.<br> + Removed in {{CompatGeckoDesktop("7.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>getUserData()</code>, <code>setUserData()</code> and <code>hasAttributes()</code> {{deprecated_inline}}</td> + <td>{{CompatNo}}</td> + <td>Supported from {{CompatGeckoDesktop("1.0")}} to {{CompatGeckoDesktop("21.0")}}.<br> + Removed in {{CompatGeckoDesktop("22.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>isSameNode()</code> {{obsolete_inline}}</td> + <td>{{CompatNo}}</td> + <td>Supported from {{CompatGeckoDesktop("1.0")}} to {{CompatGeckoDesktop("9.0")}}.<br> + Removed in {{CompatGeckoDesktop("10.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>isSupported()</code> {{obsolete_inline}}</td> + <td>{{CompatUnknown}}</td> + <td>Supported from {{CompatGeckoDesktop("1.0")}} to {{CompatGeckoDesktop("21.0")}}.<br> + Removed in {{CompatGeckoDesktop("22.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>attributes</code></td> + <td>{{CompatNo}}</td> + <td>Supported from {{CompatGeckoDesktop("1.0")}} to {{CompatGeckoDesktop("21.0")}}.<br> + Moved to {{domxref("Element")}} in {{CompatGeckoDesktop("22.0")}}</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>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("1.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>getFeature()</code>{{obsolete_inline}}</td> + <td>{{CompatNo}}</td> + <td>Supported from {{CompatGeckoDesktop("1.0")}} to {{CompatGeckoDesktop("6.0")}}.<br> + Removed in {{CompatGeckoDesktop("7.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Webkit and Blink incorrectly do not make <code>Node</code> inherit from {{domxref("EventTarget")}}.</p> diff --git a/files/es/web/api/node/insertarantes/index.html b/files/es/web/api/node/insertarantes/index.html new file mode 100644 index 0000000000..102d4dfbdd --- /dev/null +++ b/files/es/web/api/node/insertarantes/index.html @@ -0,0 +1,172 @@ +--- +title: Node.insertBefore() +slug: Web/API/Node/insertarAntes +tags: + - API + - DOM + - Nodo + - Referencia + - metodo +translation_of: Web/API/Node/insertBefore +--- +<div>{{APIRef("DOM")}}</div> + +<p>El método <strong><code>Node.insertBefore()</code></strong> inserta un nodo antes del nodo de referencia como hijo de un nodo padre indicado. Si el nodo hijo es una referencia a un nodo ya existente en el documento, <code>insertBefore()</code> lo mueve de la posición actual a la nueva posición (no hay necesidad de eliminar el nodo de su nodo padre antes de agregarlo al algún nodo nuevo).</p> + +<p>Esto significa que el nodo no puede estar en dos puntos del documento al simultáneamente. Por lo que si el nodo ya tiene un padre, primero se elimina el nodo, y luego se inserta en la nueva posición. {{domxref("Node.cloneNode()")}} puede utilizarse para hacer una copia de un nodo antes de insertarlo en un nuevo padre. Ten en cuenta que las copias hechas con <code>cloneNode()</code> no se mantendrán sincronizadas automáticamente.</p> + +<p>Si el nodo de referencia es <code>null</code>, el nodo indicado se añadirá al final de la lista de hijos del nodo padre especificado.</p> + +<p>Si el hijo proporcionado es un {{domxref("DocumentFragment")}}, el contenido completo del <code>DocumentFragment</code> se moverá a la lista de hijos del nodo padre indicado.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var <em>insertedNode</em> = <em>parentNode</em>.insertBefore(<em>newNode</em>, <em>referenceNode</em>); +</pre> + +<ul> + <li><code>insertedNode</code> El nodo que esta siendo insertado, es decir, <code>newNode</code></li> + <li><code>parentNode</code> El padre del nodo recién insertado.</li> + <li><code>newNode</code> El nodo a insertar.</li> + <li><code>referenceNode</code> El nodo antes del cual se inserta <code>newNode</code>.</li> +</ul> + +<p>Si <code>referenceNode</code> es <code>null</code>, el <code>newNode</code> se insertará al final de la lista de nodos hijos.</p> + +<div class="note"> +<p><code>referenceNode</code> <strong>no</strong> es un parámetro opcional -- debes pasar explícitamente un <code>Node</code> o <code>null</code>. No proporcionándolo o pasando valores no válidos podría provocar un <a href="https://code.google.com/p/chromium/issues/detail?id=419780">comportamiento</a> <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=119489">distinto</a> en diferentes versiones de navegadores.</p> +</div> + +<h3 id="Valor_devuelto">Valor devuelto</h3> + +<p>El valor devuelto es el hijo añadido excepto cuando <code>newNode</code> es un {{domxref("DocumentFragment")}}, en cuyo caso se devuelve un {{domxref("DocumentFragment")}}.</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<h3 id="Ejemplo_1">Ejemplo 1</h3> + +<pre class="brush: html"><div id="parentElement"> + <span id="childElement">foo bar</span> +</div> + +<script> +// Crear el nodo a insertar +var newNode = document.createElement("span"); + +// Obtener una referencia al nodo padre +var parentDiv = document.getElementById("childElement").parentNode; + +// Comienzo del test [ 1 ] : Existe un childElement --> Todo funciona correctamente +var sp2 = document.getElementById("childElement"); +parentDiv.insertBefore(newNode, sp2); +// Fin del test [ 1 ] + +// Comienzo del test [ 2 ] : childElement no es del tipo undefined +var sp2 = undefined; // No existe un nodo con id "childElement" +parentDiv.insertBefore(newNode, sp2); // Implicit dynamic cast to type Node +// Fin del test [ 2 ] + +// Comienzo del test [ 3 ] : childElement es de Tipo "undefined" ( string ) +var sp2 = "undefined"; // No existe un nodo con id "childElement" +parentDiv.insertBefore(newNode, sp2); // Genera "Type Error: Invalid Argument" +// Fin del test [ 3 ] +</script> +</pre> + +<h3 id="Ejemplo_2">Ejemplo 2</h3> + +<pre class="brush:html"><div id="parentElement"> + <span id="childElement">foo bar</span> +</div> + +<script> +// Crea un nuevo, elemento <span> +var sp1 = document.createElement("span"); + +// Obtener una referencia al elemento, antes de donde queremos insertar el elemento +var sp2 = document.getElementById("childElement"); +// Obtener una referencia al nodo padre +var parentDiv = sp2.parentNode; + +// Inserta un nuevo elemento en el DOM antes de sp2 +parentDiv.insertBefore(sp1, sp2); +</script> +</pre> + +<p>No existe el método <code>insertAfter()</code>. Puede ser emulado mediante la combinación del método con {{domxref("Node.nextSibling()")}}.</p> + +<p>En el ejemplo anterior, <code>sp1</code> podría insertarse después de <code>sp2</code> usando:</p> + +<pre class="brush: js"><code>parentDiv.insertBefore(sp1, sp2.nextSibling);</code></pre> + +<p>Si <code>sp2</code> no tiene ningún hermano depués de él, entonces debe ser el último hijo — <code>sp2.nextSibling</code> devuelve <code>null</code>, y <code>sp1</code> se inserta al final de la lista de nodos hijos (inmediatamente después de <code>sp2</code>).</p> + +<h3 id="Ejemplo_3">Ejemplo 3</h3> + +<p>Inserta un elemento antes del primer elemento hijo, utilizando la propiedad <a href="/en-US/docs/DOM/Node.firstChild" title="Node.firstChild">firstChild</a>.</p> + +<pre class="brush:js">// Obtener una referencia al elemento en el que se quiere insertar un nuevo nodo +var parentElement = document.getElementById('parentElement'); +// Obtener una referencia al primer hijo +var theFirstChild = parentElement.firstChild; + +// Crear un nuevo elemento +var newElement = document.createElement("div"); + +// Insertar el nuevo elemento antes que el primer hijo +parentElement.insertBefore(newElement, theFirstChild); +</pre> + +<p>Cuando el elemento no tiene ub primer hijo, entonces <code style="font-style: normal; line-height: 1.5;">firstChild</code><span style="line-height: 1.5;"> es </span><code style="font-style: normal; line-height: 1.5;">null</code><span style="line-height: 1.5;">. Aun así, el elemento se añade al padre después del último hijo. Puesto que el elemento padre no tenía primer hijo, tampoco tiene último hijo. Por tanto, el nuevo elemento es el único elemento después de ser insertado.</span></p> + +<h2 id="Compatibilidad_en_navegadores">Compatibilidad en navegadores</h2> + +<p>{{Compat("api.Node.insertBefore")}}</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="spectable standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('DOM WHATWG','#dom-node-insertbefore','Node.insertBefore')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Corrige errores en el algoritmo de inserción</td> + </tr> + <tr> + <td>{{SpecName('DOM4','#dom-node-insertbefore','Node.insertBefore')}}</td> + <td>{{Spec2('DOM4')}}</td> + <td>Describe el algoritmo con mayor detalle</td> + </tr> + <tr> + <td>{{SpecName('DOM3 Core','core.html#ID-952280727','Node.insertBefore')}}</td> + <td>{{Spec2('DOM3 Core')}}</td> + <td>Sin cambios notables</td> + </tr> + <tr> + <td>{{SpecName('DOM2 Core','core.html#ID-952280727','Node.insertBefore')}}</td> + <td>{{Spec2('DOM2 Core')}}</td> + <td>Sin cambios notables</td> + </tr> + <tr> + <td>{{SpecName('DOM1','level-one-core.html#method-insertBefore','Node.insertBefore')}}</td> + <td>{{Spec2('DOM1')}}</td> + <td>Introducido</td> + </tr> + </tbody> +</table> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("Node.removeChild()")}}</li> + <li>{{domxref("Node.replaceChild()")}}</li> + <li>{{domxref("Node.appendChild()")}}</li> + <li>{{domxref("Node.hasChildNodes()")}}</li> + <li>{{domxref("Element.insertAdjacentElement()")}}</li> + <li>{{domxref("ParentNode.prepend()")}}</li> +</ul> diff --git a/files/es/web/api/node/issamenode/index.html b/files/es/web/api/node/issamenode/index.html new file mode 100644 index 0000000000..205b6fd222 --- /dev/null +++ b/files/es/web/api/node/issamenode/index.html @@ -0,0 +1,110 @@ +--- +title: Node.isSameNode() +slug: Web/API/Node/isSameNode +translation_of: Web/API/Node/isSameNode +--- +<div>{{APIRef("DOM")}} {{Obsolete_header}}</div> + +<p><code><strong>Node.isSameNode()</strong></code> comprueba si dos nodos son iguales, es decir si hacen referencia al mismo objecto.</p> + +<div class="note"> +<p><strong>Warning:</strong> This method is no longer implemented in recent browsers.</p> + +<pre class="brush:js">// Instead of using +node1.isSameNode(node2) + +// use +node1 === node2 // or +node1 == node2</pre> +</div> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var <em>isSameNode</em> = <em>node</em>.isSameNode(<em>other</em>); +</pre> + +<ul> + <li><code>other</code> El nodo contra el cual se realiza la comparación.</li> +</ul> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('DOM WHATWG', '#interface-node', 'Node')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Eliminado de la especificación.</td> + </tr> + <tr> + <td>{{SpecName('DOM3 Core', 'core.html#Node3-isSameNode', 'Node.isSameNode()')}}</td> + <td>{{Spec2('DOM3 Core')}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_entre_navegadores">Compatibilidad entre navegadores</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>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("1.0")}}<br> + {{CompatNo}} {{CompatGeckoDesktop("10.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</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>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("1.0")}}<br> + {{CompatNo}} {{CompatGeckoMobile("10.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_además">Ver además</h2> + +<ul> + <li>{{domxref("Node.isEqualNode()")}}</li> +</ul> diff --git a/files/es/web/api/node/lastchild/index.html b/files/es/web/api/node/lastchild/index.html new file mode 100644 index 0000000000..0228c3264c --- /dev/null +++ b/files/es/web/api/node/lastchild/index.html @@ -0,0 +1,65 @@ +--- +title: Node.lastChild +slug: Web/API/Node/lastChild +tags: + - API + - DOM + - NecesitaCompatibilidadNavegador + - Propiedad + - Referencia +translation_of: Web/API/Node/lastChild +--- +<div>{{APIRef("DOM")}}</div> + +<p>La propiedad de sólo lectura <code><strong>Node.lastChild</strong></code> devuelve el último hijo del nodo. Si su padre es un elemento, entonces el hijo es generalmente un nodo de element, nodo de texto o un nodo de comentario. Devuelve <code>null</code> si no hay elementos hijos.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var <em>nodoHijo</em>= <var>nodo</var>.lastChild; +</pre> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush: js">var tr = document.getElementById("row1"); +var corner_td = tr.lastChild; +</pre> + +<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('DOM WHATWG', '#dom-node-lastchild', 'Node.lastChild')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Sin cambio</td> + </tr> + <tr> + <td>{{SpecName('DOM3 Core', 'core.html#ID-61AD09FB', 'Node.lastChild')}}</td> + <td>{{Spec2('DOM3 Core')}}</td> + <td>Sin cambio</td> + </tr> + <tr> + <td>{{SpecName('DOM2 Core', 'core.html#ID-61AD09FB', 'Node.lastChild')}}</td> + <td>{{Spec2('DOM2 Core')}}</td> + <td>Sin cambio</td> + </tr> + <tr> + <td>{{SpecName('DOM1', 'level-one-core.html#ID-61AD09FB', 'Node.lastChild')}}</td> + <td>{{Spec2('DOM1')}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_navegador">Compatibilidad en navegador</h2> + + + +<p>{{Compat("api.Node.lastChild")}}</p> diff --git a/files/es/web/api/node/namespaceuri/index.html b/files/es/web/api/node/namespaceuri/index.html new file mode 100644 index 0000000000..f24b54d713 --- /dev/null +++ b/files/es/web/api/node/namespaceuri/index.html @@ -0,0 +1,145 @@ +--- +title: Node.namespaceURI +slug: Web/API/Node/namespaceURI +tags: + - API + - DOM + - NecesitaCompatilibidadNavegador + - Propiedad + - Referencia + - obsoleta +translation_of: Web/API/Node/namespaceURI +--- +<div>{{APIRef("DOM")}}{{obsolete_header}}</div> + +<p>La propiedad de solo lectura <code><strong>Nodo.namespaceURI</strong></code> devuelve la URI del nodo, o null en caso de que el nodo no tenga espacio de nombres. Cuando el nodo es un documento, este devuelve el espacio de nombres del XML para el documento actual.</p> + +<div class="warning"> +<p>En DOM4 esta API fué movida desde <code>Node</code> a las interficies {{domxref("Element")}} y {{domxref("Attr")}}.</p> +</div> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><var>namespace</var> = <var>node</var>.namespaceURI</pre> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>En este fragmento, un nodo esá siendo examinado por su {{domxref("Node.localName")}} y <code>namespaceURI</code>. Si el <code>namespaceURI</code> devuelve el nombre de espaciosXUL y el <code>localName</code> devuelve "browser", entonces el nodo es entendido a ser un XUL <code><browser/></code>.</p> + +<pre class="brush:js">if (node.localName == "browser" && + node.namespaceURI == "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul") { + // Este es un navegador XUL +}</pre> + +<h2 id="Notas">Notas</h2> + +<p>Este no es un valor calculado que es el resultado de una búsqueda del espacio de nombres basada en la examinación de las declaraciones de un espacio de nombres en el ámbito. El espacio de nombres URI de un nodo es congelado ene l momento de su creación.</p> + +<p>En Firefox 3.5 y anteriores, el espacio de nombres URI para los elementos HTML en los Documents HTML es <code>null</code>. En versiones psoteriores, en conformidad con HTML5, es <code><a class="external" href="https://www.w3.org/1999/xhtml" rel="freelink">https://www.w3.org/1999/xhtml</a></code> como en XHTML. {{gecko_minversion_inline("1.9.2")}}</p> + +<p>Para nodos de cualquier {{domxref("Node.nodeType")}} distintos de <code>ELEMENT_NODE</code> y <code>ATTRIBUTE_NODE</code> el valor de <code>namespaceURI</code> es siempre <code>null</code>.</p> + +<p>Puedes crear un elemento con un <code>namespaceURI</code> concreto creando un método DOM de nivel 2 {{domxref("Document.createElementNS")}} y atributos con el método {{domxref("Element.setAttributeNS")}}.</p> + +<p>Para la especificación <a class="external" href="https://www.w3.org/TR/xml-names11/">Namespaces in XML</a>, un atributo no hereda su espacio de nombres del elemento al que está sujeto. Si un atributo no es dado de manera explícita como espacio de nombres, entonces no los tiene.</p> + +<p>El DOM no controla ni impone la validación del espacio de nombres. Depende de la aplicación DOM de hacer cualquier tipo de validación necesaria. Destacar también que el prefijo de espacio de nombre, una vez es asociado a un nodo enparticular, no puede ser modificado.</p> + +<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("DOM3 Core", "core.html#ID-NodeNSname", "Node.namespaceURI")}}</td> + <td>{{Spec2("DOM3 Core")}}</td> + <td>Specifies the behavior when it's set to <code>null</code>.</td> + </tr> + <tr> + <td>{{SpecName("DOM2 Core", "core.html#Namespaces-Considerations", "DOM Level 2 Core: XML Namespaces")}}</td> + <td>{{Spec2("DOM2 Core")}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName("DOM2 Core", "core.html#ID-NodeNSname", "Node.namespaceURI")}}</td> + <td>{{Spec2("DOM2 Core")}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatVersionUnknown}}<br> + {{CompatNo}}46.0<sup>[1]</sup></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}<sup>[2]</sup><br> + {{CompatNo}} {{CompatGeckoDesktop("48.0")}}<sup>[1]</sup></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}<sup>[2]</sup><br> + {{CompatNo}} {{CompatGeckoMobile("48.0")}}<sup>[1]</sup></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Esta API fue movida a las APIs {{domxref("Element")}} y {{domxref("Attr")}} de acuerdo con el standard de DOM4.</p> + +<p>[2] Antes de Gecko 5.0 {{geckoRelease("5.0")}}, esta propiedad era de lectura-escritura; empezando con Gecko 5.0 es sólo lectura, siguiendo la especificación.</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("Node.localName")}}</li> + <li>{{domxref("Node.prefix")}}</li> + <li>{{domxref("Element.namespaceURI")}}</li> + <li>{{domxref("Attr.namespaceURI")}}</li> +</ul> diff --git a/files/es/web/api/node/nextsibling/index.html b/files/es/web/api/node/nextsibling/index.html new file mode 100644 index 0000000000..188357f9c6 --- /dev/null +++ b/files/es/web/api/node/nextsibling/index.html @@ -0,0 +1,87 @@ +--- +title: Node.nextSibling +slug: Web/API/Node/nextSibling +tags: + - API + - DOM + - Gecko + - Nodo + - Propiedad +translation_of: Web/API/Node/nextSibling +--- +<div>{{APIRef("DOM")}}</div> + +<p>La propiedad de sólo lectura <strong><code>Node.nextSibling</code></strong> devuelve el siguiente nodo con respecto al indicado en la lista de nodos ({{domxref("Node.childNodes","childNodes")}}) a la que este pertenece o <code>null</code> si el nodo especificado es el último en dicha lista.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox"><var>siguienteNodo</var> = <var>node</var>.nextSibling +</pre> + +<h2 id="Notes" name="Notes">Notas</h2> + +<div> + +<div><p>Gecko-based browsers insert text nodes into a document to represent whitespace in the source markup. + Therefore a node obtained, for example, using <a href="/es/docs/Web/API/Node/firstChild" title="The Node.firstChild read-only property returns the node's first child in the tree, or null if the node has no children."><code>Node.firstChild</code></a> or <a href="/es/docs/Web/API/Node/previousSibling" title="La propiedad de sólo-lectura Node.previousSibling devuelve el nodo inmediatamente anterior al especificado en la lista de nodos childNodes de su padre, o null si el nodo especificado es el primero en dicha lista."><code>Node.previousSibling</code></a> may refer to a + whitespace text node rather than the actual element the author intended to get.</p> + + <p>See <a href="/en-US/docs/Web/Guide/DOM/Whitespace_in_the_DOM">Whitespace in the DOM</a> and + <a class="external" href="http://www.w3.org/DOM/faq.html#emptytext" rel="noopener">W3C DOM 3 FAQ: Why are some Text nodes empty?</a> + for more information.</p></div> + +<p>{{domxref("Element.nextElementSibling")}} debe ser utilizado para obtener el siguiente elemento ignorando cualquier nodo en blanco.</p> +</div> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre class="brush:html"><div id="div-01">Este es el div-01</div> +<div id="div-02">Este es el div-02</div> + +<script type="text/javascript"> +var el = document.getElementById('div-01').nextSibling, + i = 1; + +console.log('Hermanos de div-01:'); + +while (el) { + console.log(i + '. ' + el.nodeName); + el = el.nextSibling; + i++; +} + +</script> + +/************************************************** + Lo siguiente se escribe en la consola cuando carga: + + Nodos hermanos del div-01 + + 1. #text + 2. DIV + 3. #text + 4. SCRIPT + +**************************************************/ +</pre> + +<p>En el ejemplo anterior, se puede observar que los nodos <code>#text</code> se insertan en el DOM, donde se produce un espacio en blanco en el marcado entre las etiquetas (es decir, después de la etiqueta de cierre de un elemento y antes de la etiqueta de apertura del siguiente). No se crea ningún espacio en blanco entre los elementos insertados por la sentencia <code>document.write</code>.</p> + +<p>La posible inclusión de los nodos de texto en el DOM se debe permitir cuando se atraviese el DOM utilizando <code>nextSibling</code>. Vea los recursos en la sección Notas.</p> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<ul> + <li><a href="http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#attribute-nextSibling">DOM Level 1 Core: nextSibling</a></li> + <li><a href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-6AC54C2F">DOM Level 2 Core: nextSibling</a></li> +</ul> + +<h2 id="Compatibilidad_en_navegadores">Compatibilidad en navegadores</h2> + +<p>{{Compat("api.Node.nextSibling")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("Element.nextElementSibling")}}</li> +</ul> diff --git a/files/es/web/api/node/nodename/index.html b/files/es/web/api/node/nodename/index.html new file mode 100644 index 0000000000..5865b21e21 --- /dev/null +++ b/files/es/web/api/node/nodename/index.html @@ -0,0 +1,107 @@ +--- +title: element.nodeName +slug: Web/API/Node/nodeName +tags: + - Referencia_DOM_de_Gecko +translation_of: Web/API/Node/nodeName +--- +<div>{{APIRef("DOM")}}</div> + +<h3 id="Resumen" name="Resumen">Resumen</h3> + +<p>Devuelve el nombre del nodo actual, en forma de cadena.</p> + +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> + +<pre class="eval">var<em>str</em> =<em>node</em>.nodeName; +</pre> + +<p><code>str</code> es una variable de cadena en la que se almacena el nombre del elemento actual.</p> + +<p><code>nodeName</code> es un atributo de solo-lectura.</p> + +<h3 id="Notas" name="Notas">Notas</h3> + +<p>Aquí tenemos el valor devuelto por varios tipos de nodo.</p> + +<table class="standard-table"> + <tbody> + <tr> + <th class="header" style="text-align: center;">Interfaz</th> + <th class="header" style="text-align: center;">nodeName</th> + </tr> + <tr> + <td><a href="es/DOM/Attr">Attr</a></td> + <td>igual que <code><a href="es/DOM/Attr.name">Attr.name</a></code></td> + </tr> + <tr> + <td><a href="es/DOM/CDATASection">CDATASection</a></td> + <td>"#cdata-section"</td> + </tr> + <tr> + <td><a href="es/DOM/Comment">Comment</a></td> + <td>"#comment"</td> + </tr> + <tr> + <td><a href="es/DOM/document">Document</a></td> + <td>"#document"</td> + </tr> + <tr> + <td><a href="es/DOM/DocumentFragment">DocumentFragment</a></td> + <td>"#document-fragment"</td> + </tr> + <tr> + <td><a href="es/DOM/DocumentType">DocumentType</a></td> + <td>igual que <code><a href="es/DOM/DocumentType.name">DocumentType.name</a></code></td> + </tr> + <tr> + <td><a href="es/DOM/element">Element</a></td> + <td>igual que <code><a href="es/DOM/element.tagName">Element.tagName</a></code></td> + </tr> + <tr> + <td><a href="es/DOM/Entity">Entity</a></td> + <td>nombre de entity</td> + </tr> + <tr> + <td><a href="es/DOM/EntityReference">EntityReference</a></td> + <td>nombre de la identidad de referencia</td> + </tr> + <tr> + <td><a href="es/DOM/Notation">Notation</a></td> + <td>nombre de la notación</td> + </tr> + <tr> + <td><a href="es/DOM/ProcessingInstruction">ProcessingInstruction</a></td> + <td>igual que <code><a href="es/DOM/ProcessingInstruction.target">ProcessingInstruction.target</a></code></td> + </tr> + <tr> + <td>Text</td> + <td>"#text"</td> + </tr> + </tbody> +</table> + +<h3 id="Ejemplo" name="Ejemplo">Ejemplo</h3> + +<p>Dado el siguiente código:</p> + +<pre><div id="d1">hola mundo</div> +<input type="text" id="t"/> +</pre> + +<p>y el siguiente script:</p> + +<pre>var div1 = document.getElementById("d1"); +var text_field = document.getElementById("t"); +text_field.value = div1.nodeName; +</pre> + +<p>En XHTML (o alguna otra forma de XML) el valor de <code>text_field</code> será "div". Sin embargo, en HTML, el valor de <code>text_field</code> sería "DIV".</p> + +<p>Ten en cuenta que podríamos haber usado la propiedad <code><a href="es/DOM/element.tagName">tagName</a></code> en su lugar, ya que <code>nodeName</code> tiene el mismo valor que <code>tagName</code> para un elemento. Presta atención, sin embargo, a que <code>nodeName</code> devolverá <code>#text</code> para los nodos de texto, mientras que <code>tagName</code> devolverá <code>undefined</code>.</p> + +<h3 id="Especificaciones" name="Especificaciones">Especificaciones</h3> + +<p><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-F68D095">DOM Level 2 Core: Node.nodeName</a></p> + +<p><a class="external" href="http://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-F68D095">DOM Level 3 Core: Node.nodeName</a></p> diff --git a/files/es/web/api/node/nodetype/index.html b/files/es/web/api/node/nodetype/index.html new file mode 100644 index 0000000000..1a1f28ac39 --- /dev/null +++ b/files/es/web/api/node/nodetype/index.html @@ -0,0 +1,95 @@ +--- +title: Node.nodeType +slug: Web/API/Node/nodeType +translation_of: Web/API/Node/nodeType +--- +<div> +<div>{{APIRef("DOM")}}</div> + +<div>La propiedad de solo lectura <code style="font-style: normal;"><strong>Node.nodeType</strong></code> retornará un valor positivo entero representando el tipo de nodo.</div> + +<div> </div> +</div> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox">var <var>type</var> = <var>node</var>.nodeType; +</pre> + +<p>la variable type será un entero positivo con alguno de los siguientes valores:</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Name</th> + <th scope="col">Value</th> + </tr> + </thead> + <tbody> + <tr> + <td><a href="/en-US/docs/Web/API/Element"><code>ELEMENT_NODE</code></a></td> + <td><code>1</code></td> + </tr> + <tr> + <td><code>ATTRIBUTE_NODE</code> {{deprecated_inline()}}</td> + <td><code>2</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/API/Text"><code>TEXT_NODE</code></a></td> + <td><code>3</code></td> + </tr> + <tr> + <td><code>CDATA_SECTION_NODE</code> {{deprecated_inline()}}</td> + <td><code>4</code></td> + </tr> + <tr> + <td><code>ENTITY_REFERENCE_NODE</code> {{deprecated_inline()}}</td> + <td><code>5</code></td> + </tr> + <tr> + <td><code>ENTITY_NODE</code> {{deprecated_inline()}}</td> + <td><code>6</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/API/ProcessingInstruction"><code>PROCESSING_INSTRUCTION_NODE</code></a></td> + <td><code>7</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/API/document.createComment"><code>COMMENT_NODE</code></a></td> + <td><code>8</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/HTML/Element/html"><code>DOCUMENT_NODE</code></a></td> + <td><code>9</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/API/document.doctype"><code>DOCUMENT_TYPE_NODE</code></a></td> + <td><code>10</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/API/DocumentFragment"><code>DOCUMENT_FRAGMENT_NODE</code></a></td> + <td><code>11</code></td> + </tr> + <tr> + <td><code>NOTATION_NODE</code> {{deprecated_inline()}}</td> + <td><code>12</code></td> + </tr> + </tbody> +</table> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<p>Este es un ejemplo que verifica si el primer nodo dentro de un elemento tipo documento (document) es un comentario nodo, y si no lo es, muestra un mensaje.</p> + +<pre class="brush: js">var node = document.documentElement.firstChild; +if (node.nodeType != Node.COMMENT_NODE) + console.log("You should comment your code well!"); +</pre> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<ul> + <li><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-111237558">DOM Level 2 Core: Node.nodeType</a></li> + <li><a class="external" href="http://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-111237558">DOM Level 3 Core: Node.nodeType</a></li> + <li><a class="external" href="http://dom.spec.whatwg.org/#node">DOM Standard</a></li> +</ul> diff --git a/files/es/web/api/node/nodevalue/index.html b/files/es/web/api/node/nodevalue/index.html new file mode 100644 index 0000000000..418cecdb77 --- /dev/null +++ b/files/es/web/api/node/nodevalue/index.html @@ -0,0 +1,86 @@ +--- +title: Node.nodeValue +slug: Web/API/Node/nodeValue +translation_of: Web/API/Node/nodeValue +--- +<div> +<div>{{APIRef("DOM")}}</div> +</div> + +<p>La propiedad <code><strong>Nodo.nodeValue</strong></code> devuelve o actualiza el valor del nodo actual.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox"><em>valor</em>= <var>nodo</var>.nodeValue; +</pre> + +<p><code>valor</code> es una cadena contenedora del valor del nodo actual, si es que tiene alguno.</p> + +<h2 id="Notes" name="Notes">Notas</h2> + +<p>Para el nodo en si, <code>nodeValue</code> devuelve <code>null</code>. Para texto, comentarios, y nodos CDATA, <code>nodeValue</code> devuelve el contenido de dicho nodo. Para nodos atributos, el valor del atributo es devuelto.</p> + +<p>La siguiente table muestra los distintos valores retornados por los diferentes elementos.</p> + +<table> + <thead> + <tr> + <th>Atributo</th> + <th>valor del atributo</th> + </tr> + </thead> + <tbody> + <tr> + <td>CDATASection</td> + <td>contenido de la sección CDATA</td> + </tr> + <tr> + <td>Comment</td> + <td>Contenido del comentario</td> + </tr> + <tr> + <td>Document</td> + <td>null</td> + </tr> + <tr> + <td>DocumentFragment</td> + <td>null</td> + </tr> + <tr> + <td>DocumentType</td> + <td>null</td> + </tr> + <tr> + <td>Element</td> + <td>null</td> + </tr> + <tr> + <td>NamedNodeMap</td> + <td>null</td> + </tr> + <tr> + <td>EntityReference</td> + <td>null</td> + </tr> + <tr> + <td>Notation</td> + <td>null</td> + </tr> + <tr> + <td>ProcessingInstruction</td> + <td>Todo el contexto excluyendo el objetivo</td> + </tr> + <tr> + <td>Text</td> + <td>Contenido del nodo de texto</td> + </tr> + </tbody> +</table> + +<p>Cuando <code>nodeValue</code> es definido como <code>null</code>, actualizarlo no tiene efecto.</p> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<ul> + <li><a href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-F68D080">DOM Level 2 Core: Node.nodeValue</a></li> +</ul> diff --git a/files/es/web/api/node/nodoprincipal/index.html b/files/es/web/api/node/nodoprincipal/index.html new file mode 100644 index 0000000000..55f02037bb --- /dev/null +++ b/files/es/web/api/node/nodoprincipal/index.html @@ -0,0 +1,33 @@ +--- +title: Nodo.nodoPrincipal +slug: Web/API/Node/nodoPrincipal +tags: + - API + - DOM + - Gecko + - Propiedad +translation_of: Web/API/Node +--- +<div> +<div>{{APIRef("DOM")}}</div> +{{Non-standard_header}} + +<p>La propiedad de solo loctura de <code><strong>Nodo.nodePrincipal</strong></code> devuelve el objeto {{Interface("nsIPrincipal")}} representando el contexto de seguridad del nodo actual.</p> + +<p>{{Note("This property exists on all nodes (HTML, XUL, SVG, MathML, etc.), but only if the script trying to use it has chrome privileges.")}}</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox"><em>principalObj</em> = element.nodePrincipal +</pre> + +<h2 id="Notes" name="Notes">Notas</h2> + +<p>Esta propiedad es de solo lectura; Si intentamos editarla nos lanzará una excepción. Además, esta propiedad tan solo debería ser accesible desde código privilegiado</p> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<p>No hay especificaciones.</p> +</div> + +<p> </p> diff --git a/files/es/web/api/node/ownerdocument/index.html b/files/es/web/api/node/ownerdocument/index.html new file mode 100644 index 0000000000..b1213ac818 --- /dev/null +++ b/files/es/web/api/node/ownerdocument/index.html @@ -0,0 +1,118 @@ +--- +title: Node.ownerDocument +slug: Web/API/Node/ownerDocument +tags: + - API + - DOM + - Nodo + - Propiedad + - Referencia +translation_of: Web/API/Node/ownerDocument +--- +<div>{{APIRef("DOM")}}</div> + +<p>La propiedad de lectura <code><strong>ownerDocument</strong></code> de la interfaz {{domxref("Node")}} devuelve el objeto Document de más alto nivel/jerarquia para ese nodo.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><var>var document</var> = <var>element</var>.ownerDocument; +</pre> + +<h3 id="Resultado">Resultado</h3> + +<p><code>document</code> es el objeto {{domxref("Document")}} de más alto nivel, con el que todos los nodos descendientes se crean. Si la propiedad se usa en un nodo que el mismo es un Document, el resultado es <code>null</code>.</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush:js">// dado un nodo "p", coge el hijo que tenga la más alta jerarquia +// del objeto Document + +var d = p.ownerDocument; +var html = d.documentElement; + +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th>Especificación</th> + <th>Estado</th> + <th>Comentario</th> + </tr> + <tr> + <td>{{SpecName("DOM4", "#dom-node-ownerdocument", "Node.ownerDocument")}}</td> + <td>{{Spec2("DOM4")}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName("DOM3 Core", "core.html#node-ownerDoc", "Node.ownerDocument")}}</td> + <td>{{Spec2("DOM3 Core")}}</td> + <td>No change</td> + </tr> + <tr> + <td>{{SpecName("DOM2 Core", "core.html#node-ownerDoc", "Node.ownerDocument")}}</td> + <td>{{Spec2("DOM2 Core")}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegador">Compatibilidad de navegador</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}<sup>[1]</sup></td> + <td>6.0<sup>[2]</sup></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}<sup>[1]</sup></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Starting in Gecko 9.0 {{geckoRelease("9.0")}}, the <code>ownerDocument</code> of doctype nodes (that is, nodes for which {{domxref("Node.nodeType")}} is <code>Node.DOCUMENT_TYPE_NODE</code> or 10) is no longer <code>null</code>. Instead, the <code>ownerDocument</code> is the document on which <a href="/en-US/docs/DOM/DOMImplementation.createDocumentType"><code>document.implementation.createDocumentType()</code></a> was called.</p> + +<p>[2] <a href="http://msdn.microsoft.com/en-us/library/ie/ms534315(v=vs.85).aspx">http://msdn.microsoft.com/en-us/library/ie/ms534315(v=vs.85).aspx</a></p> diff --git a/files/es/web/api/node/parentnode/index.html b/files/es/web/api/node/parentnode/index.html new file mode 100644 index 0000000000..62bf77c4ff --- /dev/null +++ b/files/es/web/api/node/parentnode/index.html @@ -0,0 +1,105 @@ +--- +title: Node.parentNode +slug: Web/API/Node/parentNode +translation_of: Web/API/Node/parentNode +--- +<div> +<div>{{APIRef("DOM")}}</div> + +<div> </div> +</div> + +<p>La propiedad de sólo lectura <code><strong>node.parentNode</strong></code> devuelve el padre del nodo especificado en el árbol.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre><em>parentNode</em> = <em>node</em>.parentNode</pre> + +<p><font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: #eeeeee;">parentNode</span></font> es el padre del nodo actual. El padre de un elemento es un nodo del tipo <code>Element</code>, un nodo <code>Document</code>, o un nodo <code>DocumentFragment.</code></p> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre class="brush:js">if (node.parentNode) { + // Borra un nodo del árbol a no ser que + // esté ya en el árbol + node.parentNode.removeChild(node); +}</pre> + +<h2 id="Notes" name="Notes">Notas</h2> + +<p>Los nodos del tipo <code>Document</code> y <code>DocumentFragment</code> nunca van a tener un elemento padre, <code>parentNode</code> devolverá siempre <code>null</code>.</p> + +<p>También devuelve <code>null</code> si el nodo acaba de ser creado y no está atado/incorporado al árbol.</p> + +<h2 id="Compatiblidad_de_navegador">Compatiblidad de navegador</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Chrome</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(1.0)}}</td> + <td>0.2</td> + <td>{{CompatVersionUnknown}}</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>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile(1)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<ul> + <li><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-1060184317">DOM Level 2 Core: Node.parentNode</a></li> + <li><a class="external" href="http://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-1060184317">DOM Level 3 Core: Node.parentNode</a></li> +</ul> + +<h2 id="See_also" name="See_also">Ver también</h2> + +<ul> + <li>{{Domxref("Node.firstChild")}}</li> + <li>{{Domxref("Node.lastChild")}}</li> + <li>{{Domxref("Node.childNodes")}}</li> + <li>{{Domxref("Node.nextSibling")}}</li> + <li>{{Domxref("Node.parentElement")}}</li> + <li>{{Domxref("Node.previousSibling")}}</li> + <li>{{Domxref("Node.removeChild")}}</li> +</ul> diff --git a/files/es/web/api/node/previoussibling/index.html b/files/es/web/api/node/previoussibling/index.html new file mode 100644 index 0000000000..e537d09a23 --- /dev/null +++ b/files/es/web/api/node/previoussibling/index.html @@ -0,0 +1,63 @@ +--- +title: Node.previousSibling +slug: Web/API/Node/previousSibling +tags: + - API + - DOM + - Gecko + - Propiedad +translation_of: Web/API/Node/previousSibling +--- +<div> +<div>{{APIRef("DOM")}}</div> +</div> + +<p>La propiedad de sólo-lectura <code><strong>Node.previousSibling</strong></code> devuelve el nodo inmediatamente anterior al especificado en la lista de nodos {{domxref("Node.childNodes", "childNodes")}} de su padre, o <code>null</code> si el nodo especificado es el primero en dicha lista.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox"><var>nodoAnterior</var> = <em>nodo</em>.previousSibling; +</pre> + +<h2 id="Ejemplo" name="Ejemplo">Ejemplo</h2> + +<pre class="brush: html"><img id="b0"> +<img id="b1"> +<img id="b2"></pre> + +<pre class="brush:js">console.log(document.getElementById("b1").previousSibling); // <img id="b0"> +console.log(document.getElementById("b2").previousSibling.id); // "b1" +</pre> + +<h2 id="Notas" name="Notas">Notas</h2> + + +<div><p>Gecko-based browsers insert text nodes into a document to represent whitespace in the source markup. + Therefore a node obtained, for example, using <a href="/es/docs/Web/API/Node/firstChild" title="The Node.firstChild read-only property returns the node's first child in the tree, or null if the node has no children."><code>Node.firstChild</code></a> or <a href="/es/docs/Web/API/Node/previousSibling" title="La propiedad de sólo-lectura Node.previousSibling devuelve el nodo inmediatamente anterior al especificado en la lista de nodos childNodes de su padre, o null si el nodo especificado es el primero en dicha lista."><code>Node.previousSibling</code></a> may refer to a + whitespace text node rather than the actual element the author intended to get.</p> + + <p>See <a href="/en-US/docs/Web/Guide/DOM/Whitespace_in_the_DOM">Whitespace in the DOM</a> and + <a class="external" href="http://www.w3.org/DOM/faq.html#emptytext" rel="noopener">W3C DOM 3 FAQ: Why are some Text nodes empty?</a> + for more information.</p></div> + +<p>Para navegar en el sentido opuesto de la lista de nodos hijos se utiliza <a href="/en-US/docs/Web/API/Node.nextSibling" title="DOM/Node.nextSibling">Node.nextSibling</a>.</p> + +<h2 id="Especificación" name="Especificación">Especificación</h2> + +<ul> + <li><a href="http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#attribute-previousSibling">DOM Level 1 Core: previousSibling</a></li> + <li><a href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-640FB3C8">DOM Level 2 Core: previousSibling</a></li> + <li><a href="http://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-640FB3C8">DOM Level 3 Core: previousSibling</a></li> +</ul> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + + + +<p>{{Compat("api.Node.previousSibling")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("Node.nextSibling")}}</li> +</ul> diff --git a/files/es/web/api/node/removechild/index.html b/files/es/web/api/node/removechild/index.html new file mode 100644 index 0000000000..423d482bb6 --- /dev/null +++ b/files/es/web/api/node/removechild/index.html @@ -0,0 +1,94 @@ +--- +title: Node.removeChild() +slug: Web/API/Node/removeChild +translation_of: Web/API/Node/removeChild +--- +<div> +<div><font><font><font><font><font><font><font><font><font><font>{{APIRef ( "DOM")}}</font></font></font></font></font></font></font></font></font></font></div> + +<p class="syntaxbox">El método <strong><code>Node.removeChild() </code></strong>elimina un nodo hijo del DOM y puede devolver el nodo eliminado.</p> + +<h2 class="syntaxbox" id="Sintaxis">Sintaxis</h2> + +<div> +<pre class="syntaxbox"><em>var antiguoHijo </em>= <em>elemento</em>.removeChild(child); +<strong>O</strong> +<em>elemento</em>.removeChild(<code>child</code>);</pre> +</div> +</div> + +<ul> + <li><code>child</code> <code> </code>es el nodo hijo a eliminar del DOM.</li> + <li><code>elemento </code>es el nodo padre de <code>hijo</code>.(ver nota mas abajo)</li> + <li><code>antiguoHijo</code> tiene una referencia al hijo eliminado. <code>antiguoHijo === </code> <code>child</code>.</li> +</ul> + +<p>El hijo(child) eliminado aún existe en memoria pero ya no es parte del DOM. Con la primera forma de sintaxis mostrada, se puede reutilizar el nodo eliminado más tarde en el código, por medio de la referencia al objeto <code>antiguoHijo</code>. Sin embargo, en la segunda forma, la referencia a <code>antiguoHijo</code> se pierde, y suponiendo que el código no mantenga una referencia a ese objeto en alguna otra parte, inmediatamente será inutilizable e irrecuperable y será <a href="es/docs/Web/JavaScript/Gestion_de_Memoria">eliminada automáticamente </a>de memoria después de poco tiempo.</p> + +<p>Si hijo(<code>child)</code> no es en realidad hijo del nodo <code>elemento</code>, el método lanza una excepción. Esto también sucederá si <code>child </code>es en realidad hijo de <code>elemento </code>al momento de llamar al método, pero fue eliminado por un controlador(manejador) de eventos(event handler) invocado en el curso de tratar de eliminar el elemento. (e.g. blur).</p> + +<p>Por lo tanto el método removeChild(child) lanza una excepción de 2 casos diferentes: </p> + +<p style="margin-left: 36.0pt; text-indent: -18.0pt;"><span style="">1.<span style='font: 7.0pt "Times New Roman";'> </span></span>Si child es un hijo del elemento y por lo tanto existe en el DOM, pero se retiró el método lanza la siguiente excepción:</p> + +<p style="margin-left: 36.0pt;"><code><span lang="EN-US" style='font-family: "Cambria Math","serif"; font-size: 10.0pt;'></span></code><code><span lang="EN-US" style="font-size: 10.0pt;">Uncaught NotFoundError: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node</span></code><span lang="EN-US" style=""><font><font>.</font></font></span></p> + +<p style="margin-left: 36.0pt; text-indent: -18.0pt;"><span style="">2.<span style='font: 7.0pt "Times New Roman";'> </span></span>Si <code><span style="font-size: 10.0pt;">child</span></code> no existe en el DOM de la página, el método emite la siguiente excepción:<br> + <br> + <code><span style="font-size: 10.0pt;">Uncaught TypeError: Failed to execute 'removeChild' on 'Node': parameter 1 is not of type 'Node'.</span></code></p> + +<h2 id="Ejemplos">Ejemplos</h2> + +<pre class="brush: html"><!--Ejemplo 1 HTML--> +<div id="top" align="center"> </div></pre> + +<pre class="brush: js"><!--Javascript--> +// El método lanza la excepción correspondiente al (caso 2) +var top = document.getElementById("top"); +var nested = document.getElementById("nested"); +var garbage = top.removeChild(nested);</pre> + +<pre class="brush: html"><font><font><font><font><font><font><font><font><!--Ejemplo 2 </font></font></font></font></font><font><font><font><font><font>HTML--> +</font></font></font></font><font><font><font><font><font><font><div id="top"</font></font></font></font></font></font></font></font></font></font><font><font><font><font><font><font><font><font><font><font>></font></font></font></font><font><font> + <div id="anidados"></div> </font></font></font></font></font></font></font></font><font><font><font><font><font><font><font><font> +</div></font></font></font></font></font></font></font></font></pre> + +<pre class="brush: js"><font><font><!--Javascript--></font></font> +// Eliminando un elemento específico cuando se conoce su nodo padre<font><font> +var d = document.getElementById("top");</font></font><font><font> +var d_nested = document.getElementById("anidados");</font></font><font><font> +var throwawayNode = d.removeChild(d_nested);</font></font></pre> + +<pre class="brush:js"><font><font><!--Javascript--></font></font> +// Eliminando un elemento específico utilizando la propiedad parentNode, que siempre hace referencia al nodo padre de un nodo <strong>(nodoHijo.parentNode.)</strong>. +<font><font>nodo var = document.getElementById("anidados");</font></font><font><font> +if (node.parentNode) {</font></font><font><font> + node.parentNode.removeChild(nodo);</font></font> +}</pre> + +<pre class="brush:js"><font><font><!--Javascript--></font></font> +// Eliminando todos los hijos de un elemento<font><font> +elemento var = document.getElementById("top");</font></font><font><font> +while (element.firstChild) {</font></font><font><font> + element.removeChild(element.firstChild);</font></font><font><font> +}</font></font></pre> + +<h2 id="Notas"><strong><font><font>Notas:</font></font></strong></h2> + +<p><code><strong>removeChild()</strong></code> se debe invocar sobre el nodo padre del nodo que se va a eliminar.</p> + +<h2 id="Especificación">Especificación</h2> + +<ul> + <li><a href="http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#method-removeChild"><font><font>DOM Nivel 1 Core: removeChild</font></font></a></li> + <li><a href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-1734834066"><font><font>DOM Nivel 2 Core: removeChild</font></font></a></li> + <li><a href="http://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-1734834066"><font><font>DOM Nivel 3 Core: removeChild</font></font></a></li> +</ul> + +<h2 id="See_also" name="See_also">Vea también</h2> + +<ul> + <li><font><font><font><font><font><font><font><font><font><font>{{Domxref ( "Node.replaceChild")}}</font></font></font></font></font></font></font></font></font></font></li> + <li><font><font><font><font><font><font><font><font><font><font>{{Domxref ( "Node.parentNode")}}</font></font></font></font></font></font></font></font></font></font></li> + <li><font><font><font><font><font><font><font><font><font><font>{{Domxref ( "ChildNode.remove")}}</font></font></font></font></font></font></font></font></font></font></li> +</ul> diff --git a/files/es/web/api/node/replacechild/index.html b/files/es/web/api/node/replacechild/index.html new file mode 100644 index 0000000000..e93f025bd9 --- /dev/null +++ b/files/es/web/api/node/replacechild/index.html @@ -0,0 +1,73 @@ +--- +title: Node.replaceChild() +slug: Web/API/Node/replaceChild +tags: + - API + - DOM + - Nodo + - Referencia + - metodo +translation_of: Web/API/Node/replaceChild +--- +<div> +<div>{{APIRef("DOM")}}</div> +</div> + +<p>El método <strong><code>Node.replaceChild()</code></strong> reemplaza un nodo hijo del elemento especificado por otro.</p> + +<h2 id="Syntax" name="Syntax">Sintáxis</h2> + +<pre class="syntaxbox"><em>replacedNode</em> = <em>parentNode</em>.replaceChild(<em>newChild</em>, <em>oldChild</em>); +</pre> + +<ul> + <li><code>newChild</code> es el nuevo nodo con el que reemplazar <code>oldChild</code>. Si ya existe en el DOM, será eliminado previamente.</li> + <li><code>oldChild</code> es el nodo existente para ser reemplazado.</li> + <li><code>replacedNode</code> es el nodo reemplazado. Es el mismo nodo que <code>oldChild</code>.</li> +</ul> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre class="brush:js">// <div> +// <span id="childSpan">foo bar</span> +// </div> + +// crear un nodo con un elemento vacío +// sin ID, atributos, ni contenido +var sp1 = document.createElement("span"); + +// darle un atributo id llamado 'newSpan' +sp1.setAttribute("id", "newSpan"); + +// crear algún contenido para el nuevo elemento +var sp1_content = document.createTextNode("Nuevo elemento span para reemplazo."); + +// aplicar dicho contenido al nuevo elemento +sp1.appendChild(sp1_content); + +// construir una referencia al nodo existente que va a ser reemplazado +var sp2 = document.getElementById("childSpan"); +var parentDiv = sp2.parentNode; + +// reemplazar el nodo sp2 existente con el nuevo elemento span sp1 +parentDiv.replaceChild(sp1, sp2); + +// resultado: +// <div> +// <span id="newSpan">Nuevo elemento span para reemplazo.</span> +// </div> +</pre> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<ul> + <li><a href="http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#method-replaceChild">DOM Level 1 Core: replaceChild</a></li> + <li><a href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-785887307">DOM Level 2 Core: replaceChild</a></li> + <li><a href="http://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-785887307">DOM Level 3 Core: replaceChild</a></li> +</ul> + +<h2 id="See_also" name="See_also">Ver también</h2> + +<ul> + <li>{{domxref("Node.removeChild")}}</li> +</ul> diff --git a/files/es/web/api/node/textcontent/index.html b/files/es/web/api/node/textcontent/index.html new file mode 100644 index 0000000000..46586e89d5 --- /dev/null +++ b/files/es/web/api/node/textcontent/index.html @@ -0,0 +1,98 @@ +--- +title: Node.textContent +slug: Web/API/Node/textContent +translation_of: Web/API/Node/textContent +--- +<div>{{APIRef("DOM")}}</div> + +<p>La propiedad <strong><code>textContent</code></strong> de la interfaz {{domxref("Node")}} representa el contenido de texto de un nodo y sus dencendientes.</p> + +<div class="blockIndicator note"> +<p><strong>Nota:</strong> <code>textContent</code> y {{domxref("HTMLElement.innerText")}} son confundidos con facilidad, pero <a href="#Diferencias_con_innerText">ambos son diferentes en varias formas importantes</a>.</p> +</div> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var <em>text</em> = <em>Node</em>.textContent; +<em>Node</em>.textContent = <em>string</em>; +</pre> + +<h3 id="Valor_devuelto">Valor devuelto</h3> + +<p>Una cadena de texto o <code>null</code></p> + +<h2 id="Descripción">Descripción</h2> + +<p>Al obtener esta propiedad:</p> + +<ul> + <li>Si el nodo es un <a href="/es/docs/Web/API/Document">documento</a>, un <a href="/es/docs/Glossary/Doctype">DOCTYPE</a>, o una <a href="/en-US/docs/Web/API/Notation">notation</a>, <code>textContent</code> devuelve <code>null</code>. (Para obtener todo el texto y los datos de <a href="/en-US/docs/Web/API/CDATASection">CDATA data</a> del documento completo, uno podría usar <code><a href="/en-US/docs/DOM/document.documentElement">document.documentElement</a>.textContent</code>.)</li> + <li>Si el nodo es una <a href="/en-US/docs/Web/API/CDATASection">sección CDATA</a>, un comentario, una <a href="/en-US/docs/Web/API/ProcessingInstruction">instrucción de procesamiento</a>, o un <a href="/es/docs/Web/API/Document/createTextNode">nodo de texto</a>, <code>textContent</code> devuelve el texto dentro del nodo, por ejemplo, el {{domxref("Node.nodeValue")}}.</li> + <li>Para otros tipos de nodos, <code>textContent</code> retorna la concatenación del atributo <code>textContent</code> de todos los nodos hijos, excluyendo los nodos comentario y los nodos de instrucciones. Esto es una cadena vacía si el nodo no tiene hijos.</li> +</ul> + +<p>Estableciendo <code>textContent</code> en un nodo elimina todos sus hijos y los reemplaza con un solo nodo de texto con el valor dado.</p> + +<h3 id="Diferencias_con_innerText">Diferencias con innerText</h3> + +<p>Internet Explorer introdujo <code>elemento.innerText</code>. La intención es muy parecida, con un par de diferencias:</p> + +<ul> + <li>Note que mientras <code>textContent</code> lee el contenido de todos los elementos, incluyendo los elementos {{HTMLElement("script")}} y {{HTMLElement("style")}}, <code>innerText</code>, no.</li> + <li><code>innerText</code> también tiene en cuenta el estilo y no retornará el texto de elementos escondidos, mientras que <code>textContent</code> sí lo hará.</li> + <li>Como <code>innerText</code> tiene en cuenta el estilo CSS, escribirlo disparará un reflow, mientras que <code>textContent</code> no lo hará.</li> +</ul> + +<h3 id="Diferencias_con_innerHTML">Diferencias con innerHTML</h3> + +<p><code>innerHTML</code> retorna el HTML como su nombre indica. Con bastante frecuencia, para leer o escribir texto en un elemento, la gente usa <code>innerHTML</code>. <code>textContent</code> debería usarse en su lugar. Ya que el texto no es procesado es más probable que tenga mejor rendimiento. Además, esto evita un vector de ataques XSS.</p> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre class="brush: js">// Dado el siguiente fragmento HTML: +// <div id="divA">Esto <span>es</span>un texto</div> + +// Lee el contenido textual: +var text = document.getElementById("divA").textContent; +// |text| contiene la cadena "Esto es un texto". + +// Escribe el contenido textual: +document.getElementById("divA").textContent = "Esto es un nuevo texto"; +// El HTML "divA" ahora contiene una nueva cadena: +// <div id="divA">Esto es un nuevo texto</div> +</pre> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + + + +<p>{{Compat("api.Node.textContent")}}</p> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<table class="spectable standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('DOM WHATWG','#dom-node-textcontent','Node.textContent')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Sin cambios desde DOM 4</td> + </tr> + <tr> + <td>{{SpecName('DOM4','#dom-node-textcontent','Node.textContent')}}</td> + <td>{{Spec2('DOM4')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('DOM3 Core','core.html#Node3-textContent','Node.textContent')}}</td> + <td>{{Spec2('DOM3 Core')}}</td> + <td>Introducido</td> + </tr> + </tbody> +</table> + +<p> </p> diff --git a/files/es/web/api/nodelist/foreach/index.html b/files/es/web/api/nodelist/foreach/index.html new file mode 100644 index 0000000000..4cb55533e1 --- /dev/null +++ b/files/es/web/api/nodelist/foreach/index.html @@ -0,0 +1,132 @@ +--- +title: NodeList.prototype.forEach() +slug: Web/API/NodeList/forEach +tags: + - DOM + - Iterable + - Métodos + - NodeList + - Referencia + - Web +translation_of: Web/API/NodeList/forEach +--- +<p>{{APIRef("DOM")}}</p> + +<p>El método<strong><code>forEach()</code></strong> de la interfase{{domxref("NodeList")}} llama a la función callback proporcionada como parámetro una vez para cadapar de valores en la lista, en el orden en que se insertaron.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><em>nodeList.</em>forEach<em>(callback[, thisArg]);</em> +</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>Función a ser ejecutada paracada elemento, tomando eventualmente 3 argumentos: + <dl> + <dt><em><code>currentValue</code></em></dt> + <dd>El valor que esta siendo procesado en la lista de nodos.</dd> + <dt><code><em>currentIndex</em></code></dt> + <dd>El índice del elemento que esta siendo procesado en la lista de nodos.</dd> + <dt><em><code>listObj</code></em></dt> + <dd>El objeto NodeList al que se está aplicando el método<code>forEach()</code>.</dd> + </dl> + </dd> + <dt><code>thisArg</code><code> {{Optional_inline}}</code></dt> + <dd>Valor a ser usado como {{jsxref("this")}} al ejecutar<code>callback</code>.</dd> +</dl> + +<h3 id="Valor_Retornado">Valor Retornado</h3> + +<p>{{jsxref('undefined')}}.</p> + +<h2 id="Excepciones">Excepciones</h2> + +<p><em>Ninguna</em>.</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush: js;highlight:[6]">var nodo = document.createElement("div"); +var infante1 = document.createElement("p"); +var infante2 = document.createTextNode("hey"); +var infante3 = document.createElement("span"); + +nodo.appendChild(infante1); +nodo.appendChild(infante2); +nodo.appendChild(infante3); + +var list = nodo.childNodes; + +list.forEach( + function(currentValue, currentIndex, listObj) { + console.log(currentValue + ', ' + currentIndex + ', ' + this); + }, + 'miEsteArg' +);</pre> + +<p>resulta en:</p> + +<pre>[object HTMLParagraphElement], 0, miEsteArg +[object Text], 1, miEsteArg +[object HTMLSpanElement], 2, miEsteArg</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>Este {{Glossary("Polyfill","polyfill")}} le da compatibilidad a todos los navegadores que soportan <a href="https://caniuse.com/#search=es5">ES5</a>:</p> + +<pre class="brush: js">if (window.NodeList && !NodeList.prototype.forEach) { + NodeList.prototype.forEach = function (callback, thisArg) { + thisArg = thisArg || window; + for (var i = 0; i < this.length; i++) { + callback.call(thisArg, this[i], i, this); + } + }; +}</pre> + +<p>ó</p> + +<pre class="brush: js">if (window.NodeList && !NodeList.prototype.forEach) { + NodeList.prototype.forEach = Array.prototype.forEach; +}</pre> + +<p>El comportamiento ateriror esta implementado en muchos navegadores. NodeList.prototype.forEach (Chrome, Firefox for example).</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<p>Especificación</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col"></th> + <th scope="col">Status</th> + <th scope="col">Comentarios</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('DOM WHATWG', '#interface-nodelist', 'NodeList')}}</td> + <td>{{ Spec2('DOM WHATWG') }}</td> + <td>Define<code>NodeList</code> como<code><Nodo>iterable</code></td> + </tr> + <tr> + <td>{{SpecName("WebIDL", "#es-forEach", "forEach")}}</td> + <td>{{Spec2("WebIDL")}}</td> + <td>Define<code>forEach</code>en declaraciones<code>iterables</code></td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_Navegadores">Compatibilidad en Navegadores</h2> + +<div class="hidden">La tabla de compatibilidades en esta página es generada con datos estructurados. Si quisieras contribuir a los datos, revisa<a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a>y envíanos una solicitud de pull.</div> + +<p>{{Compat("api.NodeList.forEach")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("Node")}}</li> + <li>{{domxref("NodeList")}}</li> +</ul> diff --git a/files/es/web/api/nodelist/index.html b/files/es/web/api/nodelist/index.html new file mode 100644 index 0000000000..444a6cbb07 --- /dev/null +++ b/files/es/web/api/nodelist/index.html @@ -0,0 +1,123 @@ +--- +title: NodeList +slug: Web/API/NodeList +tags: + - API + - DOM + - Interfaz + - NodeList +translation_of: Web/API/NodeList +--- +<div>{{APIRef("DOM")}}</div> + +<p>Los objetos <strong><code>NodeList</code></strong> son colecciones de nodos como los devueltos por propiedades como {{domxref ("Node.childNodes")}} y el método {{domxref ("document.querySelectorAll ()")}}..</p> + +<div class="note"> +<p>Aunque <code>NodeList</code> no es un <code>Array</code>, es posible iterar sobre él utilizando <code>forEach()</code>. También puede convertirse a un <code>Array</code> usando <code>Array.from</code>.</p> + +<p>Sin embargo, algunos navegadores antiguos no han implementado <code>NodeList.forEach()</code> ni <code>Array.from()</code>. Pero esas limitaciones pueden eludirse utilizando {{jsxref("Array.forEach()", "Array.prototype.forEach()")}} (más en este documento).</p> +</div> + +<p>En algunos casos, <code>NodeList</code> es una colección <em>en vivo</em>, lo que significa que los cambios en el DOM se reflejan en la colección. Por ejemplo, {{domxref ("Node.childNodes")}} está en vivo:</p> + +<pre class="brush: js">var parent = document.getElementById('parent'); +var child_nodes = parent.childNodes; +console.log(child_nodes.length); // asumamos "2" +parent.appendChild(document.createElement('div')); +console.log(child_nodes.length); // debería imprimir "3" +</pre> + +<p>En otros casos, <code>NodeList</code> es una colección estática, lo que significa que cualquier cambio posterior en el DOM no afecta el contenido de la colección. {{domxref ("document.querySelectorAll ()")}} devuelve un <code>NodeList</code> estático.</p> + +<p>Es bueno tener en cuenta esta distinción cuando elige cómo iterar sobre los elementos en <code>NodeList</code>, y cómo guarda en caché la longitud de la lista en particular.</p> + +<h2 id="Propiedades">Propiedades</h2> + +<dl> + <dt>{{domxref("NodeList.length")}}</dt> + <dd>El número de nodos en la <code>NodeList</code>.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<dl> + <dt>{{domxref("NodeList.item()")}}</dt> +</dl> + +<dl> + <dd>Devuelve un elemento en la lista por su índice, o <code>null</code> si el índice está fuera de límites; se puede utilizar como una alternativa para acceder simplemente a <code>nodeList[idx]</code> (que en cambio devuelve indefinido cuando idx está fuera de límites).</dd> + <dt>{{domxref("NodeList.entries()")}}</dt> + <dd>Devuelve un {{jsxref ("Iteration_protocols", "iterator")}} que permite pasar por todos los pares clave / valor contenidos en este objeto.</dd> + <dt>{{domxref("NodeList.forEach()")}}</dt> + <dd>Ejecuta una función proporcionada una vez por elemento <code>NodeList</code>.</dd> + <dt>{{domxref("NodeList.keys()")}}</dt> + <dd>Devuelve un {{jsxref ("Iteration_protocols", "iterator")}} que permite pasar por todas las claves de los pares clave / valor contenidos en este objeto.</dd> + <dt>{{domxref("NodeList.values()")}}</dt> + <dd>Devuelve un {{jsxref ("Iteration_protocols", "iterator")}} que permite recorrer todos los valores de los pares clave / valor contenidos en este objeto.</dd> +</dl> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>Es posible iterar sobre los items en un <code>NodeList</code> usando:</p> + +<pre class="brush: js">for (var i = 0; i < myNodeList.length; i++) { + var item = myNodeList[i]; // No es necesario llamar a myNodeList.item(i) en JavaScript +} +</pre> + +<p>No se sienta tentado a <code><a href="/en-US/docs/JavaScript/Reference/Statements/for...in" title="JavaScript/ Reference/Statements/for...in">for...in</a></code> or <code><a href="/en-US/docs/JavaScript/Reference/Statements/for_each...in" title="JavaScript/ Reference/Statements/for each...in">for each...in</a></code> para enumerar los elementos en la lista, ya que eso también enumerará la longitud y las propiedades del elemento de <code>NodeList</code> y causará errores si su secuencia de comandos asume que solo tiene que tratar con objetos {{domxref ("element")}}. Además, <code>for..in</code> no garantiza visitar las propiedades en ningún orden en particular.</p> + +<p>Los bucles <code><a href="/en-US/docs/JavaScript/Reference/Statements/for...of" title="/en-US/docs/JavaScript/Reference/Statements/for...of">for...of</a></code> harán un bucle sobre los objetos <code>NodeList</code> correctamente:</p> + +<pre class="brush: js">var list = document.querySelectorAll( 'input[type=checkbox]' ); +for (var item of list) { + item.checked = true; +} +</pre> + +<p>Los navegadores recientes también son compatibles con los métodos de iteración, {{domxref("NodeList.forEach()", "forEach()")}}, así como {{domxref("NodeList.entries()", "entries()")}}, {{domxref("NodeList.values()", "values()")}}, y {{domxref("NodeList.keys()", "keys()")}}</p> + +<p>También hay una forma compatible con Internet Explorer de usar {{jsxref ("Array.forEach ()", "Array.prototype.forEach")}} para la iteración.</p> + +<pre class="brush: js">var list = document.querySelectorAll( 'input[type=checkbox]' ); +Array.prototype.forEach.call(list, function (item) { + item.checked = true; +});</pre> + +<h2 id="Especificaciones" name="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('DOM WHATWG', '#interface-nodelist', 'NodeList')}}</td> + <td>{{ Spec2('DOM WHATWG') }}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('DOM3 Core', 'core.html#ID-536297177', 'NodeList')}}</td> + <td>{{ Spec2('DOM3 Core') }}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('DOM2 Core', 'core.html#ID-536297177', 'NodeList')}}</td> + <td>{{ Spec2('DOM2 Core') }}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('DOM1', 'level-one-core.html#ID-536297177', 'NodeList')}}</td> + <td>{{ Spec2('DOM1') }}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_navegadores">Compatibilidad en navegadores</h2> + +<p>{{Compat("api.NodeList")}}</p> diff --git a/files/es/web/api/nondocumenttypechildnode/index.html b/files/es/web/api/nondocumenttypechildnode/index.html new file mode 100644 index 0000000000..20f5c6ea40 --- /dev/null +++ b/files/es/web/api/nondocumenttypechildnode/index.html @@ -0,0 +1,132 @@ +--- +title: NonDocumentTypeChildNode +slug: Web/API/NonDocumentTypeChildNode +tags: + - API + - DOM + - Interface + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/NonDocumentTypeChildNode +--- +<div>{{APIRef("DOM")}}</div> + +<p>The <code><strong>NonDocumentTypeChildNode</strong></code> interface contains methods that are particular to {{domxref("Node")}} objects that can have a parent, but not suitable for {{domxref("DocumentType")}}.</p> + +<p><code>NonDocumentTypeChildNode</code> is a raw interface and no object of this type can be created; it is implemented by {{domxref("Element")}}, and {{domxref("CharacterData")}} objects.</p> + +<h2 id="Properties">Properties</h2> + +<p><em>There is no inherited property.</em></p> + +<dl> + <dt>{{domxref("NonDocumentTypeChildNode.previousElementSibling")}} {{readonlyInline}}</dt> + <dd>Returns the {{domxref("Element")}} immediately prior to this node in its parent's children list, or <code>null</code> if there is no {{domxref("Element")}} in the list prior to this node.</dd> + <dt>{{domxref("NonDocumentTypeChildNode.nextElementSibling")}} {{readonlyInline}}</dt> + <dd>Returns the {{domxref("Element")}} immediately following this node in its parent's children list, or <code>null</code> if there is no {{domxref("Element")}} in the list following this node.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<p><em>There is neither inherited, nor specific method.</em></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('DOM WHATWG', '#interface-childnode', 'NonDocumentTypeChildNode')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Splitted the <code>ElementTraversal</code> interface in {{domxref("ParentNode")}}, {{domxref("ChildNode")}}, and <code>NonDocumentTypeChildNode</code>. The <code>previousElementSibling</code> and <code>nextElementSibling</code> are now defined on the latter.<br> + The {{domxref("CharacterData")}} and {{domxref("Element")}} implemented the new interfaces.</td> + </tr> + <tr> + <td>{{SpecName('Element Traversal', '#interface-elementTraversal', 'ElementTraversal')}}</td> + <td>{{Spec2('Element Traversal')}}</td> + <td>Added the initial definition of its properties to the <code>ElementTraversal</code> pure interface and use it on {{domxref("Element")}}.</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 (on {{domxref("Element")}})</td> + <td>1.0</td> + <td>{{CompatGeckoDesktop("1.9.1")}}</td> + <td>9.0</td> + <td>10.0</td> + <td>4.0</td> + </tr> + <tr> + <td>Support (on {{domxref("CharacterData")}})</td> + <td>1.0</td> + <td>{{CompatGeckoDesktop("25.0")}} [1]</td> + <td>9.0</td> + <td>10.0</td> + <td>4.0</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 (on {{domxref("Element")}})</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{CompatGeckoDesktop("1.9.1")}}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>10.0</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + <tr> + <td>Support (on {{domxref("CharacterData")}})</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{CompatGeckoDesktop("25.0")}}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>10.0</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Firefox 25 also added the two properties defined here on {{domxref("DocumentType")}}, this was removed in Firefox 28 due to compatibility problems, and led to the creation of this new pure interface.</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>The {{domxref("ParentNode")}} and {{domxref("ChildNode")}} pure interface.</li> + <li> + <div class="syntaxbox">Object types implementing this pure interface: {{domxref("CharacterData")}}, and {{domxref("Element")}}.</div> + </li> +</ul> diff --git a/files/es/web/api/nondocumenttypechildnode/nextelementsibling/index.html b/files/es/web/api/nondocumenttypechildnode/nextelementsibling/index.html new file mode 100644 index 0000000000..68395bc2b3 --- /dev/null +++ b/files/es/web/api/nondocumenttypechildnode/nextelementsibling/index.html @@ -0,0 +1,113 @@ +--- +title: NonDocumentTypeChildNode.nextElementSibling +slug: Web/API/NonDocumentTypeChildNode/nextElementSibling +tags: + - API + - DOM + - NonDocumentTypeChildNode + - Propiedad +translation_of: Web/API/NonDocumentTypeChildNode/nextElementSibling +--- +<div>{{APIRef("DOM")}}</div> + +<p>La propiedad de sólo lectura <code><strong>NonDocumentTypeChildNode.nextElementSibling</strong></code> devuelve el elemento inmediatamente posterior al especificado, dentro de la lista de elementos hijos de su padre, o bien <code>null</code> si el elemento especificado es el último en dicha lista.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var <em>nextNode</em> = elementNodeReference.nextElementSibling; </pre> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush: html"><div id="div-01">Here is div-01</div> +<div id="div-02">Here is div-02</div> + +<script type="text/javascript"> + var el = document.getElementById('div-01').nextElementSibling; + console.log('Siblings of div-01:'); + while (el) { + console.log(el.nodeName); + el = el.nextElementSibling; + } +</script> +</pre> + +<p>Este ejemplo muestra en la consola lo siguiente cuando se carga:</p> + +<pre>Siblings of div-01: +DIV +SCRIPT</pre> + +<h2 id="Polyfill_para_Internet_Explorer_8">Polyfill para Internet Explorer 8</h2> + +<p>Esta propiedad no está soportada con anterioridad a IE9, así que el siguiente fragmento de código puede utilizarse para añadir el soporte a IE8:</p> + +<pre class="brush: js">// Source: https://github.com/Alhadis/Snippets/blob/master/js/polyfills/IE8-child-elements.js +if(!("nextElementSibling" in document.documentElement)){ + Object.defineProperty(Element.prototype, "nextElementSibling", { + get: function(){ + var e = this.nextSibling; + while(e && 1 !== e.nodeType) + e = e.nextSibling; + return e; + } + }); +}</pre> + +<h2 id="Polyfill_para_Internet_Explorer_9_y_Safari">Polyfill para Internet Explorer 9+ y Safari</h2> + +<pre class="brush: js">// Source: https://github.com/jserz/js_piece/blob/master/DOM/NonDocumentTypeChildNode/nextElementSibling/nextElementSibling.md +(function (arr) { + arr.forEach(function (item) { + if (item.hasOwnProperty('nextElementSibling')) { + return; + } + Object.defineProperty(item, 'nextElementSibling', { + configurable: true, + enumerable: true, + get: function () { + var el = this; + while (el = el.nextSibling) { + if (el.nodeType === 1) { + return el; + } + } + return null; + }, + set: undefined + }); + }); +})([Element.prototype, CharacterData.prototype]);</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Observaciones</th> + </tr> + <tr> + <td>{{SpecName('DOM WHATWG', '#dom-nondocumenttypechildnode-nextelementsibling', 'ChildNodenextElementSibling')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Se dividió la interfaz <code>ElementTraversal</code> en {{domxref("ChildNode")}}, {{domxref("ParentNode")}}, y {{domxref("NonDocumentTypeChildNode")}}. Este método queda ahora definido en la primera.<br> + Los interfaces {{domxref("Element")}} y {{domxref("CharacterData")}} implementaron la nueva interfaz.</td> + </tr> + <tr> + <td>{{SpecName('Element Traversal', '#attribute-nextElementSibling', 'ElementTraversal.nextElementSibling')}}</td> + <td>{{Spec2('Element Traversal')}}</td> + <td>Añadió su definición inicial a la interfaz pura <code>ElementTraversal</code> y su uso en {{domxref("Element")}}.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<p>{{Compat("api.NonDocumentTypeChildNode.nextElementSibling")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>La interfaz pura {{domxref("ChildNode")}}.</li> + <li>Tipos de objetos que implementan esta interfaz pura: {{domxref("CharacterData")}}, {{domxref("Element")}}, y {{domxref("DocumentType")}}.</li> +</ul> diff --git a/files/es/web/api/nondocumenttypechildnode/previouselementsibling/index.html b/files/es/web/api/nondocumenttypechildnode/previouselementsibling/index.html new file mode 100644 index 0000000000..13867e8fe4 --- /dev/null +++ b/files/es/web/api/nondocumenttypechildnode/previouselementsibling/index.html @@ -0,0 +1,160 @@ +--- +title: NonDocumentTypeChildNode.previousElementSibling +slug: Web/API/NonDocumentTypeChildNode/previousElementSibling +translation_of: Web/API/NonDocumentTypeChildNode/previousElementSibling +--- +<div> +<div>{{APIRef("DOM")}}</div> +</div> + +<p>La propiedad de sólo lectura <code><strong>NonDocumentTypeChildNode.previousElementSibling</strong></code> retorna el {{domxref("Element")}} predecesor inmediato al especificado dentro de la lista de hijos de su padre, o bien <code>null</code> si el elemento especificado es el primero de dicha lista.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox"><var>prevNode</var> = elementNodeReference.previousElementSibling; +</pre> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre class="brush: html"><div id="div-01">Aquí está div-01</div> +<div id="div-02">Aquí está div-02</div> +<li>Esto es un elemento de lista</li> +<li>Esto es otro elemento de lista</li> +<div id="div-03">Aquí esta div-03</div> + +<script> + var el = document.getElementById('div-03').previousElementSibling; + document.write('<p>Hermanos de div-03</p><ol>'); + while (el) { + document.write('<li>' + el.nodeName + '</li>'); + el = el.previousElementSibling; + } + document.write('</ol>'); +</script> +</pre> + +<p>Este ejemplo muestra lo siguiente en la página cuando carga:</p> + +<pre>Hermanos de div-03 + + 1. LI + 2. LI + 3. DIV + 4. DIV +</pre> + +<h2 id="Polyfill_para_Internet_Explorer_8">Polyfill para Internet Explorer 8</h2> + +<p>Esta propiedad no está soportada con anterioridad a IE9, así que puede utilizarse el siguiente fragmento para añadri el soporte a IE8:</p> + +<pre class="brush: js">// Source: https://github.com/Alhadis/Snippets/blob/master/js/polyfills/IE8-child-elements.js +if(!("previousElementSibling" in document.documentElement)){ + Object.defineProperty(Element.prototype, "previousElementSibling", { + get: function(){ + var e = this.previousSibling; + while(e && 1 !== e.nodeType) + e = e.previousSibling; + return e; + } + }); +}</pre> + +<h2 id="Specification" name="Specification">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Observaciones</th> + </tr> + <tr> + <td>{{SpecName('DOM WHATWG', '#dom-nondocumenttypechildnode-previouselementsibling', 'NonDocumentTypeChildNode.previousElementSibling')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Dividió el interfaz <code>ElementTraversal</code> en {{domxref("ChildNode")}}, {{domxref("ParentNode")}}, y {{domxref("NonDocumentTypeChildNode")}}. Este método queda ahora definida en el primero.<br> + Los interfaces {{domxref("Element")}} y {{domxref("CharacterData")}} implementaron la nueva interfaz.</td> + </tr> + <tr> + <td>{{SpecName('Element Traversal', '#attribute-previousElementSibling', 'ElementTraversal.previousElementSibling')}}</td> + <td>{{Spec2('Element Traversal')}}</td> + <td>Añadida su definición inicial al interfaz puro <code>ElementTraversal</code> y lo usa en {{domxref("Element")}}.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Prestación</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico (en {{domxref("Element")}})</td> + <td>4</td> + <td>{{CompatGeckoDesktop("1.9.1")}}</td> + <td>9</td> + <td>9.8</td> + <td>4</td> + </tr> + <tr> + <td>Soporte en {{domxref("CharacterData")}}</td> + <td>29.0</td> + <td>{{CompatGeckoDesktop("25")}} [1]</td> + <td>{{CompatNo}}</td> + <td>16.0</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Prestación</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico (en {{domxref("Element")}})</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("1.9.1")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>9.8</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Soporte en {{domxref("CharacterData")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("25")}}</td> + <td>{{CompatNo}}</td> + <td>16.0</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Firefox 25 también añadía esta propiedad a {{domxref("DocumentType")}}, y fue eliminada en Firefox 28 debido a problemas de compatibildad.</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>El interfaz puro {{domxref("NonDocumentTypeChildNode")}}.</li> + <li> + <div class="syntaxbox">Tipos de objetos que implementan este interfaz puro: {{domxref("CharacterData")}}, y {{domxref("Element")}}.</div> + </li> +</ul> diff --git a/files/es/web/api/notification/body/index.html b/files/es/web/api/notification/body/index.html new file mode 100644 index 0000000000..46c3209386 --- /dev/null +++ b/files/es/web/api/notification/body/index.html @@ -0,0 +1,63 @@ +--- +title: Notification.body +slug: Web/API/notification/body +tags: + - API + - API Notificaciones + - Javascript Notificador + - Notificaciones +translation_of: Web/API/Notification/body +--- +<p>{{APIRef("Web Notifications")}}</p> + +<p>{{ SeeCompatTable() }}</p> + +<h2 id="Summary" name="Summary">Resumen </h2> + +<p>El <font face="Consolas, Monaco, Andale Mono, monospace">body es la </font> propiedad que representa el contenido de la notificacion.</p> + +<p>Los valores por esta propiedad son enviandos durante la <span style="line-height: 23.3333339691162px;">instanciación de </span>{{domxref("Notification")}} definiendo la propiedad body en el objeto de las opciones pasa al {{domxref("Notification")}} constructor.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="eval">var <em>body</em> = <em>instanceOfNotification</em>.body; +</pre> + +<h3 id="Return_Value" name="Return_Value">Tipo</h3> + +<p>String.</p> + +<h2 id="Especificaciones"><span style="font-family: 'Open Sans Light', sans-serif; font-weight: bold; line-height: 23.3333339691162px; background-color: rgba(212, 221, 228, 0.498039);">Especificaciones</span></h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col"><span style="font-family: 'Open Sans Light', sans-serif; font-weight: bold; line-height: 23.3333339691162px; background-color: rgba(212, 221, 228, 0.498039);">Especificacion</span></th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('Web Notifications')}}</td> + <td>{{Spec2('Web Notifications')}}</td> + <td>Initial specification.</td> + </tr> + <tr> + <td> </td> + <td> </td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Navegadores_Compatibles">Navegadores Compatibles</h2> + +<p>{{Page("/en-US/docs/Web/API/Notification","Browser compatibility")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("Notification")}}</li> + <li><a href="/en-US/docs/WebAPI/Using_Web_Notifications" title="/en-US/docs/WebAPI/Using_Web_Notifications">Using Web Notifications</a></li> +</ul> diff --git a/files/es/web/api/notification/dir/index.html b/files/es/web/api/notification/dir/index.html new file mode 100644 index 0000000000..35f58dfca7 --- /dev/null +++ b/files/es/web/api/notification/dir/index.html @@ -0,0 +1,59 @@ +--- +title: Notification.dir +slug: Web/API/notification/dir +translation_of: Web/API/Notification/dir +--- +<p>{{APIRef("Web Notifications")}}</p> + +<p>{{ SeeCompatTable() }}</p> + +<h2 id="Summary" name="Summary">Resumen</h2> + +<p><span style="line-height: 23.3333339691162px;">La propiedad dir indica la direccion para el lenguaje a usar </span><span style="line-height: 23.3333339691162px;">dentro de la notificación</span>.</p> + +<p>El valor por esta propiedad es envianda durante la instanciancion de <span style="line-height: 23.3333339691162px;">{{domxref("Notification")}} </span>mediante la definición de la propiedad dir el objeto de las opciones pasa al {{domxref ("Notificación")}} constructor.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="eval">var <em>direction</em> = <em>instanceOfNotification</em>.dir; +</pre> + +<h3 id="Return_Value" name="Return_Value">Tipo</h3> + +<p>String <span style="line-height: 23.3333339691162px;">representa la actual direccion</span>. puede ser: </p> + +<ul> + <li><code>auto</code>: La direccion es definida automaticamente.</li> + <li><code>ltr</code>: <span style="line-height: 23.3333339691162px;">El texto es desplegado de izquierda a derecha</span>.</li> + <li><code>rtl</code>: <span style="line-height: 23.3333339691162px;">El texto es desplegado de derecha a izquierda</span>.</li> +</ul> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificacion</th> + <th scope="col">Estado</th> + <th scope="col">Comentarios</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('Web Notifications')}}</td> + <td>{{Spec2('Web Notifications')}}</td> + <td>Initial specification.</td> + </tr> + </tbody> +</table> + +<h2 id="Navegadores_Compatibles">Navegadores Compatibles</h2> + +<p>{{Page("/en-US/docs/Web/API/Notification","Browser compatibility")}}</p> + +<h2 id="Ver_tambien">Ver tambien</h2> + +<ul> + <li>{{domxref("Notification")}}</li> + <li><a href="/en-US/docs/WebAPI/Using_Web_Notifications" title="/en-US/docs/WebAPI/Using_Web_Notifications">Using Web Notifications</a></li> +</ul> diff --git a/files/es/web/api/notification/icon/index.html b/files/es/web/api/notification/icon/index.html new file mode 100644 index 0000000000..deb7c0606e --- /dev/null +++ b/files/es/web/api/notification/icon/index.html @@ -0,0 +1,58 @@ +--- +title: Notification.icon +slug: Web/API/notification/icon +translation_of: Web/API/Notification/icon +--- +<p>{{APIRef("Web Notifications")}}</p> + +<p>{{ SeeCompatTable() }}</p> + +<h2 id="Summary" name="Summary">Resumen</h2> + +<p><span style="line-height: 23.3333339691162px;">La propiedad icon indica la URL del icono a usar dentro de la notificacion</span>.</p> + +<p>El valor para esta propiedad es enviada durante la instanciacion <span style="line-height: 23.3333339691162px;">{{domxref("Notification")}} definiendo la propiedad icon el objeto pasa al </span> <span style="line-height: 23.3333339691162px;">{{domxref("Notification")}} constructor.</span></p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="eval">var <em>icon</em> = <em>instanceOfNotification</em>.icon; +</pre> + +<h3 id="Return_Value" name="Return_Value">Tipo</h3> + +<p>String que representa una URL válida.</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificacion</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('Web Notifications')}}</td> + <td>{{Spec2('Web Notifications')}}</td> + <td>Initial specification.</td> + </tr> + <tr> + <td> </td> + <td> </td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Navegadores_Compatibles">Navegadores Compatibles</h2> + +<p>{{Page("/en-US/docs/Web/API/Notification","Browser compatibility")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("Notification")}}</li> + <li><a href="/en-US/docs/WebAPI/Using_Web_Notifications" title="/en-US/docs/WebAPI/Using_Web_Notifications">Using Web Notifications</a></li> +</ul> diff --git a/files/es/web/api/notification/index.html b/files/es/web/api/notification/index.html new file mode 100644 index 0000000000..a673bc5739 --- /dev/null +++ b/files/es/web/api/notification/index.html @@ -0,0 +1,430 @@ +--- +title: Notification +slug: Web/API/notification +translation_of: Web/API/Notification +--- +<div>{{APIRef("Web Notifications")}}</div> + +<div></div> + +<p>La interfaz <code>Notification</code> de la <a href="https://developer.mozilla.org/en-US/docs/Web/API/Notifications_API">Notifications API</a> se usa para configurar y mostrar notificaciones de escritorio al usuario. La apariencia y las funcionalidad especificas de esta notificacion varia a traves de las distintas plataformas, pero generalmente esta plataformas proveen un camino para proveer informacion al usuario de manera asincronica.</p> + +<p>{{AvailableInWorkers}}</p> + +<h2 id="Constructor">Constructor</h2> + +<dl> + <dt>{{domxref("Notification.Notification", "Notification()")}}</dt> + <dd>Crea una nueva instancia del objecto <code>Notification</code>.</dd> +</dl> + +<h2 id="Propiedades">Propiedades</h2> + +<h3 id="Propiedades_Estáticas">Propiedades Estáticas</h3> + +<p>Estas propiedades solo estan disponibles en el objecto <code>Notification</code> en sí mismo.</p> + + + +<dl> + <dt>{{domxref("Notification.permission")}} {{readonlyinline}}</dt> + <dd>Una cadena que representa el permiso actual para mostrar notificaciones. Los valores posibles son:</dd> +</dl> + + + +<ul> + <li><code>denied</code> (El usuario rechaza que las notificaciones sean mostradas).</li> + <li><code>granted</code> (El usuario acepta que las notificaciones sean mostradas).</li> + <li><code>default</code> (La elección del usuario es desconocida por lo tanto el navegador actuará como si el valor fuese denied).</li> +</ul> + +<dl> +</dl> + +<h3 id="Propiedades_de_Instancia">Propiedades de Instancia</h3> + +<p>Estas propiedades solo están disponibles en instancias del objecto <code>Notification</code>.</p> + +<dl> + <dt>{{domxref("Notification.actions")}} {{readonlyinline}}</dt> + <dd>Arreglo de acciones de la notificación, como se especifica en el parámetro de opciones del constructor.</dd> + <dt>{{domxref("Notification.badge")}} {{readonlyinline}}</dt> + <dd>URL de la imagen usada para representar la notificación cuando no hay espacio suficiente para mostrarla.</dd> +</dl> + +<dl> + <dt>{{domxref("Notification.title")}} {{readonlyinline}}</dt> + <dd>El título de la notificación como está especificado en el parámetro options del constructor.</dd> + <dt>{{domxref("Notification.dir")}} {{readonlyinline}}</dt> + <dd>La dirección del texto de la notificación como está especificado en el parámetro options del constructor.</dd> + <dt>{{domxref("Notification.lang")}} {{readonlyinline}}</dt> + <dd>El código del lenguaje de la notificación como está especificado en el parámetro options del constructor.</dd> + <dt>{{domxref("Notification.body")}} {{readonlyinline}}</dt> + <dd>The body string de la notificación como está especificado en el parámetro options del constructor.</dd> + <dt>{{domxref("Notification.tag")}} {{readonlyinline}}</dt> + <dd>El ID de la notificación (si hay) como está especificado en el parámetro options del constructor.</dd> + <dt>{{domxref("Notification.icon")}} {{readonlyinline}}</dt> + <dd>La URL de la imagen usada como ícono de la notificación como está especificado en el parámetro options del constructor.</dd> + <dt>{{domxref("Notification.image")}} {{readonlyinline}}</dt> + <dd>URL de una imagen para mostrar como parte de la notificación, al igual que se especifica en el parámetro de opciones del constructor.</dd> + <dt>{{domxref("Notification.data")}} {{readonlyinline}}</dt> + <dd>Retorna <span id="result_box" lang="es"><span>un clon</span> <span>estructurado de los</span> <span>datos de la notificación</span><span>.</span></span></dd> + <dt>{{domxref("Notification.requireInteraction")}} {{readonlyinline}}</dt> + <dd>Un {{jsxref("Boolean")}} indicando en dispositivos pantallas lo suficientemente grandes, una notificación debería permanecer activa hasta que el usuario haga click o la descarte.</dd> + <dt>{{domxref("Notification.silent")}} {{readonlyinline}}</dt> + <dd>Especifica si la notificación debería ser silenciada, por ejemplo sin generar sonidos o vibraciones, <span id="result_box" lang="es"><span>independientemente de</span> <span>la configuración del dispositivo</span><span>.</span></span></dd> + <dt>{{domxref("Notification.timestamp")}} {{readonlyinline}}</dt> + <dd>Especifica el tiempo en la cual una notificación fué creada o aplicable (pasado, presente o futuro).</dd> + <dt>{{domxref("Notification.vibrate")}} {{readonlyinline}}</dt> + <dd>Especifica un patrón de vibración para dispositivos que disponen de hardware para emitirlo. </dd> +</dl> + +<h4 id="Propiedades_no_soportadas">Propiedades no soportadas</h4> + +<p>Las siguientes propiedades están listadas en las especificaciones más actualizadas, pero aún no están soportadas por los navegadores. Es aconsejable verificarlas regularmente para ver si el estado de ellas ha sido actualizado, y háganos saber si encuentra información desactualizada.</p> + +<dl> + <dt>{{domxref("Notification.noscreen")}} {{readonlyinline}}</dt> + <dd>Specifies whether the notification firing should enable the device's screen or not.</dd> + <dt>{{domxref("Notification.renotify")}} {{readonlyinline}}</dt> + <dd><span id="result_box" lang="es"><span>Especifica si se debe notificar al usuario después de que una notificación nueva reemplace a una anterior.</span></span></dd> + <dt>{{domxref("Notification.sound")}} {{readonlyinline}}</dt> + <dd><span id="result_box" lang="es"><span>Especifica un recurso de sonido para reproducir cuando se activa la notificación, en lugar del sonido de notificación del sistema predeterminado.</span></span></dd> + <dt>{{domxref("Notification.sticky")}} {{readonlyinline}}</dt> + <dd> + <div id="tts_button"><span id="result_box" lang="es"><span>Especifica si la notificación debe ser 'fija', es decir, no fácilmente eliminable por el usuario.</span></span></div> + </dd> + <dt>{{domxref("Notification.vibrate")}} {{readonlyinline}}</dt> + <dd> + <div><span id="result_box" lang="es"><span>Especifica un patrón de vibración para los dispositivos con hardware de </span></span><span id="result_box" lang="es"><span class="alt-edited">vibraciones para emitir.</span></span></div> + </dd> +</dl> + +<h4 id="Manejador_de_Eventos(Event_Handler)">Manejador de Eventos(Event Handler)</h4> + +<dl> + <dt>{{domxref("Notification.onclick")}}</dt> + <dd>Un manejador para el {{event("click")}} event. Sera inicializado cada vez que el usuario de click en la notificacion.</dd> + <dt>{{domxref("Notification.onerror")}}</dt> + <dd>A handler for the {{event("error")}} event. It is triggered each time the notification encounters an error.</dd> +</dl> + +<h4 id="Obsolete_handlers">Obsolete handlers</h4> + +<p>The following event handlers are still supported as listed in the {{anch("browser compatibility")}} section below, but are no longer listed in the current spec. It is safe therefore to assume they are obsolete, and may stop working in future browser versions.</p> + +<dl> + <dt>{{domxref("Notification.onclose")}}</dt> + <dd>A handler for the {{event("close")}} event. It is triggered when the user closes the notification.</dd> + <dt>{{domxref("Notification.onshow")}}</dt> + <dd>A handler for the {{event("show")}} event. It is triggered when the notification is displayed.</dd> + <dt> + <h2 id="Methods">Methods</h2> + + <h3 id="Static_methods">Static methods</h3> + <span id="result_box" lang="es"><span>Estos métodos están disponibles solo en el objeto de </span></span><code>Notificación</code><span lang="es"><span> en sí.</span></span></dt> + <dd></dd> + <dt>{{domxref("Notification.requestPermission()")}}</dt> + <dd><span id="result_box" lang="es"><span>Solicita permiso del usuario para mostrar notificaciones.</span></span></dd> + <dt> + <h3 id="Instance_methods">Instance methods</h3> + + <p>These properties are available only on an instance of the <code>Notification</code> object or through its <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain"><code>prototype</code></a>. The <code>Notification</code> object also inherits from the {{domxref("EventTarget")}} interface.</p> + </dt> + <dt>{{domxref("Notification.close()")}}</dt> + <dd>Programmatically closes a notification.</dd> + <dt> + <h2 id="Example">Example</h2> + + <p>Assume this basic HTML:</p> + + <pre class="brush: html line-numbers language-html"><code class="language-html"><span class="tag token"><span class="tag token"><span class="punctuation token"><</span>button</span> <span class="attr-name token">onclick</span><span class="attr-value token"><span class="punctuation token">=</span><span class="punctuation token">"</span>notifyMe()<span class="punctuation token">"</span></span><span class="punctuation token">></span></span>Notify me!<span class="tag token"><span class="tag token"><span class="punctuation token"></</span>button</span><span class="punctuation token">></span></span></code></pre> + + <p>It's possible to send a notification as follows — here we present a fairly verbose and complete set of code you could use if you wanted to first check whether notifications are supported, then check if permission has been granted for the current origin to send notifications, then request permission if required, before then sending a notification.</p> + + <pre class="brush: js line-numbers language-js"><code class="language-js"><span class="keyword token">function</span> <span class="function token">notifyMe</span><span class="punctuation token">(</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="comment token">// Let's check if the browser supports notifications</span> + <span class="keyword token">if</span> <span class="punctuation token">(</span><span class="operator token">!</span><span class="punctuation token">(</span><span class="string token">"Notification"</span> <span class="keyword token">in</span> window<span class="punctuation token">)</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="function token">alert</span><span class="punctuation token">(</span><span class="string token">"This browser does not support desktop notification"</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span> + + <span class="comment token">// Let's check whether notification permissions have already been granted</span> + <span class="keyword token">else</span> <span class="keyword token">if</span> <span class="punctuation token">(</span>Notification<span class="punctuation token">.</span>permission <span class="operator token">===</span> <span class="string token">"granted"</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="comment token">// If it's okay let's create a notification</span> + <span class="keyword token">var</span> notification <span class="operator token">=</span> <span class="keyword token">new</span> <span class="class-name token">Notification</span><span class="punctuation token">(</span><span class="string token">"Hi there!"</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span> + + <span class="comment token">// Otherwise, we need to ask the user for permission</span> + <span class="keyword token">else</span> <span class="keyword token">if</span> <span class="punctuation token">(</span>Notification<span class="punctuation token">.</span>permission <span class="operator token">!==</span> <span class="string token">'denied'</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + Notification<span class="punctuation token">.</span><span class="function token">requestPermission</span><span class="punctuation token">(</span><span class="keyword token">function</span> <span class="punctuation token">(</span>permission<span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="comment token">// If the user accepts, let's create a notification</span> + <span class="keyword token">if</span> <span class="punctuation token">(</span>permission <span class="operator token">===</span> <span class="string token">"granted"</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="keyword token">var</span> notification <span class="operator token">=</span> <span class="keyword token">new</span> <span class="class-name token">Notification</span><span class="punctuation token">(</span><span class="string token">"Hi there!"</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span> + <span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span> + + <span class="comment token">// At last, if the user has denied notifications, and you </span> + <span class="comment token">// want to be respectful there is no need to bother them any more.</span> +<span class="punctuation token">}</span></code></pre> + + <p>{{EmbedLiveSample('Example', '100%', 30)}}</p> + + <p>In many cases, you don't need to be this verbose. For example, in our <a href="http://mdn.github.io/emogotchi/">Emogotchi demo</a> (<a href="https://github.com/mdn/emogotchi">see source code</a>), we simply run {{domxref("Notification.requestPermission")}} regardless to make sure we can get permission to send notifications (this uses the newer promise-based method syntax):</p> + + <pre class="brush: js line-numbers language-js"><code class="language-js">Notification<span class="punctuation token">.</span><span class="function token">requestPermission</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">.</span><span class="function token">then</span><span class="punctuation token">(</span><span class="keyword token">function</span><span class="punctuation token">(</span>result<span class="punctuation token">)</span> <span class="punctuation token">{</span> + console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span>result<span class="punctuation token">)</span><span class="punctuation token">;</span> +<span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span></code></pre> + + <p>Then we run a simple <code>spawnNotification()</code> function when we want to fire a notification — this is passed arguments to specify the body, icon and title we want, then it creates the necessary <code>options</code> object and fires the notification using the {{domxref("Notification.Notification","Notification()")}} constructor.</p> + + <pre class="brush: js line-numbers language-js"><code class="language-js"><span class="keyword token">function</span> <span class="function token">spawnNotification</span><span class="punctuation token">(</span>theBody<span class="punctuation token">,</span>theIcon<span class="punctuation token">,</span>theTitle<span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="keyword token">var</span> options <span class="operator token">=</span> <span class="punctuation token">{</span> + body<span class="punctuation token">:</span> theBody<span class="punctuation token">,</span> + icon<span class="punctuation token">:</span> theIcon + <span class="punctuation token">}</span> + <span class="keyword token">var</span> n <span class="operator token">=</span> <span class="keyword token">new</span> <span class="class-name token">Notification</span><span class="punctuation token">(</span>theTitle<span class="punctuation token">,</span>options<span class="punctuation token">)</span><span class="punctuation token">;</span> +<span class="punctuation token">}</span></code></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 Notifications')}}</td> + <td>{{Spec2('Web Notifications')}}</td> + <td>Living standard</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>5{{property_prefix("webkit")}}<sup>[1]</sup><br> + 22</td> + <td>4.0 {{property_prefix("moz")}}<sup>[2]</sup><br> + 22</td> + <td>{{CompatNo}}</td> + <td>25</td> + <td>6<sup>[3]</sup></td> + </tr> + <tr> + <td><code>icon</code></td> + <td>5{{property_prefix("webkit")}}<sup>[1]</sup><br> + 22</td> + <td>4.0 {{property_prefix("moz")}}<sup>[2]</sup><br> + 22</td> + <td>{{CompatNo}}</td> + <td>25</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>Available in workers</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("41.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>silent</code></td> + <td>{{CompatChrome(43.0)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>noscreen</code>, <code>sticky</code></td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>sound</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>renotify</code></td> + <td>{{CompatChrome(50.0)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>Promise-based <code>Notification.requestPermission()</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("47.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> + </table> + </div> + + <div id="compat-mobile"> + <table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Android Webview</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatUnknown}}</td> + <td> + <p>{{CompatVersionUnknown}}</p> + </td> + <td>4.0{{property_prefix("moz")}}<sup>[2]</sup><br> + 22</td> + <td>1.0.1{{property_prefix("moz")}}<sup>[2]</sup><br> + 1.2</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td> + <p>{{CompatVersionUnknown}}</p> + </td> + </tr> + <tr> + <td><code>icon</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>4.0{{property_prefix("moz")}}<sup>[2]</sup><br> + 22</td> + <td>1.0.1{{property_prefix("moz")}}<sup>[2]</sup><br> + 1.2</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Available in workers</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("41.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>silent</code></td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(43.0)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(43.0)}}</td> + </tr> + <tr> + <td><code>noscreen</code>, <code>sticky</code></td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>sound</code></td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>renotify</code></td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(50.0)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>Promise-based <code>Notification.requestPermission()</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("47.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> + </table> + </div> + + <p>[1] Before Chrome 22, the support for notification followed an <a href="http://www.chromium.org/developers/design-documents/desktop-notifications/api-specification">old prefixed version of the specification</a> and used the {{domxref("window.navigator.webkitNotifications","navigator.webkitNotifications")}} object to instantiate a new notification.</p> + + <p>Before Chrome 32, {{domxref("Notification.permission")}} was not supported.</p> + + <p>Before Chrome 42, service worker additions were not supported.</p> + + <p>Starting in Chrome 49, notifications do not work in incognito mode.</p> + + <p>[2] Prior to Firefox 22 (Firefox OS <1.2), the instantiation of a new notification must be done with the {{domxref("window.navigator.mozNotification", "navigator.mozNotification")}} object through its <code>createNotification</code> method.</p> + + <p>Prior to Firefox 22 (Firefox OS <1.2), the Notification was displayed when calling the <code>show</code> method and supported only the <code>click</code> and <code>close</code> events.</p> + + <p>Nick Desaulniers wrote a <a href="https://github.com/nickdesaulniers/fxos-irc/blob/master/js/notification.js">Notification shim</a> to cover both newer and older implementations.</p> + + <p>One particular Firefox OS issue is that you can <a href="https://github.com/nickdesaulniers/fxos-irc/blob/0160cf6c3a2b5c9fe33822aaf6bcba3b7e846da9/my.js#L171">pass a path to an icon</a> to use in the notification, but if the app is packaged you cannot use a relative path like <code>/my_icon.png</code>. You also can't use <code>window.location.origin + "/my_icon.png"</code> because <code>window.location.origin</code> is null in packaged apps. The <a href="https://developer.mozilla.org/en-US/Apps/Developing/Manifest#origin">manifest origin field</a> fixes this, but it is only available in Firefox OS 1.1+. A potential solution for supporting Firefox OS <1.1 is to <a href="https://github.com/nickdesaulniers/fxos-irc/blob/0160cf6c3a2b5c9fe33822aaf6bcba3b7e846da9/my.js#L168">pass an absolute URL to an externally hosted version of the icon</a>. This is less than ideal as the notification is displayed immediately without the icon, then the icon is fetched, but it works on all versions of Firefox OS.</p> + + <p>When using notifications in a Firefox OS app, be sure to add the <code>desktop-notification</code> permission in your manifest file. Notifications can be used at any permission level, hosted or above: <code>"permissions": { "desktop-notification": {} }</code></p> + + <p>[3] Safari started to support notification with Safari 6, but only on Mac OSX 10.8+ (Mountain Lion).</p> + + <h2 id="See_also">See also</h2> + <a href="https://developer.mozilla.org/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API">Using the Notifications API</a></dt> +</dl> diff --git a/files/es/web/api/notification/onclick/index.html b/files/es/web/api/notification/onclick/index.html new file mode 100644 index 0000000000..211947a1b8 --- /dev/null +++ b/files/es/web/api/notification/onclick/index.html @@ -0,0 +1,61 @@ +--- +title: Notification.onclick +slug: Web/API/notification/onclick +tags: + - API + - DOM + - Notifications + - Propiedad + - Referencia + - onclick +translation_of: Web/API/Notification/onclick +--- +<p>{{APIRef("Web Notifications")}}</p> + +<p>La propiedad <code>onclick</code> de la interfaz {{domxref("Notification")}} especifica un event listener para recibir eventos {{event("click")}}. Estos eventos ocurren cuando el usuario hace un click sobre el {{domxref("Notification")}} mostrado.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="eval">Notification.onclick = function(event) { ... }; +</pre> + +<p>El comportamiento por defecto es mover el foco al viewport del <a href="https://html.spec.whatwg.org/multipage/browsers.html#browsing-context">sitio de contexto</a> de dicha notificación. Si no deseas este comportamiento, puedes llamar <code><a href="/en-US/docs/Web/API/Event/preventDefault">preventDefault()</a></code> en el objeto del evento.</p> + +<h2 id="Ejemplos">Ejemplos</h2> + +<p>En el siguiente ejemplo, utilizamos un manejador <code>onclick</code> para abrir un sitio web en una nueva pestaña (especificado con la inclusión del parámetro <code>'_blank'</code>) una vez que la notifación es cliqueada.</p> + +<pre class="brush: js">notification.onclick = function(event) { + event.preventDefault(); // Previene al buscador de mover el foco a la pestaña del Notification + window.open('http://www.mozilla.org', '_blank'); +}</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('Web Notifications','#dom-notification-onclick','onclick')}}</td> + <td>{{Spec2('Web Notifications')}}</td> + <td>Living standard.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2> + +<p>{{Page("/en-US/docs/Web/API/Notification","Browser compatibility")}}</p> + +<h2 id="Mira_también">Mira también</h2> + +<ul> + <li>{{domxref("Notification")}}</li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API">Usando la API de Notifications</a></li> +</ul> diff --git a/files/es/web/api/notification/permission/index.html b/files/es/web/api/notification/permission/index.html new file mode 100644 index 0000000000..d528e2f9e0 --- /dev/null +++ b/files/es/web/api/notification/permission/index.html @@ -0,0 +1,191 @@ +--- +title: Notification.permission +slug: Web/API/notification/permission +translation_of: Web/API/Notification/permission +--- +<p>{{APIRef("Web Notifications")}}</p> + +<p>La propiedad <code>permission</code> es una propiedad de sólo lectura de la interfaz {{domxref("Notification")}}. Esta propiedad indica el permiso concedido por el usuario para mostrar notificaciones.</p> + +<p>{{AvailableInWorkers}}</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox">var <em>permission</em> = Notification.permission;</pre> + +<h3 id="Return_Value" name="Return_Value">Valor</h3> + +<p>Una {{domxref("DOMString")}} que representa el permiso actual. El valor puede ser:</p> + +<ul> + <li><code>granted</code>: El usuario ha concedido el permiso explicitamente al origen actual para mostrar notificaciones del sistema.</li> + <li><code>denied</code>: El usuario ha denegado el permiso explicitamente al origen actual para mostrar notificaciones del sistema.</li> + <li> + <p><code>default</code>: La decisión del usuario es deconocida; en este caso la aplicación actuará como si el permiso fuese <code>denied</code></p> + </li> +</ul> + +<h2 id="Ejemplos">Ejemplos</h2> + +<p>Podríamos usar el próximo fragmento para:</p> + +<ol> + <li>Comprobar si las notificaciones están soportadas</li> + <li>Comprobar si el permiso ha sido concedido para el origen actual + <ol> + <li>Si ha sido concedido, lanzar la notificación</li> + <li>Si no ha sido concedido, pedir el permiso</li> + <li>Si se concede, lanzar la notificación</li> + </ol> + </li> +</ol> + +<pre class="brush: js">function notifyMe() { + // Comprobamos si el navegador soporta las notificaciones + if (!("Notification" in window)) { + console.log("Este navegador no es compatible con las notificaciones de escritorio"); + } + + // Comprobamos si los permisos han sido concedidos anteriormente + else if (Notification.permission === "granted") { + // Si es correcto, lanzamos una notificación + var notification = new Notification("Hola!"); + } + + // Si no, pedimos permiso para la notificación + else if (Notification.permission !== 'denied' || Notification.permission === "default") { + Notification.requestPermission(function (permission) { + // Si el usuario nos lo concede, creamos la notificación + if (permission === "granted") { + var notification = new Notification("Hola!"); + } + }); + } + + // Por último, si el usuario ha denegado el permiso, y quieres ser respetuoso, no hay necesidad de molestarlo. +}</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName("Web Notifications","#dom-notification-permission","permission")}}</td> + <td>{{Spec2('Web Notifications')}}</td> + <td>Living standard</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_navegadores">Compatibilidad en navegadores</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>5 {{ property_prefix("webkit") }} (see notes)<br> + 22</td> + <td>{{CompatVersionUnknown}}</td> + <td>4.0 {{ property_prefix("moz") }} (see notes)<br> + 22</td> + <td>{{ CompatNo() }}</td> + <td>25</td> + <td>6 (see notes)</td> + </tr> + <tr> + <td>Available in workers</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("41.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Android Webview</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{ CompatUnknown() }}</td> + <td> + <p>{{CompatVersionUnknown}}</p> + </td> + <td>{{CompatVersionUnknown}}</td> + <td>4.0 {{ property_prefix("moz") }} (see notes)<br> + 22</td> + <td>1.0.1 {{ property_prefix("moz") }} (see notes)<br> + 1.2</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatNo() }}</td> + <td> + <p>{{CompatVersionUnknown}}</p> + </td> + </tr> + <tr> + <td>Available in workers</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile(41.0)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h3 id="Notas_de_Firefox_OS">Notas de Firefox OS</h3> + +<p>{{Page("/en-US/docs/Web/API/Notifications_API", "Firefox OS notes")}}</p> + +<h3 id="Notas_de_Chrome">Notas de Chrome</h3> + +<p>{{Page("/en-US/docs/Web/API/Notifications_API", "Chrome notes")}}</p> + +<h3 id="Notas_de_Safari">Notas de Safari</h3> + +<p>{{Page("/en-US/docs/Web/API/Notifications_API", "Safari notes")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="https://developer.mozilla.org/es/docs/Web/API/Notifications_API/Usando_la_API_de_Notificaciones">Usando la API de Notificaciones</a></li> + <li>{{domxref("Permissions_API","Permissions API")}}</li> +</ul> diff --git a/files/es/web/api/notification/requestpermission/index.html b/files/es/web/api/notification/requestpermission/index.html new file mode 100644 index 0000000000..6c4b8080b3 --- /dev/null +++ b/files/es/web/api/notification/requestpermission/index.html @@ -0,0 +1,143 @@ +--- +title: Notification.requestPermission() +slug: Web/API/notification/requestPermission +translation_of: Web/API/Notification/requestPermission +--- +<p>{{APIRef("Web Notifications")}}</p> + +<p>El método <strong><code>requestPermission()</code></strong> de la interfaz {{domxref("Notification")}} realiza una petición de permiso al usuario para que en ese <a href="https://es.wikipedia.org/wiki/Dominio_de_Internet">dominio web</a> se puedan mostrar notificaciones. </p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<p>La ultima especificación ha actualizado este método a una sintaxis basada en <code><a href="/es/docs/Web/JavaScript/Referencia/Objetos_globales/Promise">Promise</a></code>:</p> + +<pre class="brush: js">Notification.requestPermission().then(function(permission) { ... });</pre> + +<p>Anteriormente, la sintaxis se basaba en una simple retrollamada (callback); esta especificación ahora está obsoleta.</p> + +<pre class="brush: js">Notification.requestPermission(<em>callback</em>);</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code>callback</code> {{optional_inline}} {{deprecated_inline("gecko46")}}</dt> + <dd>Una retrollamada (callback) opcional que es ejecutado con el valor del permiso elegido por el usuario. Obsoleto y reemplazado por el valor de retorno de <code><a href="/es/docs/Web/JavaScript/Referencia/Objetos_globales/Promise">Promise</a></code>.</dd> +</dl> + +<h3 id="Retorno">Retorno</h3> + +<p>Devuleve un <code><a href="/es/docs/Web/JavaScript/Referencia/Objetos_globales/Promise">Promise</a></code> que se transforma a <code><a href="https://developer.mozilla.org/en-US/docs/Web/API/DOMString">DOMString</a></code> con el permiso escogido por el usuario. Los valores posibles para este son <code>granted</code>, <code>denied</code>, ó <code>default</code>.</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>El siguiente fragmento realiza la petición de permiso al usuario, después registra un resultado diferente dependiendo de la elección del usuario.</p> + +<pre class="brush: js">Notification.requestPermission(<span class="s1">function</span>(result) { + <span class="s1">if</span> (result === <span class="s2">'denied'</span>) { +<span class="s3"> console.log(</span>'Permission wasn\'t granted. Allow a retry.'<span class="s3">);</span> + <span class="s1">return</span>; + } else if (result === 'default') { + console.log('The permission request was dismissed.'); + return; + } + // Hacer algo con el permiso concedido. +});</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('Web Notifications')}}</td> + <td>{{Spec2('Web Notifications')}}</td> + <td>Living standard</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_los_buscadores">Compatibilidad con los buscadores</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>5 {{ property_prefix("webkit") }} (ver notas)<br> + 22</td> + <td>4.0 {{ property_prefix("moz") }} (ver notas)<br> + 22</td> + <td>{{ CompatNo() }}</td> + <td>25</td> + <td>6 (ver notas)</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Android Webview</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{ CompatUnknown() }}</td> + <td> + <p>{{CompatVersionUnknown}}</p> + </td> + <td>4.0 {{ property_prefix("moz") }} (ver notas)<br> + 22</td> + <td>1.0.1 {{ property_prefix("moz") }} (ver notas)<br> + 1.2</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatNo() }}</td> + <td> + <p>{{CompatVersionUnknown}}</p> + </td> + </tr> + </tbody> +</table> +</div> + +<h3 id="Notas_de_Firefox_OS">Notas de Firefox OS</h3> + +<p>{{Page("/en-US/docs/Web/API/Notifications_API", "Firefox OS notes")}}</p> + +<h3 id="Notas_de_Chrome">Notas de Chrome</h3> + +<p>{{Page("/en-US/docs/Web/API/Notifications_API", "Chrome notes")}}</p> + +<h3 id="Notas_de_Safari">Notas de Safari</h3> + +<p>{{Page("/en-US/docs/Web/API/Notifications_API", "Safari notes")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API">Usando la API de notificaciones</a></li> +</ul> diff --git a/files/es/web/api/notifications_api/index.html b/files/es/web/api/notifications_api/index.html new file mode 100644 index 0000000000..596064172e --- /dev/null +++ b/files/es/web/api/notifications_api/index.html @@ -0,0 +1,198 @@ +--- +title: Notifications API +slug: Web/API/Notifications_API +tags: + - Landing + - NeedsTranslation + - Notifications + - TopicStub + - permission + - system +translation_of: Web/API/Notifications_API +--- +<p>{{DefaultAPISidebar("Web Notifications")}}</p> + +<p class="summary">The Notifications API allows web pages to control the display of system notifications to the end user. These are outside the top-level browsing context viewport, so therefore can be displayed even when the user has switched tabs or moved to a different app. The API is designed to be compatible with existing notification systems, across different platforms.</p> + +<h2 id="Concepts_and_usage">Concepts and usage</h2> + +<p>On supported platforms, showing a system notification generally involves two things. First, the user needs to grant the current origin permission to display system notifications, which is generally done when the app or site initialises, using the {{domxref("Notification.requestPermission()")}} method. This will spawn a request dialog, along the following lines:</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/10819/notification-bubble.png" style="display: block; height: 205px; margin: 0 auto; width: 453px;"></p> + +<p>From here the user can choose to allow notifications from this origin, block notifications from this origin, or not choose at this point. Once a choice has been made, the setting will generally persist for the current session. </p> + +<div class="note"> +<p><strong>Note</strong>: As of Firefox 44, the permissions for Notifications and <a href="/en-US/docs/Web/API/Push_API">Push</a> have been merged. If permission is granted for notifications, push will also be enabled.</p> +</div> + +<p>Next, a new notification is created using the {{domxref("Notification.Notification","Notification()")}} constructor. This must be passed a title argument, and can optionally be passed an options object to specify options, such as text direction, body text, icon to display, notification sound to play, and more.</p> + +<p>{{AvailableInWorkers}}</p> + +<p>In addition, the Notifications API spec specifies a number of additions to the <a href="/en-US/docs/Web/API/ServiceWorker_API">ServiceWorker API</a>, to allow service workers to fire notifications.</p> + +<div class="note"> +<p><strong>Note</strong>: To find out more about using notifications in your own app, read <a href="/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API">Using the Notifications API</a>.</p> +</div> + +<h2 id="Notifications_interfaces">Notifications interfaces</h2> + +<dl> + <dt>{{domxref("Notification")}}</dt> + <dd>Defines a notification object.</dd> +</dl> + +<h3 id="Service_worker_additions">Service worker additions</h3> + +<dl> + <dt>{{domxref("ServiceWorkerRegistration")}}</dt> + <dd>Includes the {{domxref("ServiceWorkerRegistration.showNotification()")}} and {{domxref("ServiceWorkerRegistration.getNotifications()")}} method, for controlling the display of notifications.</dd> + <dt>{{domxref("ServiceWorkerGlobalScope")}}</dt> + <dd>Includes the {{domxref("ServiceWorkerGlobalScope.onnotificationclick")}} handler, for firing custom functions when a notification is clicked.</dd> + <dt>{{domxref("NotificationEvent")}}</dt> + <dd>A specific type of event object, based on {{domxref("ExtendableEvent")}}, which represents a notification that has fired.</dd> +</dl> + +<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 Notifications')}}</td> + <td>{{Spec2('Web Notifications')}}</td> + <td>Living standard</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>5{{property_prefix("webkit")}}<sup>[1]</sup><br> + 22</td> + <td>{{CompatGeckoDesktop("2.0")}}{{property_prefix("moz")}}<sup>[2]</sup><br> + {{CompatGeckoDesktop("22.0")}}</td> + <td>{{CompatNo}}</td> + <td>25</td> + <td>6<sup>[3]</sup></td> + </tr> + <tr> + <td>Available in workers</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("41.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Service worker additions</td> + <td> + <p>{{CompatChrome(42.0)}}</p> + </td> + <td>{{CompatGeckoDesktop("42.0")}}<sup>[4]</sup></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Android Webview</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatUnknown}}</td> + <td> + <p>{{CompatVersionUnknown}}</p> + </td> + <td>{{CompatGeckoMobile(2.0)}}{{property_prefix("moz")}}<sup>[2]</sup><br> + {{CompatGeckoMobile(22.0)}}</td> + <td>1.0.1{{property_prefix("moz")}}<sup>[2]</sup><br> + 1.2</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td> + <p>{{CompatVersionUnknown}}</p> + </td> + </tr> + <tr> + <td>Available in workers</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile(41.0)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Service worker additions</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoMobile(42.0)}}<sup>[4]</sup></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatChrome(42.0)}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Prior to Chrome 22, the support for notification followed an <a href="http://www.chromium.org/developers/design-documents/desktop-notifications/api-specification">old prefixed version of the specification</a> and used the {{domxref("window.navigator.webkitNotifications","navigator.webkitNotifications")}} object to instantiate a new notification. Prior to Chrome 32, {{domxref("Notification.permission")}} was not supported.</p> + +<p>[2] Prior to Firefox 22 (Firefox OS <1.2), the instantiation of a new notification was done with the {{domxref("window.navigator.mozNotification", "navigator.mozNotification")}} object through its <code>createNotification()</code> method. In addition, the Notification was displayed when calling the <code>show()</code> method, and supported only the <code>click</code> and <code>close</code> events (Nick Desaulniers wrote a <a href="https://github.com/nickdesaulniers/fxos-irc/blob/master/js/notification.js">Notification shim</a> to cover both newer and older implementations.)</p> + +<p>[3] Safari started to support notification with Safari 6, but only on Mac OSX 10.8+ (Mountain Lion).</p> + +<p>[4] Firefox 42 has shipped with web notifications from Service Workers disabled.</p> + +<h2 id="Firefox_OS_permissions">Firefox OS permissions</h2> + +<p>When using notifications in a Firefox OS app, be sure to add the <code>desktop-notification</code> permission in your manifest file. Notifications can be used at any permission level, hosted or above:</p> + +<pre class="brush: json">"permissions": { + "desktop-notification": {} +}</pre> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API">Using the Notifications API</a></li> +</ul> diff --git a/files/es/web/api/notifications_api/usando_la_api_de_notificaciones/index.html b/files/es/web/api/notifications_api/usando_la_api_de_notificaciones/index.html new file mode 100644 index 0000000000..8220534f63 --- /dev/null +++ b/files/es/web/api/notifications_api/usando_la_api_de_notificaciones/index.html @@ -0,0 +1,294 @@ +--- +title: Usando la API de Notificaciones +slug: Web/API/Notifications_API/Usando_la_API_de_Notificaciones +tags: + - API + - Notificaciones + - Tutorial +translation_of: Web/API/Notifications_API/Using_the_Notifications_API +--- +<p>{{APIRef("Web Notifications")}}</p> + +<p class="summary">La <a href="/en-US/docs/Web/API/Notifications_API">API de Notificaciones</a> permite a una página web enviar notificaciones que se mostrarán fuera de la web al nivel del sistema. Esto permite a las aplicaciones web enviar información al usuario aunque estas estén de fondo.</p> + +<p>{{AvailableInWorkers}}</p> + +<p>Para comenzar, tenemos que saber qué son las notificaciones y cómo se muestran. En la imagen de abajo se puede ver un ejemplo de notificaciones en android.</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/10959/android-notification.png" style="display: block; height: 184px; margin: 0px auto; width: 300px;"><img alt="" src="https://mdn.mozillademos.org/files/10961/mac-notification.png" style="display: block; height: 97px; margin: 0px auto; width: 358px;"></p> + +<p>El sistema de notificaciones variará según el navegador y la plataforma en la que estemos, pero esto no va a suponer ningún problema. La API de notificaciones está escrita de manera que sea compatible con la gran mayoría de sistemas.</p> + +<h2 id="Ejemplos">Ejemplos</h2> + +<div class="column-container"> +<div class="column-half"> +<p>Un ejemplo claro de uso de notificaciones web puede ser un mail basado en web o una aplicación IRC que nos notificará cada vez que nos llegue un nuevo mensaje, aunque estemos fuera de la aplicación. Un ejemplo de esto lo podemos ver en <a href="https://slack.com/">Slack</a>.</p> + +<p>Hemos escrito un par de ejemplos del mundo real para dar una idea más clara de cómo podemos usar las notificaciones web:</p> + +<ul> + <li><strong>Lista de pendientes</strong>: Esto es una app sencilla que almacena las tareas pendientes localmente usando <a href="/en-US/docs/Web/API/IndexedDB_API">IndexedDB</a> y avisa al usuario cuándo hay que realizar las tareas mediante notificaciones. <a href="https://github.com/mdn/to-do-notifications/tree/gh-pages">Descarga el código</a>, o echa un vistazo al <a href="http://mdn.github.io/to-do-notifications/">ejemplo en tiempo real</a>.</li> + <li><strong>Emogotchi</strong>: Una parodia absurda de Tamagotchi, en la que tienes que mantener a tu Emo miserable o perderás el juego. Esto usa las notificaciones del sistema para indicarte cómo lo estás haciendo y para quejarse de ti, TODO EL RATO. <a href="https://github.com/mdn/emogotchi">Descarga el código de Emogotchi</a>, o echa un vistazo a la <a href="http://mdn.github.io/emogotchi/">versión en tiempo real</a>.</li> +</ul> +</div> + +<div class="column-half"> +<p style="text-align: center;"><img alt="" src="https://mdn.mozillademos.org/files/10963/emogotchi.png" style="max-width: 300px; width: 70%;">.</p> +</div> +</div> + +<h2 id="Pidiendo_permiso">Pidiendo permiso</h2> + +<p>Antes de que una app pueda lanzar una notificación, el usuario tiene que darle permiso para ello. Esto es un requisito común cuando una API intenta interactuar con algo fuera de una página web — al menos una vez, el usuario tendrá que permitir a la aplicación mostrar notificaciones, de esta forma, el usuario decide qué aplicaciones le pueden mostrar notificaciones y cuáles no.</p> + +<h3 id="Comprobando_el_permiso_actual">Comprobando el permiso actual</h3> + +<p>Puedes comprobar si ya tienes permiso comprobando la propiedad {{domxref("Notification.permission")}} de solo lectura. Esta puede tener uno de los siguientes valores:</p> + +<dl> + <dt><code>default</code></dt> + <dd>No se le ha pedido permiso al usuario aún, por lo que la app no tiene permisos.</dd> + <dt><code>granted</code></dt> + <dd>El usuario ha permitido las notificaciones de la app.</dd> + <dt><code>denied</code></dt> + <dd>El usuario ha denegado las notificaciones de la app.</dd> +</dl> + +<h3 id="Obteniendo_permiso">Obteniendo permiso</h3> + +<p>Si la aplicación aún no tiene permiso para mostrar notificaciones, tendremos que hacer uso de {{domxref("Notification.requestPermission()")}} para pedir permiso al usuario. En su manera más simple, tal y como se usa en la <a href="http://mdn.github.io/emogotchi/">Demo de Emogotchi</a> (<a href="https://github.com/mdn/emogotchi">código fuente</a>), solo tenemos que incluir lo siguiente:</p> + +<pre class="brush: js">Notification.requestPermission().then(function(result) { + console.log(result); +});</pre> + +<p>Esto usa la versión promise del método, que está soportada en las versiones recientes (p.ej. Firefox 47). Si quieres soportar versiones más antiguas tendrás que usar la versión de callback, que es la siguiente:</p> + +<pre class="brush: js">Notification.requestPermission();</pre> + +<p>La versión de callback acepta de forma opcional una función callback que será ejecutada cuando el usuario responda a si quiere notificaciones o no (tal y como se ve en el segundo <code>else ... if</code> abajo). Por lo general, pedirás permiso para mostrar notificaciones una vez que hayas inicializado la app, y antes de lanzar una notificación. Si quieres ser muy cuidadoso puedes usar lo siguiente (ver <a href="https://github.com/mdn/to-do-notifications/blob/gh-pages/scripts/todo.js#L305-L344">To-do List Notifications</a>):</p> + +<pre class="brush: js">function notifyMe() { + // Comprobamos si el navegador soporta las notificaciones + if (!("Notification" in window)) { + alert("Este navegador no soporta las notificaciones del sistema"); + } + + // Comprobamos si ya nos habían dado permiso + else if (Notification.permission === "granted") { + // Si esta correcto lanzamos la notificación + var notification = new Notification("Holiwis :D"); + } + + // Si no, tendremos que pedir permiso al usuario + else if (Notification.permission !== 'denied') { + Notification.requestPermission(function (permission) { + // Si el usuario acepta, lanzamos la notificación + if (permission === "granted") { + var notification = new Notification("Gracias majo!"); + } + }); + } + + // Finalmente, si el usuario te ha denegado el permiso y + // quieres ser respetuoso no hay necesidad molestar más. +}</pre> + +<div class="note"> +<p><strong>Nota:</strong> Antes de la versión 37, Chrome no te deja llamar a {{domxref("Notification.requestPermission()")}} en manejador de eventos <code>load</code> (ver <a href="https://code.google.com/p/chromium/issues/detail?id=274284" title="https://code.google.com/p/chromium/issues/detail?id=274284">problema 274284</a>).</p> +</div> + +<h3 id="Permisos_en_Firefox_OS_manifest">Permisos en Firefox OS manifest</h3> + +<p>Ten en cuenta que mientras la API de Notificaciones no esté {{Glossary("privileged")}} o {{Glossary("certified")}}, deberías seguir inculyendo una entrada en tu archivo <code>manifest.webapp</code> cuando vayas a usarlo en una app en Firefox OS:</p> + +<pre>"permissions": { + "desktop-notification": { + "description": "Needed for creating system notifications." + } +}, +"messages": [{"notification": "path/to/your/index.html"}] + +</pre> + +<div class="note"> +<p><strong>Nota</strong>: Cuándo una aplicación es instalada, no deberías de necesitar {{anch("Getting permission","explicitly request permission")}}, pero vas a seguir necesitando los permisos y las entradas de texto de arriba para poder lanzar las notificaciones.</p> +</div> + +<h2 id="Creando_una_notificación">Creando una notificación</h2> + +<p>Crear una notificación es fácil, simplemente usa el constructor {{domxref("Notification")}}. Este constructor espera un título que mostrar en la notificación y otras opciones para mejorar la notificación, como un {{domxref("Notification.icon","icon")}} o un texto {{domxref("Notification.body","body")}}.</p> + +<p>Por ejemplo, en el <a href="https://github.com/mdn/emogotchi/blob/master/main.js#L109-L127">Ejemplo de Emogotchi</a> tenemos dos funciones que pueden ser llamadas cuando hay que lanzar una notificación; el uso de una u otra depende de si queremos establecer el contenido de la notificación, o si queremos una notificación con contenido aleatorio:</p> + +<pre class="brush: js">function spawnNotification(theBody,theIcon,theTitle) { + var options = { + body: theBody, + icon: theIcon + } + var n = new Notification(theTitle,options); + setTimeout(n.close.bind(n), 5000); +} + +function randomNotification() { + var randomQuote = quoteChooser(); + var options = { + body: randomQuote, + icon: 'img/sad_head.png', + } + + var n = new Notification('Emogotchi says',options); + setTimeout(n.close.bind(n), 5000); +}</pre> + +<h2 id="Cerrando_las_notificaciones">Cerrando las notificaciones</h2> + +<p>Firefox y Safari cierran las notificaciones automáticamente tras cierto tiempo (unos 4 segundos). Esto también puede suceder a nivel de sistema operativo (en Windows duran 7 segundos por defecto). En cambio, en algunos navegadores no se cierran automáticamente, como en Chrome, por ejemplo. Para asegurarnos de que las notificaciones se cierran en todos los navegadores, al final de las funciones de arriba, llamamos a la función {domxref("Notification.close")}} dentro de {{domxref("WindowTimers.setTimeout","setTimeout()")}} para cerrar la notificación tras 5 segundos. Date cuenta también del uso que hacemos de <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind">bind()</a></code> para asegurarnos de que la función <code>close()</code> está asociada a la notificación.</p> + +<pre class="brush: js">setTimeout(n.close.bind(n), 5000); +</pre> + +<div class="note"> +<p><strong>Nota</strong>: Cuándo recibes un evento "close", no hay ninguna garantía de que haya sido el usuario quién ha cerrado la notificación. Esto coincide con la especificación que dice: "Cuando una notificación es cerrada, sea por la misma plataforma o por el usuario, se deben lanzar los pasos de cierre para la misma".</p> +</div> + +<h2 id="Eventos_de_Notificación">Eventos de Notificación</h2> + +<p>Las especificaciones de la API de notificaciones listan cuatro eventos que pueden ser lanzados en la instancia {{domxref("Notification")}}:</p> + +<dl> + <dt>{{event("click")}}</dt> + <dd>Lanzado cuando el usuario hace click en la notificación.</dd> + <dt>{{event("error")}}</dt> + <dd>Lanzado cuando algo falla en la notificación; habitualmente es porque la notificación no se ha podido mostrar por algún motivo.</dd> +</dl> + +<p>Estos eventos se pueden monitorizar usando los manejadores {{domxref("Notification.onclick","onclick")}} y {{domxref("Notification.onerror","onerror")}}. Como {{domxref("Notification")}} también hereda de {{domxref("EventTarget")}}, es posible usar el método {{domxref("EventTarget.addEventListener","addEventListener()")}} en ella.</p> + +<p>También hay otros dos eventos que estaban listados en la especificación, pero que han sido eliminados recientemente. Estos puede que sigan funcionando en los navegadores por ahora, pero deberían tratarse como obsoletos y evitar su uso:</p> + +<dl> + <dt>{{event("close")}}</dt> + <dd>Lanzado cuándo la notificación se cierra.</dd> + <dt>{{event("show")}}</dt> + <dd>Lanzado cuándo la notificación se muestra al usuario.</dd> +</dl> + +<h2 id="Reemplazando_notificaciones_existentes">Reemplazando notificaciones existentes</h2> + +<p>Normalmente los usuario no quieren recibir muchas notificaciones en poco tiempo — por ejemplo, una aplicación de mensajería que te notifica cada mensaje que te llegue, y te llegan un montón. Para evitar el spam de notificaciones, se puede modificar la cola de notificaciones, reemplazando una o varias notificaciones pendientes, por una nueva notificación.</p> + +<p>Para hacer esto, se puede añadir una etiqueta a cualquier nueva notificación. Si ya hay una notificación con la misma etiqueta y aún no se ha mostrado, la nueva reemplazará a la anterior. Si la notificación con la misma etiqueta ya ha sido mostrada, se cerrará la anterior y se mostrará la nueva.</p> + +<h3 id="Ejemplo_de_etiquta">Ejemplo de etiquta</h3> + +<p>Teniendo el siguiente código HTML:</p> + +<pre class="brush: html"><button>Notifícame!</button></pre> + +<p>Es posible controlar múltiples notificaciones de la siguiente forma:</p> + +<pre class="brush: js">window.addEventListener('load', function () { + // Primero, comprobamos si tenemos permiso para lanzar notificaciones + // Si no lo tenemos, lo pedimos + if (window.Notification && Notification.permission !== "granted") { + Notification.requestPermission(function (status) { + if (Notification.permission !== status) { + Notification.permission = status; + } + }); + } + + var button = document.getElementsByTagName('button')[0]; + + button.addEventListener('click', function () { + // Si el usuario ha dado permiso + // le intentamos enviar 10 notificaciones + if (window.Notification && Notification.permission === "granted") { + var i = 0; + // Usamos un inteval porque algunos navegadores (Firefox incluído) bloquean las notificaciones si se envían demasiadas en cierto tiempo. + var interval = window.setInterval(function () { + // Gracias a la etiqueta, deberíamos de ver sólo la notificación "Holiws! 9" + var n = new Notification("Holiwis! " + i, {tag: 'soManyNotification'}); + if (i++ == 9) { + window.clearInterval(interval); + } + }, 200); + } + + // Si el usuario no ha dicho si quiere notificaciones + // Nota: en Chrome no estamos seguros de si la propiedad permission + // esta asignada, por lo que es inseguro comprobar el valor "default". + else if (window.Notification && Notification.permission !== "denied") { + Notification.requestPermission(function (status) { + // Si el usuario acepta + if (status === "granted") { + var i = 0; + // Usamos un inteval porque algunos navegadores (Firefox incluído) bloquean las notificaciones si se envían demasiadas en cierto tiempo. + var interval = window.setInterval(function () { + // Gracias a la etiqueta, deberíamos de ver sólo la notificación "Holiws! 9" var n = new Notification("Holiwis! " + i, {tag: 'soManyNotification'}); + if (i++ == 9) { + window.clearInterval(interval); + } + }, 200); + } + + // Otherwise, we can fallback to a regular modal alert + else { + alert("Hi!"); + } + }); + } + + // If the user refuses to get notified + else { + // We can fallback to a regular modal alert + alert("Hi!"); + } + }); +});</pre> + +<p>Comprueba el ejemplo en directo abajo:</p> + +<p>{{ EmbedLiveSample('Tag_example', '100%', 30) }}</p> + +<h2 id="Receiving_notification_of_clicks_on_app_notifications">Receiving notification of clicks on app notifications</h2> + +<p>When a user clicks on a notification generated by an app, you will be notified of this event in two different ways, depending on the circumstance:</p> + +<ol> + <li>A click event if your app has not closed or been put in the background between the time you create the notification and the time the user clicks on it.</li> + <li>A <a href="/en-US/docs/Web/API/Navigator/mozSetMessageHandler">system message</a> otherwise.</li> +</ol> + +<p>See <a href="https://github.com/mozilla/buddyup/commit/829cba7afa576052cf601c3e286b8d1981f93f45#diff-3">this code snippet</a> for an example of how to deal with this.</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('Web Notifications')}}</td> + <td>{{Spec2('Web Notifications')}}</td> + <td>Living standard</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2> + +<p>{{page("/en-US/Web/API/Notification","Browser compatibility")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="/en-US/Apps/Build/User_notifications">User notifications reference</a></li> + <li><a href="/en-US/Apps/Build/User_notifications/Notifying_users_via_the_Notification_and_Vibration">Notifying users via the Notification and Vibration APIs</a></li> + <li>{{ domxref("Notification") }}</li> +</ul> diff --git a/files/es/web/api/parentnode/append/index.html b/files/es/web/api/parentnode/append/index.html new file mode 100644 index 0000000000..3899492a80 --- /dev/null +++ b/files/es/web/api/parentnode/append/index.html @@ -0,0 +1,134 @@ +--- +title: ParentNode.append() +slug: Web/API/ParentNode/append +translation_of: Web/API/ParentNode/append +--- +<div>{{APIRef("DOM")}}</div> + +<p><code style=""><font face="Arial, x-locale-body, sans-serif"><span style="background-color: #ffffff;">El método </span></font><strong>ParentNode.append()</strong></code> inserta un conjunto de objetos de tipo {{domxref("Node")}} u objetos de tipo {{domxref("DOMString")}} después del último hijo de <code>ParentNode</code>. Los objetos {{domxref("DOMString")}} son insertados como nodos {{domxref("Text")}} equivalentes.</p> + +<p>Diferencias con {{domxref("Node.appendChild()")}}:</p> + +<ul> + <li><code>ParentNode.append()</code> te permite también agregar objetos {{domxref("DOMString")}}, mientras que <code>Node.appendChild()</code> solo acepta objetos {{domxref("Node")}}.</li> + <li><code>ParentNode.append()</code> no tiene valor de retorno, en cambio, <code>Node.appendChild()</code> devuelve el objeto {{domxref("Node")}} agregado.</li> + <li><code>ParentNode.append()</code> puede agregar varios nodos y cadenas, mientras que <code>Node.appendChild()</code> sólo puede agregar uno.</li> +</ul> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">[Throws, Unscopable] +void ParentNode.append((Node or DOMString)... nodes); +</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>nodes</code></dt> + <dd>Un conjunto de {{domxref("Node")}} u objetos {{domxref("DOMString")}} a agegar.</dd> +</dl> + +<h3 id="Exceptions">Exceptions</h3> + +<ul> + <li>{{domxref("HierarchyRequestError")}}: Node cannot be inserted at the specified point in the hierarchy.</li> +</ul> + +<h2 id="Examples">Examples</h2> + +<h3 id="Appending_an_element">Appending an element</h3> + +<pre class="brush: js">var parent = document.createElement("div"); +var p = document.createElement("p"); +parent.append(p); + +console.log(parent.childNodes); // NodeList [ <p> ] +</pre> + +<h3 id="Appending_text">Appending text</h3> + +<pre class="brush: js">var parent = document.createElement("div"); +parent.append("Some text"); + +console.log(parent.textContent); // "Some text"</pre> + +<h3 id="Appending_an_element_and_text">Appending an element and text</h3> + +<pre class="brush: js">var parent = document.createElement("div"); +var p = document.createElement("p"); +parent.append("Some text", p); + +console.log(parent.childNodes); // NodeList [ #text "Some text", <p> ]</pre> + +<h3 id="ParentNode.append_is_unscopable"><code>ParentNode.append()</code> is unscopable</h3> + +<p>The <code>append()</code> method is not scoped into the <code>with</code> statement. See {{jsxref("Symbol.unscopables")}} for more information.</p> + +<pre class="brush: js">var parent = document.createElement("div"); + +with(parent) { + append("foo"); +} +// ReferenceError: append is not defined </pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>You can polyfill the <code>append() method</code> in Internet Explorer 9 and higher with the following code:</p> + +<pre class="brush: js">// Source: https://github.com/jserz/js_piece/blob/master/DOM/ParentNode/append()/append().md +(function (arr) { + arr.forEach(function (item) { + if (item.hasOwnProperty('append')) { + return; + } + Object.defineProperty(item, 'append', { + configurable: true, + enumerable: true, + writable: true, + value: function append() { + var argArr = Array.prototype.slice.call(arguments), + docFrag = document.createDocumentFragment(); + + argArr.forEach(function (argItem) { + var isNode = argItem instanceof Node; + docFrag.appendChild(isNode ? argItem : document.createTextNode(String(argItem))); + }); + + this.appendChild(docFrag); + } + }); + }); +})([Element.prototype, Document.prototype, DocumentFragment.prototype]);</pre> + +<h2 id="Specification">Specification</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('DOM WHATWG', '#dom-parentnode-append', 'ParentNode.append()')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("api.ParentNode.append")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{domxref("ParentNode")}} and {{domxref("ChildNode")}}</li> + <li>{{domxref("ParentNode.prepend()")}}</li> + <li>{{domxref("Node.appendChild()")}}</li> + <li>{{domxref("ChildNode.after()")}}</li> + <li>{{domxref("NodeList")}}</li> +</ul> diff --git a/files/es/web/api/parentnode/childelementcount/index.html b/files/es/web/api/parentnode/childelementcount/index.html new file mode 100644 index 0000000000..3e8c834262 --- /dev/null +++ b/files/es/web/api/parentnode/childelementcount/index.html @@ -0,0 +1,126 @@ +--- +title: ParentNode.childElementCount +slug: Web/API/ParentNode/childElementCount +tags: + - API + - ChildNode + - DOM + - ParentNode + - childElement + - children +translation_of: Web/API/ParentNode/childElementCount +--- +<div> +<p>{{ APIRef("DOM") }}</p> +</div> + +<p>La propiedad de sólo lectura <code><strong>ParentNode.childElementCount</strong></code> devuelve un número del tipo <code>unsigned long</code> que representa la cantidad de elementos hijo que penden del elemento padre (ParentNode).</p> + +<div class="note"> +<p>Esta propiedad fue inicialmente definida en la interfaz pura {{domxref("ElementTraversal")}}. Como esta interfaz contenía dos conjuntos distintos de propiedades: una apuntaba al {{domxref("Node")}} con hijos y otra a los hijos, fueron trasladados a dos interfaces puras separadas: {{domxref("ParentNode")}} y {{domxref("ChildNode")}}. En este caso, <code>childElementCount</code> se mudó a {{domxref("ParentNode")}}. Este es un cambio bastante técnico que no debería afectar a la compatibilidad.</p> +</div> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox">var <var>elCount</var> = elementNodeReference.childElementCount; +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Espacificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('DOM WHATWG', '#dom-parentnode-childElementCount', 'ParentNode.childElementCount')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Dividida la interfaz <code>ElementTraversal</code> en {{domxref("ChildNode")}} y <code>ParentNode</code>. Este método está ahora definido en la segunda.<br> + Se implementaron las nuevas interfaces en {{domxref("Document")}} y {{domxref("DocumentFragment")}}.</td> + </tr> + <tr> + <td>{{SpecName('Element Traversal', '#attribute-childElementCount', 'ElementTraversal.childElementCount')}}</td> + <td>{{Spec2('Element Traversal')}}</td> + <td>Añadida su definición inicial a la interfaz pura <code>ElementTraversal</code> y se emplea en {{domxref("Element")}}.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_navegadores">Compatibilidad en navegadores</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico (para {{domxref("Element")}})</td> + <td>1.0</td> + <td>{{CompatGeckoDesktop("1.9.1")}}</td> + <td>9.0 [1]</td> + <td>10.0</td> + <td>4.0</td> + </tr> + <tr> + <td>Soporta {{domxref("Document")}} y {{domxref("DocumentFragment")}} {{experimental_inline}}</td> + <td>29.0</td> + <td>{{CompatGeckoDesktop("25.0")}}</td> + <td>{{CompatNo}}</td> + <td>16.0</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico (para {{domxref("Element")}})</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{CompatGeckoMobile("1.9.1")}}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + <tr> + <td>Soporta {{domxref("Document")}} y {{domxref("DocumentFragment")}} {{experimental_inline}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("25.0")}}</td> + <td>{{CompatNo}}</td> + <td>16.0</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Internet Explorer 6, 7 y 8 lo soportan, pero cuenta los nodos {{domxref("Comment")}} de forma incorrecta.</p> + +<h2 id="Véase_también">Véase también</h2> + +<ul> + <li>Las interfaces puras {{domxref("ParentNode")}} y {{domxref("ChildNode")}}.</li> + <li> + <div class="syntaxbox">Tipos de objeto que implementan estas interfaces: {{domxref("Document")}}, {{domxref("Element")}}, y {{domxref("DocumentFragment")}}.</div> + </li> +</ul> diff --git a/files/es/web/api/parentnode/children/index.html b/files/es/web/api/parentnode/children/index.html new file mode 100644 index 0000000000..8a9071830c --- /dev/null +++ b/files/es/web/api/parentnode/children/index.html @@ -0,0 +1,157 @@ +--- +title: ParentNode.children +slug: Web/API/ParentNode/children +tags: + - API + - DOM + - ParentNode + - Propiedad +translation_of: Web/API/ParentNode/children +--- +<p>{{ APIRef("DOM") }}</p> + +<p><code><strong>Node.children</strong></code> es una propiedad de sólo lectura que retorna una {{domxref("HTMLCollection")}} "viva" de los elementos hijos de un <code>Node</code>.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var <em>children</em> = <em>node</em>.children; </pre> + +<p><code><var>children</var></code> es una {{ domxref("HTMLCollection") }}, que es una colección ordenada de los elementos DOM que son hijos <code>de <em>node</em></code>. Si no hay elementos hijos, entonces <code><var>children</var></code> no contendrá elementos y su longitud ( <code>length</code> ) será <code>0</code>.</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush: js">var foo = document.getElementById('foo'); +for (var i = 0; i < foo.children.length; i++) { + console.log(foo.children[i].tagName); +} +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<pre class="brush: js">// Sobrescribe el prototipo 'children' nativo. +// Añade soporte para Document y DocumentFragment en IE9 y Safari. +// Devuelve un array en lugar de HTMLCollection. +;(function(constructor) { + if (constructor && + constructor.prototype && + constructor.prototype.children == null) { + Object.defineProperty(constructor.prototype, 'children', { + get: function() { + var i = 0, node, nodes = this.childNodes, children = []; + while (node = nodes[i++]) { + if (node.nodeType === 1) { + children.push(node); + } + } + return children; + } + }); + } +})(window.Node || window.Element); +</pre> + +<h2 id="Especificación">Especificación</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Observaciones</th> + </tr> + <tr> + <td>{{SpecName('DOM WHATWG', '#dom-parentnode-children', 'ParentNode.children')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Definición Inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Edge</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico (en {{domxref("Element")}})</td> + <td>1.0</td> + <td>{{CompatGeckoDesktop("1.9.1")}}</td> + <td>9.0 [1]</td> + <td>38.0</td> + <td>10.0</td> + <td>4.0</td> + </tr> + <tr> + <td>Soporte en {{domxref("Document")}} y {{domxref("DocumentFragment")}} {{experimental_inline}}</td> + <td>29.0</td> + <td>{{CompatGeckoDesktop("25.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>16.0</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>Soporte en {{domxref("SVGElement")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico (en {{domxref("Element")}})</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{CompatGeckoMobile("1.9.1")}}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + <tr> + <td>Soporte básico {{domxref("Document")}} y {{domxref("DocumentFragment")}} {{experimental_inline}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("25.0")}}</td> + <td>{{CompatNo}}</td> + <td>16.0</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Internet Explorer 6, 7 y 8 lo soportan, pero incluyen nodos {{domxref("Comment")}} de manera errónea.</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>Las interfaces {{domxref("ParentNode")}} y {{domxref("ChildNode")}}.</li> + <li> + <div class="syntaxbox">Tipos e objetos que implementan este interfaz: {{domxref("Document")}}, {{domxref("Element")}}, y {{domxref("DocumentFragment")}}.</div> + </li> +</ul> diff --git a/files/es/web/api/parentnode/firstelementchild/index.html b/files/es/web/api/parentnode/firstelementchild/index.html new file mode 100644 index 0000000000..a9993d8ccf --- /dev/null +++ b/files/es/web/api/parentnode/firstelementchild/index.html @@ -0,0 +1,143 @@ +--- +title: ParentNode.firstElementChild +slug: Web/API/ParentNode/firstElementChild +translation_of: Web/API/ParentNode/firstElementChild +--- +<p>{{ APIRef("DOM") }}</p> + +<p><span style="font-family: verdana,tahoma,sans-serif;">La propiedad de sólo lectura </span><strong><code>ParentNode.firstElementChild</code></strong> retorna el primer hijo del objeto {{domxref("Element")}}, o bien <code>null</code> si no existen elementos hijos.</p> + +<div class="note"> +<p>Esta propiedada fue definida inicialmente en el interfaz puro {{domxref("ElementTraversal")}}. Como este interfaz contenía dos juegos distintos de propiedades, uno orientado a {{domxref("Node")}} que tenía hijos, y otro a aquellos que eran hijos, se trasladaron a dos interfaces puros separados, {{domxref("ParentNode")}} y {{domxref("ChildNode")}}. En este caso, <code>firstElementChild</code> fue movido a {{domxref("ParentNode")}}. Es un cambio de carácter estrictamente técnico que no debería afectar a la compatibilidad.</p> +</div> + +<h2 id="Syntax_and_values" name="Syntax_and_values">Sintaxis</h2> + +<pre class="syntaxbox">var <em>childNode</em> = elementNodeReference.firstElementChild; +</pre> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre class="brush: html"><p id="para-01"> + <span>First span</span> +</p> + +<script type="text/javascript"> + var p01 = document.getElementById('para-01'); + alert(p01.firstElementChild.nodeName) +</script></pre> + +<p>En este ejemlpo, la alerta muestra 'span', que es el nombre de la etiqueta del primer nodo hijo dele elemento párrafo.</p> + +<h2 id="Polyfill_para_Internet_Explorer_8">Polyfill para Internet Explorer 8</h2> + +<p>Esta propiedad no está soportada con anterioridad a IE9, así que el siguiente fragmento puede ser usado para añadir el soporte a IE8:</p> + +<pre class="brush: js">// Source: https://github.com/Alhadis/Snippets/blob/master/js/polyfills/IE8-child-elements.js +if(!("firstElementChild" in document.documentElement)){ + Object.defineProperty(Element.prototype, "firstElementChild", { + get: function(){ + for(var nodes = this.children, n, i = 0, l = nodes.length; i < l; ++i) + if(n = nodes[i], 1 === n.nodeType) return n; + return null; + } + }); +}</pre> + +<h2 id="Especificación">Especificación</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Observaciones</th> + </tr> + <tr> + <td>{{SpecName('DOM WHATWG', '#dom-parentnode-firstelementchild', 'ParentNode.firstElementChild')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Dividido el interfaz <code>ElementTraversal</code> en {{domxref("ChildNode")}} y <code>ParentNode</code>. Este método queda definido ahora en el segundo.<br> + Los {{domxref("Document")}} y {{domxref("DocumentFragment")}} implementaron los nuevos interfaces.</td> + </tr> + <tr> + <td>{{SpecName('Element Traversal', '#attribute-firstElementChild', 'ElementTraversal.firstElementChild')}}</td> + <td>{{Spec2('Element Traversal')}}</td> + <td>Añadida su definición inicial al interfaz puro <code>ElementTraversal</code> y lo usa en {{domxref("Element")}}.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Prestación</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico (en {{domxref("Element")}})</td> + <td>1.0</td> + <td>{{CompatGeckoDesktop("1.9.1")}}</td> + <td>9.0</td> + <td>10.0</td> + <td>4.0</td> + </tr> + <tr> + <td>Soporte en {{domxref("Document")}} y {{domxref("DocumentFragment")}} {{experimental_inline}}</td> + <td>29.0</td> + <td>{{CompatGeckoDesktop("25.0")}}</td> + <td>{{CompatNo}}</td> + <td>16.0</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Prestación</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico (en {{domxref("Element")}})</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{CompatGeckoMobile("1.9.1")}}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + <tr> + <td>Soporte en {{domxref("Document")}} y {{domxref("DocumentFragment")}} {{experimental_inline}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("25.0")}}</td> + <td>{{CompatNo}}</td> + <td>16.0</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>Los interfaces puros {{domxref("ParentNode")}} y {{domxref("ChildNode")}}.</li> + <li> + <div class="syntaxbox">Objetos que implementan estos interfaces puros: {{domxref("Document")}}, {{domxref("Element")}}, y {{domxref("DocumentFragment")}}.</div> + </li> +</ul> diff --git a/files/es/web/api/parentnode/index.html b/files/es/web/api/parentnode/index.html new file mode 100644 index 0000000000..53af6c3203 --- /dev/null +++ b/files/es/web/api/parentnode/index.html @@ -0,0 +1,151 @@ +--- +title: ParentNode +slug: Web/API/ParentNode +tags: + - API DOM Tab + - NeedsTranslation + - TopicStub +translation_of: Web/API/ParentNode +--- +<p>{{ APIRef("DOM") }}</p> + +<p>The <code><strong>ParentNode</strong></code> interface contains methods that are particular to {{domxref("Node")}} objects that can have children.</p> + +<p><code>ParentNode</code> is a raw interface and no object of this type can be created; it is implemented by {{domxref("Element")}}, {{domxref("Document")}}, and {{domxref("DocumentFragment")}} objects.</p> + +<p> </p> + +<h2 id="Properties">Properties</h2> + +<dl> + <dt>{{ domxref("ParentNode.children") }} {{experimental_inline}} {{readonlyInline}}</dt> + <dd>Returns a live {{domxref("HTMLCollection")}} containing all objects of type {{domxref("Element")}} that are children of this <code>ParentNode</code>.</dd> + <dt>{{ domxref("ParentNode.firstElementChild") }} {{experimental_inline}} {{readonlyInline}}</dt> + <dd>Returns the {{domxref("Element")}} that is the first child of this <code>ParentNode</code>, or <code>null</code> if there is none.</dd> + <dt>{{ domxref("ParentNode.lastElementChild") }} {{experimental_inline}} {{readonlyInline}}</dt> + <dd>Returns the {{domxref("Element")}} that is the last child of this <code>ParentNode</code>, or <code>null</code> if there is none.</dd> + <dt>{{ domxref("ParentNode.childElementCount") }} {{experimental_inline}} {{readonlyInline}}</dt> + <dd>Returns an <code>unsigned long</code> giving the amount of children that the object has.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<p><em>There is no inherited or specific and implemented methods.</em></p> + +<h2 id="Specification">Specification</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('DOM WHATWG', '#dom-parentnode-firstelementchild', 'ParentNode.firstElementChild')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Splitted the <code>ElementTraversal</code> interface in {{domxref("ChildNode")}} and <code>ParentNode</code>. The <code>firstElementChild</code>, <code>lastElementChild</code>, and <code>childElementCount</code> properties are now defined on the latter.<br> + The {{domxref("Document")}} and {{domxref("DocumentFragment")}} implemented the new interfaces.<br> + Added the <code>children</code> property.<br> + Added the <code>append()</code> and <code>prepend()</code> methods.</td> + </tr> + <tr> + <td>{{SpecName('Element Traversal', '#interface-elementTraversal', 'ElementTraversal')}}</td> + <td>{{Spec2('Element Traversal')}}</td> + <td>Added the initial definition of its properties to the <code>ElementTraversal</code> pure interface and use it on {{domxref("Element")}}.</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 (on {{domxref("Element")}})</td> + <td>1.0</td> + <td>{{CompatGeckoDesktop("1.9.1")}}</td> + <td>9.0 [1]</td> + <td>10.0</td> + <td>4.0</td> + </tr> + <tr> + <td>Support on {{domxref("Document")}} and {{domxref("DocumentFragment")}} {{experimental_inline}}</td> + <td>29.0</td> + <td>{{CompatGeckoDesktop("25.0")}}</td> + <td>{{CompatNo}}</td> + <td>16.0</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>append()</code> and <code>prepend()</code> {{experimental_inline}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</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>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support (on {{domxref("Element")}})</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{CompatGeckoMobile("1.9.1")}}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + <tr> + <td>Support on {{domxref("Document")}} and {{domxref("DocumentFragment")}} {{experimental_inline}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("25.0")}}</td> + <td>{{CompatNo}}</td> + <td>16.0</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>append()</code> and <code>prepend()</code> {{experimental_inline}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Internet Explorer 6, 7 and 8 supported it, but erroneously returns {{domxref("Comment")}} nodes as part of the results.</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>The {{domxref("ChildNode")}} pure interface.</li> + <li> + <div class="syntaxbox">Object types implementing this pure interface: {{domxref("Document")}}, {{domxref("Element")}}, and {{domxref("DocumentFragment")}}.</div> + </li> +</ul> diff --git a/files/es/web/api/parentnode/lastelementchild/index.html b/files/es/web/api/parentnode/lastelementchild/index.html new file mode 100644 index 0000000000..c644b90db8 --- /dev/null +++ b/files/es/web/api/parentnode/lastelementchild/index.html @@ -0,0 +1,146 @@ +--- +title: ParentNode.lastElementChild +slug: Web/API/ParentNode/lastElementChild +translation_of: Web/API/ParentNode/lastElementChild +--- +<p>{{ APIRef("DOM") }}</p> + +<p>La propiedad de sólo lectura <code><strong>ParentNode.lastElementChild</strong></code> retorna el último hijo del objeto {{domxref("Element")}} o bien <code>null</code> si no hay elementos hijos.</p> + +<div class="note"> +<p>Esta propiedad fue inicialmente definida en el interfaz puro {{domxref("ElementTraversal")}}. Dado que este interfaz contenía dos juegos distintos de propiedades, uno dirigido al nodo {{domxref("Node")}} que tiene hijos, y otro a aquellos que son hijos, se han trasladado a dos interfaces puros separados, {{domxref("ParentNode")}} y {{domxref("ChildNode")}}. En este caso, <code>lastElementChild</code> fue movido a {{domxref("ParentNode")}}. Este es un cambio de carácter técnico que no debería afectar a la compatibilidad.</p> +</div> + +<h2 id="Syntax_and_values" name="Syntax_and_values">Sintaxis</h2> + +<pre class="syntaxbox">var <em>childNode</em> = elementNodeReference.lastElementChild; </pre> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre class="brush: html"><p id="para-01"> + <span>First span</span> + <b>bold</b> +</p> + +<script type="text/javascript"> + var p01 = document.getElementById('para-01'); + alert(p01.lastElementChild.nodeName) +</script> +</pre> + +<p>En este ejemplo, la alerta muestra "B", que es el nombre de etiqueta del último nodo hijo del elemento párrafo ("P").</p> + +<h2 id="Polyfill_para_Internet_Explorer_8">Polyfill para Internet Explorer 8</h2> + +<p>Esta propiedad no está soportada con anterioridad a IE9, así que el siguiente códigopuede ser usado para añadir el soporte a IE8:</p> + +<pre class="brush: js">// Source: https://github.com/Alhadis/Snippets/blob/master/js/polyfills/IE8-child-elements.js +if(!("lastElementChild" in document.documentElement)){ + Object.defineProperty(Element.prototype, "lastElementChild", { + get: function(){ + for(var nodes = this.children, n, i = nodes.length - 1; i >= 0; --i) + if(n = nodes[i], 1 === n.nodeType) return n; + return null; + } + }); +}</pre> + +<h2 id="Especificación">Especificación</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Observaciones</th> + </tr> + <tr> + <td>{{SpecName('DOM WHATWG', '#dom-parentnode-lastelementchild', 'ParentNode.lastElementChild')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Dividido el interfaz <code>ElementTraversal</code> en {{domxref("ChildNode")}} y <code>ParentNode</code>. Este método queda ahora definido en el segundo.<br> + {{domxref("Document")}} y {{domxref("DocumentFragment")}} implementaron los nuevos interfaces.</td> + </tr> + <tr> + <td>{{SpecName('Element Traversal', '#attribute-lastElementChild', 'ElementTraversal.lastElementChild')}}</td> + <td>{{Spec2('Element Traversal')}}</td> + <td>Añadida su definición inicial al interfaz puro <code>ElementTraversal</code> y lo usa en {{domxref("Element")}}.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Prestación</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico (en {{domxref("Element")}})</td> + <td>1.0</td> + <td>{{CompatGeckoDesktop("1.9.1")}}</td> + <td>9.0</td> + <td>10.0</td> + <td>4.0</td> + </tr> + <tr> + <td>Soporte en {{domxref("Document")}} y {{domxref("DocumentFragment")}} {{experimental_inline}}</td> + <td>29.0</td> + <td>{{CompatGeckoDesktop("25.0")}}</td> + <td>{{CompatNo}}</td> + <td>16.0</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Prestación</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico (en {{domxref("Element")}})</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{CompatGeckoMobile("1.9.1")}}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + <tr> + <td>Soporte en {{domxref("Document")}} y {{domxref("DocumentFragment")}} {{experimental_inline}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("25.0")}}</td> + <td>{{CompatNo}}</td> + <td>16.0</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<p> </p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>Los interfaces puros {{domxref("ParentNode")}} y {{domxref("ChildNode")}}.</li> + <li> + <div class="syntaxbox">Tipos de objetos que implementan este interfaz puro: {{domxref("Document")}}, {{domxref("Element")}}, y {{domxref("DocumentFragment")}}.</div> + </li> +</ul> diff --git a/files/es/web/api/payment_request_api/index.html b/files/es/web/api/payment_request_api/index.html new file mode 100644 index 0000000000..376a9899c2 --- /dev/null +++ b/files/es/web/api/payment_request_api/index.html @@ -0,0 +1,136 @@ +--- +title: API de Solicitud de Pago +slug: Web/API/Payment_Request_API +tags: + - API + - API de Solicitud de Pago + - Comercio + - Contexto seguro + - Intermediário + - Pago + - Referencia + - Solicitud de Pago + - Tarjeta de Crédito +translation_of: Web/API/Payment_Request_API +--- +<div>{{DefaultAPISidebar("Payment Request API")}}{{securecontext_header}}</div> + +<p><span class="seoSummary">El API de solicitud de pago provee una experiencia consistente tanto para comerciantes, como para usuarios. No es una nueva forma de pagar; más bien, es una manera para que los usuarios puedan seleccionar su forma de pago preferida para pagar por cosas, y que esa información esté disponible para el comerciante.</span></p> + +<h2 id="Solicitud_de_pago_conceptos_y_uso">Solicitud de pago conceptos y uso</h2> + +<p>Muchos problemas relacionados con el abandono de carros de compras en línea pueden deberse a los formularios de pago, los cuales pueden ser complicados y consumir demasiado tiempo para llenarse y a veces requieren muchos pasos para completarse. El API de Petición de Pago intenta reducir el número de pasos necesarios para completar un pago en línea, potencialmente haciendo a un lado los formularios de pago. Hace el proceso de pago mucho más fácil recordando los datos del usuario, los cuales son entregados al comerciante ojalá sin requerid un formulario HTML.</p> + +<p>Ventajas de usar la API de Solicitud de Pago con "basic-card" (pagos basados en cartas):</p> + +<ul> + <li><strong>Experiencia de compra rápida</strong>: Los usuarios ingresan sus datos una vez en el navegador y luego ya están listos para pagar por productos y servicios en la web. Ellos ya no tienen que llenar los mismos datos repetidamente a través de los diferetes sitios.</li> + <li><strong>Experiencia consistente en todos los sitios (que soporten la API):</strong> Como la hoja de pago es controlada por el navegador, puede adaptar la experiencia al usuario. Esta puede incluir la localización de la UI en el lenguaje preferido del usuario.</li> + <li><strong>Accesibilidad</strong>: Como el navegador controla los elementos de entrada de la hoja de pago, puede garantizar una accesibilidad uniforme al teclado y al lector de pantalla en cada sitio web sin necesidad de que los desarrolladores hagan algo. Un navegador web puede incluso ajustar el tamaño de la fuente o el color de contraste de la hoja de pago, haciéndola más confortable para el usuario al momento de realizar el pago.</li> + <li><strong>Administración de credenciales</strong>: Los usuarios pueden administrar sus tarjetas de crédito y direcciones de envío directamente en el navegador. Un navegador puede incluso sincronizar estas "credenciales" a través de los dispositivos, haciendo más fácil a los usuarios ir de un computador de escritorio a un dispositivo móvil y de vuelta otra vez para realizar compras.</li> + <li><strong>Manejo constante de Errores:</strong> El navegador puede checkear la validez de los números de tarjetas, y puede indicarle al usuario si una tarjeta ha expirado (o si está cerca de hacerlo). El navegador puede automáticamente sugerir que tarjeta usar basado en los patrones de uso anteriores o las restricciones del comerciante (p.e., "sólo aceptamos Visa o Mastercard"), o permitir al usuario definir cual de ellas es su tarjeta favorita o por defecto.</li> +</ul> + +<p>Para solicitar un pago, a página web crea un objeto {{domxref("PaymentRequest")}} en respuesta a una acción del usuario que inicia el pago, como hacer click en un botón "Comprar". El <code>PaymentRequest</code> permite a la página web intercambiar información agente de usuario (user agent) mientras que el usuario provee los datos para completar la transacción.</p> + +<p>Puedes encontrar una guía completa en <a href="/en-US/docs/Web/API/Payment_Request_API/Using_the_Payment_Request_API">Usando la API de Solicitud de Pago</a>.</p> + +<div class="note"> +<p><strong>Nota</strong>: La API solo está disponibledentro de elementos {{htmlelement("iframe")}} cross-origin si tienen el atributo {{htmlattrxref("allowpaymentrequest","iframe")}}.</p> +</div> + +<h2 id="Interfaces">Interfaces</h2> + +<dl> + <dt>{{domxref('PaymentAddress')}}</dt> + <dd>Un objeto que contiene la dirección; usada para facturación y despacho, por ejemplo.</dd> + <dt>{{domxref('PaymentRequest')}}</dt> + <dd>Un objeto que provee la API para crear y administrar la interfaz de pago del {{Glossary("user agent", "user agent's")}}.</dd> + <dt>{{domxref('PaymentRequestEvent')}}</dt> + <dd>Un evento entregado a un manejador de pagos cuando un {{domxref("PaymentRequest")}} es realizado.</dd> + <dt>{{domxref('PaymentRequestUpdateEvent')}}</dt> + <dd>Permite que la página web actualice los detalles de la solicitud de pago en respuesta a una acción del usuario.</dd> + <dt>{{domxref('PaymentMethodChangeEvent')}}</dt> + <dd>Representa al usuario cambiando el instrumento de pago (por ejemplo, cambiando de una tarjeta de crédito a una tarjeta de débito).</dd> + <dt>{{domxref('PaymentResponse')}}</dt> + <dd>Objeto devuelto después de que el usuario selecciona un método de pago y aprueba una solicitud de pago.</dd> + <dt>{{domxref('MerchantValidationEvent')}}</dt> + <dd>Representa el navegador que requiere que el comerciante (sitio web) se valide a sí mismo como autorizado para usar un manejador de pagos en particular (por ejemplo, registrado como autorizado para usar Apple Pay).</dd> +</dl> + +<dl> +</dl> + +<h2 id="Diccionarios">Diccionarios</h2> + +<dl> + <dt>{{domxref("AddressErrors")}}</dt> + <dd>Un diccionario que contiene cadenas que proporcionan explicaciones descriptivas de cualquier error en cualquier entrada de {{domxref ("PaymentAddress")}} que tenga errores.</dd> + <dt>{{domxref("PayerErrors")}}</dt> + <dd>Un diccionario que contiene cadenas que proporcionan explicaciones descriptivas de cualquier error relacionado con los atributos de correo electrónico, teléfono y nombre de {{domxref ("PaymentResponse")}}.</dd> + <dt>{{domxref("PaymentDetailsUpdate")}}</dt> + <dd>Un objeto que describe los cambios que deben realizarse en los detalles del pago en caso de que el servidor necesite actualizar la información después de la instanciación de la interfaz de pago, pero antes de que el usuario comience a interactuar con ella.</dd> +</dl> + +<h3 id="Diccionarios_relacionados_para_la_especificación_Basic_Card">Diccionarios relacionados para la especificación Basic Card</h3> + +<dl> + <dt>{{domxref("BasicCardChangeDetails")}}</dt> + <dd>Un objeto que proporciona información de dirección redactada que se proporciona como {{domxref ("PaymentMethodChangeEvent.methodDetails", "methodDetails")}} en el evento {{event ("paymentmethodchange")}} enviado al {{domxref ("PaymentRequest" )}} cuando el usuario cambia la información de pago.</dd> + <dt>{{domxref("BasicCardErrors")}}</dt> + <dd>Un objeto que proporciona mensajes de error asociados con los campos del objeto {{domxref ("BasicCardResponse")}} que no son válidos. Esto se usa como el valor de la propiedad {{domxref ("PaymentValidationErrors.paymentMethod", "paymentMethod")}} en el objeto {{domxref ("PaymentValidationErrors")}} enviado al {{domxref ("PaymentRequest")}} cuando ocurre un error.</dd> + <dt>{{domxref('BasicCardRequest')}}</dt> + <dd>Define una estructura de objeto para contener detalles de la solicitud de pago, como el tipo de tarjeta.</dd> + <dt>{{domxref('BasicCardResponse')}}</dt> + <dd>Define una estructura de objeto para los detalles de la respuesta de pago, como el número o la fecha de vencimiento de la tarjeta utilizada para realizar el pago y la dirección de facturación.</dd> +</dl> + +<h2 id="Specificaciones">Specificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specificación</th> + <th scope="col">Estatus</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('Payment')}}</td> + <td>{{Spec2('Payment')}}</td> + <td>Definición inicial.</td> + </tr> + <tr> + <td>{{SpecName('Basic Card Payment')}}</td> + <td>{{Spec2('Basic Card Payment')}}</td> + <td>Define {{domxref ("BasicCardRequest")}} y {{domxref ("BasicCardResponse")}}, entre otras cosas necesarias para manejar el pago con tarjeta de crédito</td> + </tr> + <tr> + <td>{{SpecName('Payment Method Identifiers')}}</td> + <td>{{Spec2('Payment Method Identifiers')}}</td> + <td>Define los identificadores de los métodos de pago y cómo se validan y, en su caso, se acuñan y se registran formalmente en el W3C.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_del_navegador">Compatibilidad del navegador</h2> + +<div> +<h3 id="Interfaz_PaymentRequest">Interfaz PaymentRequest</h3> + +<div> +<div class="hidden">La tabla de compatibilidad de esta página se genera a partir de datos estructurados. Si desea contribuir con los datos, consulte https://github.com/mdn/browser-compat-data y envíenos un "pull request".</div> + +<p>{{Compat("api.PaymentRequest", 0)}}</p> +</div> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Payment_Request_API/Using_the_Payment_Request_API">Using the Payment Request API</a></li> + <li><a href="/en-US/docs/Web/API/Payment_Request_API/Concepts">Payment processing concepts</a></li> + <li><a href="https://webkit.org/blog/8182/introducing-the-payment-request-api-for-apple-pay/">Introducing the Payment Request API for Apple Pay</a></li> + <li><a href="https://developers.google.com/pay/api/web/guides/paymentrequest/tutorial">Google Pay API PaymentRequest Tutorial</a></li> + <li><a href="https://github.com/w3c/payment-request-info/wiki/FAQ">W3C Payment Request API FAQ</a></li> + <li>Feature Policy directive {{httpheader("Feature-Policy/payment", "payment")}}</li> +</ul> diff --git a/files/es/web/api/performance/clearmarks/index.html b/files/es/web/api/performance/clearmarks/index.html new file mode 100644 index 0000000000..dca7aa8ac1 --- /dev/null +++ b/files/es/web/api/performance/clearmarks/index.html @@ -0,0 +1,95 @@ +--- +title: performance.clearMarks() +slug: Web/API/Performance/clearMarks +tags: + - API + - Referencia + - Rendimiento Web + - metodo +translation_of: Web/API/Performance/clearMarks +--- +<div>{{APIRef("User Timing API")}}</div> + +<p>El método <strong><code>clearMarks()</code></strong> elimina la <em>marca llamada</em> del búfer de rendimiento de entrada del navegador. Si el método es llamado sin argumentos, todos los {{domxref("PerformanceEntry","performance entries")}} con un {{domxref("PerformanceEntry.entryType","entry type")}} de "<code>mark</code>" serán eliminados del búfer de rendimiento de entrada.</p> + +<p>{{AvailableInWorkers}}</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><em>performance</em>.clearMarks(); +<em>performance</em>.clearMarks(name); +</pre> + +<h3 id="Argumentos">Argumentos</h3> + +<dl> + <dt>nombre {{optional_inline}}</dt> + <dd>Un {{domxref("DOMString")}} representando el nombre de la marca de tiempo. Si este argumento es omitido, todos los {{domxref("PerformanceEntry","performance entries")}} con un {{domxref("PerformanceEntry.entryType","entry type")}} de "<code>mark</code>" serán eliminados.</dd> +</dl> + +<h3 id="Valor_de_retorno">Valor de retorno</h3> + +<dl> + <dt>vacío</dt> + <dd></dd> +</dl> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>El siguiente ejemplo muestra ambos usos del método <code>clearMarks()</code>.</p> + +<pre class="brush: js">// Create a small helper to show how many PerformanceMark entries there are. +function logMarkCount() { + console.log( + "Found this many entries: " + performance.getEntriesByType("mark").length + ); +} + +// Create a bunch of marks. +performance.mark("squirrel"); +performance.mark("squirrel"); +performance.mark("monkey"); +performance.mark("monkey"); +performance.mark("dog"); +performance.mark("dog"); + +logMarkCount() // "Found this many entries: 6" + +// Delete just the "squirrel" PerformanceMark entries. +performance.clearMarks('squirrel'); +logMarkCount() // "Found this many entries: 4" + +// Delete all of the PerformanceMark entries. +performance.clearMarks(); +logMarkCount() // "Found this many entries: 0" +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('User Timing Level 2', '#dom-performance-clearmarks', 'clearMarks()')}}</td> + <td>{{Spec2('User Timing Level 2')}}</td> + <td>Se clarifica <code>clearMarks()</code>.</td> + </tr> + <tr> + <td>{{SpecName('User Timing', '#dom-performance-clearmarks', 'clearMarks()')}}</td> + <td>{{Spec2('User Timing')}}</td> + <td>Definición básica.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2> + +<div> + + +<p>{{Compat("api.Performance.clearMarks")}}</p> +</div> diff --git a/files/es/web/api/performance/clearmeasures/index.html b/files/es/web/api/performance/clearmeasures/index.html new file mode 100644 index 0000000000..63fa0dd936 --- /dev/null +++ b/files/es/web/api/performance/clearmeasures/index.html @@ -0,0 +1,96 @@ +--- +title: performance.clearMeasures() +slug: Web/API/Performance/clearMeasures +tags: + - API + - Referencia + - Rendimiento Web + - metodo +translation_of: Web/API/Performance/clearMeasures +--- +<div>{{APIRef("User Timing API")}}</div> + +<p>El método <strong><code>clearMeasures()</code></strong> elimina <em>la medida llamada </em>del búfer de rendimiento de entrada, si el método es llamado sin argumentos, todos los {{domxref("PerformanceEntry","performance entries")}} con un {{domxref("PerformanceEntry.entryType","entry type")}} de "<code>measure</code>" serán eliminados del búfer de rendimiento de entrada.</p> + +<p>{{AvailableInWorkers}}</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><em>performance</em>.clearMeasures(); +<em>performance</em>.clearMeasures(name); +</pre> + +<h3 id="Argumentos">Argumentos</h3> + +<dl> + <dt>nombre {{optional_inline}}</dt> + <dd>Un {{domxref("DOMString")}} representando el nombre de la marca de tiempo. Si el argumento se omite, todos los {{domxref("PerformanceEntry","performance entries")}} con un {{domxref("PerformanceEntry.entryType","entry type")}} de "<code>measure</code>" serán eliminados.</dd> +</dl> + +<h3 id="Valor_de_retorno">Valor de retorno</h3> + +<dl> + <dt>vacío</dt> + <dd></dd> +</dl> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>En el siguiente ejemplo se muestran los dos usos del método <code>clearMeasures()</code> .</p> + +<pre class="brush: js">// Create a small helper to show how many PerformanceMeasure entries there are. +function logMeasureCount() { + console.log( + "Found this many entries: " + performance.getEntriesByType("measure").length + ); +} + +// Create a bunch of measures. +performance.measure("from navigation"); +performance.mark("a"); +performance.measure("from mark a", "a"); +performance.measure("from navigation"); +performance.measure("from mark a", "a"); +performance.mark("b"); +performance.measure("between a and b", "a", "b"); + +logMeasureCount() // "Found this many entries: 5" + +// Delete just the "from navigation" PerformanceMeasure entries. +performance.clearMeasures("from navigation"); +logMeasureCount() // "Found this many entries: 3" + +// Delete all of the PerformanceMeasure entries. +performance.clearMeasures(); +logMeasureCount() // "Found this many entries: 0" +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('User Timing Level 2', '#dom-performance-clearmeasures', 'clearMeasures()')}}</td> + <td>{{Spec2('User Timing Level 2')}}</td> + <td>Se clarifica <code>clearMeasures()</code>.</td> + </tr> + <tr> + <td>{{SpecName('User Timing', '#dom-performance-clearmeasures', 'clearMeasures()')}}</td> + <td>{{Spec2('User Timing')}}</td> + <td>Definición básica.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2> + +<div> + + +<p>{{Compat("api.Performance.clearMeasures")}}</p> +</div> diff --git a/files/es/web/api/performance/index.html b/files/es/web/api/performance/index.html new file mode 100644 index 0000000000..00d3cbfe16 --- /dev/null +++ b/files/es/web/api/performance/index.html @@ -0,0 +1,142 @@ +--- +title: Performance +slug: Web/API/Performance +tags: + - API + - Interfaz + - Referencia + - Rendimiento + - Rendimiento Web + - Tiempo de navegación +translation_of: Web/API/Performance +--- +<div>{{APIRef("High Resolution Time")}}</div> + +<p>La interfaz <strong><code>Performance</code></strong> representa información relacionada con el tiempo de rendimiento para la página dada.</p> + +<p>Un objeto de este tipo puede ser obtenido por el llamado de el atributo de solo lectura {{domxref("Window.performance")}}.</p> + +<div class="note"> +<p><strong><em>Nota</em>: </strong>Esta interfaz y sus miembros están disponibles en <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API">Web Workers</a>, exceptuando en los mencionados abajo. También, tenga en cuenta que las marcas y medidas de rendimiento son por contexto. Si crea una marca en el hilo principal (u otro worker), no puedes verlo en un hilo de un worker, y vice versa.</p> +</div> + +<h2 id="Propiedades">Propiedades</h2> + +<p><em>La interfaz <code>Performance</code> no hereda ninguna propiedad.</em></p> + +<dl> + <dt>{{domxref("Performance.navigation")}} {{readonlyInline}} {{deprecated_inline}}</dt> + <dd>Un objeto del legado {{domxref("PerformanceNavigation")}} que provee contexto útil acerca de operaciones, incluidas en los tiempos listados en <code>timing</code>, incluyendo si la página fue cargada o refrescada, cuántas redirecciones ocurrieron, entre otros. No disponible en workers</dd> + <dt>{{domxref("Performance.timing")}} {{readonlyInline}} {{deprecated_inline}}</dt> + <dd>Un objeto del legado {domxref("PerformanceTiming")}} que contiene información relacionada con la latencia.</dd> + <dt>{{domxref("Performance.memory")}} {{readonlyInline}} {{Non-standard_inline}}</dt> + <dd>Una <em>no standarizada</em> extensión añadida a Chrome, esta propiedad provee un objeto con información básica de uso de memoria. <strong>No deberías usar </strong>esta <em>no estandarizada </em>API.</dd> + <dt>{{domxref("Performance.timeOrigin")}} {{readonlyInline}} {{Non-standard_inline}}</dt> + <dd>Retorna una marca de tiempo de alta precisión de la hora de inicio de la medida de rendimiento.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<p><em><em>La interfaz <code>Performance</code> no hereda ningún método</em></em>.</p> + +<dl> + <dt>{{domxref("Performance.clearMarks()")}}</dt> + <dd>Elimina la marca dada del búfer de entrada de rendimiento del navegador.</dd> + <dt>{{domxref("Performance.clearMeasures()")}}</dt> + <dd>Elimina las <em>medida</em> dadas del búfer de entrada del navegador.</dd> + <dt>{{domxref("Performance.clearResourceTimings()")}}</dt> + <dd>Elimina todas las {domxref("PerformanceEntry","performance entries")}} con una {{domxref("PerformanceEntry.entryType","entryType")}} de "<code>resource</code>" del búfer de datos de rendimiento del navegador.</dd> + <dt>{{domxref("Performance.getEntries()")}}</dt> + <dd>Devuelve una lista de objetos {{domxref("PerformanceEntry")}} basados en el <em>filtro dado.</em></dd> + <dt>{{domxref("Performance.getEntriesByName()")}}</dt> + <dd>Devuelve una lista de objetos {{domxref("PerformanceEntry")}} basados en el <em>nombre</em> dado y el tipo de <em>entrada</em>.</dd> + <dt>{{domxref("Performance.getEntriesByType()")}}</dt> + <dd>Devuelve una lista de objetos {{domxref("PerformanceEntry")}} de el tipo de <em>entrada</em> dado.</dd> + <dt>{{domxref("Performance.mark()")}}</dt> + <dd>Crea un {{domxref("DOMHighResTimeStamp","timestamp")}} en el <em>búfer de entrada de rendimiento</em> del navegador.</dd> + <dt>{{domxref("Performance.measure()")}}</dt> + <dd>Crea un {{domxref("DOMHighResTimeStamp","timestamp")}} nombrado en el <em>búfer de entrada de rendimiento</em> del navegador entre dos especificadas marcas (conocidas como la <em>marca de inicio</em> y <em>la marca final, </em>respectivamente).</dd> + <dt>{{domxref("Performance.now()")}}</dt> + <dd>Retorna un {{domxref("DOMHighResTimeStamp")}} representando el número de milisegundos transcurridos desde un instante de referencia.</dd> + <dt>{{domxref("Performance.setResourceTimingBufferSize()")}}</dt> + <dd>Define el tamaño del búfer de temporización de recursos de "<code>resource</code>" a los objetos {{domxref("PerformanceEntry.entryType","type")}} {{domxref("PerformanceEntry","performance entry")}}.</dd> + <dt>{{domxref("Performance.toJSON()")}}</dt> + <dd>Es un jsonizador que retorna un objeto json que respresenta el objecto <code>Performance</code>.</dd> +</dl> + +<h2 id="Eventos">Eventos</h2> + +<p>Escucha a estos eventos que están usando <code>addEventListener()</code> o por asignación de un escuchador de eventos a la propiedad <code>oneventname</code> de esta interfaz.</p> + +<dl> + <dt>{{DOMxRef("Performance.resourcetimingbufferfull_event", "resourcetimingbufferfull")}}</dt> + <dd>Disparado cuando "<a href="https://developer.mozilla.org/en-US/docs/Web/API/Performance/setResourceTimingBufferSize">resource timing buffer</a>" está lleno.<br> + También disponible usando la propiedad {{DOMxRef("Performance.onresourcetimingbufferfull", "onresourcetimingbufferfull")}}. </dd> +</dl> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('Highres Time Level 2', '#the-performance-interface', 'toJSON()')}}</td> + <td>{{Spec2('Highres Time Level 2')}}</td> + <td>Se define el método <code>toJson()</code>.</td> + </tr> + <tr> + <td>{{SpecName('Highres Time', '#the-performance-interface', 'Performance')}}</td> + <td>{{Spec2('Highres Time')}}</td> + <td>Se define el método <code>now()</code>.</td> + </tr> + <tr> + <td>{{SpecName('Navigation Timing', '#sec-window.performance-attribute', 'Performance')}}</td> + <td>{{Spec2('Navigation Timing')}}</td> + <td>Se definen las propiedades <code>timing</code> and <code>navigation</code>.</td> + </tr> + <tr> + <td>{{SpecName('Performance Timeline Level 2', '#extensions-to-the-performance-interface', 'Performance extensions')}}</td> + <td>{{Spec2('Performance Timeline Level 2')}}</td> + <td>Cambia la interfaz <code>getEntries()</code>.</td> + </tr> + <tr> + <td>{{SpecName('Performance Timeline', '#sec-window.performance-attribute', 'Performance extensions')}}</td> + <td>{{Spec2('Performance Timeline')}}</td> + <td>Se definen los métodos <code>getEntries()</code>, <code>getEntriesByType()</code> y <code>getEntriesByName()</code> .</td> + </tr> + <tr> + <td>{{SpecName('Resource Timing', '#extensions-performance-interface', 'Performance extensions')}}</td> + <td>{{Spec2('Resource Timing')}}</td> + <td>Se definen los métdos <code>clearResourceTimings()</code> y <code>setResourceTimingBufferSize()</code> y la propiedad <code>onresourcetimingbufferfull</code> .</td> + </tr> + <tr> + <td>{{SpecName('User Timing Level 2', '#extensions-performance-interface', 'Performance extensions')}}</td> + <td>{{Spec2('User Timing Level 2')}}</td> + <td>Se clarifican los métodos <code>mark()</code>, <code>clearMark()</code>, <code>measure()</code> y <code>clearMeasure()</code>.</td> + </tr> + <tr> + <td>{{SpecName('User Timing', '#extensions-performance-interface', 'Performance extensions')}}</td> + <td>{{Spec2('User Timing')}}</td> + <td>Se definen los métodos <code>mark()</code>, <code>clearMark()</code>, <code>measure()</code> y <code>clearMeasure()</code>.</td> + </tr> + <tr> + <td>{{SpecName('<span style="line-height: 1.5;">Frame Timing', '#extensions-performance-interface','Performance extensions')}}</span></td> + <td>{{Spec2('User Timing')}}</td> + <td>Se definen los métodos <code>clearFrameTimings()</code>, <code>setFrameTimingBufferSize()</code>, y <code>onframetimingbufferfull</code>.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2> + +<div> +<div> + + +<p>{{Compat("api.Performance")}}</p> +</div> +</div> diff --git a/files/es/web/api/performance/memory/index.html b/files/es/web/api/performance/memory/index.html new file mode 100644 index 0000000000..91c3dd3e0b --- /dev/null +++ b/files/es/web/api/performance/memory/index.html @@ -0,0 +1,42 @@ +--- +title: Performance.memory +slug: Web/API/Performance/memory +translation_of: Web/API/Performance/memory +--- +<p>{{APIRef}}</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><em>timingInfo</em> = <em>performance</em>.memory</pre> + +<h2 id="Atributos">Atributos</h2> + +<dl> + <dt><code>jsHeapSizeLimit</code></dt> + <dd>El tamaño máximo del heap en bytes que está disponible para el contexto.</dd> + <dt><code>totalJSHeapSize</code></dt> + <dd>El total del heap asignado, en bytes. The total allocated heap size, in bytes.</dd> +</dl> + +<dl> + <dt>usedJSHeapSize</dt> + <dd>El actualmente activo segmento de heap de JS, en bytes.</dd> +</dl> + +<h2 id="Especificaciones">Especificaciones</h2> + +<p>Ninguna.</p> + +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2> + +<div> + + +<p>{{Compat("api.Performance.memory")}}</p> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>The {{domxref("Performance")}} interface it belongs to.</li> +</ul> diff --git a/files/es/web/api/performance/navigation/index.html b/files/es/web/api/performance/navigation/index.html new file mode 100644 index 0000000000..62bef8feb5 --- /dev/null +++ b/files/es/web/api/performance/navigation/index.html @@ -0,0 +1,58 @@ +--- +title: Performance.navigation +slug: Web/API/Performance/navigation +tags: + - API + - Deprecado + - HTTP + - Legado + - Propiedad + - Rendimiento + - Solo lectura + - Tiempo de navegación +translation_of: Web/API/Performance/navigation +--- +<p>{{APIRef("Navigation Timing")}}</p> + +<div class="warning"> +<p>Esta propiedad está deprecada en <a href="https://w3c.github.io/navigation-timing/#obsolete">Navigation Timing Level 2 specification</a>.</p> +</div> + +<p>La propiedad de solo lectura <code><strong>Performance</strong></code><strong><code>.navigation</code></strong> del legado devuelve un objeto {{domxref("PerformanceNavigation")}} representado el tipo de navegación que ocurre en el contexto de navegación dado, tales como el número de redirecciones necesarias para traer el recurso.</p> + +<p>Esta propiedad no está disponible en workers.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><em>navObject</em> = <em>performance</em>.navigation;</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('Navigation Timing', '#sec-window.performance-attribute', 'Performance.navigation')}}</td> + <td>{{Spec2('Navigation Timing')}}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2> + +<div> + + +<p>{{Compat("api.Performance.navigation")}}</p> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>The {{domxref("Performance")}} interface it belongs to.</li> +</ul> diff --git a/files/es/web/api/performance/now/index.html b/files/es/web/api/performance/now/index.html new file mode 100644 index 0000000000..64f73a4916 --- /dev/null +++ b/files/es/web/api/performance/now/index.html @@ -0,0 +1,166 @@ +--- +title: performance.now() +slug: Web/API/Performance/now +tags: + - API + - Referencia + - Rendimiento + - Web Performance API + - metodo +translation_of: Web/API/Performance/now +--- +<div>{{APIRef("High Resolution Timing")}}</div> + +<p>El método <code><strong>performance.now()</strong></code> devuelve un {{domxref("DOMHighResTimeStamp")}}, medido en milisegundos, con una precisión de cinco milésimas de segundo (5 microsegundos).</p> + +<p>El valor devuelto representa el tiempo transcurrido desde el <strong>tiempo de origen</strong><strong> </strong>(la propiedad {{domxref("PerformanceTiming.navigationStart")}}). En un web worker, el tiempo de origen es el momento en que se crea su contexto de ejecución (ej. hilo o proceso). En una ventana, es el momento en que el usuario navegó (o confirmó la navegación, si la confirmación fue necesaria) al documento actual. Tenga en cuenta los siguientes puntos:</p> + +<ul> + <li>En los workers dedicados creados desde un contexto {{domxref("Window")}}, el valor del worker será inferior a <code>performance.now()</code> en la pestaña que generó el worker. Solía ser igual que <code>t0</code> del contexto principal, pero fue cambiado.</li> + <li>En service workers compartidos, el valor en el worker podría ser superior al del contexto principal debido a que la ventana puede ser creada después de esos workers.</li> +</ul> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><em>t</em> = performance.now();</pre> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush: js">var t0 = performance.now(); +hacerAlgo(); +var t1 = performance.now(); +console.log("La llamada a hacerAlgo tardó " + (t1 - t0) + " milisegundos."); +</pre> + +<p>A diferencia de otros datos de tiempo disponibles en JavaScript (por ejemplo <a href="/en-US/docs/JavaScript/Reference/Global_Objects/Date/now"><code>Date.now</code></a>), las marcas de tiempo devueltas por <code>Performance.now()</code> no se limitan a resoluciones de un milisegundo. En su lugar, representan tiempos como números en punto flotante con hasta una precisión de microsegundos.</p> + +<p>También a diferencia de <code>Date.now()</code>, los valores devueltos por <code>Performance.now() </code>siempre se incrementan a un ritmo constante, independientemente del sistema de reloj (que podría estar ajustado manualmente o manipulado por software como NTP). De todos modos, <code>performance.timing.navigationStart + performance.now() </code>será aproximadamente igual a<code> Date.now()</code>.</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('Highres Time Level 2', '#dom-performance-now', 'performance.now()')}}</td> + <td>{{Spec2('Highres Time Level 2')}}</td> + <td>Definiciones más estrictas de interfaces y tipos.</td> + </tr> + <tr> + <td>{{SpecName('Highres Time', '#dom-performance-now', 'performance.now()')}}</td> + <td>{{Spec2('Highres Time')}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatChrome("20.0")}} {{property_prefix("webkit")}}<br> + {{CompatChrome("24.0")}} [1]</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("15.0")}}</td> + <td>10.0</td> + <td>{{CompatOpera("15.0")}}</td> + <td>{{CompatSafari("8.0")}}</td> + </tr> + <tr> + <td>en Web workers</td> + <td>{{CompatChrome("33")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("34.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>now()</code> en un worker dedicado está ahora separado del contexto principal de <code>now()</code>.</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("45.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Android Webview</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome para Android</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatAndroid("4.0")}}</td> + <td>{{CompatChrome("25.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("15.0")}}</td> + <td>10.0</td> + <td>{{CompatNo}}</td> + <td>9</td> + <td>{{CompatChrome("25.0")}}</td> + </tr> + <tr> + <td>en Web workers</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("34.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>now()</code> en un worker dedicado está ahora separado del contexto principal de <code>now()</code>.</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("45.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Las versiones de Windows desde Chrome 20 al 33 devuelven <code>performance.now()</code> sólo con precisión de milisegundos.</p> + +<h2 id="Vea_también">Vea también</h2> + +<ul> + <li><a href="http://updates.html5rocks.com/2012/08/When-milliseconds-are-not-enough-performance-now">When milliseconds are not enough: performance.now() </a>de HTML5 Rocks.</li> +</ul> diff --git a/files/es/web/api/performance/timeorigin/index.html b/files/es/web/api/performance/timeorigin/index.html new file mode 100644 index 0000000000..c8f6255687 --- /dev/null +++ b/files/es/web/api/performance/timeorigin/index.html @@ -0,0 +1,48 @@ +--- +title: Performance.timeOrigin +slug: Web/API/Performance/timeOrigin +tags: + - API + - Experimental + - Propiedad + - Referencia + - Rendimiento + - timeOrigin +translation_of: Web/API/Performance/timeOrigin +--- +<p>{{SeeCompatTable}}{{APIRef("High Resolution Time")}}</p> + +<p>La propiedad de solo lectura <strong><code>timeOrigin</code></strong> de la inferfaz {{domxref("Performance")}} devuelve una marca de tiempo de alta precisión del inicio de medida de rendimiento.</p> + +<p>{{AvailableInWorkers}}</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var <em>timeOrigin</em> = performance.timeOrigin</pre> + +<h3 id="Valor">Valor</h3> + +<p>Una marca de tiempo de alta precisión.</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + </tr> + <tr> + <td>{{SpecName('Highres Time Level 2','#dom-performance-timeorigin','timeOrigin')}}</td> + <td>{{Spec2('Highres Time Level 2')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2> + +<div> + + +<p>{{Compat("api.Performance.timeOrigin")}}</p> +</div> diff --git a/files/es/web/api/performance/timing/index.html b/files/es/web/api/performance/timing/index.html new file mode 100644 index 0000000000..ef5e07387b --- /dev/null +++ b/files/es/web/api/performance/timing/index.html @@ -0,0 +1,57 @@ +--- +title: Performance.timing +slug: Web/API/Performance/timing +tags: + - API + - Deprecada + - Legado + - Propiedad + - Rendimiento + - Solo lectura + - Tiempo de navegación +translation_of: Web/API/Performance/timing +--- +<p>{{APIRef("Navigation Timing")}}{{deprecated_header}}</p> + +<div class="warning"> +<p>Esta propiedad está deprecada en <a href="https://w3c.github.io/navigation-timing/#obsolete">Navigation Timing Level 2 specification</a>. Por favor usa {{domxref("Performance.timeOrigin")}} en vez esta..</p> +</div> + +<p>La propiedad de solo lecutra <code><strong>Performance</strong></code><strong><code>.timing</code></strong> de legado devulve un objeto {{domxref("PerformanceTiming")}} que contienen información relacionada con el rendimiento en relación a la latencia.</p> + +<p>Esta propiedad no está disponible en workers.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><em>var timingInfo</em> = <em>performance</em>.timing;</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('Navigation Timing', '#sec-window.performance-attribute', 'Performance.timing')}}</td> + <td>{{Spec2('Navigation Timing')}}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2> + +<div> + + +<p>{{Compat("api.Performance.timing")}}</p> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>The {{domxref("Performance")}} interface it belongs to.</li> +</ul> diff --git a/files/es/web/api/performancenavigation/index.html b/files/es/web/api/performancenavigation/index.html new file mode 100644 index 0000000000..60ed7f1ce4 --- /dev/null +++ b/files/es/web/api/performancenavigation/index.html @@ -0,0 +1,87 @@ +--- +title: PerformanceNavigation +slug: Web/API/PerformanceNavigation +tags: + - API + - API de tiempo de navegación + - Compatibilidad + - Deprecada + - Interfaz + - Legado + - Referencia + - Rendimiento + - TIempo + - Tiempo de navegación +translation_of: Web/API/PerformanceNavigation +--- +<p>{{APIRef("Navigation Timing")}}</p> + +<div class="warning"> +<p>Esta interfaz está deprecada en <a href="https://w3c.github.io/navigation-timing/#obsolete">Navigation Timing Level 2 specification</a>. Por favor usa la interfaz {{domxref("PerformanceNavigationTiming")}} en lugar de esta.</p> +</div> + +<p>La interfaz de legado <strong><code>PerformanceNavigation</code></strong> representa información acerca de cómo la navegación en el documento actual fue hecha.</p> + +<p>Un objeto de este tipo puede ser optenido con el llamado del atributo de solo lectura {{domxref("Performance.navigation")}}.</p> + +<h2 id="Propiedades">Propiedades</h2> + +<p><em>La interfaz <code>PerformanceNavigation</code> no hereda ninguna propiedad.</em></p> + +<dl> + <dt>{{deprecated_inline}} {{domxref("PerformanceNavigation.type")}} {{readonlyInline}}</dt> + <dd>Un <code>unsigned short</code> el cual indica cómo la navegación en esta página fue hecha. Los valores posibles son:</dd> + <dd> + <dl> + <dt><code>TYPE_NAVIGATE</code> (0)</dt> + <dd>La página fue accesada por un link, un marcador, un formulario enviado, o un script, o escribiendo la URL en la barra de direcciones.</dd> + <dt><code>TYPE_RELOAD</code> (1)</dt> + <dd>La página fue accesada haciendo click al botón de Recargar o con el método {{domxref("Location.reload()")}}.</dd> + <dt><code>TYPE_BACK_FORWARD</code> (2)</dt> + <dd>La página fue accesada por la navegación en el historial.</dd> + <dt><code>TYPE_RESERVED</code> (255)</dt> + <dd>Cualquier otra forma.</dd> + </dl> + </dd> + <dt>{{deprecated_inline}} {{domxref("PerformanceNavigation.redirectCount")}} {{readonlyInline}}</dt> + <dd>Un <code>unsigned short</code> que representa el número de REDIRECTs hechos antes de llegar a la página.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<p><em><em>La interfaz <code>Performance</code> no hereda ningún método</em></em>.</p> + +<dl> + <dt>{{deprecated_inline}} {{domxref("PerformanceNavigation.toJSON()")}}</dt> + <dd>Es un jsonizer que retorna un objeto json que representa el objecto <code>PerformanceNavigation</code>.</dd> +</dl> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('Navigation Timing', '#sec-navigation-info-interface', 'PerformanceNavigation')}}</td> + <td>{{Spec2('Navigation Timing')}}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2> + + + +<p>{{Compat("api.PerformanceNavigation")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>The {{domxref("Performance")}} that allows access to an object of this type.</li> + <li>{{domxref("PerformanceNavigationTiming")}} (part of Navigation Timing Level 2) {{experimental_inline}}</li> +</ul> diff --git a/files/es/web/api/positionoptions/index.html b/files/es/web/api/positionoptions/index.html new file mode 100644 index 0000000000..349aba4631 --- /dev/null +++ b/files/es/web/api/positionoptions/index.html @@ -0,0 +1,109 @@ +--- +title: PositionOptions +slug: Web/API/PositionOptions +tags: + - Geolocalización + - Interfaz + - Referencia +translation_of: Web/API/PositionOptions +--- +<p>{{APIRef("Geolocation API")}}</p> + +<p>La interfaz <strong><code>PositionOptions</code></strong> describe las opciones disponibles cuando invocamos el "backend" de geolocalización. El navegador no crea este objeto directamente: es el script que invoca quien lo crea y usa como un parámetro de {{domxref("Geolocation.getCurrentPosition()")}} y {{domxref("Geolocation.watchPosition()")}}.</p> + +<h2 id="Propiedades">Propiedades</h2> + +<p><em>La interfaz <code>PositionOptions</code> no hereda ninguna propiedad</em>.</p> + +<dl> + <dt>{{domxref("PositionOptions.enableHighAccuracy")}}</dt> + <dd>Es un {{domxref("Boolean")}} que indica que la aplicación quiere recibir los mejores resultados posibles. Si es <code>true</code> y si el dispositivo es capaz de proporcionar una posición más precisa, así lo hará. Ten en cuenta que esto puede resultar en tiempos de respuesta más lentos o en un incremento del uso de energía (con un chip GPS en un teléfono móvil por ejemplo). Por otro lado, si es <code>false</code> (el valor por defecto), el dispositivo tiene libertad para decidir ahorrar recursos respondiendo más rápido y/o usando menos energía.</dd> + <dt>{{domxref("PositionOptions.timeout")}}</dt> + <dd>Es un valor <code>long</code> positivo que representa el máximo período de tiempo (en millisegundos) que se le permite tomar al dispositivo para retornar a una posición. El valor por defecto es <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Infinity" title="/en-US/docs/JavaScript/Reference/Global_Objects/Infinity">Infinity</a></code>, y significa que <code>getCurrentPosition()</code> no retornará hasta que esté disponible la posición.</dd> + <dt>{{domxref("PositionOptions.maximumAge")}}</dt> + <dd>Es un valor <code>long</code> positivo que indica la edad máxima en milisegundos de una posible posición "cacheada" que es aceptable retornar. Si es <code>0</code>, significa que el dispositivo no puede usar posiciones "cacheadas" y debe intentar conseguir la posición real actual. Si es <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Infinity" title="/en-US/docs/JavaScript/Reference/Global_Objects/Infinity">Infinity</a></code> el dispositivo debe retornar una posición previamente "cacheada" independientemente de su edad.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<p><em><em>La interfaz <code>PositionOptions</code> no implementa ni hereda ningún método<em>.</em></em></em></p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estatus</th> + <th scope="col">Comentario</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('Geolocation', '#positionoptions', 'PositionOptions')}}</td> + <td>{{Spec2('Geolocation')}}</td> + <td>Especificación inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegador">Compatibilidad de navegador</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>5</td> + <td>{{CompatGeckoDesktop("1.9.1")}}</td> + <td>9</td> + <td>10.60<br> + Removed in 15.0<br> + Reintroduced in 16.0</td> + <td>5</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</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>Soporte básico</td> + <td>{{CompatUnknown()}}</td> + <td>{{CompatUnknown()}}</td> + <td>{{CompatGeckoMobile("4")}}</td> + <td>{{CompatUnknown()}}</td> + <td>10.60</td> + <td>{{CompatUnknown()}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/WebAPI/Using_geolocation" title="/en-US/docs/WebAPI/Using_geolocation">Using geolocation</a></li> + <li>La interfaz {{domxref("Geolocation")}} que la usa.</li> +</ul> diff --git a/files/es/web/api/push_api/index.html b/files/es/web/api/push_api/index.html new file mode 100644 index 0000000000..0379ef3ee2 --- /dev/null +++ b/files/es/web/api/push_api/index.html @@ -0,0 +1,175 @@ +--- +title: Push API +slug: Web/API/Push_API +tags: + - API + - Experimental + - Notificaciones + - Push + - Referencia +translation_of: Web/API/Push_API +--- +<p>{{DefaultAPISidebar("Push API")}}{{SeeCompatTable}}</p> + +<p>La <strong>API Push</strong> otorga a las aplicaciones web la habilidad de recibir mensajes enviados a ellas desde un servidor, sin importar si la aplicación está o no en primer plano o cargada. Esto permite a los desarrolladores enviar notificaciones asíncronas y actualizaciones para los usuarios que las aceptan.</p> + +<div class="note"> +<p><strong>Nota</strong>: Esta documentación cubre la especificación del API Push de W3C; si estás buscando la documentación para el mecanismo push propio de Firefox OS, ve <a href="/en-US/docs/Web/API/Simple_Push_API">Simple Push</a>.</p> +</div> + +<h2 id="Push_conceptos_y_uso">Push conceptos y uso</h2> + +<p>Para que una aplicación recibá mensajes push, esta debe tener un <em><a href="/en-US/docs/Web/API/ServiceWorker_API">service worker</a></em>. Cuando el service worker esta activo, se puede suscribir usando {{domxref("PushManager.subscribe()")}}.</p> + +<p>El resultado de {{domxref("PushSubscription")}} incluye toda la información que la aplicación necesita para enviar un mensaje push: un <em>endpoint </em>y la llave de cifrado necesaria para enviar los datos.</p> + +<p>El service worker se iniciará cuando sea necesario manejar mensajes push entrantes, que se entregan al manejador de eventos. Esto permite a las aplicaciones reaccionar a los mensajes push recibidos, por ejemplo para mostrar una notiificación usando {{domxref("ServiceWorkerRegistration.showNotification()")}}.</p> + +<p>Cada suscripción es unica para un service worker. El endpoint para la subscripción es una unica <a href="http://www.w3.org/TR/capability-urls/">capability URL</a>: el conocimiento del endpoint es todo lo se necesita para enviar un mensaje a tu aplicación. La URL del endpoint por lo tanto necesita ser mantenida secreta, u otras aplicaciones podrían ser capases de enviar mensajes push a tu aplicación.</p> + +<p>Activar un Service-Worker para entregar un mensaje push puede resultar en el incremento de uso de recursos, especialmente de la batería. Los diferentes navegadores disponen de diferentes esquemas para manejar esto - en la actualidad no existe un mecanismo estándar para ello. Firefox permite un numero limitado (det. cuota) de mensajes push para enviar a una aplicación, aunque los mensajes push que generan una notificación estan exentos de este límite. Este límite se actualiza cada vez que se visita el sitio web. En comparación, Chrome no aplica límites, pero requiere que todo mensaje push muestre una notificación.</p> + +<div class="note"> +<p><strong>Note: </strong> Desde Gecko 44, la cuota permitida de Push-messages por aplicación no se ve incrementada cada vez que se emite una nueva notificación, cuando otra sigue visible, durante el periodo de 3 segundos. Esto ayuda al manejo de casos en los que se reciben rafagas de notificaciones y no todas ellas emiten una notificación visible. </p> +</div> + +<div class="note"> +<p><strong>Nota:</strong> en Chrome las versiones anteriores a la 52, requieren la cnfiguración de un proyecto en <a href="https://developers.google.com/cloud-messaging/">Google Cloud Messaging</a> para el envío de Push-Messages, así como el uso del numero de proyecto y la API key asociadas para el envío de notificaciones push. Tambien se requiere el detalle de algunos parametros especiales en el app manifest para el uso de este servicio.</p> +</div> + +<h2 id="Interfaces">Interfaces</h2> + +<dl> + <dt>{{domxref("PushEvent")}}</dt> + <dd>Represena una acción push enviada al <a href="/en-US/docs/Web/API/ServiceWorkerGlobalScope">alcance global</a> (global scope) de un {{domxref("ServiceWorker")}}. Contiene información enviada desde una aplicación a {{domxref("PushSubscription")}}.</dd> + <dt>{{domxref("PushManager")}}</dt> + <dd>Provides a way to receive notifications from third-party servers as well as request URLs for push notifications. This interface has replaced functionality offered by the obsolete {{domxref("PushRegistrationManager")}} interface.</dd> + <dt>{{domxref("PushMessageData")}}</dt> + <dd>Provee acceso a los datos push enviados por el servidor e incluye metodos para manipular los datos recibidos.</dd> + <dt>{{domxref("PushSubscription")}}</dt> + <dd>Provee el URL endpoint para una suscripción y permite la desuscripción de un servicio push.</dd> +</dl> + +<h2 id="Service_worker_Adiciones">Service worker: Adiciones</h2> + +<p>Las siguientes adiciones al <a href="/en-US/docs/Web/API/Service_Worker_API">Service Worker API</a> han sido especificadas en la Push API, para proveer un punto de entrada al uso de Push messages. Tambien monitorizan y responden a los cambios en los eventos Push y Subscription.</p> + +<dl> + <dt>{{domxref("ServiceWorkerRegistration.pushManager")}} {{readonlyinline}}</dt> + <dd>Devuelve una referencia a la interfaz {{domxref("PushManager")}} para el manejo de las suscripciones incluyendo: la suscripción, obteniendo una suscripción activa y accediendo al estado de permiso de push. Este es el punto de inicio para el uso de Push messaging.</dd> + <dt>{{domxref("ServiceWorkerGlobalScope.onpush")}}</dt> + <dd>Manipulador de eventos activado, cada vez que ocurre un evento {{Event("push")}}; Eto es, cada vez que se recibe un push-message del servidor.</dd> + <dt>{{domxref("ServiceWorkerGlobalScope.onpushsubscriptionchange")}}</dt> + <dd>Manipulador de eventos activado, cada vez que ocurre un evento {{Event("pushsubscriptionchange")}}; Por ejemplo, cuando una suscripción ha sido invalidada o esta apunto de serlo. (P.ej. cuando un push service determina un tiempo de expiración.)</dd> +</dl> + +<h2 id="Ejemplos">Ejemplos</h2> + +<p>Mozilla's <a href="https://serviceworke.rs/">ServiceWorker Cookbook</a> contiene varios ejemplos Push muy utiles</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("Push API")}}</td> + <td>{{Spec2("Push API")}}</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>{{CompatChrome(42.0)}}</td> + <td>{{CompatGeckoDesktop(44.0)}}<sup>[1]</sup></td> + <td>{{CompatUnknown}}<sup>[2]</sup></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>{{domxref("PushEvent.data")}},<br> + {{domxref("PushMessageData")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop(44.0)}}</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>Android Webview</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}<sup>[2]</sup></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatChrome(42.0)}}</td> + </tr> + <tr> + <td>{{domxref("PushEvent.data")}},<br> + {{domxref("PushMessageData")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Currently available only on desktop versions of Firefox; also, push messages are only delivered when Firefox is running.</p> + +<p>[2]: <a href="https://dev.modern.ie/platform/status/pushapi/">Microsoft Edge status: Under Consideration; Roadmap Priority: Low</a></p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="Web/API/Push_API/Using_the_Push_API">¿Cómo usar la API Push?</a></li> + <li><a href="https://github.com/chrisdavidmills/push-api-demo">Push API Demo</a>, on Github</li> + <li><a href="http://updates.html5rocks.com/2015/03/push-notificatons-on-the-open-web">Push Notifications on the Open Web</a>, Matt Gaunt</li> + <li><a href="/en-US/docs/Web/API/Service_Worker_API">Service Worker API</a></li> +</ul> diff --git a/files/es/web/api/push_api/using_the_push_api/index.html b/files/es/web/api/push_api/using_the_push_api/index.html new file mode 100644 index 0000000000..0088b97dd7 --- /dev/null +++ b/files/es/web/api/push_api/using_the_push_api/index.html @@ -0,0 +1,432 @@ +--- +title: Usando la API Push +slug: Web/API/Push_API/Using_the_Push_API +translation_of: Web/API/Push_API +--- +<p class="summary"><span class="seoSummary">La W3C <a href="/en-US/docs/Web/API/Push_API">Push API</a> offers some exciting new functionality for developers to use in web applications: this article provides an introduction to getting Push notifications setup and running, with a simple demo.</span></p> + +<p>La habilidad de enviar mensajes o notificaciones de un servidor a un cliente en cualquier momento —si la aplicación está activa en su sitema o no—es algo que ha sido disfrutado por las plataformas nativas durante algún tiempo, y esta finalmente llega a la web! el soporte para muchos push está ahora disponible en Firefox 43+ y Chrome 42+ en escritorio, esperamos seguir pronto con las plataformas moviles. {{domxref("PushMessageData")}} actualmente solo es soportada experimentalmente en Firefox (44+), y la implementación está sujeta a cambios.</p> + +<div class="note"> +<p><strong>Note</strong>: Early versions of Firefox OS used a proprietary version of this API called <a href="/en-US/docs/Web/API/Simple_Push_API">Simple Push</a>. This is being rendered obsolete by the Push API standard.</p> +</div> + +<h2 id="Demo_las_bases_de_una_simple_app_de_servidor_de_chat">Demo: las bases de una simple app de servidor de chat</h2> + +<p>La demo que hemos creado proporciona los principios de una simple app de chat. Esta presenta un formulario para que ingreses un identificador de chat y un boton que al presionar se suscriba a los mensajes push.</p> + +<p>En este punto, el nombre de los nuevos suscriptores aparecerá en la lista de suscriptores, junto con un campo de texto y un botón de envío para permitir al suscriptor enviar mensajes.</p> + +<p>At this point, the new subscriber's name will appear in the subscriber's list, along with a text field and submit button to allow the subscriber to send messages.</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/11823/push-api-demo.png" style="border: 1px solid black; display: block; height: 406px; margin: 0px auto; width: 705px;"></p> + +<p>Para correr la demo, siga las instrucciones de <a href="https://github.com/chrisdavidmills/push-api-demo">push-api-demo README</a>. Tenga en cuenta que el componente server-side aún nesecita un poco de trabajo para que funcione en chrome y se ejecute de una manera más rezonable. Pero los aspectos de push pueden ser explicados a fondo; Nos sumergiremos en ella después de revisar las tecnologías en juego.</p> + +<h2 id="Visión_de_la_tecnología">Visión de la tecnología</h2> + +<p>Esta sección proporciona un esquema de qué tecnologías están involucradas en este ejemplo.</p> + +<p>Los mensajes web push hacen parte de la familia tecnológica <a href="/en-US/docs/Web/API/Service_Worker_API">service workers</a>; en particular, se requiere que un service worker esté activo en la página para recibir mensajes push. el service worker recibe el mensaje push, y acontinuación depende de usted cómo notificar a la página. Usted puede:</p> + +<p>Web Push messages are part of the <a href="/en-US/docs/Web/API/Service_Worker_API">service workers</a> technology family; in particular, a service worker is required to be active on the page for it to receive push messages. The service worker receives the push message, and then it is up to you how to then notify the page. You can:</p> + +<ul> + <li>Enviar una <a href="/en-US/docs/Web/API/Notifications_API">notificación web</a> emergente para alertar al usuario. Esto requiere que sean concedidos los permisos para enviar el mensaje push.</li> + <li>Envía un mensaje a la página principal a través de un {{domxref("MessageChannel")}}.</li> +</ul> + +<p>A menudo una combinación de los dos será necesario; La demo a continuación muestra un ejemplo de cada uno.</p> + +<div class="note"> +<p><strong>Nota</strong>: Usted necesita algún tipo de código que se ejecute en el servidor para manejar el cifrado de punto final/datos y enviar las solicitudes de notificaciones push. En nuestra demostración hemos creado un servidor quick-and-dirty usando <a href="https://nodejs.org/">NodeJS</a>.</p> +</div> + +<p>El service worker también tiene que suscribirse al servicio de mensajería psuh. Cada sesión recibe su propio punto final único cuando se suscribe al servicio de mensajería. Este punto final es obtenido desde la propiedad ({{domxref("PushSubscription.endpoint")}}) en el objeto de suscripción. Este punto final se puede enviar a su servidor y se utiliza para enviar un mensaje al service worker asctivo en esta sesión. Cada navegador tiene su propio servidor de mensajería push para manejar el envío del mensaje push.</p> + +<h3 id="Encryption">Encryption</h3> + +<div class="note"> +<p><strong>Note</strong>: For an interactive walkthrough, try JR Conlin's <a href="https://jrconlin.github.io/WebPushDataTestPage/">Web Push Data Encryption Test Page</a>.</p> +</div> + +<p>To send data via a push message, it needs to be encrypted. This requires a public key created using the {{domxref("PushSubscription.getKey()")}} method, which relies upon some complex encryption mechanisms that are run server-side; read <a href="https://tools.ietf.org/html/draft-ietf-webpush-encryption-01">Message Encryption for Web Push</a> for more details. As time goes on, libraries will appear to handle key generation and encryption/decryption of push messages; for this demo we used Marco Castelluccio's NodeJS <a href="https://github.com/marco-c/web-push">web-push library</a>.</p> + +<div class="note"> +<p><strong>Note</strong>: There is also another library to handle the encryption with a Node and Python version available, see <a href="https://github.com/martinthomson/encrypted-content-encoding">encrypted-content-encoding</a>.</p> +</div> + +<h3 id="Push_workflow_summary">Push workflow summary</h3> + +<p>To summarize, here is what is needed to implement push messaging. You can find more details about specific parts of the demo code in subsequent sections.</p> + +<ol> + <li>Request permission for web notifications, or anything else you are using that requires permissions.</li> + <li>Register a service worker to control the page by calling {{domxref("ServiceWorkerContainer.register()")}}.</li> + <li>Subscribe to the push messaging service using {{domxref("PushManager.subscribe()")}}.</li> + <li>Retrieve the endpoint associated with the subscription and generate a client public key ({{domxref("PushSubscription.endpoint")}} and {{domxref("PushSubscription.getKey()")}}. Note that <code>getKey()</code> is currently experimental and Firefox only.)</li> + <li>Send these details to the server so it can send push message when required. This demo uses {{domxref("XMLHttpRequest")}}, but you could use <a href="/en-US/docs/Web/API/Fetch_API">Fetch</a>.</li> + <li>If you are using the <a href="/en-US/docs/Web/API/Channel_Messaging_API">Channel Messaging API</a> to comunicate with the service worker, set up a new message channel ({{domxref("MessageChannel.MessageChannel()")}}) and send <code>port2</code> over to the service worker by calling {{domxref("Worker.postMessage()")}} on the service worker, in order to open up the communication channel. You should also set up a listener to respond to messages sent back from the service worker.</li> + <li>On the server side, store the endpoint and any other required details so they are available when a push message needs to be sent to a push subscriber (we are using a simple text file, but you could use a database or whatever you like). In a production app, make sure you keep these details hidden, so malicious parties can't steal endpoints and spam subscribers with push messages.</li> + <li>To send a push message, you need to send an HTTP <code>POST</code> to the endpoint URL. The request must include a <code>TTL</code> header that limits how long the message should be queued if the user is not online. To include payload data in your request, you must encrypt it (which involves the client public key). In our demo, we are using the <a href="https://github.com/marco-c/web-push">web-push</a> module, which handles all the hard work for you.</li> + <li>Over in your service worker, set up a <code>push</code> event handler to respond to push messages being received. + <ol> + <li>If you want to respond by sending a channel message back to the main context (see Step 6) you need to first get a reference to the <code>port2</code> we sent over to the service worker context ({{domxref("MessagePort")}}). This is available on the {{domxref("MessageEvent")}} object passed to the <code>onmessage</code> handler ({{domxref("ServiceWorkerGlobalScope.onmessage")}}). Specifically, this is found in the <code>ports</code> property, index 0. Once this is done, you can send a message back to <code>port1</code>, using {{domxref("MessagePort.postMessage()")}}.</li> + <li>If you want to respond by firing a system notification, you can do this by calling {{domxref("ServiceWorkerRegistration.showNotification()")}}. Note that in our code we have run this inside an {{domxref("ExtendableEvent.waitUntil()")}} method — this extends the lifetime of the event until after the notification has been fired, so we can make sure everything has happened that we want to happen.<span id="cke_bm_307E" style="display: none;"> </span></li> + </ol> + </li> +</ol> + +<h2 id="Construyendo_la_demo">Construyendo la demo</h2> + +<p>Vamos a ensayar el código para esta demo, podemos empezar a entender como trabaja todo esto.</p> + +<ul> + <li> + <h3 id="HTML_y_CSS">HTML y CSS</h3> + </li> +</ul> + +<p>No hay nada destacalbe sobre el HTML y el CSS para la demo; el HTML inicialmente contiene un simple formulario que permite introducir un udentificador para la sala de chat, un boton que al hacer click se suscribe a las notificaciones push, y dos listas con los suscriptores y los mensajes. Una vez suscrito, aparecerán controles adicionales para permitir al usuario actual escribir mensajes en el chat.</p> + +<p>El CSS ha sido muy minimo para no desvirtuar la explicación de la funcionalidad Push Api.</p> + +<ul> + <li> + <h3 id="El_archivo_JavaScript_principal">El archivo JavaScript principal</h3> + </li> +</ul> + +<p>El JavaScript es obviamente más sustancial. Echemos un vistazo al archivo JavaScript principal.</p> + +<h4 id="Variables_y_configuración_inicial">Variables y configuración inicial</h4> + +<p>Para iniciar, nosotros declaramos algunas variables a usar en nuestra app:</p> + +<pre class="brush: js">var isPushEnabled = false; +var useNotifications = false; + +var subBtn = document.querySelector('.subscribe'); +var sendBtn; +var sendInput; + +var controlsBlock = document.querySelector('.controls'); +var subscribersList = document.querySelector('.subscribers ul'); +var messagesList = document.querySelector('.messages ul'); + +var nameForm = document.querySelector('#form'); +var nameInput = document.querySelector('#name-input'); +nameForm.onsubmit = function(e) { + e.preventDefault() +}; +nameInput.value = 'Bob';</pre> + +<p>Primero, tenemos dos boleanos para hacer un seguimiento si se a suscrito a push, y si ha permitido las notificaciones.</p> + +<p>A continuación, tomamos una referencia al suscrito/no-suscrito <code>{{htmlelement("button")}}</code>, y se declaran variables para almacenar referencias a nuestro mensaje enviado boton/entrada (sólo se crean cuando la suscripsión es correcta.)</p> + +<p>Las siguientes variables toman referencia a los trés elementos principales <code>{{htmlelement("div")}}</code> en el diseño, por lo que podemos insertar elementos en ellos (por ejemplo cuando aparezca el botón <em>envíar el mensaje de chat</em> o el mensaje de chat aparezca en la lista de <em>mensajes</em>.)</p> + +<p>Finalmente tomamos referencia a nuestro formulario de selección de nombre y el elemento <code>{{htmlelement("input")}},</code> damos a la entrada un valor por defecto, y usamos <code><a href="/en-US/docs/Web/API/Event/preventDefault">preventDefault()</a></code> para detener el envío del formulario cuando este es enviado pulsando return.</p> + +<p>A continuación, pedimos permiso para enviar las notificaciones web, usando <code>{{domxref("Notification.requestPermission","requestPermission()")}}</code>:</p> + +<pre class="brush: js">Notification.requestPermission();</pre> + +<p>Ahora ejecutamos una sección de código cuando se dispara el <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/onload">onload</a></code>, para empezar el proceso de inicialización de la app cuando se carga pro primera vez. En primer lugar añadimos un detector de eventos de clik al botón Sucribirse/unsubscribe que ejecuta nuestra funcion <code>unsubscribe()</code> si actualmente estamos suscritos (<code>isPushEnabled</code> is <code>true</code>), y <code>subscribe()</code> de la otra manera:</p> + +<pre class="brush: js">window.addEventListener('load', function() { + subBtn.addEventListener('click', function() { + if (isPushEnabled) { + unsubscribe(); + } else { + subscribe(); + } + });</pre> + +<p>A continuación verificamos el service worked es soportado. Si es así, registramos un service worker usando <code>{{domxref("ServiceWorkerContainer.register()")}}</code>, y ejecutando nuestra función <code>initialiseState()</code>. Si no es así, entregamos un mensaje de error a la consola.</p> + +<pre class="brush: js"> // Check that service workers are supported, if so, progressively + // enhance and add push messaging support, otherwise continue without it. + if ('serviceWorker' in navigator) { + navigator.serviceWorker.register('sw.js').then(function(reg) { + if(reg.installing) { + console.log('Service worker installing'); + } else if(reg.waiting) { + console.log('Service worker installed'); + } else if(reg.active) { + console.log('Service worker active'); + } + + initialiseState(reg); + }); + } else { + console.log('Service workers aren\'t supported in this browser.'); + } +}); +</pre> + +<p>La siguiente cosa en el código es la función <code>initialiseState()</code> — para el codigo completo comentado, mira en <a href="https://github.com/chrisdavidmills/push-api-demo/blob/gh-pages/main.js"><code>initialiseState()</code> source on Github</a> (no lo estamos repitiendo aquí por brevedad.)</p> + +<p><code>initialiseState()</code> primero comprueba si las notificaciones son soportadas en los service workers, entonces establece la variable <code>useNotifications</code> a verdadero. A continuación comprueba si dichas notificaciones están permitidas por el usuario y si los mensajes push están soportados, y reacciona deacuerdo a cada uno.</p> + +<p>Finalmente, se usa <code>{{domxref("ServiceWorkerContainer.ready()")}}</code> para esperar a que el service worker esté activo y listo para hacer las cosas. Una vez se revuelva el promise, recuperamos nuestra suscripsión para enviar los mensajes push usando la propiedad <code>{{domxref("ServiceWorkerRegistration.pushManager")}}</code>, que devuelve un objeto <code>{{domxref("PushManager")}}</code> cuando llamamos a <code>{{domxref("PushManager.getSubscription()")}}</code>. Una vez la segunda promesa interna se resuelva, habilitamos el botón subscribe/unsubscribe (<code>subBtn.disabled = false;</code>), y verificamos que tenemos un objeto suscripsión para trabajar.</p> + +<p>Si lo hacemos, entonces ya estamos suscritos. Esto es posible cuando la app no está abierta en el navegador; el service worker aun puede ser activado en segundo plano. si estamos suscritos, actualizamos la UI para mostrar que estamos suscritos por la actualizacion del label en el botón, entonces establecemos <code>isPushEnabled</code> to <code>true</code>, toma el punto final de suscripsión desde <code>{{domxref("PushSubscription.endpoint")}}</code>, genera una public key usando <code>{{domxref("PushSubscription.getKey()")}}</code>, y ejecutando nuestra función <code>updateStatus()</code>, que como verá más adelante se comunica con el servidor.</p> + +<p>Como un bonus añadido, configuramos un nuevo <code>{{domxref("MessageChannel")}}</code> usando el constructor <code>{{domxref("MessageChannel.MessageChannel()")}}</code>, toma una referencia al service worker activo usando <code>{{domxref("ServiceworkerRegistration.active")}}</code>, luego configure un canal entre el contexto principal del navegador y el contexto del service worker usando <code>{{domxref("Worker.postMessage()")}}</code>. El contexto del navegador recive mensajes en <code>{{domxref("MessageChannel.port1")}}</code>; Cuando esto suceda, ejecutamos la función <code>handleChannelMessage()</code> para decidir que hacer con esos datos (mirar la sección <code>{{anch("Handling channel messages sent from the service worker")}}</code> ).</p> + +<h4 id="Subscribing_and_unsubscribing">Subscribing and unsubscribing</h4> + +<p>Ahora regresamos la atención a las funciones <code>subscribe()</code> y <code>unsubscribe()</code> usadas para subscribe/unsubscribe al servicion de notificaciones push.</p> + +<p>In the case of subscription, we again check that our service worker is active and ready by calling {{domxref("ServiceWorkerContainer.ready()")}}. When the promise resolves, we subscribe to the service using {{domxref("PushManager.subscribe()")}}. If the subscription is successful, we get a {{domxref("PushSubscription")}} object, extract the subscription endpoint from this and generate a public key (again, {{domxref("PushSubscription.endpoint")}} and {{domxref("PushSubscription.getKey()")}}), and pass them to our <code>updateStatus()</code> function along with the update type (<code>subscribe</code>) to send the necessary details to the server.</p> + +<p>We also make the necessary updates to the app state (set <code>isPushEnabled</code> to <code>true</code>) and UI (enable the subscribe/unsubscribe button and set its label text to show that the next time it is pressed it will unsubscribe.)</p> + +<p>The <code>unsubscribe()</code> function is pretty similar in structure, but it basically does the opposite; the most notable difference is that it gets the current subscription using {{domxref("PushManager.getSubscription()")}}, and when that promise resolves it unsubscribes using {{domxref("PushSubscription.unsubscribe()")}}.</p> + +<p>Appropriate error handling is also provided in both functions. </p> + +<p>We only show the <code>subscribe()</code> code below, for brevity; see the full <a href="https://github.com/chrisdavidmills/push-api-demo/blob/gh-pages/main.js">subscribe/unsubscribe code on Github</a>.</p> + +<pre class="brush: js">function subscribe() { + // Disable the button so it can't be changed while + // we process the permission request + + subBtn.disabled = true; + + navigator.serviceWorker.ready.then(function(reg) { + reg.pushManager.subscribe({userVisibleOnly: true}) + .then(function(subscription) { + // The subscription was successful + isPushEnabled = true; + subBtn.textContent = 'Unsubscribe from Push Messaging'; + subBtn.disabled = false; + + // Update status to subscribe current user on server, and to let + // other users know this user has subscribed + var endpoint = subscription.endpoint; + var key = subscription.getKey('p256dh'); + updateStatus(endpoint,key,'subscribe'); + }) + .catch(function(e) { + if (Notification.permission === 'denied') { + // The user denied the notification permission which + // means we failed to subscribe and the user will need + // to manually change the notification permission to + // subscribe to push messages + console.log('Permission for Notifications was denied'); + + } else { + // A problem occurred with the subscription, this can + // often be down to an issue or lack of the gcm_sender_id + // and / or gcm_user_visible_only + console.log('Unable to subscribe to push.', e); + subBtn.disabled = false; + subBtn.textContent = 'Subscribe to Push Messaging'; + } + }); + }); +}</pre> + +<h4 id="Updating_the_status_in_the_app_and_server">Updating the status in the app and server</h4> + +<p>The next function in our main JavaScript is <code>updateStatus()</code>, which updates the UI for sending chat messages when subscribing/unsubscribing and sends a request to update this information on the server.</p> + +<p>The function does one of three different things, depending on the value of the <code>statusType</code> parameter passed into it:</p> + +<ul> + <li><code>subscribe</code>: The button and text input for sending chat messages are created and inserted into the UI, and an object is sent to the server via XHR containing the status type (<code>subscribe</code>), username of the subscriber, subscription endpoint, and client public key.</li> + <li><code>unsubscribe</code>: This basically works in the opposite way to subscribe — the chat UI elements are removed, and an object is sent to the server to tell it that the user has unsubscribed.</li> + <li><code>init</code>: This is run when the app is first loaded/initialised — it creates the chat UI elements, and sends an object to the server to tell it that which user has reinitialised (reloaded.)</li> +</ul> + +<p>Again, we have not included the entire function listing for brevity. Examine the <a href="https://github.com/chrisdavidmills/push-api-demo/blob/gh-pages/main.js">full <code>updateStatus()</code> code on Github</a>.</p> + +<h4 id="Handling_channel_messages_sent_from_the_service_worker">Handling channel messages sent from the service worker</h4> + +<p>As mentioned earlier, when a <a href="/en-US/docs/Web/API/Channel_Messaging_API">channel message</a> is received from the service worker, our <code>handleChannelMessage()</code> function is called to handle it. This is done by our handler for the {{event("message")}} event, {{domxref("channel.port1.onmessage")}}:</p> + +<pre class="brush: js">channel.port1.onmessage = function(e) { + handleChannelMessage(e.data); +}</pre> + +<p>This occurs when the <a href="https://github.com/chrisdavidmills/push-api-demo/blob/gh-pages/sw.js#L8">service worker sends a channel message over</a>.</p> + +<p>The <code>handleChannelMessage()</code> function looks like this:</p> + +<pre class="brush: js">function handleChannelMessage(data) { + if(data.action === 'subscribe' || data.action === 'init') { + var listItem = document.createElement('li'); + listItem.textContent = data.name; + subscribersList.appendChild(listItem); + } else if(data.action === 'unsubscribe') { + for(i = 0; i < subscribersList.children.length; i++) { + if(subscribersList.children[i].textContent === data.name) { + subscribersList.children[i].parentNode.removeChild(subscribersList.children[i]); + } + } + nameInput.disabled = false; + } else if(data.action === 'chatMsg') { + var listItem = document.createElement('li'); + listItem.textContent = data.name + ": " + data.msg; + messagesList.appendChild(listItem); + sendInput.value = ''; + } +}</pre> + +<p>What happens here depends on what the <code>action</code> property on the <code>data</code> object is set to:</p> + +<ul> + <li><code>subscribe</code> or <code>init</code> (at both startup and restart, we need to do the same thing in this sample): An {{htmlelement("li")}} element is created, its text content is set to <code>data.name</code> (the name of the subscriber), and it is appended to the subscribers list (a simple {{htmlelement("ul")}} element) so there is visual feedback that a subscriber has (re)joined the chat.</li> + <li><code>unsubscribe</code>: We loop through the children of the subscribers list, find the one whose text content is equal to <code>data.name</code> (the name of the unsubscriber), and delete that node to provide visual feedback that someone has unsubscribed.</li> + <li><code>chatMsg</code>: In a similar manner to the first case, an {{htmlelement("li")}} element is created, its text content is set to <code>data.name + ": " + data.msg</code> (so for example "Chris: This is my message"), and it is appended to the chat messages list; this is how the chat messages appear on the UI for each user.</li> +</ul> + +<div class="note"> +<p><strong>Note</strong>: We have to pass the data back to the main context before we do DOM updates because service workers don't have access to the DOM. You should be aware of the limitations of service workers before attemping to ue them. Read <a href="/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers">Using Service Workers</a> for more details.</p> +</div> + +<h4 id="Sending_chat_messages">Sending chat messages</h4> + +<p>When the <em>Send Chat Message</em> button is clicked, the content of the associated text field is sent as a chat message. This is handled by the <a href="https://github.com/chrisdavidmills/push-api-demo/blob/gh-pages/main.js"><code>sendChatMessage()</code> function</a> (again, not shown in full for brevity). This works in a similar way to the different parts of the <code>updateStatus()</code> function (see {{anch("Updating the status in the app and server")}}) — we retrieve an endpoint and public key via a {{domxref("PushSubscription")}} object, which is itself retrieved via {{domxref("ServiceWorkerContainer.ready()")}} and {{domxref("PushManager.subscribe()")}}. These are sent to the server via {{domxref("XMLHttpRequest")}} in a message object, along with the name of the subscribed user, the chat message to send, and a <code>statusType</code> of <code>chatMsg</code>.</p> + +<h3 id="The_server">The server</h3> + +<p>As mentioned above, we need a server-side component in our app, to handle storing subscription details, and send out push messages when updates occur. We've hacked together a quick-and-dirty server using <a href="http://nodejs.org/">NodeJS</a> (<code><a href="https://github.com/chrisdavidmills/push-api-demo/blob/gh-pages/server.js">server.js</a></code>), which handles the XHR requests sent by our client-side JavaScript code.</p> + +<p>It uses a text file (<code><a href="https://github.com/chrisdavidmills/push-api-demo/blob/gh-pages/endpoint.txt">endpoint.txt</a></code>) to store subscription details; this file starts out empty. There are four different types of request, marked by the <code>statusType</code> property of the object sent over in the request; these are the same as those understood client-side, and perform the required server actions for that same situation. Here's what each means in the context of the server:</p> + +<ul> + <li><code>subscribe</code>: The server adds the new subscriber's details into the subscription data store (<code><a href="https://github.com/chrisdavidmills/push-api-demo/blob/gh-pages/endpoint.txt">endpoint.txt</a></code>), including the endpoint, and then sends a push message to all the endpoints it has stored to tell each subscriber that someone new has joined the chat.</li> + <li><code>unsubscribe</code>: The server finds the sending subscriber's details in the subscription store and removes it, then sends a push message to all remaining subscribers telling them the user has unsubscribed.</li> + <li><code>init</code>: The server reads all the current subscribers from the text file, and sends each one a push message to tell them a user has initialized (rejoined) the chat.</li> + <li><code>chatMsg</code>: Sent by a subscriber that wishes to deliver a message to all users; the server reads the list of all current subscribers from the subscription store file, then sends each one a push message containing the new chat message they should display.</li> +</ul> + +<p>A couple more things to note:</p> + +<ul> + <li>We are using the Node.js <a href="https://nodejs.org/api/https.html">https module</a> to create the server, because for security purposes, service workers only work on a secure connection. This is why we need to include the <code>.pfx</code> security cert in the app, and reference it when creating the server in the Node code.</li> + <li>When you send a push message without data, you simply send it to the endpoint URL using an HTTP <code>POST</code> request. However, when the push message contains data, you need to encrypt it, which is quite a complex process. As time goes on, libraries will appear to do this kind of thing for you; for this demo we used Marco Castelluccio's NodeJS <a href="https://github.com/marco-c/web-push">web-push library</a>. Have a look at the source code to get more of an idea of how the encryption is done (and read <a href="https://tools.ietf.org/html/draft-ietf-webpush-encryption-01">Message Encryption for Web Push</a> for more details.) The library <a href="https://github.com/chrisdavidmills/push-api-demo/blob/gh-pages/server.js#L43-L46">makes sending a push message simple</a>.</li> + <li>If you wish to have messages that collapse (newer updates will replace older updates), you can use the Topic feature. A topic is a special class of subscription update that has a <code>Topic</code> header. A topic name can be any URL safe, base64 string. For example, a header like "<code>Topic: MyFavoriteTopic-For2016</code>" is fine, but "<code>Topic: OMG! Kitties :)</code>" is not. Topic messages are collapsed when the subscriber is offline or unavailable. When they come back, they will receive only the lastest message per topic, along with whatever other messages are pending. "<a href="https://hacks.mozilla.org/2016/11/mozilla-push-server-now-supports-topics/">Mozilla Push Server now supports Topics</a>" on the Mozilla Hacks blog gives more details and examples.</li> +</ul> + +<h3 id="The_service_worker">The service worker</h3> + +<p>Now let's have a look at the service worker code (<code><a href="https://github.com/chrisdavidmills/push-api-demo/blob/gh-pages/sw.js">sw.js</a></code>), which responds to the push messages, represented by {{Event("push")}} events. These are handled on the service worker's scope by the ({{domxref("ServiceWorkerGlobalScope.onpush")}}) event handler; its job is to work out what to do in response to each received message. We first convert the received message back into an object by calling {{domxref("PushMessageData.json()")}}. Next, we check what type of push message it is, by looking at the object's <code>action</code> property:</p> + +<ul> + <li><code>subscribe</code> or <code>unsubscribe</code>: We send a system notification via the <code>fireNotification()</code> function, but also send a message back to the main context on our {{domxref("MessageChannel")}} so we can update the subscriber list accordingly (see {{anch("Handling channel messages sent from the service worker")}} for more details).</li> + <li><code>init</code> or <code>chatMsg</code>: We just send a channel message back to the main context to handle the <code>init</code> and <code>chatMsg</code> cases (these don't need a system notification).</li> +</ul> + +<pre class="brush: js">self.addEventListener('push', function(event) { + var obj = event.data.json(); + + if(obj.action === 'subscribe' || obj.action === 'unsubscribe') { + fireNotification(obj, event); + port.postMessage(obj); + } else if(obj.action === 'init' || obj.action === 'chatMsg') { + port.postMessage(obj); + } +});</pre> + +<p>Next, let's look at the <code>fireNotification()</code> function (which is blissfully pretty simple).</p> + +<pre class="brush: js">function fireNotification(obj, event) { + var title = 'Subscription change'; + var body = obj.name + ' has ' + obj.action + 'd.'; + var icon = 'push-icon.png'; + var tag = 'push'; + + event.waitUntil(self.registration.showNotification(title, { + body: body, + icon: icon, + tag: tag + })); +}</pre> + +<p>Here we assemble the assets needed by the notification box: the title, body, and icon. Then we send a notification via the {{domxref("ServiceWorkerRegistration.showNotification()")}} method, providing that information as well as the tag "push", which we can use to identify this notification among any other notifications we might be using. When the notification is successfully sent, it manifests as a system notification dialog on the users computers/devices in whatever style system notifications look like on those systems (the following image shows a Mac OSX system notification.)</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/11855/subscribe-notification.png" style="display: block; height: 65px; margin: 0px auto; width: 326px;"></p> + +<p>Note that we do this from inside an {{domxref("ExtendableEvent.waitUntil()")}} method; this is to make sure the service worker remains active until the notification has been sent. <code>waitUntil()</code> will extend the life cycle of the service worker until everything inside this method has completed.</p> + +<div class="note"> +<p><strong>Note</strong>: Web notifications from service workers were introduced around Firefox version 42, but are likely to be removed again while the surrounding functionality (such as <code>Clients.openWindow()</code>) is properly implemented (see {{bug(1203324)}} for more details.)</p> +</div> + +<h2 id="Handling_premature_subscription_expiration">Handling premature subscription expiration</h2> + +<p>Sometimes push subscriptions expire prematurely, without {{domxref("PushSubscription.unsubscribe()")}} being called. This can happen when the server gets overloaded, or if you are offline for a long time, for example. This is highly server-dependent, so the exact behavior is difficult to predict. In any case, you can handle this problem by watching for the {{Event("pushsubscriptionchange")}} event, which you can listen for by providing a {{domxref("ServiceWorkerGlobalScope.onpushsubscriptionchange")}} event handler; this event is fired only in this specific case.</p> + +<pre class="brush: js language-js"><code class="language-js">self<span class="punctuation token">.</span><span class="function token">addEventListener<span class="punctuation token">(</span></span><span class="string token">'pushsubscriptionchange'</span><span class="punctuation token">,</span> <span class="keyword token">function</span><span class="punctuation token">(</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="comment token"> // do something, usually resubscribe to push and +</span> <span class="comment token"> // send the new subscription details back to the +</span> <span class="comment token"> // server via XHR or Fetch +</span><span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span></code></pre> + +<p>Note that we don't cover this case in our demo, as a subscription ending is not a big deal for a simple chat server. But for a more complex example you'd probably want to resubscribe the user.</p> + +<h2 id="Extra_steps_for_Chrome_support">Extra steps for Chrome support</h2> + +<p>To get the app working on Chrome, we need a few extra steps, as Chrome currently relies on Google's Cloud Messaging service to work.</p> + +<h3 id="Setting_up_Google_Cloud_Messaging">Setting up Google Cloud Messaging</h3> + +<p>To get this set up, follow these steps:</p> + +<ol> + <li>Navigate to the <a href="https://console.developers.google.com">Google Developers Console</a> and set up a new project.</li> + <li>Go to your project's homepage (ours is at <code>https://console.developers.google.com/project/push-project-978</code>, for example), then + <ol> + <li>Select the <em>Enable Google APIs for use in your apps</em> option.</li> + <li>In the next screen, click <em>Cloud Messaging for Android</em> under the <em>Mobile APIs</em> section.</li> + <li>Click the <em>Enable API</em> button.</li> + </ol> + </li> + <li>Now you need to make a note of your project number and API key because you'll need them later. To find them: + <ol> + <li><strong>Project number</strong>: click <em>Home</em> on the left; the project number is clearly marked at the top of your project's home page.</li> + <li><strong>API key</strong>: click <em>Credentials</em> on the left hand menu; the API key can be found on that screen.</li> + </ol> + </li> +</ol> + +<h3 id="manifest.json">manifest.json</h3> + +<p>You need to include a Google app-style <code>manifest.json</code> file in your app, which references the project number you made a note of earlier in the <code>gcm_sender_id</code> parameter. Here is our simple example <a href="https://github.com/chrisdavidmills/push-api-demo/blob/gh-pages/manifest.json">manifest.json</a>:</p> + +<pre class="brush: js">{ + "name": "Push Demo", + "short_name": "Push Demo", + "icons": [{ + "src": "push-icon.png", + "sizes": "111x111", + "type": "image/png" + }], + "start_url": "/index.html", + "display": "standalone", + "gcm_sender_id": "224273183921" +}</pre> + +<p>You also need to reference your manifest using a {{HTMLElement("link")}} element in your HTML:</p> + +<pre class="brush: html"><link rel="manifest" href="manifest.json"></pre> + +<h3 id="userVisibleOnly">userVisibleOnly</h3> + +<p>Chrome requires you to set the <a href="/en-US/docs/Web/API/PushManager/subscribe#Parameters"><code>userVisibleOnly</code> parameter</a> to <code>true</code> when subscribing to the push service, which indicates that we are promising to show a notification whenever a push is received. This can be <a href="https://github.com/chrisdavidmills/push-api-demo/blob/gh-pages/main.js#L127">seen in action in our <code>subscribe()</code> function</a>.</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Push_API">Push API</a></li> + <li><a href="/en-US/docs/Web/API/Service_Worker_API">Service Worker API</a></li> +</ul> + +<div class="note"> +<p><strong>Note</strong>: Some of the client-side code in our Push demo is heavily influenced by Matt Gaunt's excellent examples in <a href="http://updates.html5rocks.com/2015/03/push-notificatons-on-the-open-web">Push Notifications on the Open Web</a>. Thanks for the awesome work, Matt!</p> +</div> diff --git a/files/es/web/api/pushmanager/index.html b/files/es/web/api/pushmanager/index.html new file mode 100644 index 0000000000..2e42155112 --- /dev/null +++ b/files/es/web/api/pushmanager/index.html @@ -0,0 +1,161 @@ +--- +title: PushManager +slug: Web/API/PushManager +tags: + - API + - Experimental + - Interface + - NeedsTranslation + - Push + - Push API + - Reference + - Service Workers + - TopicStub + - WebAPI +translation_of: Web/API/PushManager +--- +<p>{{SeeCompatTable}}{{ApiRef("Push API")}}</p> + +<p>The <code>PushManager</code> interface of the <a href="/en-US/docs/Web/API/Push_API">Push API</a> provides a way to receive notifications from third-party servers as well as request URLs for push notifications.</p> + +<p>This interface is accessed via the {{domxref("ServiceWorkerRegistration.pushManager")}} property.</p> + +<div class="note"> +<p><strong>Note</strong>: This interface replaces functionality previously offered by the obsolete {{domxref("PushRegistrationManager")}} interface.</p> +</div> + +<h2 id="Properties">Properties</h2> + +<p><em>None.</em></p> + +<h2 id="Methods">Methods</h2> + +<dl> + <dt>{{domxref("PushManager.getSubscription()")}}</dt> + <dd>Retrieves an existing push subscription. It returns a {{jsxref("Promise")}} that resolves to a {{domxref("PushSubscription")}} object containing details of an existing subscription. If no existing subscription exists, this resolves to a <code>null</code> value.</dd> + <dt>{{domxref("PushManager.permissionState()")}}</dt> + <dd>Returns a {{jsxref("Promise")}} that resolves to the permission state of the current {{domxref("PushManager")}}, which will be one of <code>'granted'</code>, <code>'denied'</code>, or <code>'default'</code>.</dd> + <dt>{{domxref("PushManager.subscribe()")}}</dt> + <dd>Subscribes to a push service. It returns a {{jsxref("Promise")}} that resolves to a {{domxref("PushSubscription")}} object containing details of a push subscription. A new push subscription is created if the current service worker does not have an existing subscription.</dd> +</dl> + +<h3 id="Deprecated_methods">Deprecated methods</h3> + +<dl> + <dt>{{domxref("PushManager.hasPermission()")}} {{deprecated_inline}}</dt> + <dd>Returns a {{jsxref("Promise")}} that resolves to the <code>PushPermissionStatus</code> of the requesting webapp, which will be one of <code>granted</code>, <code>denied</code>, or <code>default</code>. Replaced by {{domxref("PushManager.permissionState()")}}.</dd> + <dt>{{domxref("PushManager.register()")}} {{deprecated_inline}}</dt> + <dd>Subscribes to a push subscription. Replaced by {{domxref("PushManager.subscribe()")}}.</dd> + <dt>{{domxref("PushManager.registrations()")}} {{deprecated_inline}}</dt> + <dd>Retrieves existing push subscriptions. Replaced by {{domxref("PushManager.getSubscription()")}}.</dd> + <dt>{{domxref("PushManager.unregister()")}} {{deprecated_inline}}</dt> + <dd>Unregisters and deletes a specified subscription endpoint. In the updated API, a subscription is unregistered by calling the {{domxref("PushSubscription.unsubscribe()")}} method.</dd> +</dl> + +<h2 id="Example">Example</h2> + +<pre class="brush: js">this.onpush = function(event) { + console.log(event.data); + // From here we can write the data to IndexedDB, send it to any open + // windows, display a notification, etc. +} + +navigator.serviceWorker.register('serviceworker.js').then( + function(serviceWorkerRegistration) { + serviceWorkerRegistration.pushManager.subscribe().then( + function(pushSubscription) { + console.log(pushSubscription.subscriptionId); + console.log(pushSubscription.endpoint); + // The push subscription details needed by the application + // server are now available, and can be sent to it using, + // for example, an XMLHttpRequest. + }, function(error) { + // During development it often helps to log errors to the + // console. In a production environment it might make sense to + // also report information about errors back to the + // application server. + console.log(error); + } + ); + });</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('Push API','#pushmanager-interface','PushManager')}}</td> + <td>{{Spec2('Push API')}}</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>{{CompatChrome(42.0)}}</td> + <td>{{CompatGeckoDesktop(44.0)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</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>Android Webview</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(42.0)}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Push_API/Using_the_Push_API">Using the Push API</a></li> + <li><a href="/en-US/docs/Web/API/Push_API">Push API</a></li> + <li><a href="/en-US/docs/Web/API/Service_Worker_API">Service Worker API</a></li> +</ul> diff --git a/files/es/web/api/pushmanager/permissionstate/index.html b/files/es/web/api/pushmanager/permissionstate/index.html new file mode 100644 index 0000000000..f017b2da93 --- /dev/null +++ b/files/es/web/api/pushmanager/permissionstate/index.html @@ -0,0 +1,111 @@ +--- +title: PushManager.permissionState() +slug: Web/API/PushManager/permissionState +translation_of: Web/API/PushManager/permissionState +--- +<p>{{SeeCompatTable}}{{ApiRef("Push API")}}</p> + +<p>El metodo <strong><code>permissionState()</code></strong> de la interface {{domxref("PushManager")}} retorna un {{jsxref("Promise")}} that resolves to a {{domxref("DOMString")}} indicating the permission state of the push manager. Possible values are <code>'prompt'</code>, <code>'denied'</code>, or <code>'granted'</code>.</p> + +<div class="note"> +<p><strong>Note</strong>: As of Firefox 44, the permissions for <a href="/en-US/docs/Web/API/Notifications_API">Notifications</a> and <a href="/en-US/docs/Web/API/Push_API">Push</a> have been merged. If permission is granted for notifications, push will also be enabled.</p> +</div> + +<h2 id="Sintaxis"><span>Sintaxis</span></h2> + +<pre class="syntaxbox">PushManager.permissionState(options).then(function(PushMessagingState) { ... }); +</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code>opciones {{optional_inline}}</code></dt> + <dd>An object containing optional configuration parameters. It can have the following properties: + <ul> + <li><code>userVisibleOnly</code>: A boolean indicating that the returned push subscription will only be used for messages whose effect is made visible to the user.</li> + </ul> + </dd> +</dl> + +<h3 id="Retorna">Retorna</h3> + +<p>Un {{jsxref("Promise")}} que resuelve a un {{domxref("DOMString")}} con un valor de <code>'prompt'</code>, <code>'denied'</code>, o <code>'granted'</code>.</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('Push API','#widl-PushManager-permissionState-Promise-PushPermissionState--PushSubscriptionOptions-options','permissionState()')}}</td> + <td>{{Spec2('Push API')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Compactibilidad_del_Navegador">Compactibilidad del Navegador</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</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>{{CompatChrome(42.0)}}</td> + <td>{{CompatGeckoDesktop(44.0)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Android Webview</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(42.0)}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Push_API/Using_the_Push_API">Using the Push API</a></li> +</ul> diff --git a/files/es/web/api/pushmanager/supportedcontentencodings/index.html b/files/es/web/api/pushmanager/supportedcontentencodings/index.html new file mode 100644 index 0000000000..9966fa3cda --- /dev/null +++ b/files/es/web/api/pushmanager/supportedcontentencodings/index.html @@ -0,0 +1,43 @@ +--- +title: PushManager.supportedContentEncodings +slug: Web/API/PushManager/supportedContentEncodings +translation_of: Web/API/PushManager/supportedContentEncodings +--- +<p>{{SeeCompatTable}}{{APIRef("Push API")}}</p> + +<p>La propiedad<strong><code>supportedContentEncodings</code></strong> de solo lectura (read-only) de la interfaz {{domxref("PushManager")}} devuelve un array de los codigos de contenido que puede soportar y que pueden ser usados para encriptar los datos (payload) de un push-message.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var <em>encodings</em>[] = PushManager.<em>supportedContentEncodings</em></pre> + +<h3 id="Valor">Valor</h3> + +<p>Un <em>array </em>de <em>Strings</em></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('Push API','#dom-pushmanager-supportedcontentencodings','supportedContentEncodings')}}</td> + <td>{{Spec2('Push API')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_Compatibility">Browser Compatibility</h2> + +<div> +<div> + + +<p>{{Compat("api.PushManager.supportedContentEncodings")}}</p> +</div> +</div> diff --git a/files/es/web/api/randomsource/index.html b/files/es/web/api/randomsource/index.html new file mode 100644 index 0000000000..7c68f85c01 --- /dev/null +++ b/files/es/web/api/randomsource/index.html @@ -0,0 +1,110 @@ +--- +title: RandomSource +slug: Web/API/RandomSource +tags: + - API + - Interface + - NeedsTranslation + - RandomSource + - Reference + - TopicStub + - Web Crypto API +translation_of: Web/API/Crypto/getRandomValues +--- +<p>{{APIRef("Web Crypto API")}}</p> + +<p><strong><code>RandomSource</code></strong> represents a source of cryptographically secure random numbers. It is available via the {{domxref("Crypto")}} object of the global object: {{domxref("Window.crypto")}} on Web pages, {{domxref("WorkerGlobalScope.crypto")}} in workers.</p> + +<p><code>RandomSource</code> is a not an interface and no object of this type can be created.</p> + +<h2 id="Properties">Properties</h2> + +<p><em><code>RandomSource</code> neither defines nor inherits any property.</em></p> + +<dl> +</dl> + +<h2 id="Methods">Methods</h2> + +<dl> + <dt>{{ domxref("RandomSource.getRandomValues()") }}</dt> + <dd>Fills the passed {{ domxref("ArrayBufferView") }} with cryptographically sound random values.</dd> +</dl> + +<h2 id="Specification" name="Specification">Specification</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 Crypto API', '#dfn-RandomSource')}}</td> + <td>{{Spec2('Web Crypto API')}}</td> + <td>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>11.0 {{ webkitbug("22049") }}</td> + <td>{{CompatGeckoDesktop(21)}} [1]</td> + <td>11.0</td> + <td>15.0</td> + <td>3.1</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>23</td> + <td>{{CompatGeckoMobile(21)}}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>6</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Although the transparent <code>RandomSource</code> is only available since Firefox 26, the feature was available in Firefox 21.</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{ domxref("Window.crypto") }} to get a {{domxref("Crypto")}} object.</li> + <li>{{jsxref("Math.random")}}, a non-cryptographic source of random numbers.</li> +</ul> diff --git a/files/es/web/api/randomsource/obtenervaloresaleatorios/index.html b/files/es/web/api/randomsource/obtenervaloresaleatorios/index.html new file mode 100644 index 0000000000..b6e09439a9 --- /dev/null +++ b/files/es/web/api/randomsource/obtenervaloresaleatorios/index.html @@ -0,0 +1,75 @@ +--- +title: Crypto.getRandomValues() +slug: Web/API/RandomSource/Obtenervaloresaleatorios +tags: + - API + - Criptografía + - Referencia + - metodo +translation_of: Web/API/Crypto/getRandomValues +--- +<p>{{APIRef("Web Crypto API")}}</p> + +<p>El método <code><strong>Crypto.getRandomValues()</strong></code> permite obtener valores aleatorios criptográficamente fuertes. El array que se pasa como parámetro se rellena con números aleatorios (entiéndase aleatorios en el sentido criptográfico).</p> + +<p>Con el fin de garantizar un rendimiento razonable, las distintas implementaciones no utilizan un generador de numeros aleatorios puro, sino que utilizan un generador numérico pseudo-aleatorio, sembrado con un valor con suficiente entropía. Los generadores numéricos pseudo-aleatorios utilizados difieren entre {{Glossary("user agent", "user agents")}}, pero son adecuados para usos criptográficos. Se require también que las distintas implementaciones usen una semilla con suficiente entropía, como una fuente de entropía a nivel de sistema.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><em>cryptoObj</em>.getRandomValues(<em>typedArray</em>);</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><em>typedArray</em></dt> + <dd>Es un entero {{jsxref("TypedArray")}}, que puede ser un {{jsxref("Int8Array")}}, un {{jsxref("Uint8Array")}}, un {{jsxref("Int16Array")}}, un {{jsxref("Uint16Array")}}, un {{jsxref("Int32Array")}}, o un {{jsxref("Uint32Array")}}. Todos los elementos dentro del array seran sobreescritos con números aleatorios.</dd> +</dl> + +<h3 id="Excepciones">Excepciones</h3> + +<ul> + <li>Una {{exception("QuotaExceededError")}} {{domxref("DOMException")}} es lanzada si la longitud solicitada es mayor a 65536 bytes.</li> +</ul> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush: js">/* Asumiendo que window.crypto.getRandomValues está disponible */ + +var array = new Uint32Array(10); +window.crypto.getRandomValues(array); + +console.log("Tus numeros de la suerte:"); +for (var i = 0; i < array.length; i++) { + console.log(array[i]); +} +</pre> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('Web Crypto API', '#RandomSource-method-getRandomValues')}}</td> + <td>{{Spec2('Web Crypto API')}}</td> + <td>Definición Inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_del_navegador">Compatibilidad del navegador</h2> + +<p>La tabla de compatibilidad de esta página se genera a partir de datos estructurados. Si desea contribuir a los datos, por favor, compruebe <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> y envianos un pull request.</p> + +<p>{{Compat("api.Crypto.getRandomValues")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{ domxref("Window.crypto") }} para obtener un objeto tipo {{domxref("Crypto")}}.</li> + <li>{{jsxref("Math.random")}}, una fuente no criptográfica de números aleatorios.</li> +</ul> diff --git a/files/es/web/api/range/collapsed/index.html b/files/es/web/api/range/collapsed/index.html new file mode 100644 index 0000000000..ce3b6fa91f --- /dev/null +++ b/files/es/web/api/range/collapsed/index.html @@ -0,0 +1,35 @@ +--- +title: range.collapsed +slug: Web/API/Range/collapsed +translation_of: Web/API/Range/collapsed +--- +<p>{{ APIRef("DOM") }}</p> + +<h3 id="Resumen" name="Resumen">Resumen</h3> + +<p>Devuelve un valor booleano verdadero indicando si los puntos de inicio y fin de un rango están en la misma posición.</p> + +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> + +<pre class="eval">isCollapsed = range.collapsed; +</pre> + +<h3 id="Ejemplo" name="Ejemplo">Ejemplo</h3> + +<pre class="eval">range = document.createRange(); +range.setStart(startNode,startOffset); +range.setEnd(endNode,endOffset); +isCollapsed = range.collapsed; +</pre> + +<h3 id="Notas" name="Notas">Notas</h3> + +<p>Devuelve un valor boleano verdadero si los puntos límite inicial y final del rango están en el mismo punto en el DOM, y devuelve un valor falso si no lo están.</p> + +<p>Un rango plegado está vacío, sin tener algún contenido, especificando un simple punto en el árbol del DOM. La propiedad plegada es de sólo lectura. Para plegar un rango, vea el método <a href="es/DOM/range.collapse"> collapse</a>.</p> + +<h3 id="Especificaci.C3.B3n" name="Especificaci.C3.B3n">Especificación</h3> + +<p><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html#Level-2-Range-attr-collapsed">collapsed</a></p> + +<p>{{ languages( { "en": "en/DOM/range.collapsed", "ja": "ja/DOM/range.collapsed" } ) }}</p> diff --git a/files/es/web/api/range/commonancestorcontainer/index.html b/files/es/web/api/range/commonancestorcontainer/index.html new file mode 100644 index 0000000000..0f449e5858 --- /dev/null +++ b/files/es/web/api/range/commonancestorcontainer/index.html @@ -0,0 +1,35 @@ +--- +title: range.commonAncestorContainer +slug: Web/API/Range/commonAncestorContainer +translation_of: Web/API/Range/commonAncestorContainer +--- +<div>{{ApiRef("DOM")}}</div> + +<h3 id="Resumen" name="Resumen">Resumen</h3> + +<p>Devuelve el nodo más profundo que contienen los nodos <a href="es/DOM/range.startContainer"> startContainer</a> y <a href="es/DOM/range.endContainer"> endContainer</a>.</p> + +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> + +<pre class="eval">rangeAncestor = range.commonAncestorContainer; +</pre> + +<h3 id="Ejemplo" name="Ejemplo">Ejemplo</h3> + +<pre class="eval">range = document.createRange(); +range.setStart(startNode,startOffset); +range.setEnd(endNode,endOffset); +rangeAncestor = range.commonAncestorContainer; +</pre> + +<h3 id="Notas" name="Notas">Notas</h3> + +<p>Devuelve el último nodo, o el más lejano a lo largo del árbol del documento, que contienen los nodos <a href="es/DOM/range.startContainer"> startContainer</a> y <a href="es/DOM/range.endContainer"> endContainer</a>. Ya que un rango no necesita ser contínuo y puede seleccionar nodos parcialmente, ésta es una forma conveniente para encontrar un nodo que encierra un rango.</p> + +<p>Esta propiedad es de sólo lectura. Para cambiar el contenedor ancestro de un nodo, considere usar varios métodos para definir las posiciones iniciales y finales de el rango.</p> + +<h3 id="Especificaci.C3.B3n" name="Especificaci.C3.B3n">Especificación</h3> + +<p><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html#Level-2-Range-attr-commonParent">commonAncestorContainer</a></p> + +<p>{{ languages( { "en": "en/DOM/range.commonAncestorContainer" } ) }}</p> diff --git a/files/es/web/api/range/getclientrects/index.html b/files/es/web/api/range/getclientrects/index.html new file mode 100644 index 0000000000..c324753d0b --- /dev/null +++ b/files/es/web/api/range/getclientrects/index.html @@ -0,0 +1,103 @@ +--- +title: Range.getClientRects() +slug: Web/API/Range/getClientRects +tags: + - API + - Experimental + - Rango + - Vista CSSOM + - metodo +translation_of: Web/API/Range/getClientRects +--- +<p>{{ApiRef("DOM")}}{{ seeCompatTable }}</p> + +<p>El método <strong><code>Range.getClientRects()</code></strong><strong> </strong>regresa una lista de objetos {{ domxref("DOMRect") }} los cuales representan el área de la pantalla ocupada por el <a href="/es/DOM/range" title="https://developer.mozilla.org/es/dom:range">rango</a>. El resultado es generado al agregar los resultados de las llamadas a {{ domxref("Element.getClientRects()") }} para cada uno de los elementos dentro del rango.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox"><em>rectList</em> = <em>range</em>.getClientRects() +</pre> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre class="brush: js">range = document.createRange(); +range.selectNode(document.getElementsByTagName("div").item(0)); +rectList = range.getClientRects(); +</pre> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estatus</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('CSSOM View', '#dom-range-getclientrects', 'Range.getClientRects()')}}</td> + <td>{{Spec2('CSSOM View')}}</td> + <td>Especificación inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_los_Navegadores">Compatibilidad en los Navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("2.0")}}</td> + <td>9</td> + <td>15.0</td> + <td>5</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("2.0")}}</td> + <td>{{CompatNo}}</td> + <td>15.0</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("Range")}}</li> +</ul> diff --git a/files/es/web/api/range/index.html b/files/es/web/api/range/index.html new file mode 100644 index 0000000000..8a9cc686ea --- /dev/null +++ b/files/es/web/api/range/index.html @@ -0,0 +1,108 @@ +--- +title: range +slug: Web/API/Range +tags: + - DOM + - Todas_las_Categorías +translation_of: Web/API/Range +--- +<p>{{ APIRef("DOM") }}</p> + +<h3 id="Introducci.C3.B3n" name="Introducci.C3.B3n">Introducción</h3> + +<p>El objeto <code>Range</code> representa un fragmento de un documento que puede contener nodos y partes de nodos de texto en un documento dado.</p> + +<p>Un rango puede ser creado usando el método <code><a href="es/DOM/document.createRange">createRange</a></code> del objeto <code><a href="es/DOM/document">document</a></code>. Los objetos rango pueden ser recuperados usando el método <code><a href="es/DOM/Selection/getRangeAt">getRangeAt</a></code> del objeto <code><a href="es/DOM/selection">Selection</a></code>.</p> + +<h3 id="Propiedades" name="Propiedades">Propiedades</h3> + +<dl> + <dt><a href="es/DOM/range.collapsed">collapsed</a></dt> + <dd>Devuelve un valor booleano indicando si los puntos de inicio y fin están en la misma posición.</dd> + <dt><a href="es/DOM/range.commonAncestorContainer">commonAncestorContainer</a></dt> + <dd>Devuelve el nodo más profundo que contiene los nodos <strong>startContainer</strong> y <strong>endContainer</strong>.</dd> + <dt><a href="es/DOM/range.endContainer">endContainer</a></dt> + <dd>Devuelve el nodo dentro del cual termina el rango.</dd> + <dt><a href="es/DOM/range.endOffset">endOffset</a></dt> + <dd>Devuelve un número representando donde termina el <code>Range</code> en el <code>endContainer</code>.</dd> + <dt><a href="es/DOM/range.startContainer">startContainer</a></dt> + <dd>Devuelve el nodo dentro del cual comienza el rango.</dd> + <dt><a href="es/DOM/range.startOffset">startOffset</a></dt> + <dd>Devuelve un número representando donde empieza el <code>Range</code> en el <code>endContainer</code>.</dd> +</dl> + +<h3 id="M.C3.A9todos" name="M.C3.A9todos">Métodos</h3> + +<h4 id="M.C3.A9todos_de_ubicaci.C3.B3n" name="M.C3.A9todos_de_ubicaci.C3.B3n">Métodos de ubicación</h4> + +<p>Estos métodos definen el punto de inicio y fin de un rango.</p> + +<dl> + <dt><a href="es/DOM/range.setStart">setStart</a></dt> + <dd>Define la posición inicial de un rango.</dd> + <dt><a href="es/DOM/range.setEnd">setEnd</a></dt> + <dd>Define la posición final de un rango.</dd> + <dt><a href="es/DOM/range.setStartBefore">setStartBefore</a></dt> + <dd>Define la posición inicial de un rango relativa a otro nodo.</dd> + <dt><a href="es/DOM/range.setStartAfter">setStartAfter</a></dt> + <dd>Define la posición inicial de un rango relativa a otro nodo.</dd> + <dt><a href="es/DOM/range.setEndBefore">setEndBefore</a></dt> + <dd>Define la posición final de un rango relativa a otro nodo.</dd> + <dt><a href="es/DOM/range.setEndAfter">setEndAfter</a></dt> + <dd>Define la posición final de un rango relativa a otro nodo.</dd> + <dt><a href="es/DOM/range.selectNode">selectNode</a></dt> + <dd>Define el rango a contener el nodo y sus contenidos.</dd> + <dt><a href="es/DOM/range.selectNodeContents">selectNodeContents</a></dt> + <dd>Define el rango a contener los contenidos de un nodo.</dd> + <dt><a href="es/DOM/range.collapse">collapse</a></dt> + <dd>Pliega el Rango a uno de sus puntos límite.</dd> +</dl> + +<h4 id="Editando_m.C3.A9todos" name="Editando_m.C3.A9todos">Editando métodos</h4> + +<p>Estos métodos recuperan nodos de un rango y modifican los contenidos de un rango.</p> + +<dl> + <dt><a href="es/DOM/range.cloneContents">cloneContents</a></dt> + <dd>Devuelve un fragmento de documento copiando los nodos de un rango.</dd> + <dt><a href="es/DOM/range.deleteContents">deleteContents</a></dt> + <dd>Elimina del documento los contenidos de un rango.</dd> + <dt><a href="es/DOM/range.extractContents">extractContents</a></dt> + <dd>Mueve los contenidos de un rango del árbol de documento a un fragmento del documento.</dd> + <dt><a href="es/DOM/range.insertNode">insertNode</a></dt> + <dd>Inserta un nodo al comienzo de un rango.</dd> + <dt><a href="es/DOM/range.surroundContents">surroundContents</a></dt> + <dd>Mueve el contenido de un rango a un nodo nuevo.</dd> +</dl> + +<h4 id="Otros_m.C3.A9todos" name="Otros_m.C3.A9todos">Otros métodos</h4> + +<dl> + <dt><a href="es/DOM/range.compareBoundaryPoints">compareBoundaryPoints</a></dt> + <dd>Compara los puntos límite de dos rangos.</dd> + <dt><a href="es/DOM/range.cloneRange">cloneRange</a></dt> + <dd>Devuelve un objeto rango con puntos límites idénticos al rango clonado.</dd> + <dt><a href="es/DOM/range.detach">detach</a></dt> + <dd>Libera el Rango desde el uso para mejorar el rendimiento.</dd> + <dt><a href="es/DOM/range.toString">toString</a></dt> + <dd>Devuelve el texto del rango.</dd> +</dl> + +<h4 id="M.C3.A9todos_de_Gecko" name="M.C3.A9todos_de_Gecko">Métodos de Gecko</h4> + +<p>Esta sección describe métodos de <code>Range</code> que son particulares a Mozilla y no son parte de las especificaciones DOM W3C.</p> + +<dl> + <dt><a href="es/DOM/range.compareNode">compareNode</a> {{obsolete_inline}}</dt> + <dd>Devuelve una constante representando si el nodo está antes, después, dentro o alrededor del rango.</dd> + <dt><a href="es/DOM/range.comparePoint">comparePoint</a></dt> + <dd>Devuelve -1, 0, or 1 indicando si el punto ocurre antes, dentro o después del rango.</dd> + <dt><a href="es/DOM/range.createContextualFragment">createContextualFragment</a></dt> + <dd>Devuelve un fragmenteo de documento creado de un texto de código.</dd> + <dt><a href="es/DOM/range.intersectsNode">intersectsNode</a> {{obsolete_inline}}</dt> + <dd>Devuelve un valor boleano verdadero si el nodo dado intersecta el rango.</dd> + <dt><a href="es/DOM/range.isPointInRange">isPointInRange</a></dt> + <dd>Devuelve un valor boleano verdadero indicando si el punto dado está en el rango.</dd> +</dl> + +<p>{{ languages( { "en": "en/DOM/range", "fr": "fr/DOM/range", "ja": "ja/DOM/range", "pl": "pl/DOM/range" } ) }}</p> diff --git a/files/es/web/api/range/intersectsnode/index.html b/files/es/web/api/range/intersectsnode/index.html new file mode 100644 index 0000000000..5ffd11b79e --- /dev/null +++ b/files/es/web/api/range/intersectsnode/index.html @@ -0,0 +1,48 @@ +--- +title: range.intersectsNode +slug: Web/API/Range/intersectsNode +tags: + - Referencia_DOM_de_Gecko +translation_of: Web/API/Range/intersectsNode +--- +<p>{{ ApiRef() }}</p> +<h3 id="Summary" name="Summary">Summary</h3> +<p>{{ Obsolete_header() }} Returns a boolean indicating whether the given node intersects the range.</p> +<h3 id="Syntax" name="Syntax">Syntax</h3> +<pre class="eval">bool = range.intersectsNode( referenceNode ) +</pre> +<h3 id="Parameters" name="Parameters">Parameters</h3> +<dl> + <dt> + referenceNode </dt> + <dd> + The <code>Node</code> to compare with the <code>Range</code>.</dd> +</dl> +<h3 id="Example" name="Example">Example</h3> +<pre class="eval">range = document.createRange(); +range.selectNode(document.getElementsByTagName("div").item(0)); +bool = range.intersectsNode(document.getElementsByTagName("p").item(0)); +</pre> +<h3 id="Notes" name="Notes">Notes</h3> +<p>This method is obsolete; you should instead use the W3C DOM Range methods (see <code><a href="es/DOM/range.compareBoundaryPoints">compareBoundaryPoints()</a></code>).</p> +<div class="warning"> + <b>Warning:</b> This method <a href="es/Gecko_1.9_Changes_affecting_websites">has been removed</a> from <a href="es/Gecko">Gecko</a> 1.9 and will not exist in future versions of Firefox; you should switch to <code>compareBoundaryPoints()</code> as soon as possible.</div> +<p>The following function can be used as replacement:</p> +<pre class="eval">function rangeIntersectsNode(range, node) { + var nodeRange = node.ownerDocument.createRange(); + try { + nodeRange.selectNode(node); + } + catch (e) { + nodeRange.selectNodeContents(node); + } + + return range.compareBoundaryPoints(Range.END_TO_START, nodeRange) == -1 && + range.compareBoundaryPoints(Range.START_TO_END, nodeRange) == 1; +} +</pre> +<h3 id="Specification" name="Specification">Specification</h3> +<p>This method is not part of a specification.</p> +<div class="noinclude"> + </div> +<p>{{ languages( { "en": "en/DOM/range.intersectsNode", "pl": "pl/DOM/range.intersectsNode" } ) }}</p> diff --git a/files/es/web/api/range/setstart/index.html b/files/es/web/api/range/setstart/index.html new file mode 100644 index 0000000000..f4a991615c --- /dev/null +++ b/files/es/web/api/range/setstart/index.html @@ -0,0 +1,120 @@ +--- +title: Range.setStart() +slug: Web/API/Range/setStart +translation_of: Web/API/Range/setStart +--- +<p>{{ApiRef("DOM")}}</p> + +<p>El método <strong><code>Range.setStart()</code></strong> establece la posición de inicio de un {{ domxref("Range") }}.</p> + +<p>Si <code>startNode</code> es un {{ domxref("Node") }} de tipo <code>Text</code>, <code>Comment</code>, o <code>CDATASection</code>, entonces <code>startOffset</code> es el número de caracteres de partida de <code>startNode</code>. Para otros tiposde nodos, <code>startOffset</code> es el número de nodos hijos entre el inicio de los <code>startNode</code>.</p> + +<p>Setting the start point below (lower in the document) the end point will result in a collapsed range with the start and end points both set to the specified start position.</p> + +<p>Definiendo el punto de partida abajo (más abajo en el documento) el punto final resultará en un rango colapsado con el punto tanto de inicio como de entrada establecidos a la posición de partida especificada.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><em>range</em>.setStart(<em>startNode</em>, <em>startOffset</em>); +</pre> + +<h3 id="Parameters" name="Parameters">Parámetros</h3> + +<dl> + <dt><em>startNode</em></dt> + <dd>El {{ domxref("Node") }} donde {{ domxref("Range") }} debe empezar.</dd> + <dt><em>startOffset</em><code> </code></dt> + <dd>Un entero mayor o igual a cero representando el offset o desplazamiento de caracteres para el inicio del {{ domxref("Range") }} desde el comienzo de <code>startNode</code>.</dd> +</dl> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre class="brush: js">var range = document.createRange(); +var startNode = document.getElementsByTagName("p").item(2); +var startOffset = 0; +range.setStart(startNode,startOffset); +</pre> + +<h2 id="Specification" name="Specification">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estatus</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('DOM WHATWG', '#dom-range-setstart', 'Range.setStart()')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Sin cambio.</td> + </tr> + <tr> + <td>{{SpecName('DOM2 Traversal_Range', 'ranges.html#Level2-Range-method-setStart', 'Range.setStart()')}}</td> + <td>{{Spec2('DOM2 Traversal_Range')}}</td> + <td>Especificación inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_del_navegador">Compatibilidad del navegador</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("1.0")}}</td> + <td>9.0</td> + <td>9.0</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>Edge</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}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("1.0")}}</td> + <td>9.0</td> + <td>9.0</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="sect1"> </h2> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/DOM/DOM_Reference" title="/en-US/docs/DOM/DOM_Reference">The DOM interfaces index</a></li> +</ul> diff --git a/files/es/web/api/request/headers/index.html b/files/es/web/api/request/headers/index.html new file mode 100644 index 0000000000..e36f914087 --- /dev/null +++ b/files/es/web/api/request/headers/index.html @@ -0,0 +1,68 @@ +--- +title: Request.headers +slug: Web/API/Request/headers +translation_of: Web/API/Request/headers +--- +<div>{{APIRef("Fetch")}}</div> + +<p>La propiedad de solo lectura <strong>headers</strong> de la interface {{domxref("Request")}} es un objeto de tipo {{domxref("Headers")}}, asociado a la petición.</p> + +<h2 id="Sintax">Sintax</h2> + +<pre class="syntaxbox">var <var>myHeaders</var> = <var>request</var>.headers;</pre> + +<h3 id="Valor">Valor</h3> + +<p>Un objeto de tipo {{domxref("Headers")}}.</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>En el siguiente fragmento de código, crearemos una nueva petición utilizando el constructor del {{domxref("Request.Request()")}} (para un archivo de imagen ubicado en el mismo directorio del script), guardamos el encabezado de la petición en una variable:</p> + +<pre class="brush: js">var myRequest = new Request('flowers.jpg'); +var myHeaders = myRequest.headers; // Headers {}</pre> + +<p>Para agregar encabezados al objeto {{domxref("Headers")}} usamos {{domxref("Headers.append")}}; creamos una nueva petición usando el parametro init del constructor y asignamos los encabezados como una opción del parametro init:</p> + +<pre class="brush: js">var myHeaders = new Headers(); +myHeaders.append('Content-Type', 'image/jpeg'); + +var myInit = { method: 'GET', + headers: myHeaders, + mode: 'cors', + cache: 'default' }; + +var myRequest = new Request('flowers.jpg',myInit); + +myContentType = myRequest.headers.get('Content-Type'); // returns 'image/jpeg'</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('Fetch','#dom-request-headers','headers')}}</td> + <td>{{Spec2('Fetch')}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + + + +<p>{{Compat("api.Request.headers")}}</p> + +<h2 id="Ver_también">Ver también</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> diff --git a/files/es/web/api/request/index.html b/files/es/web/api/request/index.html new file mode 100644 index 0000000000..770647619e --- /dev/null +++ b/files/es/web/api/request/index.html @@ -0,0 +1,170 @@ +--- +title: Request +slug: Web/API/Request +tags: + - API + - Experimental + - Fetch + - Fetch API + - Interface + - NeedsTranslation + - Reference + - TopicStub + - request +translation_of: Web/API/Request +--- +<div>{{APIRef("Fetch")}}</div> + +<p>La interfaz <strong><code>Request</code></strong> de la <a href="/en-US/docs/Web/API/Fetch_API">API Fetch</a> representa una solicitud de respuesta.</p> + +<p>Puedes crear un nuevo objeto <code>Request</code> usando el constructor {{domxref("Request.Request()")}}, pero es preferible encontrar un objeto <code>Request</code> que sea devuelto como el resultado de otra operacion API, como un operador de servicio {{domxref("FetchEvent.request")}}.</p> + +<h2 id="Constructor">Constructor</h2> + +<dl> + <dt>{{domxref("Request.Request()")}}</dt> + <dd>Crea un nuevo objeto <code>Request</code>.</dd> +</dl> + +<h2 id="Propiedades">Propiedades</h2> + +<dl> + <dt>{{domxref("Request.method")}} {{readonlyInline}}</dt> + <dd>Contiene el metodo de solicitud (<code>GET</code>, <code>POST</code>, etc.)</dd> + <dt>{{domxref("Request.url")}} {{readonlyInline}}</dt> + <dd>Contiene la URL de la solicitud.</dd> + <dt>{{domxref("Request.headers")}} {{readonlyInline}}</dt> + <dd>Contiene el objeto asociado de la solicitud {{domxref("Headers")}}</dd> + <dt>{{domxref("Request.context")}} {{readonlyInline}} {{deprecated_inline()}}</dt> + <dd>Contiene el contexto de la solicitud (p.ej., <code>audio</code>, <code>image</code>, <code>iframe</code>, etc.)</dd> + <dt>{{domxref("Request.referrer")}} {{readonlyInline}}</dt> + <dd>Contiene la referencia de la soliditud (p.ej., <code>client</code>).</dd> + <dt>{{domxref("Request.referrerPolicy")}} {{readonlyInline}}</dt> + <dd>Contiene la política de referencia de la solicitud (p.ej., <code>no-referrer</code>).</dd> + <dt>{{domxref("Request.mode")}} {{readonlyInline}}</dt> + <dd>Contiene el modo de la solicitud. (p.ej., <code>cors</code>, <code>no-cors</code>, <code>same-origin</code>, <code>navigate</code>.)</dd> + <dt>{{domxref("Request.credentials")}} {{readonlyInline}}</dt> + <dd>Contiene las credenciales de la solicitud (p.ej., <code>omit</code>, <code>same-origin</code>).</dd> + <dt>{{domxref("Request.redirect")}} {{readonlyinline}}</dt> + <dd>Contiene el modo de cómo son manipuladas las redirecciones. Puede ser <code>follow</code>, <code>error</code>, o <code>manual</code>.</dd> + <dt>{{domxref("Request.integrity")}} {{readonlyInline}}</dt> + <dd>Contiene el valor del subrecurso de integridad (<a href="/en-US/docs/Web/Security/Subresource_Integrity">subresource integrity</a>) de la solicitud (p.ej., <code>sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=</code>).</dd> + <dt>{{domxref("Request.cache")}} {{readonlyInline}}</dt> + <dd>Contiene el modo de caché de la solicitud (p.ej., <code>default</code>, <code>reload</code>, <code>no-cache</code>).</dd> +</dl> + +<p><code>Request</code> implementa {{domxref("Body")}}, por lo que también tiene las siguientes propiedades disponibles:</p> + +<dl> + <dt>{{domxref("Body.body")}} {{readonlyInline}}</dt> + <dd>Un simple getter usado para exponer un contenido del cuerpo {{domxref("ReadableStream")}}</dd> + <dt>{{domxref("Body.bodyUsed")}} {{readonlyInline}}</dt> + <dd>Almacena un {{domxref("Boolean")}} que declara si ya se ha usado el cuerpo en una respuesta.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<dl> + <dt>{{domxref("Request.clone()")}}</dt> + <dd>Crea una copia del objeto actual <code>Request</code>.</dd> +</dl> + +<p><code>Request</code> implementa {{domxref("Body")}}, por lo que también tiene los siguientes métodos disponibles:</p> + +<dl> + <dt>{{domxref("Body.arrayBuffer()")}}</dt> + <dd>Devuelve una promesa que se resuelve con una representación {{domxref("ArrayBuffer")}} del cuerpo de la solicitud.</dd> + <dt>{{domxref("Body.blob()")}}</dt> + <dd>Devuelve una promesa que se resuelve con una representación {{domxref("Blob")}} del cuerpo de la solicitud.</dd> + <dt>{{domxref("Body.formData()")}}</dt> + <dd>Devuelve una promesa que se resuelve con una representación {{domxref("FormData")}} del cuerpo de la solicitud.</dd> + <dt>{{domxref("Body.json()")}}</dt> + <dd>Devuelve una promesa que se resuelve con una representación {{domxref ("JSON")}} del cuerpo de la solicitud.</dd> + <dt>{{domxref("Body.text()")}}</dt> + <dd>Devuelve una promesa que se resuelve con una representación {{domxref("USVString")}} (text) del cuerpo de la solicitud.</dd> +</dl> + +<div class="note"> +<p><strong>Nota</strong>: Las funciones {{domxref("Body")}} solo pueden ser ejecutadas una vez; Las siguientes llamadas se resolverán con strings/ArrayBuffers vacíos.</p> +</div> + +<h2 id="Ejemplos">Ejemplos</h2> + +<p>En el siguiente fragmento de código, creamos una nueva solicitud utilizando el constructor <code>Request()</code> (para un archivo de imagen en el mismo directorio que el script), luego devolvemos algunos valores de propiedad de la solicitud:</p> + +<pre class="brush: js">const myRequest = new Request('http://localhost/flowers.jpg'); + +const myURL = myRequest.url; // http://localhost/flowers.jpg +const myMethod = myRequest.method; // GET +const myCred = myRequest.credentials; // omit +</pre> + +<p>Puede obtener esta solicitud pasando el objeto <code>Request</code> como parámetro a una llamada {{domxref("GlobalFetch.fetch()")}}, por ejemplo:</p> + +<pre class="brush: js">fetch(myRequest) + .then(response => response.blob()) + .then(blob => { + myImage.src = URL.createObjectURL(blob); + });</pre> + +<p>En el siguiente fragmento de código, creamos una nueva solicitud utilizando el constructor <code>Request()</code> con algunos datos iniciales y contenido del cuerpo para una solicitud de API que necesita una carga útil del cuerpo:</p> + +<pre class="brush: js">const myRequest = new Request('http://localhost/api', {method: 'POST', body: '{"foo":"bar"}'}); + +const myURL = myRequest.url; // http://localhost/api +const myMethod = myRequest.method; // POST +const myCred = myRequest.credentials; // omit +const bodyUsed = myRequest.bodyUsed; // true +</pre> + +<div class="note"> +<p><strong>Nota:</strong> El tipo de cuerpo solo puede ser {{domxref("Blob")}}, {{domxref("BufferSource")}}, {{domxref("FormData")}}, {{domxref("URLSearchParams")}}, {{domxref("USVString")}} o tipo {{domxref("ReadableStream")}}, así que para añadir un objeto JSON a la carga útil, necesitas convertir a string (stringify) dicho objeto.</p> +</div> + +<p>Puede obtener esta solicitud de API pasando el objeto <code>Request</code> como parámetro a una llamada {{domxref("GlobalFetch.fetch()")}}, por ejemplo, y obtener la respuesta:</p> + +<pre class="brush: js">fetch(myRequest) + .then(response => { + if (response.status === 200) { + return response.json(); + } else { + throw new Error('Something went wrong on api server!'); + } + }) + .then(response => { + console.debug(response); + // ... + }).catch(error => { + console.error(error); + });</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('Fetch','#request-class','Request')}}</td> + <td>{{Spec2('Fetch')}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2> + + + +<p>{{Compat("api.Request")}}</p> + +<h2 id="Ver_también">Ver también</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> diff --git a/files/es/web/api/response/index.html b/files/es/web/api/response/index.html new file mode 100644 index 0000000000..11e18a501c --- /dev/null +++ b/files/es/web/api/response/index.html @@ -0,0 +1,128 @@ +--- +title: Response +slug: Web/API/Response +tags: + - API + - Experimental + - Fetch + - Interface + - Referencia + - Respuesta +translation_of: Web/API/Response +--- +<div>{{APIRef("Fetch API")}}</div> + +<p>La interfaz <strong><code>Response</code></strong> de la <a href="/en-US/docs/Web/API/Fetch_API">Fetch API</a> representa la respuesta a una petición.</p> + +<p>Tú puedes crear un nuevo objeto <code>Response</code> usando el constructor{{domxref("Response.Response()")}}, pero es más probable encontrar un objeto Response siendo devuelto como resultado de la operación de otra API, por ejemplo un service worker {{domxref("Fetchevent.respondWith")}}, o un simple {{domxref("GlobalFetch.fetch()")}}.</p> + +<h2 id="Constructor">Constructor</h2> + +<dl> + <dt>{{domxref("Response.Response","Response()")}}</dt> + <dd>Crea un nuevo objeto <code>Response</code>.</dd> +</dl> + +<h2 id="Propiedades">Propiedades</h2> + +<dl> + <dt>{{domxref("Response.headers")}} {{readonlyinline}}</dt> + <dd>Contiene el objeto {{domxref("Headers")}} asociado con la respuesta.</dd> + <dt>{{domxref("Response.ok")}} {{readonlyinline}}</dt> + <dd>Contiene un estado indicando si la respuesta fue exitosa (estado en el rango 200-299) o no.</dd> + <dt>{{domxref("Response.redirected")}} {{ReadOnlyInline}}</dt> + <dd>Indica si la respuesta es o no el resultado de una redirección; eso es, su lista de URL tiene más de una entrada.</dd> + <dt>{{domxref("Response.status")}} {{readonlyinline}}</dt> + <dd>Contiene el código de estado de la respuesta (e.g., <code>200</code> si fue exitosa).</dd> + <dt>{{domxref("Response.statusText")}} {{readonlyinline}}</dt> + <dd>Contiene el mensaje de estado correspondiente al código de estado (e.g., <code>OK</code> para el Código <code>200</code>).</dd> + <dt>{{domxref("Response.type")}} {{readonlyinline}}</dt> + <dd>Contiene el tipo de respuesta (e.g., <code>basic</code>, <code>cors</code>).</dd> + <dt>{{domxref("Response.url")}} {{readonlyinline}}</dt> + <dd>Contiene la URL de respuesta.</dd> + <dt>{{domxref("Response.useFinalURL")}}</dt> + <dd>Contiene un valor booleano indicando si ésta es la URL final de respuesta.</dd> +</dl> + +<p><code>Response</code> implementa {{domxref("Body")}}, de modo que además contiene las propiedades que se detallan a continuación:</p> + +<dl> + <dt>{{domxref("Body.body")}} {{readonlyInline}}</dt> + <dd>Un simple método get que expone un {{domxref("ReadableStream")}} de los contenidos del body.</dd> + <dt>{{domxref("Body.bodyUsed")}} {{readonlyInline}}</dt> + <dd>Almacena un {{domxref("Boolean")}} en el cuál declara si el body ya fue enviado como respuesta anteriormente.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<dl> + <dt>{{domxref("Response.clone()")}}</dt> + <dd>Clona un Objeto Respuesta.</dd> + <dt>{{domxref("Response.error()")}}</dt> + <dd>Devuelve un nuevo objeto Respuesta asociado a un error de red.</dd> + <dt>{{domxref("Response.redirect()")}}</dt> + <dd>Crea una nueva respuesta con un URL distinto.</dd> + <dd><code>Response</code> iimplementa {{domxref("Body")}}, de modo que además contiene los métodos que se detallan a continuación:</dd> +</dl> + +<dl> + <dt>{{domxref("Body.arrayBuffer()")}}</dt> + <dd>Toma un flujo {{domxref("Response")}} y lo lee hasta completarlo. Devuelve una promesa que resuelve con un {{domxref("ArrayBuffer")}}.</dd> + <dt>{{domxref("Body.blob()")}}</dt> + <dd>Toma un flujo {{domxref("Response")}} y lo lee hasta completarlo. Devuelve una promesa que resuelve con un {{domxref("Blob")}}.</dd> + <dt>{{domxref("Body.formData()")}}</dt> + <dd>Toma un flujo {{domxref("Response")}} y lo lee hasta completarlo. Devuelve una promesa que resuelve con un objeto {{domxref("FormData")}}.</dd> + <dt>{{domxref("Body.json()")}}</dt> + <dd>Recibe un flujo {{domxref("Response")}} y lo lee hasta completarlo. Devuelve una promesa que resuelve como {{jsxref("JSON")}} el texto del Body enviado.</dd> + <dt>{{domxref("Body.text()")}}</dt> + <dd>Recibe un flujo {{domxref("Response")}} y lo lee hasta completarlo. Devuelve una promesa que resuelve con un {{domxref("USVString")}} (texto).</dd> +</dl> + +<h2 id="Examples">Examples</h2> + +<p>En nuestro <a href="https://github.com/mdn/fetch-examples/tree/gh-pages/basic-fetch">ejemplo básico de ferch</a> (<a href="http://mdn.github.io/fetch-examples/basic-fetch/">ejecutar el ejemplo</a>) usamos una llamada <code>fetch()</code> para descargar una imagen y mostrarla en una etiqueta {{htmlelement("img")}} . La llamda a <code>fetch()</code> call devuelve una promesa, la cual resuelve a un objeto<code>Response</code> asociado a la operación fetch.</p> + +<p>Observa como ya que lo que estamos solicitando es una imagen, necesitamos ejecutar {{domxref("Body.blob")}} ({{domxref("Response")}} implements body) para darle a la respuesta su tipo MIME correcto.</p> + +<pre class="brush: js notranslate">var myImage = document.querySelector('.my-image'); +fetch('flowers.jpg').then(function(response) { + return response.blob(); +}).then(function(blob) { + var objectURL = URL.createObjectURL(blob); + myImage.src = objectURL; +});</pre> + +<p>También puedes usar el constructor {{domxref("Response.Response()")}} para crear tus objetos <code>Response</code> personalizados:</p> + +<pre class="brush: js notranslate">var myResponse = new Response();</pre> + +<h2 id="Especificaciones">Especificaciones</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','#response-class','Response')}}</td> + <td>{{Spec2('Fetch')}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_entre_navegadores">Compatibilidad entre navegadores</h2> + + + +<p>{{Compat("api.Response")}}</p> + +<h2 id="Ver_también">Ver también</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> diff --git a/files/es/web/api/response/ok/index.html b/files/es/web/api/response/ok/index.html new file mode 100644 index 0000000000..1bff7fe5db --- /dev/null +++ b/files/es/web/api/response/ok/index.html @@ -0,0 +1,66 @@ +--- +title: Response.ok +slug: Web/API/Response/ok +translation_of: Web/API/Response/ok +--- +<div>{{APIRef("Fetch")}}<br> +La propiedad de solo lectura <code><strong>ok</strong></code> de la interfaz {{domxref("Response")}} contiene un Booleano que indica si la respuesta fue exitosa (estado en un rango de 200 a 299) o no.</div> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var <var>miOK</var> = <var>respuesta</var>.ok;</pre> + +<h3 id="Valor">Valor</h3> + +<p>Un {{domxref("Boolean")}}.</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>En nuestro <a href="https://github.com/mdn/fetch-examples/tree/master/fetch-response">ejemplo de Fetch Response</a> (véase <a href="http://mdn.github.io/fetch-examples/fetch-response/">Fetch Response en vivo</a>) creamos un nuevo {{domxref("Request")}} usando el constructor {{domxref("Request.Request","Request()")}}, pasando una ruta a un JPG. Luego traemos esta petición usando {{domxref("GlobalFetch.fetch","fetch()")}}, extraemos un blob de la respuesta usando {{domxref("Body.blob")}}, creamos un objeto URL usando {{domxref("URL.createObjectURL")}}, y mostrar esto en un {{htmlelement("img")}}.</p> + +<div class="note"> +<p><strong>Nota:</strong> en la parte superior del bloque de <code>fetch()</code> imprimimos el valor de <code>ok</code> en la consola.</p> +</div> + +<pre class="brush: js">var imagen = document.querySelector('img'); + +var peticion = new Request('flowers.jpg'); + +fetch(peticion).then(function(respuesta) { + console.log(respuesta.ok); //retorna true si la respuesta fue exitosa + respuesta.blob().then(function(miBlob) { + var objectoURL = URL.createObjectURL(miBlob); + imagen.src = objectURL; + }); +});</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{Spec2('Fetch')}}</td> + <td>{{Spec2('Fetch')}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2> + + + +<p>{{Compat("api.Response.ok")}}</p> + +<h2 id="Ver_también">Ver también</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> diff --git a/files/es/web/api/response/response/index.html b/files/es/web/api/response/response/index.html new file mode 100644 index 0000000000..f967d677f2 --- /dev/null +++ b/files/es/web/api/response/response/index.html @@ -0,0 +1,75 @@ +--- +title: Response() +slug: Web/API/Response/Response +translation_of: Web/API/Response/Response +--- +<div>{{APIRef("Fetch")}}</div> + +<p>El constructor <code><strong>Response()</strong></code> crea un nuevo objeto {{domxref("Response")}}</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var <var>miRespuesta</var> = new Response(<var>cuerpo</var>,<em>opciones</em>);</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><em>cuerpo</em> {{optional_inline}}</dt> + <dd>Un objeto que define el cuerpo de la respuesta. Puede ser <code>null</code>, o uno de los siguientes elementos: + <ul> + <li>{{domxref("Blob")}}</li> + <li>{{domxref("BufferSource")}}</li> + <li>{{domxref("FormData")}}</li> + <li>{{domxref("ReadableStream")}}</li> + <li>{{domxref("URLSearchParams")}}</li> + <li>{{domxref("USVString")}}</li> + </ul> + </dd> + <dt><em>opciones</em> {{optional_inline}}</dt> + <dd>Un objeto que contiene las opciones de personalización para la respuesta HTTP. Las opciones posibles son: + <ul> + <li><code>status</code>: El código de estado HTTP, p.e.: <code>200</code>.</li> + <li><code>statusText</code>: El mensaje de estado asociado con el código de estado HTTP, p.e.: <code>OK</code>.</li> + <li><code>headers</code>: Cualquier cabecera que quieras añadir a la respuesta. Puede ser un objeto {{domxref("Headers")}} o un objeto literal de {{domxref("ByteString")}} pares claves/valor (ver <a href="/en-US/docs/Web/HTTP/Headers">Cabeceras HTTP</a> para más información).</li> + </ul> + </dd> +</dl> + +<h2 id="Ejemplos">Ejemplos</h2> + +<p>En nuestro <a href="https://github.com/mdn/fetch-examples/tree/master/fetch-response">ejemplo Fetch Response</a> (ver <a href="http://mdn.github.io/fetch-examples/fetch-response/">Fetch Response live</a>) creamos un nuevo objeto <code>Response</code> usando el constructor, pasándole un nuevo objeto {{domxref("Blob")}} como cuerpo, y un objeto con <code>status</code> y<code>statusText</code> como opciones:</p> + +<pre class="brush: js">var miBlob = new Blob(); +var opciones = { "status" : 200 , "statusText" : "Flipante!" }; +var miRespuesta = new Response(miBlob,opciones);</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentarios</th> + </tr> + <tr> + <td>{{SpecName('Fetch','#dom-response','Response()')}}</td> + <td>{{Spec2('Fetch')}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_navegadores">Compatibilidad en navegadores</h2> + +<div class="hidden">La tabla de compatibilidad de esta página está generada a partir de datos estructurados. Si deseas contribuir a los datos, por favor échale un vistazo a <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> y envíanos un pull request.</div> + +<p>{{Compat("api.Response.Response")}}</p> + +<h2 id="Relacionado">Relacionado</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> diff --git a/files/es/web/api/response/status/index.html b/files/es/web/api/response/status/index.html new file mode 100644 index 0000000000..eecaf02967 --- /dev/null +++ b/files/es/web/api/response/status/index.html @@ -0,0 +1,73 @@ +--- +title: Response.status +slug: Web/API/Response/status +tags: + - API + - Experimental + - Fetch + - Property + - Reference + - Response + - status +translation_of: Web/API/Response/status +--- +<div>{{APIRef("Fetch")}}</div> + +<p>La propiedad de solo lectura <strong><code>status</code></strong> de la interfaz {{domxref("Response")}} contiene el código de estado de la respuesta (ejm., <code>200</code> para un éxito).</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var <var>myStatus</var> = <var>response</var>.status;</pre> + +<h3 id="Valor">Valor</h3> + +<p>Un número (para ser preciso, uno corto sin signo).</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>En nuestro <a href="https://github.com/mdn/fetch-examples/tree/master/fetch-response">ejemplo Fetch Response</a> (ver <a href="http://mdn.github.io/fetch-examples/fetch-response/">Fetch Response en vivo</a>) nosotros creamos un nuevo objeto {{domxref("Request")}} usando el constructor {{domxref("Request.Request","Request()")}}, pasándole una ruta JPG. Luego buscamos esta solicitud usando {{domxref("GlobalFetch.fetch","fetch()")}}, extraemos un blob de la respuesta usando {{domxref("Body.blob")}}, creamos un objeto URL fuera de ella usando {{domxref("URL.createObjectURL")}}, y mostramos esto en un {{htmlelement("img")}}.</p> + +<p>Tenga en cuenta que en la parte superior del bloque <code>fetch()</code> registramos el valor de la respuesta <code>status</code> en la consola.</p> + +<pre class="brush: js">var myImage = document.querySelector('img'); + +var myRequest = new Request('flowers.jpg'); + +fetch(myRequest).then(function(response) { + console.log(response.status); // returns 200 + response.blob().then(function(myBlob) { + var objectURL = URL.createObjectURL(myBlob); + myImage.src = objectURL; + }); +});</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estatus</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('Fetch','#dom-response-status','status')}}</td> + <td>{{Spec2('Fetch')}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_del_navegador">Compatibilidad del navegador</h2> + +<div class="hidden">La tabla de compatibilidad en esta página se genera a partir de datos estructurados. Si desea contribuir a los datos, consulte <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> y envíenos una solicitud de extracción.</div> + +<p>{{Compat("api.Response.status")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/ServiceWorker_API">API de Servicio Worker</a></li> + <li><a href="/en-US/docs/Web/HTTP/Access_control_CORS">Control de acceso HTTP (CORS)</a></li> + <li><a href="/en-US/docs/Web/HTTP">HTTP</a></li> +</ul> diff --git a/files/es/web/api/rtcpeerconnection/cantrickleicecandidates/index.html b/files/es/web/api/rtcpeerconnection/cantrickleicecandidates/index.html new file mode 100644 index 0000000000..d455433b6c --- /dev/null +++ b/files/es/web/api/rtcpeerconnection/cantrickleicecandidates/index.html @@ -0,0 +1,87 @@ +--- +title: RTCPeerConnection.canTrickleIceCandidates +slug: Web/API/RTCPeerConnection/canTrickleIceCandidates +translation_of: Web/API/RTCPeerConnection/canTrickleIceCandidates +--- +<div>{{APIRef("WebRTC")}}</div> + +<p><span class="seoSummary">La propiedad <strong>{{domxref("RTCPeerConnection")}}</strong> es de solo lectura <code><strong>canTrickleIceCandidates</strong></code> , </span>devuelve un <span class="seoSummary"> {{jsxref("Boolean")}} que indica si el par remoto puede aceptar o no <a href="https://tools.ietf.org/html/draft-ietf-mmusic-trickle-ice">candidatos ICE</a>.</span></p> + +<p><strong>ICE trickling</strong> is the process of continuing to send candidates after the initial offer or answer has already been sent to the other peer.</p> + +<p>This property is only set after having called {{domxref("RTCPeerConnection.setRemoteDescription()")}}. Ideally, your signaling protocol provides a way to detect trickling support, so that you don't need to rely on this property. A WebRTC browser will always support trickle ICE. If trickling isn't supported, or you aren't able to tell, you can check for a falsy value for this property and then wait until the value of {{domxref("RTCPeerConnection.iceGatheringState", "iceGatheringState")}} changes to <code>"completed"</code> before creating and sending the initial offer. That way, the offer contains all of the candidates.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox notranslate"> var <em>canTrickle</em> = <em>RTCPeerConnection</em>.canTrickleIceCandidates;</pre> + +<h3 id="Value">Value</h3> + +<p>A {{jsxref("Boolean")}} that is <code>true</code> if the remote peer can accept trickled ICE candidates and <code>false</code> if it cannot. If no remote peer has been established, this value is <code>null</code>.</p> + +<div class="note"> +<p><strong>Note:</strong> This property's value is determined once the local peer has called {{domxref("RTCPeerConnection.setRemoteDescription()")}}; the provided description is used by the ICE agent to determine whether or not the remote peer supports trickled ICE candidates.</p> +</div> + +<h2 id="Example">Example</h2> + +<pre class="brush: js notranslate">var pc = new RTCPeerConnection(); +// The following code might be used to handle an offer from a peer when +// it isn't known whether it supports trickle ICE. +pc.setRemoteDescription(remoteOffer) + .then(_ => pc.createAnswer()) + .then(answer => pc.setLocalDescription(answer)) + .then(_ => + if (pc.canTrickleIceCandidates) { + return pc.localDescription; + } + return new Promise(r => { + pc.addEventListener('icegatheringstatechange', e => { + if (e.target.iceGatheringState === 'complete') { + r(pc.localDescription); + } + }); + }); + }) + .then(answer => sendAnswerToPeer(answer)) // signaling message + .catch(e => handleError(e)); + +pc.addEventListener('icecandidate', e => { + if (pc.canTrickleIceCandidates) { + sendCandidateToPeer(e.candidate); // signaling message + } +}); +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('WebRTC 1.0', '#dom-rtcpeerconnection-cantrickleicecandidates', 'RTCPeerConnection.canTrickleIceCandidates') }}</td> + <td>{{ Spec2('WebRTC 1.0') }}</td> + <td>Initial specification.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("api.RTCPeerConnection.canTrickleIceCandidates")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/Guide/API/WebRTC">WebRTC</a></li> + <li>{{domxref("RTCPeerConnection.addIceCandidate()")}}</li> + <li><a href="/en-US/docs/Web/API/WebRTC_API/Session_lifetime">Lifetime of a WebRTC session</a></li> +</ul> diff --git a/files/es/web/api/rtcpeerconnection/index.html b/files/es/web/api/rtcpeerconnection/index.html new file mode 100644 index 0000000000..8a902d3ab5 --- /dev/null +++ b/files/es/web/api/rtcpeerconnection/index.html @@ -0,0 +1,444 @@ +--- +title: RTCPeerConnection +slug: Web/API/RTCPeerConnection +translation_of: Web/API/RTCPeerConnection +--- +<p>{{APIRef('WebRTC')}}{{draft}}</p> + +<p><span class="seoSummary">La interfaz <strong><code>RTCPeerConnection</code></strong> representa una conexión WebRTC entre un computador local y un par remoto (otro computador). Esta interfaz provee métodos para: conectar un equipo remoto (remote peer), mantener y monitorear esa coneexión y cerrar la conexión una vez que no se necesite más.</span></p> + +<div class="note"> +<p><code>RTCPeerConnection</code> y {{domxref("RTCSessionDescription")}} aún están prefijados en algunos navegadores. Se <strong>recomienda encarecidamente </strong>usar una librería de ajuste (shim) como la excelente y ampliamente soportada <a href="https://github.com/webrtc/adapter/">Adapter.js</a>, para asegurar la compatibilidad más amplia posible de su sitio o aplicación web. <span id="result_box" lang="es"><span>Vale la pena señalar que </span></span><a href="https://github.com/webrtc/adapter/">Adapter.js</a><span lang="es"><span> va más allá del manejo de prefijos, esta librería implementa ajustes (shims) para asegurar la compatibilidad entre las distintas implementaciones de WebRTC de los distintos navegadores.</span></span></p> +</div> + +<p>{{InheritanceDiagram}}</p> + +<p>{{InterfaceOverview("WebRTC")}}</p> + +<h3 id="Método_obsoleto">Método obsoleto</h3> + +<p>El siguiente método fue declarado obsoleto ya hace un tiempo, admás, nunca fue implementado en los navegadores más importantes.</p> + +<dl> + <dt>{{domxref("RTCPeerConnection.createDTMFSender()")}} {{obsolete_inline}}</dt> + <dd>Crea un nuevo {{domxref("RTCDTMFSender")}}, que se asocia a un {{domxref("MediaStreamTrack")}} específico, that will be able to send {{Glossary("DTMF")}} phone signaling over the connection.</dd> +</dl> + +<h2 id="Constantes">Constantes</h2> + +<h3 id="RTCBundlePolicy_enum">RTCBundlePolicy enum</h3> + +<p>The <code>RTCBundlePolicy</code> enum defines string constants which are used to request a specific policy for gathering ICE candidates if the remote peer isn't compatible with the <a href="https://webrtcstandards.info/sdp-bundle/">SDP BUNDLE standard</a> for bundling multiple media streams on a single transport link.</p> + +<div class="note"> +<p>In technical terms, a BUNDLE lets all media flow between two peers flow across a single <strong>5-tuple</strong>; that is, from the same IP and port on one peer to the same IP and port on the other peer, using the same transport protocol.</p> +</div> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>"balanced"</code></td> + <td>On BUNDLE-aware connections, the ICE agent should gather candidates for all of the media types in use (audio, video, and data). Otherwise, the ICE agent should only negotiate one audio and video track on separate transports.</td> + </tr> + <tr> + <td><code>"max-compat"</code></td> + <td>The ICE agent should gather candidates for each track, using separate transports to negotiate all media tracks for connections which aren't BUNDLE-compatible.</td> + </tr> + <tr> + <td><code>"max-bundle"</code></td> + <td>The ICE agent should gather candidates for just one track. If the connection isn't BUNDLE-compatible, then the ICE agent should negotiate just one media track.</td> + </tr> + </tbody> +</table> + +<h3 id="RTCIceConnectionState_enum">RTCIceConnectionState enum</h3> + +<p>The <code>RTCIceConnectionState</code> enum defines the string constants used to describe the current state of the ICE agent and its connection to the ICE server (that is, the {{Glossary("STUN")}} or {{Glossary("TURN")}} server).</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>"new"</code></td> + <td>The ICE agent is gathering addresses or is waiting to be given remote candidates through calls to {{domxref("RTCPeerConnection.addIceCandidate()")}} (or both).</td> + </tr> + <tr> + <td><code>"checking"</code></td> + <td>The ICE agent has been given one or more remote candidates and is checking pairs of local and remote candidates against one another to try to find a compatible match, but has not yet found a pair which will allow the peer connection to be made. It's possible that gathering of candidates is also still underway.</td> + </tr> + <tr> + <td><code>"connected"</code></td> + <td>A usable pairing of local and remote candidates has been found for all components of the connection, and the connection has been established. It's possible that gathering is still underway, and it's also possible that the ICE agent is still checking candidates against one another looking for a better connection to use.</td> + </tr> + <tr> + <td><code>"completed"</code></td> + <td>The ICE agent has finished gathering candidates, has checked all pairs against one another, and has found a connection for all components.</td> + </tr> + <tr> + <td><code>"failed"</code></td> + <td>The ICE candidate has checked all candidates pairs against one another and has failed to find compatible matches for all components of the connection. It is, however, possible that the ICE agent did find compatible connections for some components.</td> + </tr> + <tr> + <td><code>"disconnected"</code></td> + <td>Checks to ensure that components are still connected failed for at least one component of the {{domxref("RTCPeerConnection")}}. This is a less stringent test than <code>"failed"</code> and may trigger intermittently and resolve just as spontaneously on less reliable networks, or during temporary disconnections. When the problem resolves, the connection may return to the <code>"connected"</code> state.</td> + </tr> + <tr> + <td><code>"closed"</code></td> + <td>The ICE agent for this {{domxref("RTCPeerConnection")}} has shut down and is no longer handling requests.</td> + </tr> + </tbody> +</table> + +<h3 id="RTCIceGatheringState_enum">RTCIceGatheringState enum</h3> + +<p>The <code>RTCIceGatheringState</code> enum defines string constants which reflect the current status of ICE gathering, as returned using the {{domxref("RTCPeerConnection.iceGatheringState")}} property. You can detect when this value changes by watching for an event of type {{event("icegatheringstatechange")}}.</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>"new"</code></td> + <td>The peer connection was just created and hasn't done any networking yet.</td> + </tr> + <tr> + <td><code>"gathering"</code></td> + <td>The ICE agent is in the process of gathering candidates for the connection.</td> + </tr> + <tr> + <td><code>"complete"</code></td> + <td>The ICE agent has finished gathering candidates. If something happens that requires collecting new candidates, such as a new interface being added or the addition of a new ICE server, the state will revert to "gathering" to gather those candidates.</td> + </tr> + </tbody> +</table> + +<h3 id="RTCIceTransportPolicy_enum">RTCIceTransportPolicy enum</h3> + +<p>The <code>RTCIceTransportPolicy</code> enum defines string constants which can be used to limit the transport policies of the ICE candidates to be considered during the connection process.</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>"all"</code></td> + <td>All ICE candidates will be considered.</td> + </tr> + <tr> + <td><code>"public" </code>{{obsolete_inline}}</td> + <td>Only ICE candidates with public IP addresses will be considered. <em>Removed from the specification's May 13, 2016 working draft.</em></td> + </tr> + <tr> + <td><code>"relay"</code></td> + <td>Only ICE candidates whose IP addresses are being relayed, such as those being passed through a TURN server, will be considered.</td> + </tr> + </tbody> +</table> + +<h3 id="RTCPeerConnectionState_enum">RTCPeerConnectionState enum</h3> + +<p>The <code>RTCPeerConnectionState</code> enum defines string constants which describe states in which the <code>RTCPeerConnection</code> may be. These values are returned by the {{domxref("RTCPeerConnection.connectionState", "connectionState")}} property. This state essentially represents the aggregate state of all ICE transports (which are of type {{domxref("RTCIceTransport")}} or {{domxref("RTCDtlsTransport")}}) being used by the connection.</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>"new"</code></td> + <td>At least one of the connection's ICE transports ({{domxref("RTCIceTransport")}}s or {{domxref("RTCDtlsTransport")}}s) are in the <code>"new"</code> state, and none of them are in one of the following states: <code>"connecting"</code>, <code>"checking"</code>, <code>"failed"</code>, or <code>"disconnected"</code>, <em>or</em> all of the connection's transports are in the <code>"closed"</code> state.</td> + </tr> + <tr> + <td><code>"connecting"</code></td> + <td>One or more of the ICE transports are currently in the process of establishing a connection; that is, their <code>RTCIceConnectionState</code> is either <code>"checking"</code> or <code>"connected"</code>, and no transports are in the <code>"failed"</code> state. <strong><<< Make this a link once I know where that will be documented</strong></td> + </tr> + <tr> + <td><code>"connected"</code></td> + <td>Every ICE transport used by the connection is either in use (state <code>"connected"</code> or <code>"completed"</code>) or is closed (state <code>"closed"</code>); in addition, at least one transport is either <code>"connected"</code> or <code>"completed"</code>.</td> + </tr> + <tr> + <td><code>"disconnected"</code></td> + <td>At least one of the ICE transports for the connection is in the <code>"disconnected"</code> state and none of the other transports are in the state <code>"failed"</code>, <code>"connecting"</code>, or <code>"checking"</code>.</td> + </tr> + <tr> + <td><code>"failed"</code></td> + <td>One or more of the ICE transports on the connection is in the <code>"failed"</code> state.</td> + </tr> + <tr> + <td><code>"closed"</code></td> + <td> + <p>The <code>RTCPeerConnection</code> is closed.</p> + + <p>This value was in the <a href="#RTCSignalingState_enum"><code>RTCSignalingState</code> enum</a> (and therefore found by reading the value of the {{domxref("RTCPeerConnection.signalingState", "signalingState")}}) property until the May 13, 2016 draft of the specification.</p> + </td> + </tr> + </tbody> +</table> + +<h3 id="RTCRtcpMuxPolicy_enum">RTCRtcpMuxPolicy enum</h3> + +<p>The <code>RTCRtcpMuxPolicy</code> enum defines string constants which specify what ICE candidates are gathered to support non-multiplexed RTCP. <strong><<<add a link to info about multiplexed RTCP.</strong></p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>"negotiate"</code></td> + <td>Instructs the ICE agent to gather both {{Glossary("RTP")}} and {{Glossary("RTCP")}} candidates. If the remote peer can multiplex RTCP, then RTCP candidates are multiplexed atop the corresponding RTP candidates. Otherwise, both the RTP and RTCP candidates are returned, separately.</td> + </tr> + <tr> + <td><code>"require"</code></td> + <td>Tells the ICE agent to gather ICE candidates for only RTP, and to multiplex RTCP atop them. If the remote peer doesn't support RTCP multiplexing, then session negotiation fails.</td> + </tr> + </tbody> +</table> + +<h3 id="RTCSignalingState_enum">RTCSignalingState enum</h3> + +<p>The <code>RTCSignalingState</code> enum specifies the possible values of {{domxref("RTCPeerConnection.signalingState")}}, which indicates where in the process of signaling the exchange of offer and answer the connection currently is.</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>"stable"</code></td> + <td>There is no ongoing exchange of offer and answer underway. This may mean that the {{domxref("RTCPeerConnection")}} object is new, in which case both the {{domxref("RTCPeerConnection.localDescription", "localDescription")}} and {{domxref("RTCPeerConnection.remoteDescription", "remoteDescription")}} are <code>null</code>; it may also mean that negotiation is complete and a connection has been established.</td> + </tr> + <tr> + <td><code>"have-local-offer"</code></td> + <td>The local peer has called {{domxref("RTCPeerConnection.setLocalDescription()")}}, passing in SDP representing an offer (usually created by calling {{domxref("RTCPeerConnection.createOffer()")}}), and the offer has been applied successfully.</td> + </tr> + <tr> + <td><code>"have-remote-offer"</code></td> + <td>The remote peer has created an offer and used the signaling server to deliver it to the local peer, which has set the offer as the remote description by calling {{domxref("RTCPeerConnection.setRemoteDescription()")}}.</td> + </tr> + <tr> + <td><code>"have-local-pranswer"</code></td> + <td>The offer sent by the remote peer has been applied and an answer has been created (usually by calling {{domxref("RTCPeerConnection.createAnswer()")}}) and applied by calling {{domxref("RTCPeerConnection.setLocalDescription()")}}. This provisional answer describes the supported media formats and so forth, but may not have a complete set of ICE candidates included. Further candidates will be delivered separately later.</td> + </tr> + <tr> + <td><code>"have-remote-pranswer"</code></td> + <td>A provisional answer has been received and successfully applied in response to an offer previously sent and established by calling <code>setLocalDescription()</code>.</td> + </tr> + <tr> + <td><code>"closed"</code> {{obsolete_inline}}</td> + <td> + <p>The connection is closed.</p> + + <div class="note"> + <p>This value moved into the <a href="#RTCPeerConnectionState_enum"><code>RTCPeerConnectionState</code> enum</a> in the May 13, 2016 draft of the specification, as it reflects the state of the <code>RTCPeerConnection</code>, not the signaling connection. You now detect a closed connection by checking for {{domxref("RTCPeerConnection.connectionState", "connectionState")}} to be <code>"closed"</code> instead.</p> + </div> + </td> + </tr> + </tbody> +</table> + +<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('WebRTC 1.0', '#interface-definition', 'RTCPeerConnection')}}</td> + <td>{{Spec2('WebRTC 1.0')}}</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>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Microsoft Edge</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}{{property_prefix("-webkit")}}<br> + {{CompatChrome(56)}} (unprefixed)</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(22)}}<br> + {{property_prefix("-moz")}} until Firefox 44</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>addTrack()</code></td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{ CompatGeckoDesktop(45) }} <sup>[1]</sup></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>iceConnectionState</code>: <code>disconnected</code></td> + <td>{{CompatChrome(48)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop(52)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>onicegatheringstatechange</code></td> + <td>{{CompatChrome(59)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>removeTrack()</code></td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{ CompatVersionUnknown }}[2]</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android Webview</th> + <th>Chrome for Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}{{property_prefix("-webkit")}}<br> + {{CompatChrome(56)}} (unprefixed)</td> + <td>{{CompatVersionUnknown}}{{property_prefix("-webkit")}}<br> + {{CompatChrome(56)}} (unprefixed)</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(22)}}<br> + {{property_prefix("-moz")}} until Firefox 44</td> + <td>22</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>addTrack()</code></td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{ CompatGeckoDesktop(45) }}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td> </td> + </tr> + <tr> + <td><code>iceConnectionState</code>: <code>disconnected</code></td> + <td>{{CompatChrome(48)}}</td> + <td>{{CompatChrome(48)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop(52)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>onicegatheringstatechange</code></td> + <td>{{CompatChrome(59)}}</td> + <td>{{CompatChrome(59)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>removeTrack()</code></td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td> </td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Prior to Firefox 49, the specified track was required to be component of all passed {{domxref("MediaStream")}}s. Starting in Firefox 49, this is no longer the case. See {{bug(1271669)}} for specifics.</p> + +<p>[2] Firefox currently removes the {{domxref("RTCRtpSender")}} from the list of senders as reported by {{domxref("RTCPeerConnection.getSenders()")}}. This was correct in earlier versions of the specification, but no longer is. See {{bug(1290949)}}.</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="https://github.com/jesup/nightly-gupshup/blob/master/static/js/chat.js">https://github.com/jesup/nightly-gupshup/blob/master/static/js/chat.js</a></li> + <li><a href="http://www.html5rocks.com/en/tutorials/webrtc/basics/#toc-simple">http://www.html5rocks.com/en/tutorials/webrtc/basics/#toc-simple</a></li> + <li><a href="https://github.com/chrisjohndigital/TutorRoom">TutorRoom</a>: Node.js HTML5 video capture, peer-to-peer video and filesharing application (<a href="https://github.com/chrisjohndigital/TutorRoom">source on GitHub</a>)</li> +</ul> diff --git a/files/es/web/api/rtcrtpreceiver/index.html b/files/es/web/api/rtcrtpreceiver/index.html new file mode 100644 index 0000000000..0944e1d163 --- /dev/null +++ b/files/es/web/api/rtcrtpreceiver/index.html @@ -0,0 +1,72 @@ +--- +title: RTCRtpReceiver +slug: Web/API/RTCRtpReceiver +translation_of: Web/API/RTCRtpReceiver +--- +<div>{{APIRef("WebRTC")}}</div> + +<p><span class="seoSummary">La interfaz <strong><code>RTCRtpReceiver</code></strong> de la <a href="/en-US/docs/Web/API/WebRTC_API">WebRTC API</a> </span>gestiona la recepción y decodificación de los datos para una<span class="seoSummary"> {{domxref("MediaStreamTrack")}} a una {{domxref("RTCPeerConnection")}}.</span></p> + +<h2 id="Propiedades">Propiedades</h2> + +<dl> + <dt>{{domxref("RTCRtpReceiver.track")}} {{readonlyinline}}</dt> + <dd>Devuelve el {{domxref("MediaStreamTrack")}} asociado con la instancia actual de <code>RTCRtpReceiver</code></dd> + <dt>{{domxref("RTCRtpReceiver.rtcpTransport")}} {{readonlyinline}}</dt> + <dd>Devuelve la instancia {{domxref("RTCDtlsTransport")}} en la que se envía y se recibe el RTCP.</dd> + <dt>{{domxref("RTCRtpReceiver.transport")}} {{readonlyinline}}</dt> + <dd>Devuelve la instancia {{domxref("RTCDtlsTransport")}} en la que se reciben los medios para la pista del receptor.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<dl> + <dt>{{domxref("RTCRtpReceiver.getContributingSources()")}}</dt> + <dd>Devuelve un array de instancia {{domxref("RTCRtpContributingSource")}} para cada identificador CSRC (fuente contribuyente) identificador recibido actual <code>RTCRtpReceiver</code> en los últimos 10 segundos.</dd> + <dt>{{domxref("RTCRtpReceiver.getParameters()")}} </dt> + <dd>Devuelve un objeto <code>RTCRtpParameters</code> que contiene información sobre cómo se van a decodificar los datos de RTC.</dd> + <dt>{{domxref("RTCRtpReceiver.getStats()")}}</dt> + <dd>Devuelve un {{jsxref("Promise")}} cuyo controlador de cumplimiento recibe un<br> + {{domxref("RTCStatsReport")}} que contiene estadísticas sobre los flujos entrantes y sus dependencias.</dd> + <dt>{{domxref("RTCRtpReceiver.getSynchronizationSources()")}} </dt> + <dd>Devuelve un arreglo que incluye una instancia {{domxref("RTCRtpSynchronizationSource")}} para cada identificador SSRC (fuente de sincronización) único recibido por el <code>RTCRtpReceiver</code> actual en los últimos diez segundos.</dd> +</dl> + +<h2 id="Métodos_estáticos">Métodos estáticos</h2> + +<dl> + <dt>{{domxref("RTCRtpReceiver.getCapabilities()")}}</dt> + <dd>Devuelve la visión más optimista de las capacidades del sistema para recibir medios de comunicación del tipo dado.</dd> +</dl> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Status</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('WebRTC 1.0','#rtcrtpreceiver-interface','RTCRtpReceiver')}}</td> + <td>{{Spec2('WebRTC 1.0')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad">Compatibilidad</h2> + + + +<p>{{Compat("api.RTCRtpReceiver")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/WebRTC_API">WebRTC</a></li> + <li>{{domxref("RTCStatsReport")}}</li> + <li>{{domxref("RTCRtpSender")}}</li> + <li>{{domxref("RTCPeerConnection.getStats()")}}</li> +</ul> diff --git a/files/es/web/api/screen/index.html b/files/es/web/api/screen/index.html new file mode 100644 index 0000000000..0d5e87f9c9 --- /dev/null +++ b/files/es/web/api/screen/index.html @@ -0,0 +1,89 @@ +--- +title: Screen +slug: Web/API/Screen +translation_of: Web/API/Screen +--- +<div>{{APIRef("CSSOM View")}}</div> + +<p>La interfaz <code>Screen</code> representa una pantallaa, usualmente la misma donde la ventana actual está siendo visualizada.</p> + +<p>Usualmente es también la única en la que la ventana actual está siendo visualizada, obtenida utilizando <code>window.screen</code>.</p> + +<h2 id="Example" name="Example">Propiedades</h2> + +<dl> + <dt>{{domxref("Screen.availTop")}}</dt> + <dd>Especifica la coordenada-y del primer pixel que no está asignado a prestaciones permanentes o semipermanentes de la interfaz de usuario.</dd> + <dt>{{domxref("Screen.availLeft")}}</dt> + <dd>Retorna el primer pixel disponible desde el border izquierdo de la pantalla.</dd> + <dt>{{domxref("Screen.availHeight")}}</dt> + <dd>Especifica la altura de la pantalla, en pixels, menos la altura de los elementos permanentes o semipermanentes de la interfaz de usuario visualizados por el sistema operativo, como la barra de tareas de Windows.</dd> + <dt>{{domxref("Screen.availWidth")}}</dt> + <dd>Retorna el total de espacio horizontal en pixels disponibles para la ventana.</dd> + <dt>{{domxref("Screen.colorDepth")}}</dt> + <dd>Retorna la profundidad de color de la pantalla.</dd> + <dt>{{domxref("Screen.height")}}</dt> + <dd>Retorna la altura de la pantalla en pixels.</dd> + <dt>{{domxref("Screen.left")}}</dt> + <dd>Retorna la distancia en pixels desde el borde izquierdo de la pantalla principal al borde izquierdo de la pantalla actual.</dd> + <dt>{{domxref("Screen.orientation")}}</dt> + <dd>Retorna la orientación actual de la pantalla.</dd> + <dt>{{domxref("Screen.pixelDepth")}}</dt> + <dd>Obtiene la profundidad de bits de la pantalla.</dd> + <dt>{{domxref("Screen.top")}}</dt> + <dd>Retorna la distancia en pixels desde el borde supierior de la pantalla principal al border superior de la pantalla actual.</dd> + <dt>{{domxref("Screen.width")}}</dt> + <dd>Retorna la anchura de la pantalla.</dd> + <dt>{{domxref("Screen.mozEnabled")}} {{gecko_minversion_inline("12.0")}}</dt> + <dd>Booleano. Estableciendo su valor a false desactivará el dispositivo de pantalla.</dd> + <dt>{{domxref("Screen.mozBrightness")}} {{gecko_minversion_inline("12.0")}}</dt> + <dd>Controla el brillo del dispositivo de pantalla. Espera un valor doble-precisión entre 0 y 1.0.</dd> +</dl> + +<h3 id="Manejador_de_eventos">Manejador de eventos</h3> + +<dl> + <dt>{{domxref("Screen.onorientationchange")}}</dt> + <dd>Un manejador para los eventos {{event("orientationchange")}}.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<dl> + <dt>{{domxref("Screen.lockOrientation")}}</dt> + <dd>Bloquea la orientación de pantalla (sólo funciona en pantalla completa o para apps instaladas)</dd> + <dt>{{domxref("Screen.unlockOrientation")}}</dt> + <dd>Desbloquea la orientación de pantalla (sólo funciona en pantalla completa o para apps instaladas)</dd> +</dl> + +<p>Métodos heredados de {{domxref("EventTarget")}}</p> + +<p>{{page("/en-US/docs/Web/API/EventTarget","Methods")}}</p> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre class="brush:js">if (screen.pixelDepth < 8) { + // usa versión low-color de la página +} else { + // usa versión regular, a todo color de la página +} +</pre> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Observaciones</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('CSSOM View', '#the-screen-interface', 'Screen') }}</td> + <td>{{ Spec2('CSSOM View') }}</td> + <td></td> + </tr> + </tbody> +</table> diff --git a/files/es/web/api/selection/addrange/index.html b/files/es/web/api/selection/addrange/index.html new file mode 100644 index 0000000000..a684954e9c --- /dev/null +++ b/files/es/web/api/selection/addrange/index.html @@ -0,0 +1,46 @@ +--- +title: addRange +slug: Web/API/Selection/addRange +tags: + - páginas_a_traducir +translation_of: Web/API/Selection/addRange +--- +<p>{{ ApiRef("DOM") }}</p> + +<h3 id="Resumen" name="Resumen">Resumen</h3> + +<p>Añade un objeto de rango a la selección.</p> + +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> + +<pre class="eval"><i>sel</i>.addRange( +<i>range</i>) +</pre> + +<h3 id="Par.C3.A1metros" name="Par.C3.A1metros">Parámetros</h3> + +<dl> + <dt> + <i><code>range</code></i> + </dt> + <dd>Un objeto <a href="es/DOM/range">range</a> que será añadido a la selección.</dd> +</dl> + +<h3 id="Ejemplos" name="Ejemplos">Ejemplos</h3> + +<pre class="eval"> /* Seleccionar todos los elementos en NEGRITA en un documento HTML */ + var strongs = document.getElementsByTagName("strong"); + var s = window.getSelection(); + if(s.rangeCount > 0) s.removeAllRanges(); + for(var i = 0; i < strongs.length; i++) { + var range = document.createRange(); + range.selectNode(strongs[i]); + s.addRange(range); + } +</pre> + +<p> </p> + +<div class="noinclude"> </div> + +<p>{{ languages( { "en": "en/DOM/Selection/addRange", "it": "it/DOM/Selection/addRange", "pl": "pl/DOM/Selection/addRange" } ) }}</p> diff --git a/files/es/web/api/selection/anchornode/index.html b/files/es/web/api/selection/anchornode/index.html new file mode 100644 index 0000000000..dcb4b194b0 --- /dev/null +++ b/files/es/web/api/selection/anchornode/index.html @@ -0,0 +1,27 @@ +--- +title: anchorNode +slug: Web/API/Selection/anchorNode +tags: + - páginas_a_traducir +translation_of: Web/API/Selection/anchorNode +--- +<p>{{ ApiRef("DOM") }}</p> + +<h3 id="Resumen" name="Resumen">Resumen</h3> + +<p>Devuelve el nodo en el cual empieza la selección.</p> + +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> + +<pre class="eval"><i>sel</i>.anchorNode +</pre> + +<h3 id="Notas" name="Notas">Notas</h3> + +<p>Un usuario puede hacer una selección de izquierda a derecha (en el orden del documento) o de derehca a izquierda (en el orden contrario del documento). El ancla es donde el usuario empezó la selección. Ésta puede ser visualizada manteniendo presionada la tecla <b>Shift</b> y presionando las flechas de movimiento del teclado. El ancla de la selección no se mueve, pero el foco de ésta (el otro "final" de la selección) sí se mueve.</p> + +<p> </p> + +<div class="noinclude"> </div> + +<p>{{ languages( { "en": "en/DOM/Selection/anchorNode", "it": "it/DOM/Selection/anchorNode", "pl": "pl/DOM/Selection/anchorNode" } ) }}</p> diff --git a/files/es/web/api/selection/anchoroffset/index.html b/files/es/web/api/selection/anchoroffset/index.html new file mode 100644 index 0000000000..e228803085 --- /dev/null +++ b/files/es/web/api/selection/anchoroffset/index.html @@ -0,0 +1,27 @@ +--- +title: anchorOffset +slug: Web/API/Selection/anchorOffset +tags: + - páginas_a_traducir +translation_of: Web/API/Selection/anchorOffset +--- +<p>{{ ApiRef("DOM") }}</p> + +<h3 id="Resumen" name="Resumen">Resumen</h3> + +<p>Devuelve el número de caracteres en que el ancla de la selección es colocada dentro de <a href="es/DOM/Selection/anchorNode">anchorNode</a>.</p> + +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> + +<pre class="eval"><i>sel</i>.anchorOffset +</pre> + +<h3 id="Notas" name="Notas">Notas</h3> + +<p>Este número está basado en cero. Si la selección empieza con el primer carácter en <a href="es/DOM/Selection/anchorNode">anchorNode</a>, el número devuelto será 0.</p> + +<p> </p> + +<div class="noinclude"> </div> + +<p>{{ languages( { "en": "en/DOM/Selection/anchorOffset", "it": "it/DOM/Selection/anchorOffset", "pl": "pl/DOM/Selection/anchorOffset" } ) }}</p> diff --git a/files/es/web/api/selection/collapse/index.html b/files/es/web/api/selection/collapse/index.html new file mode 100644 index 0000000000..a0540265c3 --- /dev/null +++ b/files/es/web/api/selection/collapse/index.html @@ -0,0 +1,50 @@ +--- +title: collapse +slug: Web/API/Selection/collapse +tags: + - páginas_a_traducir +translation_of: Web/API/Selection/collapse +--- +<p>{{ ApiRef("DOM") }}</p> + +<h3 id="Resumen" name="Resumen">Resumen</h3> + +<p>Pliega la selección a un simple punto. El documento no es modificado. Si el contenido es enfocado y editable, el cursor parpadeará ahí.</p> + +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> + +<pre class="eval"><i>sel</i>.collapse( +<i>parentNode</i>, +<i>offset</i>); +</pre> + +<h3 id="Par.C3.A1metros" name="Par.C3.A1metros">Parámetros</h3> + +<dl> + <dt> + <i><code>parentNode</code></i> + </dt> + <dd>La localización del cursor estará dentro de este nodo.</dd> +</dl> + +<dl> + <dt> + <i><code>offset</code></i> + </dt> + <dd>El cursor estará colocado éste número de caracteres desdel el comienzo del texto de + <i><code>parentNode</code>'</i> + s text.</dd> +</dl> + +<h3 id="Ejemplos" name="Ejemplos">Ejemplos</h3> + +<pre class="eval">/* Colocar el cursor al principio del cuerpo de un documento HTML. */ +var body = document.getElementsByTagName("body")[0]; +window.getSelection().collapse(body,0); +</pre> + +<p> </p> + +<div class="noinclude"> </div> + +<p>{{ languages( { "en": "en/DOM/Selection/collapse", "it": "it/DOM/Selection/collapse", "pl": "pl/DOM/Selection/collapse" } ) }}</p> diff --git a/files/es/web/api/selection/collapsetoend/index.html b/files/es/web/api/selection/collapsetoend/index.html new file mode 100644 index 0000000000..f0f729b928 --- /dev/null +++ b/files/es/web/api/selection/collapsetoend/index.html @@ -0,0 +1,27 @@ +--- +title: collapseToEnd +slug: Web/API/Selection/collapseToEnd +tags: + - páginas_a_traducir +translation_of: Web/API/Selection/collapseToEnd +--- +<p>{{ ApiRef("DOM") }}</p> + +<h3 id="Resumen" name="Resumen">Resumen</h3> + +<p>Traslada el ancla hasta el mismo punto del foco. El foco no se mueve. Si el contenido es enfocado y editable, el cursor parpadeará ahí.</p> + +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> + +<pre class="eval"><i>sel</i>.collapseToEnd() +</pre> + +<h3 id="Par.C3.A1metros" name="Par.C3.A1metros">Parámetros</h3> + +<p>Ninguno.</p> + +<p> </p> + +<div class="noinclude"> </div> + +<p>{{ languages( { "en": "en/DOM/Selection/collapseToEnd", "it": "it/DOM/Selection/collapseToEnd", "pl": "pl/DOM/Selection/collapseToEnd" } ) }}</p> diff --git a/files/es/web/api/selection/collapsetostart/index.html b/files/es/web/api/selection/collapsetostart/index.html new file mode 100644 index 0000000000..ce04e7a985 --- /dev/null +++ b/files/es/web/api/selection/collapsetostart/index.html @@ -0,0 +1,29 @@ +--- +title: collapseToStart +slug: Web/API/Selection/collapseToStart +tags: + - páginas_a_traducir +translation_of: Web/API/Selection/collapseToStart +--- +<p>{{ ApiRef("DOM") }}</p> + +<h3 id="Resumen" name="Resumen">Resumen</h3> + +<p>Traslada el foco de la selección al mismo punto que el ancla. El ancla no se mueve. Si el contenido es enfocado y editable, el cursor parpadeará ahí.</p> + +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> + +<pre class="eval"><i>sel</i>.collapseToStart() +</pre> + +<h3 id="Par.C3.A1metros" name="Par.C3.A1metros">Parámetros</h3> + +<p>Ninguno.</p> + +<p> </p> + +<p> </p> + +<div class="noinclude"> </div> + +<p>{{ languages( { "en": "en/DOM/Selection/collapseToStart", "it": "it/DOM/Selection/collapseToStart", "pl": "pl/DOM/Selection/collapseToStart" } ) }}</p> diff --git a/files/es/web/api/selection/containsnode/index.html b/files/es/web/api/selection/containsnode/index.html new file mode 100644 index 0000000000..272c7e71af --- /dev/null +++ b/files/es/web/api/selection/containsnode/index.html @@ -0,0 +1,49 @@ +--- +title: containsNode +slug: Web/API/Selection/containsNode +tags: + - páginas_a_traducir +translation_of: Web/API/Selection/containsNode +--- +<p>{{ ApiRef("DOM") }}</p> + +<h3 id="Resumen" name="Resumen">Resumen</h3> + +<p>Indica si tal nodo es parte de la selección.</p> + +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> + +<pre class="eval"><i>sel</i>.containsNode( +<i>aNode</i>, +<i>aPartlyContained</i>) +</pre> + +<h3 id="Par.C3.A1metros" name="Par.C3.A1metros">Parámetros</h3> + +<dl> + <dt> + <i><code>aNode</code></i> + </dt> + <dd>El nodo que está siendo vigilado por si es parte de la selección.</dd> + <dt> + <i><code>aPartlyContained</code></i> + </dt> + <dd>Cuando da un valor + <i>verdadero</i> + , <code>containsNode</code> devuelve verdadero cuanbdo una parte del nodo es parte de la selección.</dd> + <dd>Cuando da un valor + <i>falso</i> + , <code>containsNode</code> solo devuelve verdadeor cuando el nodo completo es parte de la selección.</dd> +</dl> + +<h3 id="Ejemplos" name="Ejemplos">Ejemplos</h3> + +<pre class="eval"> /* Checar si algo dentro del elemento cuerpo (etiquetas body) está seleccionado */ + alert(window.getSelection().containsNode(document.body, true)); +</pre> + +<p> </p> + +<div class="noinclude"> </div> + +<p>{{ languages( { "en": "en/DOM/Selection/containsNode", "it": "it/DOM/Selection/containsNode", "pl": "pl/DOM/Selection/containsNode" } ) }}</p> diff --git a/files/es/web/api/selection/deletefromdocument/index.html b/files/es/web/api/selection/deletefromdocument/index.html new file mode 100644 index 0000000000..808461dba4 --- /dev/null +++ b/files/es/web/api/selection/deletefromdocument/index.html @@ -0,0 +1,31 @@ +--- +title: deleteFromDocument +slug: Web/API/Selection/deleteFromDocument +tags: + - páginas_a_traducir +translation_of: Web/API/Selection/deleteFromDocument +--- +<p>{{ ApiRef("DOM") }}</p> + +<h3 id="Resumen" name="Resumen">Resumen</h3> + +<p>Elimina del documento el contenido de la selección.</p> + +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> + +<pre class="eval"><i>sel</i>.deleteFromDocument() +</pre> + +<h3 id="Par.C3.A1metros" name="Par.C3.A1metros">Parámetros</h3> + +<p>Ninguno.</p> + +<h3 id="Ejemplos" name="Ejemplos">Ejemplos</h3> + +<p>Un usuario selecciona el texto (imaginario) "jos tienen do" del texto "Los conejos tienen dos orejas." en una página web. Después el usuario da click en un botón que ejecuta la acción cortar de JavaScript <code>window.getSelection().deleteFromDocument()</code>. El texto del documento quedaría como "Los cones orejas."</p> + +<p> </p> + +<div class="noinclude"> </div> + +<p>{{ languages( { "en": "en/DOM/Selection/deleteFromDocument", "it": "it/DOM/Selection/deleteFromDocument", "pl": "pl/DOM/Selection/deleteFromDocument" } ) }}</p> diff --git a/files/es/web/api/selection/extend/index.html b/files/es/web/api/selection/extend/index.html new file mode 100644 index 0000000000..d4c0315631 --- /dev/null +++ b/files/es/web/api/selection/extend/index.html @@ -0,0 +1,41 @@ +--- +title: extend +slug: Web/API/Selection/extend +tags: + - páginas_a_traducir +translation_of: Web/API/Selection/extend +--- +<p>{{ ApiRef("DOM") }}</p> + +<h3 id="Resumen" name="Resumen">Resumen</h3> + +<p>Traslada el foco de la selección a un punto especificado. El ancla de la selección no se mueve. La selección será desde el ancla hasta el nuevo focus regardless of direction.</p> + +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> + +<pre class="eval"><i>sel</i>.extend( +<i>parentNode</i>, +<i>offset</i>) +</pre> + +<h3 id="Par.C3.A1metros" name="Par.C3.A1metros">Parámetros</h3> + +<dl> + <dt> + <i><code>parentNode</code></i> + </dt> + <dd>El nodo dentro del cual el foco será movido.</dd> +</dl> + +<dl> + <dt> + <i><code>offset</code></i> + </dt> + <dd>El número de caracteres que habrá desde el principio del texto + <i><code>parentNode</code></i> + hasta donde el foco se colocará.</dd> +</dl> + +<div class="noinclude"> </div> + +<p>{{ languages( { "en": "en/DOM/Selection/extend", "it": "it/DOM/Selection/extend", "pl": "pl/DOM/Selection/extend" } ) }}</p> diff --git a/files/es/web/api/selection/focusnode/index.html b/files/es/web/api/selection/focusnode/index.html new file mode 100644 index 0000000000..6ccaae09fe --- /dev/null +++ b/files/es/web/api/selection/focusnode/index.html @@ -0,0 +1,25 @@ +--- +title: focusNode +slug: Web/API/Selection/focusNode +tags: + - páginas_a_traducir +translation_of: Web/API/Selection/focusNode +--- +<p>{{ ApiRef("DOM") }}</p> + +<h3 id="Resumen" name="Resumen">Resumen</h3> + +<p>Devuelve el nudo en el cual acaba la selección.</p> + +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> + +<pre class="eval"><i>sel</i>.focusNode +</pre> + +<h3 id="Notas" name="Notas">Notas</h3> + +<p>Un usuario puede hacer una selección de izquierda a derecha (en el orden del documento) o de derehca a izquierda (en el orden contrario del documento). El foco es donde el usuario terminó la selección. Éste puede ser visualizado manteniendo presionada la tecla Shift y presionando las flechas de movimiento del teclado para modificar la selección. El foco de la selección se mueve, pero el ancla de ésta (el otro final de la selección) no se mueve.</p> + +<div class="noinclude"> </div> + +<p>{{ languages( { "en": "en/DOM/Selection/focusNode", "it": "it/DOM/Selection/focusNode", "pl": "pl/DOM/Selection/focusNode" } ) }}</p> diff --git a/files/es/web/api/selection/focusoffset/index.html b/files/es/web/api/selection/focusoffset/index.html new file mode 100644 index 0000000000..88f525f887 --- /dev/null +++ b/files/es/web/api/selection/focusoffset/index.html @@ -0,0 +1,27 @@ +--- +title: focusOffset +slug: Web/API/Selection/focusOffset +tags: + - páginas_a_traducir +translation_of: Web/API/Selection/focusOffset +--- +<p>{{ ApiRef("DOM") }}</p> + +<h3 id="Resumen" name="Resumen">Resumen</h3> + +<p>Devuelve el número de caracteres en que el foco de la selección es colocado dentro de <a href="es/DOM/Selection/focusNode">focusNode</a>.</p> + +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> + +<pre class="eval"><i>sel</i>.focusOffset +</pre> + +<h3 id="Notas" name="Notas">Notas</h3> + +<p>Este número está basado en cero. Si la selección termina con el primer carácter en <a href="es/DOM/Selection/focusNode">focusNode</a>, el número devuelto será 0.</p> + +<p> </p> + +<div class="noinclude"> </div> + +<p>{{ languages( { "en": "en/DOM/Selection/focusOffset", "it": "it/DOM/Selection/focusOffset", "pl": "pl/DOM/Selection/focusOffset" } ) }}</p> diff --git a/files/es/web/api/selection/getrangeat/index.html b/files/es/web/api/selection/getrangeat/index.html new file mode 100644 index 0000000000..db0505dd77 --- /dev/null +++ b/files/es/web/api/selection/getrangeat/index.html @@ -0,0 +1,49 @@ +--- +title: getRangeAt +slug: Web/API/Selection/getRangeAt +tags: + - páginas_a_traducir +translation_of: Web/API/Selection/getRangeAt +--- +<p>{{ ApiRef("DOM") }}</p> + +<h3 id="Resumen" name="Resumen">Resumen</h3> + +<p>Devuelve un objeto de rango representando uno de los rangos seleccionados.</p> + +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> + +<pre class="eval"><i>range</i> = +<i>sel</i>.getRangeAt( +<i>index</i>) +</pre> + +<h3 id="Par.C3.A1metros" name="Par.C3.A1metros">Parámetros</h3> + +<dl> + <dt> + <i><code>range</code></i> + </dt> + <dd>El objeto <a href="es/DOM/range">range</a> (rango) que será devuelto.</dd> +</dl> + +<dl> + <dt> + <i><code>index</code></i> + </dt> + <dd>El exponente (basado en cero) del rango a devolver. Un número negativo o un número mayor o igual a <a href="es/DOM/Selection/rangeCount">rangeCount</a> provocará un error.</dd> +</dl> + +<h3 id="Ejemplos" name="Ejemplos">Ejemplos</h3> + +<pre class="eval">ranges = []; +sel = window.getSelection(); +for(var i = 0; i < sel.rangeCount; i++) { + ranges[i] = sel.getRangeAt(i); +} +/* Cada artículo en el array de rangos ahora es + * un objeto rango representando uno de los + * rangos en la selección */ +</pre> + +<p>{{ languages( { "en": "en/DOM/Selection/getRangeAt", "pl": "pl/DOM/Selection/getRangeAt" } ) }}</p> diff --git a/files/es/web/api/selection/index.html b/files/es/web/api/selection/index.html new file mode 100644 index 0000000000..d267e3b16b --- /dev/null +++ b/files/es/web/api/selection/index.html @@ -0,0 +1,105 @@ +--- +title: Selection +slug: Web/API/Selection +tags: + - DOM + - Todas_las_Categorías +translation_of: Web/API/Selection +--- +<p>{{ ApiRef("DOM") }}</p> + +<h3 id="Introducci.C3.B3n" name="Introducci.C3.B3n">Introducción</h3> + +<p>Selección es la clase de objeto devuelto por <code><a href="es/DOM/window.getSelection"> window.getSelection()</a></code> y otros métodos.</p> + +<p>Un objeto de selección representa los <a href="es/DOM/range">rangos</a> que el usuario ha seleccionado. Suele llevar un sólo rango, accesado como sigue:</p> + +<pre class="eval">range = sel.getRangeAt(0); +</pre> + +<p>Llamar al método <code><a href="es/DOM/Selection/toString">toString()</a></code> devuelve el texto contenido en la selección, ej:</p> + +<pre class="eval">selObj = window.getSelection(); +window.alert(selObj.toString()); +</pre> + +<p> </p> + +<h3 id="Glosario" name="Glosario">Glosario</h3> + +<p>Otros términos claves usados en esta parte.</p> + +<dl> + <dt>anchor</dt> + <dd>El ancla de una selección es el punto inicial de ésta. Cuando se hace una selección con el ratón, el ancla es el punto donde se presionó por primera vez el botón del ratón. Cuando el usuario mueve la selección utilizando el ratón o el teclado, el ancla no se mueve.</dd> + <dt>focus</dt> + <dd>El foco de una selección es el punto último de ésta. Cuando se hace la selección con el ratón, el foco es el punto donde se suelta el botón del ratón. Cuando el usuario mueve la selección utilizando el "mouse" o el teclado, el foco es el final de la selección que el usuario está moviendo.</dd> + <dt>range</dt> + <dd>Un rango es una parte contigua de un documento. Un rango puede contener un nodo entero así como porciones de nodos, por ejemplo una parte de un nodo de texto. Normalmente un usuario seleccionará únicamente un solo rango a la vez, pero también le es posible seleccionar múltiples rangos (por ejemplo, utilizando la tecla control<em>Ctrl</em> ). Un rango puede ser recuperado de una selección como un objeto de <a href="es/DOM/range">rango</a>. Los objetos de rango también pueden ser creados vía el DOM y programadamente adheridos o removidos de una selección.</dd> +</dl> + +<h3 id="Propiedades" name="Propiedades">Propiedades</h3> + +<dl> + <dt><a href="es/DOM/Selection/anchorNode">anchorNode</a></dt> + <dd>Devuelve el nodo en el cual empieza la selección.</dd> + <dt><a href="es/DOM/Selection/anchorOffset">anchorOffset</a></dt> + <dd>Devuelve el número de caracteres en que el ancla de la selección es colocada dentro de <code>anchorNode.</code></dd> + <dt><a href="es/DOM/Selection/focusNode">focusNode</a></dt> + <dd>Devuelve el nodo en el cual acaba la selección.</dd> + <dt><a href="es/DOM/Selection/focusOffset">focusOffset</a></dt> + <dd>Devuelve el número de caracteres en que el foco de la selección es colocado dentro de <code>focusNode.</code></dd> + <dt><a href="es/DOM/Selection/isCollapsed">isCollapsed</a></dt> + <dd>Devuelve un valor boleano verdadero si los puntos de inicio y fin de la selección están en la misma posición.</dd> + <dt><a href="es/DOM/Selection/rangeCount">rangeCount</a></dt> + <dd>Devuelve el número de los rangos que hay en la selección.</dd> +</dl> + +<h3 id="M.C3.A9todos" name="M.C3.A9todos">Métodos</h3> + +<dl> + <dt><a href="es/DOM/Selection/getRangeAt">getRangeAt</a></dt> + <dd>Devuelve un objeto de rango representando uno de los rangos seleccionados.</dd> + <dt><a href="es/DOM/Selection/collapse">collapse</a></dt> + <dd>Pliega la selección a un simple punto.</dd> + <dt><a href="es/DOM/Selection/extend">extend</a></dt> + <dd>Traslada el foco de la selección a un punto especificado.</dd> + <dt><a href="es/DOM/Selection/collapseToStart">collapseToStart</a></dt> + <dd>Traslada el foco de la selección al mismo punto que el ancla.</dd> + <dt><a href="es/DOM/Selection/collapseToEnd">collapseToEnd</a></dt> + <dd>Traslada el ancla hasta el mismo punto del foco. El foco no se mueve.</dd> + <dt><a href="es/DOM/Selection/selectAllChildren">selectAllChildren</a></dt> + <dd>Añadirá todos los "hijos" del nodo especificado a la selección.</dd> + <dt><a href="es/DOM/Selection/addRange">addRange</a></dt> + <dd>Añade un objeto de rango a la selección.</dd> + <dt><a href="es/DOM/Selection/removeRange">removeRange</a></dt> + <dd>Quita un rango de la selección.</dd> + <dt><a href="es/DOM/Selection/removeAllRanges">removeAllRanges</a></dt> + <dd>Quita todos los rangos de la selección.</dd> + <dt><a href="es/DOM/Selection/deleteFromDocument">deleteFromDocument</a></dt> + <dd>Elimina del documento el contenido de la selección.</dd> + <dt><a href="es/DOM/Selection/selectionLanguageChange">selectionLanguageChange</a></dt> + <dd>NO IMPLEMENTADA, Cambia la direccion de la seleccion de Izquierda a Derecha a Derecha a Izquierda</dd> + <dt><a href="es/DOM/Selection/toString">toString</a></dt> + <dd>Devuelve una cadena de caracteres (texto), la cual es representada por el objeto de selección, es decir, el texto seleccionado.</dd> + <dt><a href="es/DOM/Selection/containsNode">containsNode</a></dt> + <dd>Indica si tal nodo es parte de la selección.</dd> +</dl> + +<h3 id="Ver_tambi.C3.A9n" name="Ver_tambi.C3.A9n">Ver también</h3> + +<p><a href="es/DOM/window.getSelection">window.getSelection</a>, <a href="es/DOM/range">Rango</a></p> + +<h3 id="Enlaces_externos" name="Enlaces_externos">Enlaces externos</h3> + +<ul> + <li><a class="external" href="http://lxr.mozilla.org/mozilla/source/content/base/public/nsISelection.idl">IDL definition in Mozilla cross-reference</a></li> +</ul> + +<p> </p> + +<p> </p> + +<div class="noinclude"> </div> + +<p>{{ languages( { "en": "en/DOM/Selection", "fr": "fr/DOM/selection", "it": "it/DOM/Selection", "ja": "ja/DOM/selection", "pl": "pl/DOM/Selection" } ) }}</p> diff --git a/files/es/web/api/selection/iscollapsed/index.html b/files/es/web/api/selection/iscollapsed/index.html new file mode 100644 index 0000000000..230c9f147d --- /dev/null +++ b/files/es/web/api/selection/iscollapsed/index.html @@ -0,0 +1,25 @@ +--- +title: isCollapsed +slug: Web/API/Selection/isCollapsed +tags: + - páginas_a_traducir +translation_of: Web/API/Selection/isCollapsed +--- +<p>{{ ApiRef("DOM") }}</p> + +<h3 id="Resumen" name="Resumen">Resumen</h3> + +<p>Devuelve un valor boleano verdadero si los puntos de inicio y fin de la selección están en la misma posición.</p> + +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> + +<pre class="eval"><i>sel</i>.isCollapsed +</pre> + +<h3 id="Notas" name="Notas">Notas</h3> + +<p>Incluso hasta una selección colapsada/plegada puede tener un rangeCount mayor que 0. <code>sel.getRangeAt(0)</code> puede retornar un rango que también esté colapsado/plegado.</p> + +<div class="noinclude"> </div> + +<p>{{ languages( { "en": "en/DOM/Selection/isCollapsed", "it": "it/DOM/Selection/isCollapsed", "pl": "pl/DOM/Selection/isCollapsed" } ) }}</p> diff --git a/files/es/web/api/selection/rangecount/index.html b/files/es/web/api/selection/rangecount/index.html new file mode 100644 index 0000000000..fb39e6be07 --- /dev/null +++ b/files/es/web/api/selection/rangecount/index.html @@ -0,0 +1,28 @@ +--- +title: rangeCount +slug: Web/API/Selection/rangeCount +tags: + - páginas_a_traducir +translation_of: Web/API/Selection/rangeCount +--- +<p>{{ ApiRef("DOM") }}</p> + +<h3 id="Resumen" name="Resumen">Resumen</h3> + +<p>Devuelve el número de los rangos que hay en la selección.</p> + +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> + +<pre class="eval"><i>sel</i>.rangeCount +</pre> + +<h3 id="Notas" name="Notas">Notas</h3> + +<p>Antes de que el usuario haya hecho + <i>click</i> + en una página recién cargada, el <code>rangeCount</code> es 0. Un usuario normalmente puede seleccionar un rango a la vez, entonces el <code>rangeCount</code> usualmente será 1. El + + <i>scripting</i> + puede usarse para hacer que la selección contenga más de 1 rango.</p> + +<p>{{ languages( { "en": "en/DOM/Selection/rangeCount", "it": "it/DOM/Selection/rangeCount", "pl": "pl/DOM/Selection/rangeCount" } ) }}</p> diff --git a/files/es/web/api/selection/removeallranges/index.html b/files/es/web/api/selection/removeallranges/index.html new file mode 100644 index 0000000000..5c8ad3f311 --- /dev/null +++ b/files/es/web/api/selection/removeallranges/index.html @@ -0,0 +1,27 @@ +--- +title: removeAllRanges +slug: Web/API/Selection/removeAllRanges +tags: + - páginas_a_traducir +translation_of: Web/API/Selection/removeAllRanges +--- +<p>{{ ApiRef("DOM") }}</p> + +<h3 id="Resumen" name="Resumen">Resumen</h3> + +<p>Quita todos los rangos de la selección, dejando las propiedades <a href="es/DOM/Selection/anchorNode">anchorNode</a> y <a href="es/DOM/Selection/focusNode">focusNode</a> con un valor <code>null</code> (nulo) y dejando nada seleccionado.</p> + +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> + +<pre class="eval"><i>sel</i>.removeAllRanges(); +</pre> + +<h3 id="Par.C3.A1metros" name="Par.C3.A1metros">Parámetros</h3> + +<p>Ninguno.</p> + +<p> </p> + +<div class="noinclude"> </div> + +<p>{{ languages( { "en": "en/DOM/Selection/removeAllRanges", "it": "it/DOM/Selection/removeAllRanges", "pl": "pl/DOM/Selection/removeAllRanges" } ) }}</p> diff --git a/files/es/web/api/selection/removerange/index.html b/files/es/web/api/selection/removerange/index.html new file mode 100644 index 0000000000..fa617c49b9 --- /dev/null +++ b/files/es/web/api/selection/removerange/index.html @@ -0,0 +1,45 @@ +--- +title: removeRange +slug: Web/API/Selection/removeRange +tags: + - páginas_a_traducir +translation_of: Web/API/Selection/removeRange +--- +<p>{{ ApiRef("DOM") }}</p> + +<h3 id="Resumen" name="Resumen">Resumen</h3> + +<p>Quita un rango de la selección.</p> + +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> + +<pre class="eval"><i>sel</i>.removeRange( +<i>range</i>) +</pre> + +<h3 id="Par.C3.A1metros" name="Par.C3.A1metros">Parámetros</h3> + +<dl> + <dt> + <i><code>range</code></i> + </dt> + <dd>Un objeto rango que será eliminado de la selección.</dd> +</dl> + +<h3 id="Ejemplos" name="Ejemplos">Ejemplos</h3> + +<pre class="eval">/* Programadamente, mas de un rango puede ser seleccionado. + * Esto eliminará todos los rangos excepto el primero. */ +s = window.getSelection(); +if(s.rangeCount > 1) { + for(var i = 1; i < s.rangeCount; i++) { + s.removeRange(s.getRangeAt(i)); + } +} +</pre> + +<p> </p> + +<div class="noinclude"> </div> + +<p>{{ languages( { "en": "en/DOM/Selection/removeRange", "it": "it/DOM/Selection/removeRange", "pl": "pl/DOM/Selection/removeRange" } ) }}</p> diff --git a/files/es/web/api/selection/selectallchildren/index.html b/files/es/web/api/selection/selectallchildren/index.html new file mode 100644 index 0000000000..5f824dc200 --- /dev/null +++ b/files/es/web/api/selection/selectallchildren/index.html @@ -0,0 +1,45 @@ +--- +title: selectAllChildren +slug: Web/API/Selection/selectAllChildren +tags: + - páginas_a_traducir +translation_of: Web/API/Selection/selectAllChildren +--- +<p>{{ ApiRef("DOM") }}</p> + +<h3 id="Resumen" name="Resumen">Resumen</h3> + +<p>Añadirá todos los "hijos" del nodo especificado a la selección. La selección previa se pierde.</p> + +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> + +<pre class="eval"><i>sel</i>.selectAllChildren( +<i>parentNode</i>) +</pre> + +<h3 id="Par.C3.A1metros" name="Par.C3.A1metros">Parámetros</h3> + +<dl> + <dt> + <i><code>parentNode</code></i> + </dt> + <dd>Todos los "hijos" de + <i><code>parentNode</code></i> + serán seleccionados. El mismo + + <i><code>parentNode</code></i> + no es parte de la selección.</dd> +</dl> + +<h3 id="Ejemplos" name="Ejemplos">Ejemplos</h3> + +<pre class="eval">footer = document.getElementById("footer"); +window.getSelection().selectAllChildren(footer); +/* Todo el contendio del pie de página ahora está seleccionado */ +</pre> + +<p> </p> + +<div class="noinclude"> </div> + +<p>{{ languages( { "en": "en/DOM/Selection/selectAllChildren", "it": "it/DOM/Selection/selectAllChildren", "pl": "pl/DOM/Selection/selectAllChildren" } ) }}</p> diff --git a/files/es/web/api/selection/tostring/index.html b/files/es/web/api/selection/tostring/index.html new file mode 100644 index 0000000000..0a70de979b --- /dev/null +++ b/files/es/web/api/selection/tostring/index.html @@ -0,0 +1,48 @@ +--- +title: toString +slug: Web/API/Selection/toString +tags: + - páginas_a_traducir +translation_of: Web/API/Selection/toString +--- +<p>{{ ApiRef("DOM") }}</p> + +<h3 id="Resumen" name="Resumen">Resumen</h3> + +<p>Devuelve una cadena de caracteres (texto), la cual es representada por el objeto de selección, es decir, el texto seleccionado.</p> + +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> + +<pre class="eval"><i>string</i> = +<i>sel</i>.toString() +</pre> + +<ul> + <li><code>string</code> es la representación del texto de selección.</li> +</ul> + +<h3 id="Par.C3.A1metros" name="Par.C3.A1metros">Parámetros</h3> + +<p>Ninguno.</p> + +<h3 id="Descripci.C3.B3n" name="Descripci.C3.B3n">Descripción</h3> + +<p>Este método devuelve el texto seleccionado.</p> + +<p>En <a href="es/JavaScript">JavaScript</a>, este método es llamado automáticamente cuando una función, a la cual es pasado como parámetro el objeto de selección, requiere una cadena de caracteres (texto):</p> + +<pre class="eval">alert(window.getSelection()) // Lo que se llama. +alert(window.getSelection().toString()) // Lo que está siendo efectivamente llamado. +</pre> + +<h3 id="Ver_tambi.C3.A9n" name="Ver_tambi.C3.A9n">Ver también</h3> + +<ul> + <li><a href="es/Core_JavaScript_1.5_Reference/Objects/Object/toString">Object.toString</a></li> +</ul> + +<p> </p> + +<div class="noinclude"> </div> + +<p>{{ languages( { "en": "en/DOM/Selection/toString", "fr": "fr/DOM/Selection/toString", "it": "it/DOM/Selection/toString", "pl": "pl/DOM/Selection/toString" } ) }}</p> diff --git a/files/es/web/api/service_worker_api/index.html b/files/es/web/api/service_worker_api/index.html new file mode 100644 index 0000000000..8b0b05e252 --- /dev/null +++ b/files/es/web/api/service_worker_api/index.html @@ -0,0 +1,311 @@ +--- +title: Service Worker API +slug: Web/API/Service_Worker_API +tags: + - API + - Landing + - NeedsTranslation + - Offline + - Overview + - Reference + - Service Workers + - TopicStub + - Workers +translation_of: Web/API/Service_Worker_API +--- +<div> +<p>{{ServiceWorkerSidebar}}</p> + +<p class="summary">Los Service workers actúan esencialmente como proxy servers asentados entre las aplicaciones web, el navegador y la red (cuando está accesible). Están destinados, entre otras cosas, a permitir la creación de experiencias offline efectivas, interceptando peticiones de red y realizando la acción apropiada si la conexión de red está disponible y hay disponibles contenidos actualizados en el servidor. También permitirán el acceso a notificaciones tipo push y APIs de sincronización en segundo plano.</p> +</div> + +<h2 id="Conceptos_y_uso_de_Service_worker">Conceptos y uso de Service worker</h2> + +<p>Un service worker es un <a href="https://developer.mozilla.org/en-US/docs/Web/API/Worker">worker</a> manejado por eventos registrado para una fuente y una ruta. Consiste en un fichero JavaScript que controla la página web (o el sitio) con el que está asociado, interceptando y modificando la navegación y las peticiones de recursos, y cacheando los recursos de manera muy granular para ofrecer un control completo sobre cómo la aplicación debe comportarse en ciertas situaciones (la mas obvia es cuando la red no está disponible).</p> + +<p>Un service worker se ejecuta en un contexto worker: por lo tanto no tiene acceso al DOM, y se ejecuta en un hilo distinto al JavaScript principal de la aplicación, de manera que no es bloqueante. Está diseñado para ser completamente asíncrono, por lo que APIs como el <a href="/en-US/docs/Web/API/XMLHttpRequest">XHR</a> asíncrono y <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage">localStorage</a> no se pueden usar dentro de un service worker.</p> + +<p>Los service workers solo funcionan sobre HTTPS, por razones de seguridad. Modificar las peticiones de red en abierto permitiría ataques man in the middle realmente peligrosos. En Firefox, las APIs de service worker se ocultan y no pueden ser empleadas cuando el usuario está en <a href="https://support.mozilla.org/en-US/kb/private-browsing-use-firefox-without-history">modo de navegación en privado</a>.</p> + +<div class="note"> +<p><strong>Nota</strong>: Los Service Workers mejoran los intentos anteriores en este área tal como <a href="http://alistapart.com/article/application-cache-is-a-douchebag">AppCache</a> puesto que no hacen suposiciones sobre qué se está intentando hacer para luego tener que cortar cuando las suposiciones no son correctas; hay control granular sobre todos los aspectos.</p> +</div> + +<div class="note"> +<p><strong>Nota</strong>: Los Service workers hace un uso intensivo de las <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">promesas</a>, por lo que generalmente esperarán a que lleguen las respuestasas correspondientes, tras lo cual responderán con una acción de éxito o de fracaso. La arquitectura de promesas es ideal en este caso.</p> +</div> + +<h3 id="Registro">Registro</h3> + +<p>Un service worker se registra primero mediante el método {{domxref("ServiceWorkerContainer.register()")}}. Si ha habido éxito, el service worker se descargará al cliente e intentará la instalación/activación (ver más abajo) de las URLs accedidas por el usuario dentro de todo su origen de datos, o dentro de algún subconjunto especificado por el autor.</p> + +<h3 id="Descarga_instalación_y_activación">Descarga, instalación y activación</h3> + +<p>En este punto, su service worker observará el siguiente ciclo de vida:</p> + +<ol> + <li>Descarga</li> + <li>Instalación</li> + <li>Activación</li> +</ol> + +<p>El service worker se descaga inmediatamente cuando un usuario accede por primera vez a un sitio controlado por el mismo.</p> + +<p>Después de esto se descarga cada 24 horas aproximadamente. Se puede descargar con más frecuencia, pero <strong>debe</strong> ser descargado cada 24 horas para prevenir que una mala programación sea molesta durante mucho tiempo.</p> + +<p>La instalación se realiza cuando el fichero descargado es nuevo, es decir, diferente a otro service worker existente (comparado byte a byte), o si es el primero descargado para esta página/sitio.</p> + +<p>Si es la primera vez que el service worker está disponible se intenta la instalación, y tras una instalación satisfactoria se activa.</p> + +<p>Si ya existe un service worker disponible la nueva versión se instala en segundo plano, pero no se activa -en ese momento se llama <em>worker in waiting.</em> Sólo se activa cuando ya no hay más páginas cargadas que utilicen el antiguo service worker. En cuanto no hay más páginas de este estilo cargadas, el nuevo service worker se activa (pasando a ser el <em>active worker).</em> La activación se puede realizar antes mediante {{domxref("ServiceWorkerGlobalScope.skipWaiting()")}} y las páginas existentes se pueden llamar por el active worker usando {{domxref("Clients.claim()")}}.</p> + +<p>Presta atención a {{domxref("InstallEvent")}}; es habitual preparar tu service worker para usarlo cuando se dispara, por ejemplo creando una caché que utilice la API incorporada de almacenamiento, y colocando los contenidos dentro de ella para poder usarlos con la aplicación offline.</p> + +<p>También hay un evento <code>activate</code>. El momento en el que este evento se activa es, en general, un bueno momento para limpiar viejas cachés y demás cosas asociadas con la versión previa de tu service worker.</p> + +<p>Tu service worker puede responder a las peticiones usando el evento {{domxref("FetchEvent")}}. Puedes modificar la respuesta a estas peticiones de la manera que quieras, usando el método {{domxref("FetchEvent.respondWith") }}.</p> + +<div class="note"> +<p><strong>Nota</strong>: Dado que <code>oninstall</code>/<code>onactivate</code> puede tardar un poco en completarse, la especificación de service worker spec provee un método <code>waitUntil</code> que, cuando es llamado <code>oninstall</code> o <code>onactivate</code>, pasa una promesa. Los eventos funcionales no se envían al service worker hasta que la promesa se resuelve con éxito.</p> +</div> + +<p>Para un tutorial completo que muestra cómo construir tu primer ejemplo básico, lee <a href="/en-US/docs/Web/API/ServiceWorker_API/Using_Service_Workers">Using Service Workers</a>.</p> + +<h2 id="Otras_posibilidades">Otras posibilidades</h2> + +<p>Los service workers también pueden usarse para cosas como:</p> + +<ul> + <li>Sincronización de datos en background</li> + <li>Responder a peticiones de recursos desde otros orígenes</li> + <li>Recibir actualizaciones centralizadas de datos costosos de calcular tales como geolocalización o giroscopio, de manera que muchas páginas puedan hacer uso de un mismo conjunto de datos</li> + <li>Compilación Client-side y gestión de dependencias de CoffeeScript, less, CJS/AMD modules, etc. para desarrollo</li> + <li>Enlace para servicios en background </li> + <li>Plantillas personalizadas basadas en ciertos patrones URL </li> + <li>Mejoras de rendimiento, por ejemplo pre-fetching de recursos que es probable que el usuario requiera en un futuro próximo, como las próximas imágenes de un album de fotos.</li> +</ul> + +<p>En el futuro, los service workers podrán hacer una cantidad de cosas útiles para la plataforma web que estarán muy próximos a las aplicaciones nativas. Interesantement, otras especificacions pueden comenzar y lo harán a hacer uso del contexto de service worker, por ejemplo:</p> + +<ul> + <li><a href="https://github.com/slightlyoff/BackgroundSync">Sincronización en background</a>: Pone en marcha un service worker aunque el usuario no esté en el sitio de manera que las cachés se puedan actualizar, etc.</li> + <li><a href="/en-US/docs/Web/API/Push_API">Reacción a mensajes tipo push</a>: Pone en marcha un service worker para enviar a los usuarios un mensaje para notificarles de que hay disponible nuevos contenidos.</li> + <li>Reacción ante una fecha y hora determinados.</li> + <li>Creación de geo-fronteras</li> +</ul> + +<h2 id="Interfaces">Interfaces</h2> + +<dl> + <dt>{{domxref("Cache") }}</dt> + <dd>Representa el almacenamiento para un par de objetos {{domxref("Request")}} / {{domxref("Response")}} que son cacheados como parte del ciclo de vida de {{domxref("ServiceWorker")}}.</dd> + <dt>{{domxref("CacheStorage") }}</dt> + <dd>Representa el almacenamiento de objetos {{domxref("Cache")}}. Proporciona un directorio maestro de todos los nombres de caché a los que puede acceder un {{domxref("ServiceWorker")}} y mantiene un mapa de nombres (strings) correspondientes a objetos {{domxref("Cache")}}.</dd> + <dt>{{domxref("Client") }}</dt> + <dd>Representa el ámbito de un cliente service worker. Un cliente service worker es bien un documento en un contexto de navador, bien un {{domxref("SharedWorker")}}, que está controlado por un worker activo.</dd> + <dt>{{domxref("Clients") }}</dt> + <dd>Representa un contenedor para una lista de objetos {{domxref("Client")}}; principal vía de acceso de los clientes service worker al origen actual.</dd> + <dt>{{domxref("ExtendableEvent") }}</dt> + <dd>Extiende el tiempo de vida de los eventos<code>install</code> y <code>activate</code> lanzados en {{domxref("ServiceWorkerGlobalScope")}} como parte del ciclo de vida del service worker. Esto asegura que cualquier evento funcional (como {{domxref("FetchEvent")}}) no se despachan al {{domxref("ServiceWorker")}} hasta que actualiza los esquemas de base de datos, borra entradas de caché antiguas, etc.</dd> + <dt>{{domxref("ExtendableMessageEvent") }}</dt> + <dd>Es el objeto evento de un {{event("message_(ServiceWorker)","message")}} lanzado en un service worker (cuando se recibe un mensaje en el {{domxref("ServiceWorkerGlobalScope")}} desde otro contexto) — extiende el tiempo de vida de tales eventos.</dd> + <dt>{{domxref("FetchEvent") }}</dt> + <dd>Parametro pasado en el controlador {{domxref("ServiceWorkerGlobalScope.onfetch")}}, <code>FetchEvent</code> representa una acción de consulta (fetch) despachada en el {{domxref("ServiceWorkerGlobalScope")}} de un {{domxref("ServiceWorker")}}. Contiene información sobre la petición y respuesta resultante, y proporciona el método {{domxref("FetchEvent.respondWith", "FetchEvent.respondWith()")}}, que nos permite proporcionar una respuesta arbitraria a la página controlada.</dd> + <dt>{{domxref("InstallEvent") }}</dt> + <dd>Parámetro pasado en el controlador {{domxref("ServiceWorkerGlobalScope.oninstall", "oninstall")}}, el interfaz<code>InstallEvent</code> representa una acctión de instalación realizada en el {{domxref("ServiceWorkerGlobalScope")}} de un {{domxref("ServiceWorker")}}. Como hijo de {{domxref("ExtendableEvent")}}, asegura que los eventos funcionales como {{domxref("FetchEvent")}} no se llevan a cabo durante la instalación. </dd> + <dt>{{domxref("Navigator.serviceWorker") }}</dt> + <dd>Devuelve un objeto {{domxref("ServiceWorkerContainer")}}, que proporciona acceso al registro, eliminación, actualización y comunicación con los objetos {{domxref("ServiceWorker")}} para el <a href="https://html.spec.whatwg.org/multipage/browsers.html#concept-document-window">documento asociado</a>.</dd> + <dt>{{domxref("NotificationEvent") }}</dt> + <dd>Parámetro pasado en el controlador {{domxref("ServiceWorkerGlobalScope.onnotificationclick", "onnotificationclick")}}, el interfaz <code>NotificationEvent</code> representa una notificación del evento click ejecutado en {{domxref("ServiceWorkerGlobalScope")}} de un {{domxref("ServiceWorker")}}.</dd> + <dt>{{domxref("ServiceWorker") }}</dt> + <dd>Representa un service worker. Multiples contextos de navegación (e.g. pages, workers, etc.) se pueden asociar con el mismo objeto <code>ServiceWorker</code>.</dd> + <dt>{{domxref("ServiceWorkerContainer") }}</dt> + <dd>Proporciona un objeto que representa el service worker como una unidad en el ecosistema de red, incluyendo servicios para registrar, eliminar y actualizar los service workers, y acceder al estado de los service workers y sus registros.</dd> + <dt>{{domxref("ServiceWorkerGlobalScope") }}</dt> + <dd>Representa el contexto global de ejecución de un service worker.</dd> + <dt>{{domxref("ServiceWorkerMessageEvent")}} {{deprecated_inline}}</dt> + <dd>Representa un mensaje envaido a un{{domxref("ServiceWorkerGlobalScope")}}. <strong>Observese que este interfaz está considerado obsoleto en navegadores modernos. Los mensajes de service worker no podrán utilizar el interfaz {{domxref("MessageEvent")}}, por consistencia con otras características de mensajería web.</strong></dd> + <dt>{{domxref("ServiceWorkerRegistration") }}</dt> + <dd>Representa un registro service worker.</dd> + <dt>{{domxref("SyncEvent")}} {{non-standard_inline}}</dt> + <dd> + <p>El interfaz SyncEvent representa una acción sync ejecutada en el {{domxref("ServiceWorkerGlobalScope")}} de un ServiceWorker. </p> + </dd> + <dt>{{domxref("SyncManager")}} {{non-standard_inline}}</dt> + <dd>Proporciona un interfaz para registrar y listar registros sync.</dd> + <dt>{{domxref("WindowClient") }}</dt> + <dd>Representa el ámbito de un cliente service worker que es un documento en un contexto de navegador, controlado por un worker activo. Es un tipo especial de objeto {{domxref("Client")}}, con algunos métodos y propiedades adicionales disponibles.</dd> +</dl> + +<h2 id="Especificaciones">Especificaciones</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('Service Workers')}}</td> + <td>{{Spec2('Service Workers')}}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2> + +<div>{{ CompatibilityTable() }}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome(40.0)}}</td> + <td>{{CompatNo}}<sup>[1]</sup></td> + <td>{{ CompatGeckoDesktop("44.0") }}<sup>[2]</sup></td> + <td>{{ CompatNo() }}</td> + <td>24</td> + <td>{{ CompatNo() }}</td> + </tr> + <tr> + <td>install/activate events</td> + <td>{{ CompatChrome(40.0) }}</td> + <td>{{CompatNo}}<sup>[1]</sup></td> + <td>{{ CompatGeckoDesktop("44.0") }}<sup>[2]</sup></td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatNo() }}</td> + </tr> + <tr> + <td>fetch event/request/<br> + <code>respondWith()</code></td> + <td>{{CompatChrome(40.0)}}</td> + <td>{{CompatNo}}<sup>[1]</sup></td> + <td>{{ CompatGeckoDesktop("44.0") }}<sup>[2]</sup></td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + </tr> + <tr> + <td>caches/cache</td> + <td> + <p class="p1">{{CompatChrome(42.0)}}</p> + </td> + <td>{{CompatNo}}<sup>[1]</sup></td> + <td>{{ CompatGeckoDesktop("39.0") }}<sup>[2]</sup></td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + </tr> + <tr> + <td>{{domxref("ServiceWorkerMessageEvent")}} deprecated in favour of {{domxref("MessageEvent")}}</td> + <td> + <p class="p1">{{CompatChrome(57.0)}}</p> + </td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatGeckoDesktop("55.0") }}<sup>[2]</sup></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 Webview</th> + <th>Chrome for Android</th> + <th>Edge</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>{{CompatChrome(40.0)}}</td> + <td>{{CompatNo}}<sup>[1]</sup></td> + <td>{{ CompatGeckoMobile("44.0") }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatNo() }}</td> + </tr> + <tr> + <td> install/activate events</td> + <td>{{ CompatNo() }}</td> + <td>{{CompatChrome(40.0)}}</td> + <td>{{CompatNo}}<sup>[1]</sup></td> + <td>{{ CompatGeckoMobile("44.0") }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatNo() }}</td> + </tr> + <tr> + <td>fetch event/request/<br> + <code>respondWith()</code></td> + <td>{{ CompatNo() }}</td> + <td>{{CompatChrome(40.0)}}</td> + <td>{{CompatNo}}<sup>[1]</sup></td> + <td>{{ CompatGeckoMobile("44.0") }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + </tr> + <tr> + <td>caches/cache</td> + <td>{{ CompatNo() }}</td> + <td>{{CompatChrome(40.0)}}</td> + <td>{{CompatNo}}<sup>[1]</sup></td> + <td>{{ CompatGeckoMobile("39.0") }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + </tr> + <tr> + <td>{{domxref("ServiceWorkerMessageEvent")}} deprecated in favour of {{domxref("MessageEvent")}}</td> + <td>{{ CompatNo() }}</td> + <td> + <p class="p1">{{CompatChrome(57.0)}}</p> + </td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatGeckoMobile("55.0") }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Esta característica aún no está soportada, aunque está <a href="https://developer.microsoft.com/en-us/microsoft-edge/platform/status/serviceworker/">ya en desarrollo</a>.</p> + +<p>[2] Service workers (y <a href="/en-US/docs/Web/API/Push_API">Push</a>) han sido inhabilitados en <a href="https://www.mozilla.org/en-US/firefox/organizations/">Firefox 45 & 52 Extended Support Releases</a> (ESR.)</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="https://serviceworke.rs">ServiceWorker Cookbook</a></li> + <li><a href="/en-US/docs/Web/API/ServiceWorker_API/Using_Service_Workers">Using Service Workers</a></li> + <li><a href="https://github.com/mdn/sw-test">Service workers basic code example</a></li> + <li><a href="https://jakearchibald.github.io/isserviceworkerready/">Is ServiceWorker ready?</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promises</a></li> + <li><a href="/en-US/docs/Web/Guide/Performance/Using_web_workers">Using web workers</a></li> + <li><a href="https://www.fastly.com/blog/best-practices-for-using-the-vary-header">Best Practices for using the VARY header</a></li> +</ul> diff --git a/files/es/web/api/service_worker_api/using_service_workers/index.html b/files/es/web/api/service_worker_api/using_service_workers/index.html new file mode 100644 index 0000000000..d687cddd19 --- /dev/null +++ b/files/es/web/api/service_worker_api/using_service_workers/index.html @@ -0,0 +1,526 @@ +--- +title: Usando Service Workers +slug: Web/API/Service_Worker_API/Using_Service_Workers +tags: + - Guía + - básico +translation_of: Web/API/Service_Worker_API/Using_Service_Workers +--- +<p>{{ServiceWorkerSidebar}}</p> + +<p>{{ SeeCompatTable() }}</p> + +<div class="summary"> +<p>Este articulo provee información sobre cómo empezar con los service workers, incluyendo su arquitectura básica, el registro de un service worker, el proceso de instalación y activación de un nuevo service worker, cómo actualizar un service worker, controlar su cache y respuestas personalizadas, todo esto en el contexto de una simple aplicación con la capacidad de trabajar offline (sin internet).</p> +</div> + +<h2 id="La_premisa_de_los_service_workers">La premisa de los service workers</h2> + +<p>Un problema primordial que los usuarios de la web han sufrido durante años es la pérdida de conectividad. La mejor aplicación web en el mundo ofrecerá una experiencia de usuario terrible si simplemente no se puede utilizar. Han habido varios intentos de crear tecnologías para resolver este problema, como muestra nuestra página <a href="https://developer.mozilla.org/en-US/Apps/Build/Offline">offline</a>, y algunos problemas han sido solucionados. Pero el problema primordial es que todavía no hay un mecanismo de control eficiente para el almacenamiento en caché de activos y solicitudes de red personalizadas.</p> + +<p>El mecanismo previamente utilizado -el AppCache- parecía una buena idea porque te permitía especificar los recursos que almacenarías en caché de una forma realmente fácil. Sin embargo, AppCache presuponía lo que el desarrollador trataba de crear y fallaba demasiado cuando la aplicación no se comportaba exactamente según las suposiciones iniciales. Veáse el artículo de Jake Archibald <a href="http://alistapart.com/article/application-cache-is-a-douchebag">Application Cache is a Douchebag</a> para más información.</p> + +<div class="note"> +<p><strong>Nota</strong>: A partir de Firefox 44, cuando se usa <a href="/en-US/docs/Web/HTML/Using_the_application_cache">AppCache</a> para proveer soporte offline a una página se muestra un mensaje de advertencia en la consola aconsejandole al desarrollador para que use <a href="/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers">Service workers</a> en su lugar ({{bug("1204581")}}.)</p> +</div> + +<p>Los Service workers deberían finalmente solucionar estos inconvenientes. Aunque la sintaxis de Service Worker es más compleja que la de AppCache, presenta la ventaja de que puede usar JavaScript para controlar los recursos de cache con gran detalle, permitiendo gestionar los problemas asociados a AppCache, y muchos más.</p> + +<p>Al utilizar un Service Worker, puedes configurar fácilmente una aplicación para que utilice primero los recursos en caché antes de obtener alguna información de la red (Comunmente conocido como <a href="/es/docs/">Offline First</a>) lo que proporciona la experiencia de uso predeterminada incluso cuando se está offline. Este paradigma se usa en aplicaciones nativas, y es una de las principales razones por las que a menudo éstas se eligen por encima de las aplicaciones web.</p> + +<h2 id="Setting_up_to_play_with_service_workers">Setting up to play with service workers</h2> + +<p>Many service workers features are now enabled by default in newer versions of supporting browsers. If however you find that demo code is not working in your installed versions, you might need to enable a pref:</p> + +<ul> + <li><strong>Firefox Nightly</strong>: Go to <code>about:config</code> and set <code>dom.serviceWorkers.enabled</code> to true; restart browser.</li> + <li><strong>Chrome Canary</strong>: Go to <code>chrome://flags</code> and turn on <code>experimental-web-platform-features</code>; restart browser (note that some features are now enabled by default in Chrome.)</li> + <li><strong>Opera</strong>: Go to <code>opera://flags</code> and enable <code>Support for ServiceWorker</code>; restart browser.</li> +</ul> + +<p>You’ll also need to serve your code via HTTPS — Service workers are restricted to running across HTTPS for security reasons. GitHub is therefore a good place to host experiments, as it supports HTTPS. In order to facilitate local development, <code>localhost</code> is considered a secure origin by browsers as well.</p> + +<h2 id="Basic_architecture">Basic architecture</h2> + +<p>With service workers, the following steps are generally observed for basic set up:</p> + +<ol> + <li>The service worker URL is fetched and registered via {{domxref("serviceWorkerContainer.register()")}}.</li> + <li>If successful, the service worker is executed in a {{domxref("ServiceWorkerGlobalScope") }}; this is basically a special kind of worker context, running off the main script execution thread, with no DOM access.</li> + <li>The service worker is now ready to process events.</li> + <li>Installation of the worker is attempted when service worker-controlled pages are accessed subsequently. An Install event is always the first one sent to a service worker (this can be used to start the process of populating an IndexedDB, and caching site assets). This is really the same kind of procedure as installing a native or Firefox OS app — making everything available for use offline.</li> + <li>When the <code>oninstall</code> handler completes, the service worker is considered installed.</li> + <li>Next is activation. When the service worker is installed, it then receives an activate event. The primary use of <code>onactivate</code> is for cleanup of resources used in previous versions of a Service worker script.</li> + <li>The Service worker will now control pages, but only those opened after the <code>register()</code> is successful. i.e. a document starts life with or without a Service worker and maintains that for its lifetime. So documents will have to be reloaded to actually be controlled.</li> +</ol> + +<p><img alt="" src="https://mdn.mozillademos.org/files/12636/sw-lifecycle.png" style="display: block; height: 867px; margin: 0px auto; width: 579px;"></p> + +<p>The below graphic shows a summary of the available service worker events:</p> + +<p><img alt="install, activate, message, fetch, sync, push" src="https://mdn.mozillademos.org/files/12632/sw-events.png" style="display: block; margin: 0px auto;"></p> + +<h3 id="Promises">Promises</h3> + +<p>Las promesas (<a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promises</a>) son un gran mecanismo para ejecutar operaciones asíncronas, con éxito dependiente el uno del otro. Esto es fundamental para la forma en que trabajan los service workers.<br> + <br> + Promises can do a great many things, but for now, all you need to know is that if something returns a promise, you can attach <code>.then()</code> to the end and include callbacks inside it for success, failure, etc., or you can insert <code>.catch()</code> on the end if you want to include a failure callback.</p> + +<p>Let’s compare a traditional synchronous callback structure to its asynchronous promise equivalent.</p> + +<h4 id="sync">sync</h4> + +<pre class="brush: js">try { + var value = myFunction(); + console.log(value); +} catch(err) { + console.log(err); +}</pre> + +<h4 id="async">async</h4> + +<pre class="brush: js">myFunction().then(function(value) { + console.log(value); +}).catch(function(err) { + console.log(err); +});</pre> + +<p>In the first example, we have to wait for <code>myFunction()</code> to run and return <code>value</code> before any more of the code can execute. In the second example, <code>myFunction()</code> returns a promise for <code>value</code>, then the rest of the code can carry on running. When the promise resolves, the code inside <code>then</code> will be run, asynchronously.<br> + <br> + Now for a real example — what if we wanted to load images dynamically, but we wanted to make sure the images were loaded before we tried to display them? This is a standard thing to want to do, but it can be a bit of a pain. We can use <code>.onload</code> to only display the image after it’s loaded, but what about events that start happening before we start listening to them? We could try to work around this using <code>.complete</code>, but it’s still not foolproof, and what about multiple images? And, ummm, it’s still synchronous, so blocks the main thread.<br> + <br> + Instead, we could build our own promise to handle this kind of case. (See our <a href="https://github.com/mdn/promises-test">Promises test</a> example for the source code, or <a href="https://mdn.github.io/promises-test/">look at it running live</a>.)</p> + +<p>{{note("A real service worker implementation would use caching and onfetch rather than the deprecated XMLHttpRequest API. Those features are not used here so that you can focus on understanding Promises.")}}</p> + +<pre class="brush: js">function imgLoad(url) { + return new Promise(function(resolve, reject) { + var request = new XMLHttpRequest(); + request.open('GET', url); + request.responseType = 'blob'; + + request.onload = function() { + if (request.status == 200) { + resolve(request.response); + } else { + reject(Error('Image didn\'t load successfully; error code:' + request.statusText)); + } + }; + + request.onerror = function() { + reject(Error('There was a network error.')); + }; + + request.send(); + }); +}</pre> + +<p>We return a new promise using the <code>Promise()</code> constructor, which takes as an argument a callback function with <code>resolve</code> and <code>reject</code> parameters. Somewhere in the function, we need to define what happens for the promise to resolve successfully or be rejected — in this case return a 200 OK status or not — and then call <code>resolve</code> on success, or <code>reject</code> on failure. The rest of the contents of this function is fairly standard XHR stuff, so we won’t worry about that for now.</p> + +<p>When we come to call the <code>imgLoad()</code> function, we call it with the url to the image we want to load, as we might expect, but the rest of the code is a little different:</p> + +<pre class="brush: js">var body = document.querySelector('body'); +var myImage = new Image(); + +imgLoad('myLittleVader.jpg').then(function(response) { + var imageURL = window.URL.createObjectURL(response); + myImage.src = imageURL; + body.appendChild(myImage); +}, function(Error) { + console.log(Error); +});</pre> + +<p>On to the end of the function call, we chain the promise <code>then()</code> method, which contains two functions — the first one is executed when the promise successfully resolves, and the second is called when the promise is rejected. In the resolved case, we display the image inside <code>myImage</code> and append it to the body (it’s argument is the <code>request.response</code> contained inside the promise’s <code>resolve</code> method); in the rejected case we return an error to the console.</p> + +<p>This all happens asynchronously.</p> + +<div class="note"> +<p><strong>Note</strong>: You can also chain promise calls together, for example:<br> + <code>myPromise().then(success, failure).then(success).catch(failure);</code></p> +</div> + +<div class="note"> +<p><strong>Note</strong>: You can find a lot more out about promises by reading Jake Archibald’s excellent <a href="http://www.html5rocks.com/en/tutorials/es6/promises/">JavaScript Promises: there and back again</a>.</p> +</div> + +<h2 id="Service_workers_demo">Service workers demo</h2> + +<p>To demonstrate just the very basics of registering and installing a service worker, we have created a simple demo called <a href="https://github.com/mdn/sw-test">sw-test</a>, which is a simple Star wars Lego image gallery. It uses a promise-powered function to read image data from a JSON object and load the images using Ajax, before displaying the images in a line down the page. We’ve kept things static and simple for now. It also registers, installs, and activates a service worker, and when more of the spec is supported by browsers it will cache all the files required so it will work offline!</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/8243/demo-screenshot.png" style="display: block; height: 410px; margin: 0px auto; width: 480px;"><br> + <br> + <br> + You can see the <a href="https://github.com/mdn/sw-test/">source code on GitHub</a>, and <a href="https://mdn.github.io/sw-test/">view the example live</a>. The one bit we’ll call out here is the promise (see <a href="https://github.com/mdn/sw-test/blob/gh-pages/app.js#L22-L47">app.js lines 22-47</a>), which is a modified version of what you read about above, in the <a href="https://github.com/mdn/promises-test">Promises test demo</a>. It is different in the following ways:</p> + +<ol> + <li>In the original, we only passed in a URL to an image we wanted to load. In this version, we pass in a JSON fragment containing all the data for a single image (see what they look like in <a href="https://github.com/mdn/sw-test/blob/gh-pages/image-list.js">image-list.js</a>). This is because all the data for each promise resolve has to be passed in with the promise, as it is asynchronous. If you just passed in the url, and then tried to access the other items in the JSON separately when the <code>for()</code> loop is being iterated through later on, it wouldn’t work, as the promise wouldn’t resolve at the same time as the iterations are being done (that is a synchronous process.)</li> + <li>We actually resolve the promise with an array, as we want to make the loaded image blob available to the resolving function later on in the code, but also the image name, credits and alt text (see <a href="https://github.com/mdn/sw-test/blob/gh-pages/app.js#L31-L34">app.js lines 31-34</a>). Promises will only resolve with a single argument, so if you want to resolve with multiple values, you need to use an array/object.</li> + <li>To access the resolved promise values, we then access this function as you’d then expect (see <a href="https://github.com/mdn/sw-test/blob/gh-pages/app.js#L60-L64">app.js lines 60-64</a>). This may seem a bit odd at first, but this is the way promises work.</li> +</ol> + +<h2 id="Enter_service_workers">Enter service workers</h2> + +<p>Now let’s get on to service workers!</p> + +<h3 id="Registering_your_worker">Registering your worker</h3> + +<p>The first block of code in our app’s JavaScript file — <code>app.js</code> — is as follows. This is our entry point into using service workers.</p> + +<pre class="brush: js">if ('serviceWorker' in navigator) { + navigator.serviceWorker.register('/sw-test/sw.js', {scope: '/sw-test/'}) + .then(function(reg) { + // registration worked + console.log('Registration succeeded. Scope is ' + reg.scope); + }).catch(function(error) { + // registration failed + console.log('Registration failed with ' + error); + }); +}</pre> + +<ol> + <li>The outer block performs a feature detection test to make sure service workers are supported before trying to register one.</li> + <li>Next, we use the {{domxref("ServiceWorkerContainer.register()") }} function to register the service worker for this site, which is just a JavaScript file residing inside our app (note this is the file's URL relative to the origin, not the JS file that references it.)</li> + <li>The <code>scope</code> parameter is optional, and can be used to specify the subset of your content that you want the service worker to control. In this case, we have specified '<code>/sw-test/'</code>, which means all content under the app's origin. If you leave it out, it will default to this value anyway, but we specified it here for illustration purposes.</li> + <li>The <code>.then()</code> promise function is used to chain a success case onto our promise structure. When the promise resolves successfully, the code inside it executes.</li> + <li>Finally, we chain a <code>.catch()</code> function onto the end that will run if the promise is rejected.</li> +</ol> + +<p>This registers a service worker, which runs in a worker context, and therefore has no DOM access. You then run code in the service worker outside of your normal pages to control their loading.<br> + <br> + A single service worker can control many pages. Each time a page within your scope is loaded, the service worker is installed against that page and operates on it. Bear in mind therefore that you need to be careful with global variables in the service worker script: each page doesn’t get its own unique worker.</p> + +<div class="note"> +<p><strong>Note</strong>: Your service worker functions like a proxy server, allowing you to modify requests and responses, replace them with items from its own cache, and more.</p> +</div> + +<div class="note"> +<p><strong>Note</strong>: One great thing about service workers is that if you use feature detection like we’ve shown above, browsers that don’t support service workers can just use your app online in the normal expected fashion. Furthermore, if you use AppCache and SW on a page, browsers that don’t support SW but do support AppCache will use that, and browsers that support both will ignore the AppCache and let SW take over.</p> +</div> + +<h4 id="Why_is_my_service_worker_failing_to_register">Why is my service worker failing to register?</h4> + +<p>This could be for the following reasons:</p> + +<ol> + <li>You are not running your application through HTTPS.</li> + <li>The path to your service worker file is not written correctly — it needs to be written relative to the origin, not your app’s root directory. In our example, the worker is at <code>https://mdn.github.io/sw-test/sw.js</code>, and the app’s root is <code>https://mdn.github.io/sw-test/</code>. But the path needs to be written as <code>/sw-test/sw.js</code>, not <code>/sw.js</code>.</li> + <li>The service worker being pointed to is on a different origin to that of your app. This is also not allowed.</li> +</ol> + +<p><img alt="" src="https://mdn.mozillademos.org/files/12630/important-notes.png" style="display: block; height: 277px; margin: 0px auto; width: 574px;"></p> + +<p>Also note:</p> + +<ul> + <li>The service worker will only catch requests from clients under the service worker's scope.</li> + <li>The max scope for a service worker is the location of the worker.</li> + <li>If your server worker is active on a client being served with the <code>Service-Worker-Allowed</code> header, you can specify a list of max scopes for that worker.</li> + <li>In Firefox, Service Worker APIs are hidden and cannot be used when the user is in <a href="https://support.mozilla.org/en-US/kb/private-browsing-use-firefox-without-history">private browsing mode</a>.</li> +</ul> + +<h3 id="Install_and_activate_populating_your_cache">Install and activate: populating your cache</h3> + +<p>After your service worker is registered, the browser will attempt to install then activate the service worker for your page/site.<br> + <br> + The install event is fired when an install is successfully completed. The install event is generally used to populate your browser’s offline caching capabilities with the assets you need to run your app offline. To do this, we use Service Worker’s brand new storage API — {{domxref("cache")}} — a global on the service worker that allows us to store assets delivered by responses, and keyed by their requests. This API works in a similar way to the browser’s standard cache, but it is specific to your domain. It persists until you tell it not to — again, you have full control.</p> + +<div class="note"> +<p><strong>Note</strong>: The Cache API is not supported in every browser. (See the {{anch("Browser support")}} section for more information.) If you want to use this now, you could consider using a polyfill like the one available in <a href="https://github.com/Polymer/topeka/blob/master/sw.js">Google's Topeka demo</a>, or perhaps store your assets in <a href="/en-US/docs/Web/API/IndexedDB_API">IndexedDB</a>.</p> +</div> + +<p>Let’s start this section by looking at a code sample — this is the <a href="https://github.com/mdn/sw-test/blob/gh-pages/sw.js#L1-L18">first block you’ll find in our service worker</a>:</p> + +<pre class="brush: js">this.addEventListener('install', function(event) { + event.waitUntil( + caches.open('v1').then(function(cache) { + return cache.addAll([ + '/sw-test/', + '/sw-test/index.html', + '/sw-test/style.css', + '/sw-test/app.js', + '/sw-test/image-list.js', + '/sw-test/star-wars-logo.jpg', + '/sw-test/gallery/', + '/sw-test/gallery/bountyHunters.jpg', + '/sw-test/gallery/myLittleVader.jpg', + '/sw-test/gallery/snowTroopers.jpg' + ]); + }) + ); +});</pre> + +<ol> + <li>Here we add an <code>install</code> event listener to the service worker (hence <code>this</code>), and then chain a {{domxref("ExtendableEvent.waitUntil()") }} method onto the event — this ensures that the service worker will not install until the code inside <code>waitUntil()</code> has successfully occurred.</li> + <li>Inside <code>waitUntil()</code> we use the <a href="/en-US/docs/Web/API/CacheStorage/open"><code>caches.open()</code></a> method to create a new cache called <code>v1</code>, which will be version 1 of our site resources cache. This returns a promise for a created cache; once resolved, we then call a function that calls <code>addAll()</code> on the created cache, which for its parameter takes an array of origin-relative URLs to all the resources you want to cache.</li> + <li>If the promise is rejected, the install fails, and the worker won’t do anything. This is ok, as you can fix your code and then try again the next time registration occurs.</li> + <li>After a successful installation, the service worker activates. This doesn’t have much of a distinct use the first time your service worker is installed/activated, but it means more when the service worker is updated (see the {{anch("Updating your service worker") }} section later on.)</li> +</ol> + +<div class="note"> +<p><strong>Note</strong>: <a href="/en-US/docs/Web/Guide/API/DOM/Storage">localStorage</a> works in a similar way to service worker cache, but it is synchronous, so not allowed in service workers.</p> +</div> + +<div class="note"> +<p><strong>Note</strong>: <a href="/en-US/docs/Web/API/IndexedDB_API">IndexedDB</a> can be used inside a service worker for data storage if you require it.</p> +</div> + +<h3 id="Custom_responses_to_requests">Custom responses to requests</h3> + +<p>Now you’ve got your site assets cached, you need to tell service workers to do something with the cached content. This is easily done with the <code>fetch</code> event.</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/12634/sw-fetch.png" style="display: block; margin: 0 auto;"></p> + +<p>A <code>fetch</code> event fires every time any resource controlled by a service worker is fetched, which includes the documents inside the specified scope, and any resources referenced in those documents (for example if <code>index.html</code> makes a cross origin request to embed an image, that still goes through its service worker.)</p> + +<p>You can attach a <code>fetch</code> event listener to the service worker, then call the <code>respondWith()</code> method on the event to hijack our HTTP responses and update them with your own magic.</p> + +<pre class="brush: js">this.addEventListener('fetch', function(event) { + event.respondWith( + // magic goes here + ); +});</pre> + +<p>We could start by simply responding with the resource whose url matches that of the network request, in each case:</p> + +<pre class="brush: js">this.addEventListener('fetch', function(event) { + event.respondWith( + caches.match(event.request) + ); +});</pre> + +<p><code>caches.match(event.request)</code> allows us to match each resource requested from the network with the equivalent resource available in the cache, if there is a matching one available. The matching is done via url and vary headers, just like with normal HTTP requests.</p> + +<p>Let’s look at a few other options we have when defining our magic (see our <a href="/en-US/docs/Web/API/Fetch_API">Fetch API documentation</a> for more information about {{domxref("Request")}} and {{domxref("Response")}} objects.)</p> + +<ol> + <li> + <p>The <code>{{domxref("Response.Response","Response()")}}</code> constructor allows you to create a custom response. In this case, we are just returning a simple text string:</p> + + <pre class="brush: js">new Response('Hello from your friendly neighbourhood service worker!');</pre> + </li> + <li> + <p>This more complex <code>Response</code> below shows that you can optionally pass a set of headers in with your response, emulating standard HTTP response headers. Here we are just telling the browser what the content type of our synthetic response is:</p> + + <pre class="brush: js">new Response('<p>Hello from your friendly neighbourhood service worker!</p>', { + headers: { 'Content-Type': 'text/html' } +});</pre> + </li> + <li> + <p>If a match wasn’t found in the cache, you could tell the browser to simply {{domxref("GlobalFetch.fetch","fetch")}} the default network request for that resource, to get the new resource from the network if it is available:</p> + + <pre class="brush: js">fetch(event.request);</pre> + </li> + <li> + <p>If a match wasn’t found in the cache, and the network isn’t available, you could just match the request with some kind of default fallback page as a response using {{domxref("CacheStorage.match","match()")}}, like this:</p> + + <pre class="brush: js">caches.match('/fallback.html');</pre> + </li> + <li> + <p>You can retrieve a lot of information about each request by calling parameters of the {{domxref("Request")}} object returned by the {{domxref("FetchEvent")}}:</p> + + <pre class="brush: js">event.request.url +event.request.method +event.request.headers +event.request.body</pre> + </li> +</ol> + +<h2 id="Recovering_failed_requests">Recovering failed requests</h2> + +<p>So <code>caches.match(event.request)</code> is great when there is a match in the service worker cache, but what about cases when there isn’t a match? If we didn’t provide any kind of failure handling, our promise would resolve with <code>undefined</code> and we wouldn't get anything returned.</p> + +<p>Fortunately service workers’ promise-based structure makes it trivial to provide further options towards success. We could do this:</p> + +<pre class="brush: js">this.addEventListener('fetch', function(event) { + event.respondWith( + caches.match(event.request).then(function(response) { + return response || fetch(event.request); + }) + ); +});</pre> + +<p>If the resources isn't in the cache, it is requested from the network.</p> + +<p>If we were being really clever, we would not only request the resource from the network; we would also save it into the cache so that later requests for that resource could be retrieved offline too! This would mean that if extra images were added to the Star Wars gallery, our app could automatically grab them and cache them. The following would do the trick:</p> + +<pre class="brush: js">this.addEventListener('fetch', function(event) { + event.respondWith( + caches.match(event.request).then(function(resp) { + return resp || fetch(event.request).then(function(response) { + return caches.open('v1').then(function(cache) { + cache.put(event.request, response.clone()); + return response; + }); + }); + }) + ); +});</pre> + +<p>Here we return the default network request with <code>return fetch(event.request)</code>, which returns a promise. When this promise is resolved, we respond by running a function that grabs our cache using <code>caches.open('v1')</code>; this also returns a promise. When that promise resolves, <code>cache.put()</code> is used to add the resource to the cache. The resource is grabbed from <code>event.request</code>, and the response is then cloned with <code>response.clone()</code> and added to the cache. The clone is put in the cache, and the original response is returned to the browser to be given to the page that called it.</p> + +<p>Cloning the response is necessary because request and response streams can only be read once. In order to return the response to the browser and put it in the cache we have to clone it. So the original gets returned to the browser and the clone gets sent to the cache. They are each read once.</p> + +<p>The only trouble we have now is that if the request doesn’t match anything in the cache, and the network is not available, our request will still fail. Let’s provide a default fallback so that whatever happens, the user will at least get something:</p> + +<pre class="brush: js">this.addEventListener('fetch', function(event) { + event.respondWith( + caches.match(event.request).then(function(resp) { + return resp || fetch(event.request).then(function(response) { + caches.open('v1').then(function(cache) { + cache.put(event.request, response.clone()); + }); + return response; + }); + }).catch(function() { + return caches.match('/sw-test/gallery/myLittleVader.jpg'); + }) + ); +});</pre> + +<p>We have opted for this fallback image because the only updates that are likely to fail are new images, as everything else is depended on for installation in the <code>install</code> event listener we saw earlier.</p> + +<h2 id="Updating_your_service_worker"><a id="Updating your service worker" name="Updating your service worker">Updating your service worker</a></h2> + +<p>If your service worker has previously been installed, but then a new version of the worker is available on refresh or page load, the new version is installed in the background, but not yet activated. It is only activated when there are no longer any pages loaded that are still using the old service worker. As soon as there are no more such pages still loaded, the new service worker activates.</p> + +<p>You’ll want to update your <code>install</code> event listener in the new service worker to something like this (notice the new version number):</p> + +<pre class="brush: js">this.addEventListener('install', function(event) { + event.waitUntil( + caches.open('v2').then(function(cache) { + return cache.addAll([ + '/sw-test/', + '/sw-test/index.html', + '/sw-test/style.css', + '/sw-test/app.js', + '/sw-test/image-list.js', + + … + + // include other new resources for the new version... + ]); + }) + ); +});</pre> + +<p>While this happens, the previous version is still responsible for fetches. The new version is installing in the background. We are calling the new cache <code>v2</code>, so the previous <code>v1</code> cache isn't disturbed.</p> + +<p>When no pages are using the current version, the new worker activates and becomes responsible for fetches.</p> + +<h3 id="Deleting_old_caches">Deleting old caches</h3> + +<p>You also get an <code>activate</code> event. This is a generally used to do stuff that would have broken the previous version while it was still running, for example getting rid of old caches. This is also useful for removing data that is no longer needed to avoid filling up too much disk space — each browser has a hard limit on the amount of cache storage that a given service worker can use. The browser does its best to manage disk space, but it may delete the Cache storage for an origin. The browser will generally delete all of the data for an origin or none of the data for an origin.</p> + +<p>Promises passed into <code>waitUntil()</code> will block other events until completion, so you can rest assured that your clean-up operation will have completed by the time you get your first <code>fetch</code> event on the new cache.</p> + +<pre class="brush: js">this.addEventListener('activate', function(event) { + var cacheWhitelist = ['v2']; + + event.waitUntil( + caches.keys().then(function(keyList) { + return Promise.all(keyList.map(function(key) { + if (cacheWhitelist.indexOf(key) === -1) { + return caches.delete(key); + } + })); + }) + ); +});</pre> + +<h2 id="Developer_tools">Developer tools</h2> + +<p>Chrome has <code>chrome://inspect/#service-workers</code>, which shows current service worker activity and storage on a device, and <code>chrome://serviceworker-internals</code>, which shows more detail and allows you to start/stop/debug the worker process. In the future they will have throttling/offline modes to simulate bad or non-existent connections, which will be a really good thing.</p> + +<p>Firefox has also started to implement some useful tools related to service workers:</p> + +<ul> + <li>You can navigate to <code><a href="/en-US/docs/Tools/about:debugging">about:debugging</a></code> to see what SWs are registered and update/remove them.</li> + <li>When testing you can get around the HTTPS restriction by checking the "Enable Service Workers over HTTP (when toolbox is open)" option in the <a href="/en-US/docs/Tools/Settings">Firefox Developer Tools settings</a>.</li> +</ul> + +<div class="note"> +<p><strong>Note</strong>: You may serve your app from <code>http://localhost</code> (e.g. using <code>me@localhost:/my/app$ <strong>python -m SimpleHTTPServer</strong></code>) for local development. See <a href="https://www.w3.org/TR/service-workers/#security-considerations">Security considerations</a></p> +</div> + +<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('Service Workers', '')}}</td> + <td>{{Spec2('Service 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>{{CompatChrome(40.0)}}</td> + <td>{{ CompatGeckoDesktop("33.0") }}<sup>[1]</sup></td> + <td>{{CompatNo}}</td> + <td>24</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android Webview</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(40.0)}}</td> + <td>{{ CompatVersionUnknown }}</td> + <td>{{ CompatVersionUnknown }}</td> + <td>{{CompatNo}}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Service workers (and <a href="/en-US/docs/Web/API/Push_API">Push</a>) have been disabled in the <a href="https://www.mozilla.org/en-US/firefox/organizations/">Firefox 45 Extended Support Release</a> (ESR.)</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="https://serviceworke.rs/">The Service Worker Cookbook</a></li> + <li><a href="https://jakearchibald.github.io/isserviceworkerready/">Is ServiceWorker ready?</a></li> + <li>Download the <a href="https://mdn.mozillademos.org/files/12638/sw101.png">Service Workers 101 cheatsheet</a>.</li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promises</a></li> + <li><a href="/en-US/docs/Web/Guide/Performance/Using_web_workers">Using web workers</a></li> +</ul> diff --git a/files/es/web/api/serviceworkercontainer/index.html b/files/es/web/api/serviceworkercontainer/index.html new file mode 100644 index 0000000000..36eca36006 --- /dev/null +++ b/files/es/web/api/serviceworkercontainer/index.html @@ -0,0 +1,127 @@ +--- +title: ServiceWorkerContainer +slug: Web/API/ServiceWorkerContainer +tags: + - API + - Draft + - Interface + - NeedsTranslation + - Offline + - Reference + - Service Workers + - Service worker API + - ServiceWorkerContainer + - TopicStub + - Workers +translation_of: Web/API/ServiceWorkerContainer +--- +<p>{{SeeCompatTable}}{{APIRef("Service Workers API")}}</p> + +<p><span class="seoSummary">The <code>ServiceWorkerContainer</code> interface of the <a href="https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker_API">ServiceWorker API</a> provides an object representing the service worker as an overall unit in the network ecosystem, including facilities to register, unregister and update service workers, and access the state of service workers and their registrations.</span></p> + +<p>Most importantly, it exposes the {{domxref("ServiceWorkerContainer.register", "ServiceWorkerContainer.register()")}} method used to register service workers, and the {{domxref("ServiceWorkerContainer.controller")}} property used to determine whether or not the current page is actively controlled.</p> + +<h2 id="Properties">Properties</h2> + +<dl> + <dt>{{domxref("ServiceWorkerContainer.controller")}} {{readonlyinline}}</dt> + <dd>Returns a {{domxref("ServiceWorker")}} object if its state is <code>activated</code> (the same object returned by {{domxref("ServiceWorkerRegistration.active")}}). This property returns <code>null</code> during a force-refresh request (<em>Shift</em> + refresh) or if there is no active worker.</dd> +</dl> + +<dl> + <dt>{{domxref("ServiceWorkerContainer.ready")}} {{readonlyinline}}</dt> + <dd>Provides a way of delaying code execution until a service worker is active. It returns a {{jsxref("Promise")}} that will never reject, and which waits indefinitely until the {{domxref("ServiceWorkerRegistration")}} associated with the current page has an {{domxref("ServiceWorkerRegistration.active")}} worker. Once that condition is met, it resolves with the {{domxref("ServiceWorkerRegistration")}}.</dd> +</dl> + +<h3 id="Event_handlers">Event handlers</h3> + +<dl> + <dt>{{domxref("ServiceWorkerContainer.oncontrollerchange")}}</dt> + <dd>Fired whenever a {{Event("controllerchange")}} event occurs — when the document's associated {{domxref("ServiceWorkerRegistration")}} acquires a new {{domxref("ServiceWorkerRegistration.active","active")}} worker.</dd> + <dt>{{domxref("ServiceWorkerContainer.onerror")}}</dt> + <dd>Fired whenever an {{Event("error")}} event occurs in the associated service workers.</dd> + <dt>{{domxref("ServiceWorkerContainer.onmessage")}}</dt> + <dd>Fired whenever a {{Event("message")}} event occurs — when incoming messages are received to the {{domxref("ServiceWorkerContainer")}} object (e.g. via a {{domxref("MessagePort.postMessage()")}} call.)</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<dl> + <dt>{{domxref("ServiceWorkerContainer.register", "ServiceWorkerContainer.register()")}} </dt> + <dd>Creates or updates a {{domxref("ServiceWorkerRegistration")}} for the given <code>scriptURL</code>.</dd> + <dt>{{domxref("ServiceWorkerContainer.getRegistration()")}}</dt> + <dd>Gets a {{domxref("ServiceWorkerRegistration")}} object whose scope matches the provided document URL. If the method can't return a {{domxref("ServiceWorkerRegistration")}}, it returns a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" title="The Promise object is used for deferred and asynchronous computations. A Promise is in one of the three states:"><code>Promise</code></a>. </dd> + <dt>{{domxref("ServiceWorkerContainer.getRegistrations()")}}</dt> + <dd>Returns all {{domxref("ServiceWorkerRegistration")}} objects associated with a <code>ServiceWorkerContainer</code> in an array. If the method can't return {{domxref("ServiceWorkerRegistration")}} objects, it returns a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" title="The Promise object is used for deferred and asynchronous computations. A Promise is in one of the three states:"><code>Promise</code></a>. </dd> +</dl> + +<h2 id="Examples">Examples</h2> + +<p>The example below first checks to see if the browser supports service workers. If supported, the code registers the service worker and determines if the page is actively controlled by the service worker. If it isn't, it prompts the user to reload the page so the service worker can take control. The code also reports any registration failures.</p> + +<pre class="brush: js">if ('serviceWorker' in navigator) { + // Register a service worker hosted at the root of the + // site using the default scope. + navigator.serviceWorker.register('/sw.js').then(function(registration) { + console.log('Service worker registration succeeded:', registration); + + // At this point, you can optionally do something + // with registration. See https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration + }).catch(function(error) { + console.log('Service worker registration failed:', error); + }); + + // Independent of the registration, let's also display + // information about whether the current page is controlled + // by an existing service worker, and when that + // controller changes. + + // First, do a one-off check if there's currently a + // service worker in control. + if (navigator.serviceWorker.controller) { + console.log('This page is currently controlled by:', navigator.serviceWorker.controller); + } + + // Then, register a handler to detect when a new or + // updated service worker takes control. + navigator.serviceWorker.oncontrollerchange = function() { + console.log('This page is now controlled by:', navigator.serviceWorker.controller); + }; +} else { + console.log('Service workers are not supported.'); +}</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('Service Workers', '#service-worker-container', 'ServiceWorkerContainer')}}</td> + <td>{{Spec2('Service Workers')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("api.ServiceWorkerContainer")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker_API/Using_Service_Workers">Using Service Workers</a></li> + <li><a class="external external-icon" href="https://github.com/mdn/sw-test">Service workers basic code example</a></li> + <li><a class="external external-icon" href="https://jakearchibald.github.io/isserviceworkerready/">Is ServiceWorker ready?</a></li> + <li>{{jsxref("Promise")}}</li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/Guide/Performance/Using_web_workers">Using web workers</a></li> +</ul> diff --git a/files/es/web/api/serviceworkercontainer/register/index.html b/files/es/web/api/serviceworkercontainer/register/index.html new file mode 100644 index 0000000000..c5b1d3ed8a --- /dev/null +++ b/files/es/web/api/serviceworkercontainer/register/index.html @@ -0,0 +1,92 @@ +--- +title: ServiceWorkerContainer.register() +slug: Web/API/ServiceWorkerContainer/register +translation_of: Web/API/ServiceWorkerContainer/register +--- +<div>{{SeeCompatTable}}{{APIRef("Service Workers API")}}</div> + +<p><span class="seoSummary">El método <strong><code>register()</code></strong>de la interfaz {{domxref("ServiceWorkerContainer")}} crea o actualiza un {{domxref("ServiceWorkerRegistration")}} para un <code>scriptURL</code>. dado</span></p> + +<p>Si tiene éxito, el registro de un "service worker" relaciona la URL del script proporcionada con un ámbito, que posteriormente se utiliza para la coincidencia de navegación. Puede llamar a este método incondicionalmente desde la página controlada. Es decir, no necesita verificar primero si hay un registro activo.</p> + +<p>Existe una confusión frecuente en torno al significado y uso del alcance. Dado que un trabajador de servicio no puede tener un alcance más amplio que su propia ubicación, solo use la opción de ámbito cuando necesite un alcance que sea más estrecho que el predeterminado.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">ServiceWorkerContainer.register(scriptURL, options) + .then(function(ServiceWorkerRegistration) { ... });</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code>scriptURL</code></dt> + <dd>La URL del script de trabajador de servicio.</dd> + <dt><code>options</code> <code>{{optional_inline}}</code></dt> + <dd>Un objeto que contiene opciones de registro. Las opciones disponibles actualmente son: + <ul> + <li><code>alcance</code>: {{domxref("USVString")}} representa una URL que define el alcance de registro de un "service worker"; es decir, qué rango de URL puede controlar un "service worker". Esto es generalmente una URL relativa. El valor predeterminado es la URL que obtendría si resolviera './' utilizando la ubicación de la página web como base. No es, como se cree comúnmente, relativo a la ubicación del "service worker". Vea la sección de Ejemplos para más información sobre cómo funciona.</li> + </ul> + </dd> +</dl> + +<h3 id="Valor_retornado">Valor retornado</h3> + +<p>A {{domxref("Promise")}} that resolves with a {{domxref("ServiceWorkerRegistration")}} object.</p> + +<h2 id="Ejemplos">Ejemplos</h2> + +<p>The examples described here should be taken together to get a better understanding of how service workers scope applies to a page.</p> + +<p>The following example uses the default value of <code>scope</code> (by omitting it). The service worker in this case will control <code>example.com/index.html</code> as well as pages underneath it, like <code>example.com/product/description.html</code>.</p> + +<pre class="brush: js">if ('serviceWorker' in navigator) { + // Register a service worker hosted at the root of the + // site using the default scope. + navigator.serviceWorker.register('/sw.js').then(function(registration) { + console.log('Service worker registration succeeded:', registration); + }).catch(function(error) { + console.log('Service worker registration failed:', error); + }); +} else { + console.log('Service workers are not supported.'); +}</pre> + +<p>The following code, if included in a page at the root of a site, would apply to exactly the same pages as the example above. Remember the scope, when included, uses the page's location as its base. Alternatively, if this code were included in a page at <code>example.com/product/description.html</code>, the scope of <code>'./'</code> would mean that the service worker only applies to resources under <code>example.com/product</code>. If I needed to register a service worker on <code>example.com/product/description.html</code> that applied to all of <code>example.com</code>, I would leave off the scope as above.</p> + +<pre class="brush: js">if ('serviceWorker' in navigator) { + // Register a service worker hosted at the root of the + // site using a more restrictive scope. + navigator.serviceWorker.register('/sw.js', {scope: './'}).then(function(registration) { + console.log('Service worker registration succeeded:', registration); + }).catch(function(error) { + console.log('Service worker registration failed:', error); + }); +} else { + console.log('Service workers are not supported.'); +} +</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('Service Workers', '#service-worker-container', 'ServiceWorkerContainer')}}</td> + <td>{{Spec2('Service Workers')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("api.ServiceWorkerContainer.register")}}</p> +</div> diff --git a/files/es/web/api/serviceworkerregistration/index.html b/files/es/web/api/serviceworkerregistration/index.html new file mode 100644 index 0000000000..88f1c3da52 --- /dev/null +++ b/files/es/web/api/serviceworkerregistration/index.html @@ -0,0 +1,145 @@ +--- +title: ServiceWorkerRegistration +slug: Web/API/ServiceWorkerRegistration +tags: + - API + - Interface + - NeedsTranslation + - Offline + - Reference + - Service Workers + - Service worker API + - ServiceWorkerRegistration + - TopicStub + - Workers +translation_of: Web/API/ServiceWorkerRegistration +--- +<div> +<div>{{SeeCompatTable}}{{APIRef("Service Workers API")}}</div> +</div> + +<p><span class="seoSummary">The <code>ServiceWorkerRegistration</code> interface of the <a href="/en-US/docs/Web/API/ServiceWorker_API">ServiceWorker API</a> represents the service worker registration. You register a service worker to control one or more pages that share the same origin.</span></p> + +<p>The lifetime of a service worker registration is beyond that of the <code>ServiceWorkerRegistration</code> objects that represent them within the lifetime of their corresponding service worker clients. The browser maintains a persistent list of active <code>ServiceWorkerRegistration</code> objects.</p> + +<div class="note"> +<p><strong>Note</strong>: This feature is available in <a href="/en-US/docs/Web/API/Web_Workers_API">Web Workers</a>.</p> +</div> + +<h2 id="Properties">Properties</h2> + +<p><em>Also implements properties from its parent interface, </em>{{domxref("EventTarget")}}.</p> + +<dl> + <dt>{{domxref("ServiceWorkerRegistration.scope")}} {{readonlyinline}}</dt> + <dd>Returns a unique identifier for a service worker registration. This must be on the same origin as the document that registers the {{domxref("ServiceWorker")}}.</dd> + <dt>{{domxref("ServiceWorkerRegistration.installing")}} <strong style="font-weight: bold;">{{readonlyinline}}</strong></dt> + <dd>Returns a service worker whose state is <code>installing</code>. This is initially set to <code>null</code>.</dd> + <dt>{{domxref("ServiceWorkerRegistration.waiting")}} <strong style="font-weight: bold;">{{readonlyinline}}</strong></dt> + <dd>Returns a service worker whose state is <code>waiting</code>. This is initially set to <code>null</code>.</dd> + <dt>{{domxref("ServiceWorkerRegistration.active")}} <strong style="font-weight: bold;">{{readonlyinline}}</strong></dt> + <dd>Returns a service worker whose state is either <code>activating</code> or <code>activated</code>. This is initially set to <code>null</code>. An active worker will control a {{domxref("ServiceWorkerClient")}} if the client's URL falls within the scope of the registration (the <code>scope</code> option set when {{domxref("ServiceWorkerContainer.register")}} is first called.)</dd> + <dt>{{domxref("ServiceWorkerRegistration.navigationPreload")}} {{readonlyinline}}</dt> + <dd>Returns the instance of {{domxref("NavigationPreloadManager")}} associated with the current service worker registration.</dd> + <dt>{{domxref("serviceWorkerRegistration.periodicSync")}} {{non-standard_inline}} {{readonlyinline}}</dt> + <dd>Returns a reference to the {{domxref("PeriodicSyncManager")}} interface, which manages periodic background synchronization processes.</dd> + <dt>{{domxref("ServiceWorkerRegistration.pushManager")}} {{readonlyinline}}</dt> + <dd>Returns a reference to the {{domxref("PushManager")}} interface for managing push subscriptions including subscribing, getting an active subscription, and accessing push permission status.</dd> + <dt>{{domxref("ServiceWorkerRegistration.sync")}} <strong style="font-weight: bold; line-height: 19.0909080505371px;">{{non-standard_inline}} </strong>{{readonlyinline}} </dt> + <dd>Returns a reference to the {{domxref("SyncManager")}} interface, which manages background synchronization processes.</dd> +</dl> + +<h3 id="Event_handlers">Event handlers</h3> + +<dl> + <dt>{{domxref("ServiceWorkerRegistration.onupdatefound")}} {{readonlyinline}}</dt> + <dd>An <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventListener" title="This method is called whenever an event occurs of the type for which the EventListener interface was registered."><code>EventListener</code></a> property called whenever an event of type <code>updatefound</code> is fired; it is fired any time the {{domxref("ServiceWorkerRegistration.installing")}} property acquires a new service worker.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<p><em>Also implements methods from its parent interface, </em>{{domxref("EventTarget")}}.</p> + +<dl> + <dt>{{domxref("ServiceWorkerRegistration.getNotifications()")}}</dt> + <dd>Returns a {{jsxref("Promise")}} that resolves to an array of {{domxref("Notification")}} objects.</dd> + <dt>{{domxref("ServiceWorkerRegistration.showNotification()")}}</dt> + <dd>Displays the notification with the requested title.</dd> + <dt>{{domxref("ServiceWorkerRegistration.update()")}}</dt> + <dd>Checks the server for an updated version of the service worker without consulting caches.</dd> + <dt>{{domxref("ServiceWorkerRegistration.unregister()")}}</dt> + <dd>Unregisters the service worker registration and returns a {{jsxref("Promise")}}. The service worker will finish any ongoing operations before it is unregistered.</dd> +</dl> + +<h2 id="Examples">Examples</h2> + +<p>In this example, the code first checks whether the browser supports service workers and if so registers one. Next, it adds and <code>updatefound</code> event in which it uses the service worker registration to listen for further changes to the service worker's state. If the service worker hasn't changed since the last time it was registered, than the <code>updatefound</code> event will not be fired.</p> + +<pre class="brush: js">if ('serviceWorker' in navigator) { + navigator.serviceWorker.register('/sw.js') + .then(function(registration) { + registration.addEventListener('updatefound', function() { + // If updatefound is fired, it means that there's + // a new service worker being installed. + var installingWorker = registration.installing; + console.log('A new service worker is being installed:', + installingWorker); + + // You can listen for changes to the installing service worker's + // state via installingWorker.onstatechange + }); + }) + .catch(function(error) { + console.log('Service worker registration failed:', error); + }); +} else { + console.log('Service workers are not supported.'); +}</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('Service Workers', '#service-worker-registration-obj', 'ServiceWorkerRegistration')}}</td> + <td>{{Spec2('Service Workers')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('Push API', '#widl-ServiceWorkerRegistration-pushManager', 'PushManager')}}</td> + <td>{{Spec2('Push API')}}</td> + <td>Adds the {{domxref("PushManager","pushManager")}} property.</td> + </tr> + <tr> + <td>{{SpecName('Web Notifications')}}</td> + <td>{{Spec2('Web Notifications')}}</td> + <td>Adds the {{domxref("ServiceWorkerRegistration.showNotification()","showNotification()")}} method and the {{domxref("ServiceWorkerRegistration.getNotifications()","getNotifications()")}} method.</td> + </tr> + <tr> + <td>{{SpecName('Background Sync')}}</td> + <td>{{Spec2('Background Sync')}}</td> + <td>Adds the {{domxref("ServiceWorkerRegistration.sync","sync")}} property.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("api.ServiceWorkerRegistration")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/ServiceWorker_API/Using_Service_Workers">Using Service Workers</a></li> + <li><a href="https://github.com/mdn/sw-test">Service workers basic code example</a></li> + <li><a href="https://jakearchibald.github.io/isserviceworkerready/">Is ServiceWorker ready?</a></li> + <li>{{jsxref("Promise")}}</li> + <li><a href="/en-US/docs/Web/Guide/Performance/Using_web_workers">Using web workers</a></li> +</ul> diff --git a/files/es/web/api/simple_push_api/index.html b/files/es/web/api/simple_push_api/index.html new file mode 100644 index 0000000000..d3d4dd4d1a --- /dev/null +++ b/files/es/web/api/simple_push_api/index.html @@ -0,0 +1,235 @@ +--- +title: Simple Push +slug: Web/API/Simple_Push_API +translation_of: Archive/B2G_OS/API/Simple_Push_API +--- +<p>{{ non-standard_header() }}</p> + +<div class="note"> +<p><strong>Nota</strong>: Esta documentación cubre el mecanismo propietario Simple Push de Firefox OS; si usted está buscando la documentación sobre el W3C Push API, diríjase a <a href="/en-US/docs/Web/API/Push_API">Push API</a>.</p> +</div> + +<p>El <strong>Simple Push API</strong>, también conocido como Push Notification API, provee a las aplicaciones la habilidad de ser despertadas para recibir notificaciones. Usted puede utilizar Simple Push como un mecanismo de sincronización, o incluso para traer datos desde servidores de terceros.</p> + +<p>Un "push" (empujón) no es más que un evento enviado a un servidor remoto. Así es como funciona: una aplicación usa el <span style="line-height: 1.5;">Simple Push API para solicitar una URL especial y única llamada endpoint (punto final). Esta solicitud viaja hacia un servidor existente mantenido por Mozilla especialmente para este proposito (este se denomina "push server"). Cuando la aplicación recibe el endpoint de vuelta desde el push server, la aplicación envía el endpoint a su propio servidor (su servidor de aplicación). El servidor de aplicación guarda este endpoint, luego cuando quiere despertar la aplicación, llama al endpoint con un número de versión, y el push server contacta a la aplicación con una notificación del número de versión. La aplicación puede hacer cualquier cosa al momento de recibir la notificación, incluso ignorarla.</span></p> + +<p>El Simple Push API extiende <code>Window.navigator</code> con una propiedad <code>push</code> que es un objeto {{domxref("PushManager")}}, e incluye algunos eventos nuevos que usted puede recibir para monitorear el estado del empuje.</p> + +<h2 id="Ejemplo_mostrando_los_conceptos_básicos">Ejemplo mostrando los conceptos básicos</h2> + +<p>Existen varias formas de usar la Simple Push API. Este ejemplos cubren los conceptos básicos de como usarla. El ejemplo consta de los siguientes pasos generales. Consulte las siguientes secciones para obtener información completa sobre cada paso.</p> + +<ol> + <li><a href="#Add_push_to_manifest">Añadir configuración push al manifiesto de la aplicación</a></li> + <li><a href="#2._Call_PushManager.register()_to_request_an_endpoint">LLamar a <code>PushManager.register</code> para solicitar un endpoint</a></li> + <li><a href="#3._Send_the_endpoint_to_your_server">Enviar un endpoint a su servidor</a></li> + <li><a href="#4._Add_a_message_handler_for_push_notifications_to_your_app">Agregar a su aplicación controladores de mensajes para notificaciones push</a></li> + <li><a href="#5._Send_a_notification_from_your_server_using_the_endpoint">Enviar una notificación desde su servidor utilizando el endpoint</a></li> +</ol> + +<h2 id="1._Añadir_configuración_push_al_manifiesto_de_la_aplicación"><a name="Add_push_to_manifest"></a>1. Añadir configuración push al manifiesto de la aplicación</h2> + +<p>Usted necesita cambiar dos cosas en el manifiesto de la aplicación para poder utilizar Simple Push:</p> + +<ol> + <li><a href="/docs/Web/Apps/Manifest#messages" title="https://developer.mozilla.org/en-US/docs/Web/Apps/Manifest?redirectlocale=en-US&redirectslug=Apps%2FManifest#messages">Campo <code>messages</code></a> - Añadir <code>push</code> y <code>push-register</code> a <code>messages</code>.<br> + Esto le hace saber a la página de aplicación que recibirá cada uno de estos eventos (<code>push</code> y <code>push-register</code>). En este ejemplo, ambos van a la misma página: "/index.html", pero también pueden usar otras páginas. Observe a continuación para mayor información sobre cada uno de estos eventos.</li> + <li><a href="/docs/Web/Apps/Manifest#permissions" title="https://developer.mozilla.org/en-US/docs/Web/Apps/Manifest?redirectlocale=en-US&redirectslug=Apps%2FManifest#permissions">Campo <code>permissions</code></a> - Añadir que su aplicación quiere recibir notificaciones push.<br> + Es una buena idea proveer una descripción clara en este campo para que el usuario final entienda por qué usted necesita permisos de empuje ("push").</li> +</ol> + +<pre><span class="s2">"messages"</span><span class="o">:</span> <span class="cp">[</span> + <span class="p">{</span> <span class="s2">"push"</span><span class="p">:</span> <span class="s2">"/index.html"</span><span class="p">},</span> + <span class="p">{</span> <span class="s2">"push-register"</span><span class="p">:</span> <span class="s2">"/index.html"</span><span class="p">}</span> +<span class="cp">]</span><span class="o">,</span> +<span class="s2">"permissions"</span><span class="o">:</span> <span class="p">{</span> + <span class="s2">"push"</span><span class="o">:</span> <span class="err">{ + </span>"description": "Required for being updated with new goals in soccer matches"<span class="err"> +</span><span class="p"> }</span> +<span class="err">}</span></pre> + +<h2 id="2._LLamar_a_PushManager.register()_para_solicitar_un_endpoint">2. LLamar a <code>PushManager.register()</code> para solicitar un endpoint</h2> + +<p>La aplicación necesita solicitar un endpoint llamando {{domxref("PushManager.register")}}. Usted debe decidir cuando este debe ser llamado. Usted podría llamarlo cuando el usuario ha iniciado sesión en el servicio, o cuando el usuario decide comenzar a ver un partido de fútbol, o en cualquier otro momento. El código a continuación es una forma de hacerlo.</p> + +<pre class="brush: js"><span class="k">if</span> <span class="p">(</span><span class="nx">navigator</span><span class="p">.</span><span class="nx">push</span><span class="p">)</span> <span class="p">{ + // Solicitar el endpoint. Esto usa PushManager.register().</span> + <span class="kd">var</span> <span class="nx">req</span> <span class="o">=</span> <span class="nx">navigator</span><span class="p">.</span><span class="nx">push</span><span class="p">.</span><span class="nx">register</span><span class="p">();</span> + + <span class="nx">req</span><span class="p">.</span><span class="brush: js">onsuccess</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">e</span><span class="p">)</span> <span class="p">{</span> + <span class="kd">var</span> <span class="nx">endpoint</span> <span class="o">=</span> <span class="nx">req</span><span class="p">.</span><span class="nx">result</span><span class="p">;</span> + console.log<span class="p">(</span><span class="s2">"New endpoint: "</span> <span class="o">+</span> <span class="nx">endpoint</span> <span class="p">); + // En este punto, usted deberá usar algunos llamados para enviar el + // endpoint a su servidor. Por ejemplo: + /* + var post = XMLHTTPRequest(); + post.open("POST", "https://your.server.here/registerEndpoint"); + post.setRequestHeader("Content-Type", "</span>application/x-www-form-urlencoded"); + post.send("endpoint=" + encodeURIComponents( endpoint ) ); + */ + // Obviamente usted querrá añadir controladores .onload y .onerror, + // añadir información de id del usuario, y cualquier otra cosa que podría + // necesitar para asocial el endpoint con el usuario. + <span class="p">}</span> + + <span class="nx">req</span><span class="p">.</span><span class="nx">onerror</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">e</span><span class="p">)</span> <span class="p">{</span> + console.error<span class="p">(</span><span class="s2">"Error getting a new endpoint: "</span> <span class="o">+</span> <span class="nx">JSON</span><span class="p">.</span><span class="nx">stringify</span><span class="p">(</span><span class="nx">e</span><span class="p">));</span> + <span class="p">}</span> +<span class="p">}</span> <span class="k">else</span> <span class="p">{</span> + <span class="c1">// push no se encuentra disponible en el DOM, así que haga algo diferente.</span> +<span class="p">}</span></pre> + +<h2 id="3._Enviar_un_endpoint_a_su_servidor">3. Enviar un endpoint a su servidor</h2> + +<p>Una vez que la aplicación ha recibido un endpoint, esta necesita enviarla a su servidor de aplicación. Hay más de una forma de hacer esto. Por ejemplo usted puede enviarla por email, o enviarla a través de <code>POST</code>, <code>PUT</code>, o incluso <code>GET</code>. Nosotros recomendamos que almacene el endpoint con algunos datos de usuario desde la aplicación, tales como una cookie, un username, o lo que sea que usted utilice para identificar su par enpoint-user.</p> + +<p>Pero si usted está enviando a su servidor, nosotros recomendamos que siga estas buenas prácticas:</p> + +<ul> + <li>Enviarla a tráves de XMLHttpRequest.</li> + <li>Siempre usar HTTPS. De otro modo, si alguien intercepta su endpoint, este puede comenzar a enviar notificaciones a su aplicación.</li> + <li>Usar algo para emparejar al usuario (o la instalación de la aplicación) con el endpoint, como una cookie por ejemplo.</li> + <li>Mantener el endpoint a salvo! Cualquier sistema con acceso a su endpoint puede hacer que su aplicación drene la batería del usuario o amarre innecesariamente su servidor, entre otras molestias. Usted siempre puede hacer que el cliente obtenga un nuevo endpoint y descartar el antiguo, pero siempre asegurese de que su servidor reconozca el cambio.</li> +</ul> + +<h2 id="4._Agregar_a_su_aplicación_controladores_de_mensajes_para_notificaciones_push">4. Agregar a su aplicación controladores de mensajes para notificaciones push</h2> + +<p>Una vez haya configurado su endpoint siguiendo los pasos anteriores, usted está listo para hacer que su aplicación comience a escuchar mensajes <code>push</code> y <code>push-register</code> utilizando los controladores de mensajes.</p> + +<h3 id="Añadir_un_controlador_de_mensajes_push">Añadir un controlador de mensajes <code>push</code></h3> + +<p>El controlador de mensajes push puede encontrarse en su archivo <code>index.html</code> o en su script <code>main.js</code>, o incluso en un archivo específico <code>push-message.html</code> que contiene solamente el controlador de mensajes. Esto puede ser útil si un mensaje <code>push</code> es enviado y su aplicación se encuentra cerrada, porque cargará solamente una pequeña porción del código HTML/JavaScript, y usted puede decidir si la aplicación necesita estar completamente abierta o puede hacer algo en segundo plano. Donde sea que usted decida ubicar el controlador de mensajes <code>push</code>, asegurese de que el manifiesto apunte a la ubicación correcta (ver el primer paso anterior), de otro modo su aplicación podría no obtener actualizaciones. Aquí hay un ejemplo de un controlador de mensajes <code>push</code>:</p> + +<pre class="brush: js"><span class="k">if</span> <span class="p">(</span><span class="nb">window</span><span class="p">.</span><span class="nx">navigator</span><span class="p">.</span><span class="nx">mozSetMessageHandler</span><span class="p">)</span> <span class="p">{</span> + <span class="nb">window</span><span class="p">.</span><span class="nx">navigator</span><span class="p">.</span><span class="nx">mozSetMessageHandler</span><span class="p">(</span><span class="s1">'push'</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">e</span><span class="p">)</span> <span class="p">{</span> + console.log<span class="p">(</span><span class="s1">'My endpoint is '</span> <span class="o">+</span> <span class="nx">e</span><span class="p">.</span><span class="nx">pushEndpoint</span><span class="p">);</span> + console.log<span class="p">(</span><span class="s1">'My new version is '</span> <span class="o">+</span> <span class="nx">e</span><span class="p">.</span><span class="nx">version</span><span class="p">);</span> + <span class="c1">// Recuerde que usted puede controlar aquí si tiene más de</span> + <span class="c1">// un pushEndpoint</span> + <span class="k">if</span> <span class="p">(</span><span class="nx">e</span><span class="p">.</span><span class="nx">pushEndpoint</span> <span class="o">===</span> <span class="nx">emailEndpoint</span><span class="p">)</span> <span class="p">{</span> + <span class="nx">emailHandler</span><span class="p">(</span><span class="nx">e</span><span class="p">.</span><span class="nx">version</span><span class="p">);</span> + <span class="p">}</span> <span class="k">else</span> <span class="k">if</span> <span class="p">(</span><span class="nx">e</span><span class="p">.</span><span class="nx">pushEndpoint</span> <span class="o">===</span> <span class="nx">imEndpoint</span><span class="p">)</span> <span class="p">{</span> + <span class="nx">imHandler</span><span class="p">(</span><span class="nx">e</span><span class="p">.</span><span class="nx">version</span><span class="p">);</span> + <span class="p">}</span> + <span class="p">});</span> +<span class="p">}</span> <span class="k">else</span> <span class="p">{</span> + <span class="c1">// Controlador No message</span> +<span class="p">}</span></pre> + +<h3 id="Añadir_un_controlador_de_mensajes_push-register">Añadir un controlador de mensajes <code>push-register</code></h3> + +<div class="note"> +<p><strong>Nota:</strong> Asegurese de añadir este controlador y verificar que funciona. Si ustedes no registra de nuevo sus endpoints cuando este mensaje es recibido por su aplicación, la aplicación <strong>NO SERÁ CAPAZ</strong> de recibir nuevas notificaciones push.</p> +</div> + +<p>Un mensaje push-register será enviado a todas las aplicaciones cuando el dispositivo cambie su identificador interno (llamado el UAID o User Agent Identifier). Esto puede deberse a que el servidor push ha cambiado, o se ha caido y necesita recuperarse, o cualquier otra circunstancia. Si cualquiera de estas cosas llegara a ocurrir, ustedes <strong>DEBE</strong> registrar de nuevo todos sus endpoints, porque sus previos endpoints ya no serán válidos. Por lo tanto su aplicación necesita implementar un controlador de mensajes <code>push-register</code>. Observe el siguiente código de ejemplo.</p> + +<pre class="brush: js"><span class="k">if</span> <span class="p">(</span><span class="nb">window</span><span class="p">.</span><span class="nx">navigator</span><span class="p">.</span><span class="nx">mozSetMessageHandler</span><span class="p">)</span> <span class="p">{</span> + <span class="nb">window</span><span class="p">.</span><span class="nx">navigator</span><span class="p">.</span><span class="nx">mozSetMessageHandler</span><span class="p">(</span><span class="s1">'push-register'</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">e</span><span class="p">)</span> <span class="p">{</span> + console.log<span class="p">(</span><span class="s1">'push-register received, I need to register my endpoint(s) again!'</span><span class="p">);</span> + +<span class="c1"> <span class="kd">var</span> <span class="nx">req</span> <span class="o">=</span> <span class="nx">navigator</span><span class="p">.</span><span class="nx">push</span><span class="p">.</span><span class="nx">register</span><span class="p">();</span> + <span class="nx"> req</span><span class="p">.</span><span class="brush: js">onsuccess</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">e</span><span class="p">)</span> <span class="p">{</span> + <span class="kd"> var</span> <span class="nx">endpoint</span> <span class="o">=</span> <span class="nx">req</span><span class="p">.</span><span class="nx">result</span><span class="p">;</span> + console.log<span class="p">(</span><span class="s2">"New endpoint: "</span> <span class="o">+</span> <span class="nx">endpoint</span> <span class="p">); + localStorage.endpoint = endpoint;</span> + <span class="p">}</span> + + <span class="nx"> req</span><span class="p">.</span><span class="nx">onerror</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">e</span><span class="p">)</span> <span class="p">{</span> + console.error<span class="p">(</span><span class="s2">"Error getting a new endpoint: "</span> <span class="o">+</span> <span class="nx">JSON</span><span class="p">.</span><span class="nx">stringify</span><span class="p">(</span><span class="nx">e</span><span class="p">));</span> + <span class="p"> }</span></span> + <span class="p">});</span> +<span class="p">}</span> <span class="k">else</span> <span class="p">{</span> + <span class="c1">// Controlador No message</span> +<span class="p">}</span></pre> + +<h2 id="5._Enviar_una_notificación_desde_su_servidor_utilizando_el_endpoint">5. Enviar una notificación desde su servidor utilizando el endpoint</h2> + +<p>Una vez usted tiene el endpoint en su servidor, usted puede enviar una notificación simplemente enviando una petición HTTP PUT al endpoint con el cuerpo <code>version=<version></code>. Por ejemplo, imagine un endpoint con la siguiente URL:</p> + +<pre><code>https://updates.push.services.mozilla.com/update/abcdef01234567890abcdefabcdef01234567890abcdef</code></pre> + +<p>y con la version 5:</p> + +<pre><code>version=5</code></pre> + +<p>Así es como la notificación se verá utilizando curl:</p> + +<pre><code>curl -X PUT -d "version=5" https://updates.push.services.mozilla.com/update/abcdef01234567890abcdefabcdef01234567890abcdef</code></pre> + +<p>Si el servidor push esta corriendo correctamente, usted recibirá una respuesta con un <code>200 Status (OK)</code> y un <code>{}</code> como cuerpo. También podría recibir un <code>200 Status</code> indicando que el mensaje fue aceptado, pero que pudo haber sido controlado por un sistema alternativo. Si no, una respuesta <code>error</code> HTTP valida con un JSON explicando el error será retornada.</p> + +<div class="note"> +<p><strong>Por favor recuerde:</strong> Solo porque Simple Push ha aceptado el mensaje, esto no garantiza que el mensaje será entregado exitosamente a la aplicación. Muchos factores, desde un dispositivo desconectado a varios fallos de transmisión de datos, pueden ocacionar que no se entregue exitosamente una notificación. Nosotros hacemos nuestro mejor esfuerzo, pero a veces el universo tiene otros planes.</p> +</div> + +<p>Recuerde que el valor de version debe ser números enteros, e incrementales. Las aplicaciones <em>no recibirán</em> nuevas notificaciones si la versión en menor a aquella almacenada en el servidor y/o dispositivo. Las versiones pueden ser útiles para que la aplicación indique si existen eventos "perdidos" que realmente debería verificar. Usted también podriá simplemente usar el UTC (el número de segundos desde la media noche del 1 de enero de 1970, GMT) actual si el valor de la versión no es muy importante para usted.</p> + +<h3 id="Anular_el_registro_de_un_endpoint">Anular el registro de un endpoint</h3> + +<p>Una vez haya terminado de utilizar el endpoint y no desee recibir más notificaciones, le rogamos anular el registro del antiguo endpoint mediante {{domxref("PushManager.unregister")}}. Esto limpiará la cantidad de datos que el dispositivo envía al servidor push, y además disminuirá el consumo de batería al no enviar notificaciones de las aplicaciones que no las usen.</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<p>{{page("/en-US/docs/Web/API/PushManager","Specifications")}}</p> + +<h2 id="Conpatibilidad_con_navegadores">Conpatibilidad con navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</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>Característica</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>Soporte básico</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("PushManager")}}</li> + <li><a href="/en-US/docs/Web/API/Navigator.push">Window.navigator.push</a></li> + <li><a href="https://github.com/frsela/pushJSlibrary" title="https://github.com/frsela/pushJSlibrary">pushJSLibrary, a push shim for browsers that do not implement the API</a></li> + <li><a href="https://wiki.mozilla.org/WebAPI/SimplePush">SimplePush original design and discussion page</a></li> +</ul> diff --git a/files/es/web/api/storage/clear/index.html b/files/es/web/api/storage/clear/index.html new file mode 100644 index 0000000000..fc9e9890b2 --- /dev/null +++ b/files/es/web/api/storage/clear/index.html @@ -0,0 +1,131 @@ +--- +title: Storage.clear() +slug: Web/API/Storage/clear +tags: + - API + - Almacenamiento local + - Storage + - Web Storage + - sessionStorage +translation_of: Web/API/Storage/clear +--- +<p>{{APIRef("Web Storage API")}}</p> + +<p>El método <code>clear()</code> de la interfaz {{domxref("Storage")}}, al invocarlo, elimina todos los registros del almacen local.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="brush: js"><em>storage</em>.clear();</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<p><em>No recibe parámetros.</em></p> + +<h3 id="Devuelve">Devuelve</h3> + +<p><em>No devuelve ningún valor.</em></p> + +<p> </p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p> </p> + +<p>La siguiente función crea tres elementos con datos dentro del almacen local, seguidamente, los elimina usando <code>clear()</code>.</p> + +<pre class="brush: js">function populateStorage() { + localStorage.setItem('bgcolor', 'red'); + localStorage.setItem('font', 'Helvetica'); + localStorage.setItem('image', 'myCat.png'); + + localStorage.clear(); +}</pre> + +<div class="note"> +<p><strong>Nota</strong>: Para ver un ejemplo real, vea nuestro <a href="https://github.com/mdn/web-storage-demo">Web Storage Demo</a>.</p> +</div> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('Web Storage', '#dom-storage-clear', 'clear()')}}</td> + <td>{{Spec2('Web Storage')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_navegadores">Compatibilidad en navegadores</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>localStorage</td> + <td>4</td> + <td>3.5</td> + <td>8</td> + <td>10.50</td> + <td>4</td> + </tr> + <tr> + <td>sessionStorage</td> + <td>5</td> + <td>2</td> + <td>8</td> + <td>10.50</td> + <td>4</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>2.1</td> + <td>{{ CompatUnknown }}</td> + <td>8</td> + <td>11</td> + <td>iOS 3.2</td> + </tr> + </tbody> +</table> +</div> + +<p>Los navegadores tienen diferentes niveles de capacidad, tanto para el localStorage como para el sesionStorage. He aquí una <a class="external external-icon" href="http://dev-test.nemikor.com/web-storage/support-test/" title="http://dev-test.nemikor.com/web-storage/support-test/">lista detallada de todas las capacidades de almacenamiento para varios navegadores</a>.</p> + +<div class="note"> +<p><strong>Nota: </strong> desde la versión 5.1 de iOS, Safari Mobile almacena los datos de localStorage en la carpeta de la caché, la cual se vacía a intervalos, a criterio del sistema operativo, generalmente, si hay una falta de espacio.</p> +</div> + +<h2 id="Vea_también">Vea también</h2> + +<p><a href="/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API">Uso de la Web Storage API</a></p> diff --git a/files/es/web/api/storage/getitem/index.html b/files/es/web/api/storage/getitem/index.html new file mode 100644 index 0000000000..ea5da3292b --- /dev/null +++ b/files/es/web/api/storage/getitem/index.html @@ -0,0 +1,139 @@ +--- +title: Storage.getItem() +slug: Web/API/Storage/getItem +tags: + - API + - Almacenamiento + - Almacenamiento web + - Referencia + - Storage + - Web Storage + - metodo +translation_of: Web/API/Storage/getItem +--- +<p>{{APIRef("Web Storage API")}}</p> + +<p>El método <code>getItem()</code> de la interfaz {{domxref("Storage")}} devuelve el valor de la clave cuyo nombre se le pasa por parámetro.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var <em>aValue</em> = <em>storage</em>.getItem(<em>keyName</em>); +</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><em><code>keyName</code></em></dt> + <dd>Una {{domxref("DOMString")}} que contiene el nombre de la clave cuyo valor se quiere obtener.</dd> +</dl> + +<h3 id="Devuelve">Devuelve</h3> + +<p>Una {{domxref("DOMString")}} que contiene el valor de la clave. Si la clave no existe, devuelve <code>null</code>.</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>La siguiente función toma 3 elementos del almacenamiento local (local storage) y los utiliza para establecer estilos personalizados en una página.</p> + +<pre class="brush: js">function setStyles() { + var currentColor = localStorage.getItem('bgcolor'); + var currentFont = localStorage.getItem('font'); + var currentImage = localStorage.getItem('image'); + + document.getElementById('bgcolor').value = currentColor; + document.getElementById('font').value = currentFont; + document.getElementById('image').value = currentImage; + + htmlElem.style.backgroundColor = '#' + currentColor; + pElem.style.fontFamily = currentFont; + imgElem.setAttribute('src', currentImage); +}</pre> + +<div class="note"> +<p><strong>Nota</strong>: Para ver esto utilizado en un ejemplo real, vea nuestra <a href="https://github.com/mdn/web-storage-demo">Demo de Web Storage</a>.</p> +</div> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentarios</th> + </tr> + <tr> + <td>{{SpecName('Web Storage', '#dom-storage-getitem', 'getItem()')}}</td> + <td>{{Spec2('Web Storage')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>localStorage</td> + <td>4</td> + <td>3.5</td> + <td>8</td> + <td>10.50</td> + <td>4</td> + </tr> + <tr> + <td>sessionStorage</td> + <td>5</td> + <td>2</td> + <td>8</td> + <td>10.50</td> + <td>4</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>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>2.1</td> + <td>{{ CompatUnknown }}</td> + <td>8</td> + <td>11</td> + <td>iOS 3.2</td> + </tr> + </tbody> +</table> +</div> + +<p>Todos los navegadores tienen diferentes niveles de capacidad tanto para localStorage como para sessionStorage. Aquí hay un <a class="external" href="http://dev-test.nemikor.com/web-storage/support-test/" title="http://dev-test.nemikor.com/web-storage/support-test/">resumen detallado de la capacidad de almacenamiento para diversos navegadores</a>.</p> + +<div class="note"> +<p><strong>Nota: </strong>desde iOS 5.1, Safari Mobile almacena los datos de localStorage en la carpeta de cache, que está sujeta a borrados ocasionales a petición del sistema operativo, típicamente cuando queda poco espacio.</p> +</div> + +<h2 id="Vea_también">Vea también</h2> + +<p><a href="/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API">Utilizando la API de Web Storage</a></p> diff --git a/files/es/web/api/storage/index.html b/files/es/web/api/storage/index.html new file mode 100644 index 0000000000..f5116f0fff --- /dev/null +++ b/files/es/web/api/storage/index.html @@ -0,0 +1,162 @@ +--- +title: Almacenamiento +slug: Web/API/Storage +tags: + - API + - Almacenamiento + - Almacenamiento web + - Interface + - Reference + - TopicStub + - data +translation_of: Web/API/Storage +--- +<p>{{APIRef("Web Storage API")}}</p> + +<p>La interfaz <code>Storage</code> de la API de almacenamiento web provee acceso al almacenamiento de la sesión o al almacenamiento local para un dominio en particular, permitiéndote por ejemplo añadir, modificar o eliminar elementos de dato almacenados.</p> + +<p>Si deseas manipular el almacenamiento de sesión para un dominio, debes llamar al método {{domxref("Window.sessionStorage")}}; Si deseas manipular el almacenamiento local para un dominio, debes llamar a {{domxref("Window.localStorage")}}.</p> + +<h2 id="Propiedades">Propiedades</h2> + +<dl> + <dt>{{domxref("Storage.length")}} {{readonlyInline}}</dt> + <dd>Retorna un entero que representa el número de elementos almacenados en el objeto<code> Storage</code>.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<dl> + <dt>{{domxref("Storage.key()")}}</dt> + <dd>Cuando se le pasa un número n, éste método retorna el nombre de la enésima clave en el almacenamiento.</dd> +</dl> + +<dl> + <dt>{{domxref("Storage.getItem()")}}</dt> + <dd>Cuando se le pasa un nombre de clave, retorna el valor de esa clave.</dd> + <dt>{{domxref("Storage.setItem()")}}</dt> + <dd>Cuando se le pasa un nombre de clave y un valor, añade dicha clave al almacenamiento, o la actualiza el valor de la clave si ya existe.</dd> + <dt>{{domxref("Storage.removeItem()")}}</dt> + <dd>Cuando se le pasa el nombre de una clave, eliminará dicha clave del almacenamiento.</dd> + <dt>{{domxref("Storage.clear()")}}</dt> + <dd>Cuando es invocado vacía todas las claves del almacenamiento.</dd> +</dl> + +<h2 id="Ejemplos">Ejemplos</h2> + +<p>Aquí tenemos un objeto <code>Storage</code> al llamar a <code>localStorage</code>. Primero probamos si el almacenamiento local contiene elementos de dato usando <code>!localStorage.getItem('bgcolor')</code>. Si lo hace, ejecutamos una función llamada <code>setStyles()</code> que obtiene los elementos usando {{domxref("localStorage.getItem()")}} y utiliza dichos valores para actualizar los estilos de la página. Si no, ejecutamos otra función, <code>populateStorage()</code>, que utiliza {{domxref("localStorage.setItem()")}} para definir los valores de los elementos, luego ejecuta <code>setStyles()</code>.</p> + +<pre class="brush: js">if(!localStorage.getItem('bgcolor')) { + populateStorage(); +} else { + setStyles(); +} + +function populateStorage() { + localStorage.setItem('bgcolor', document.getElementById('bgcolor').value); + localStorage.setItem('font', document.getElementById('font').value); + localStorage.setItem('image', document.getElementById('image').value); + + setStyles(); +} + +function setStyles() { + var currentColor = localStorage.getItem('bgcolor'); + var currentFont = localStorage.getItem('font'); + var currentImage = localStorage.getItem('image'); + + document.getElementById('bgcolor').value = currentColor; + document.getElementById('font').value = currentFont; + document.getElementById('image').value = currentImage; + + htmlElem.style.backgroundColor = '#' + currentColor; + pElem.style.fontFamily = currentFont; + imgElem.setAttribute('src', currentImage); +}</pre> + +<div class="note"> +<p><strong>Nota</strong>: Para ver la ejecución de esto como un ejemplo funcional completo, mira nuestra <a href="https://github.com/mdn/web-storage-demo">Demo de almacenamiento web</a>.</p> +</div> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('Web Storage', '#the-storage-interface', 'Storage')}}</td> + <td>{{Spec2('Web Storage')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>localStorage</td> + <td>4</td> + <td>3.5</td> + <td>8</td> + <td>10.50</td> + <td>4</td> + </tr> + <tr> + <td>sessionStorage</td> + <td>5</td> + <td>2</td> + <td>8</td> + <td>10.50</td> + <td>4</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>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>2.1</td> + <td>{{ CompatUnknown }}</td> + <td>8</td> + <td>11</td> + <td>3.2[1]</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] A partir de iOS 5.1, Safari Mobile almacena los datos de <code>localStorage</code> en la carpeta cache, que es sujeta a ser vaciada ocasionalmente a petición del SO, típicamente si hay poco espacio disponible.</p> + +<p>Todos los navegadores tienen diferentes niveles de capacidad tanto para localStorage y sessionStorage. Aquí hay un <a href="http://dev-test.nemikor.com/web-storage/support-test/">análisis detallado de todas las capacidades de almacenamiento para diferentes navegadores</a>.</p> + +<h2 id="Ver_también">Ver también</h2> + +<p><a href="/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API">Usar la API de almacenamiento Web</a></p> diff --git a/files/es/web/api/storage/length/index.html b/files/es/web/api/storage/length/index.html new file mode 100644 index 0000000000..47434b2813 --- /dev/null +++ b/files/es/web/api/storage/length/index.html @@ -0,0 +1,117 @@ +--- +title: Storage.length +slug: Web/API/Storage/length +translation_of: Web/API/Storage/length +--- +<p>{{APIRef("Web Storage API")}}</p> + +<p>La propiedad de sólo lectura <code>length</code> de la interfaz {{domxref("Storage")}} devuelve un entero que indica el numero de elementos guardados en el objeto<code> Storage</code>.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var <em>aLength</em> = <em>storage</em>.length;</pre> + +<h3 id="Valor_devuelto">Valor devuelto</h3> + +<p>Entero</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>La siguiente función añade tres elementos de datos en el almacen local para el dominio actual, posteriormente, devuelve el número de elementos guardados en el almacen:</p> + +<pre class="brush: js">function populateStorage() { + localStorage.setItem('bgcolor', 'yellow'); + localStorage.setItem('font', 'Helvetica'); + localStorage.setItem('image', 'cats.png'); + + localStorage.length; // should return 3 +}</pre> + +<div class="note"> +<p><strong>Nota</strong>: Para un ejemplo real, vea nuestro <a href="https://github.com/mdn/web-storage-demo">Web Storage Demo</a>.</p> +</div> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificacíon</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('Web Storage', '#dom-storage-length', 'length')}}</td> + <td>{{Spec2('Web Storage')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_navegadores">Compatibilidad en navegadores</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>localStorage</td> + <td>4</td> + <td>3.5</td> + <td>8</td> + <td>10.50</td> + <td>4</td> + </tr> + <tr> + <td>sessionStorage</td> + <td>5</td> + <td>2</td> + <td>8</td> + <td>10.50</td> + <td>4</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>2.1</td> + <td>{{ CompatUnknown }}</td> + <td>8</td> + <td>11</td> + <td>iOS 3.2</td> + </tr> + </tbody> +</table> +</div> + +<p>Los navegadores tienen diferentes niveles de capacidad, tanto para el localStorage como para el sesionStorage. He aquí una <a class="external" href="http://dev-test.nemikor.com/web-storage/support-test/" title="http://dev-test.nemikor.com/web-storage/support-test/">lista detallada de todas las capacidades de almacenamiento para varios navegadores</a>.</p> + +<div class="note"> +<p><strong>Nota: </strong>desde la versión 5.1 de iOS, Safari Mobile almacena los datos de localStorage en la carpeta de la caché, la cual se vacía a intervalos, a criterio del sistema operativo, generalmente, si hay una falta de espacio.</p> +</div> + +<h2 id="Vea_también">Vea también</h2> + +<p><a href="/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API">Uso de la Web Storage API</a></p> diff --git a/files/es/web/api/storage/localstorage/index.html b/files/es/web/api/storage/localstorage/index.html new file mode 100644 index 0000000000..80a54ff11b --- /dev/null +++ b/files/es/web/api/storage/localstorage/index.html @@ -0,0 +1,135 @@ +--- +title: LocalStorage +slug: Web/API/Storage/LocalStorage +tags: + - Almacenamiento en Navegador + - Almacenamiento local +translation_of: Web/API/Window/localStorage +--- +<p><code>localStorage</code> (almacenamiento local) es lo mismo que<code> <a href="/en-US/docs/Web/API/sessionStorage">sessionStorage</a> </code>(almacenamiento de sesión), con las mismas reglas de mismo-origen aplicadas, pero es persistente a través de diferentes sesiones. <code>localStorage</code> se introdujo en la version Firefox 3.5.</p> + +<div class="note"><strong>Nota:</strong> Cuando el navegador está en modo de navegación privado, una nueva base de datos temporal se crea para guardar <em>datos </em>de almacenamiento local. Esta base de datos se vacía y descarta cuando salimos del modo de navegación privado.</div> + +<pre class="brush:js notranslate" style="font-size: 14px;">// Guardar datos al almacenamiento local actual +localStorage.setItem("nombredeusuario", "John"); + +// Acceder a datos almacenados +alert( "nombredeusuario = " + localStorage.getItem("nombredeusuario"));</pre> + +<p class="note">La persistencia de <code>localStorage</code> lo hace útil para una variedad de cosas, incluyendo contadores de páginas, como se demuestra en <a href="http://codepen.io/awesom3/pen/Hlfma">este tutorial en Codepen</a>.</p> + +<h4 id="Compatibilidad" style="line-height: 18px; font-size: 1.28571428571429rem;">Compatibilidad</h4> + +<p>Los objetos de <code>Storage</code> (almacenamiento) son una adición reciente al estándar, por lo que pueden no estar presentes en todos los navegadores. Esto se puede solucionar si introduce uno de los dos códigos al principio de sus <em>scripts</em>, permitiendo el uso de el objeto <code>localStorage</code> en implementaciones que no lo soportan de forma nativa.</p> + +<p>Este algoritmo es una imitación exacta del objeto <code>localStorage</code>, pero hace uso de cookies.</p> + +<pre class="brush:js notranslate" style="font-size: 14px;">if (!window.localStorage) { + Object.defineProperty(window, "localStorage", new (function () { + var aKeys = [], oStorage = {}; + Object.defineProperty(oStorage, "getItem", { + value: function (sKey) { return sKey ? this[sKey] : null; }, + writable: false, + configurable: false, + enumerable: false + }); + Object.defineProperty(oStorage, "key", { + value: function (nKeyId) { return aKeys[nKeyId]; }, + writable: false, + configurable: false, + enumerable: false + }); + Object.defineProperty(oStorage, "setItem", { + value: function (sKey, sValue) { + if(!sKey) { return; } + document.cookie = escape(sKey) + "=" + escape(sValue) + "; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"; + }, + writable: false, + configurable: false, + enumerable: false + }); + Object.defineProperty(oStorage, "length", { + get: function () { return aKeys.length; }, + configurable: false, + enumerable: false + }); + Object.defineProperty(oStorage, "removeItem", { + value: function (sKey) { + if(!sKey) { return; } + document.cookie = escape(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/"; + }, + writable: false, + configurable: false, + enumerable: false + }); + this.get = function () { + var iThisIndx; + for (var sKey in oStorage) { + iThisIndx = aKeys.indexOf(sKey); + if (iThisIndx === -1) { oStorage.setItem(sKey, oStorage[sKey]); } + else { aKeys.splice(iThisIndx, 1); } + delete oStorage[sKey]; + } + for (aKeys; aKeys.length > 0; aKeys.splice(0, 1)) { oStorage.removeItem(aKeys[0]); } + for (var aCouple, iKey, nIdx = 0, aCouples = document.cookie.split(/\s*;\s*/); nIdx < aCouples.length; nIdx++) { + aCouple = aCouples[nIdx].split(/\s*=\s*/); + if (aCouple.length > 1) { + oStorage[iKey = unescape(aCouple[0])] = unescape(aCouple[1]); + aKeys.push(iKey); + } + } + return oStorage; + }; + this.configurable = false; + this.enumerable = true; + })()); +} +</pre> + +<div class="note"><strong>Nota:</strong> El tamaño máximo de datos que se puede guardar está muy restringido por el uso de cookies. Con este algoritmo, utilize las funciones <code>localStorage.getItem()</code>, <code>localStorage.setItem()</code>, y <code>localStorage.removeItem()</code> para agregar, cambiar, o quitar una clave. El uso del método <code>localStorage.suClave</code> para obtener, establecer, o borrar una clave <strong>no está permitido con este código</strong>. También se puede cambiar el nombre y usarse sólo para gestionar las cookies de el documento sin importar el objeto localStorage.</div> + +<div class="note"><strong>Nota:</strong> Al cambiar la cadena <code style="background: rgb(204, 204, 204);">"; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"</code> a: <code style="background: rgb(204, 204, 204);">"; path=/"</code> (y al cambiar el nombre del objeto), esto se pasará a ser un <code>sessionStorage</code> <em>polyfill</em> en vez de un <code>localStorage</code> <em>polyfill</em>. Sin embargo, esta implementación compartirá valores almacenados a través de pestañas y ventanas del navegador (y sólo se borrará cuando todas las ventanas del navegador hayan sido cerradas), mientras que una implementación <span style="font-family: 'Courier New','Andale Mono',monospace; line-height: normal;">sessionStorage</span><span style="line-height: 1.5em;"> completamente compatible sólo restringirá los valores guardados al contexto actual del navegador.</span></div> + +<p>Esta es otra imitación menos exacta de el objeto <code>localStorage</code>, es más simple que la anterior, pero es compatible con navegadores antiguos, como Internet Explorer < 8 (<strong>probado y funcional incluso en Internet Explorer 6</strong>). También hace uso de cookies.</p> + +<pre class="brush:js notranslate" style="font-size: 14px;">if (!window.localStorage) { + window.localStorage = { + getItem: function (sKey) { + if (!sKey || !this.hasOwnProperty(sKey)) { return null; } + return unescape(document.cookie.replace(new RegExp("(?:^|.*;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"), "$1")); + }, + key: function (nKeyId) { + return unescape(document.cookie.replace(/\s*\=(?:.(?!;))*$/, "").split(/\s*\=(?:[^;](?!;))*[^;]?;\s*/)[nKeyId]); + }, + setItem: function (sKey, sValue) { + if(!sKey) { return; } + document.cookie = escape(sKey) + "=" + escape(sValue) + "; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"; + this.length = document.cookie.match(/\=/g).length; + }, + length: 0, + removeItem: function (sKey) { + if (!sKey || !this.hasOwnProperty(sKey)) { return; } + document.cookie = escape(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/"; + this.length--; + }, + hasOwnProperty: function (sKey) { + return (new RegExp("(?:^|;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie); + } + }; + window.localStorage.length = (document.cookie.match(/\=/g) || window.localStorage).length; +} +</pre> + +<div class="note"><strong>Nota:</strong> El tamaño máximo de datos que se puede guardar está muy restringido por el uso de cookies. Con este algoritmo, utilize las funciones <code>localStorage.getItem()</code>, <code>localStorage.setItem()</code>, y <code>localStorage.removeItem()</code> para agregar, cambiar, o quitar una clave. El uso del método <code>localStorage.suClave</code> para obtener, establecer, o borrar una clave <strong>no está permitido con este código</strong>. También se puede cambiar el nombre y usarse sólo para gestionar las cookies de el documento sin importar el objeto localStorage.</div> + +<div class="note"><strong>Nota:</strong> Al cambiar la cadena <code style="background: rgb(204, 204, 204);">"; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"</code> a: <code style="background: rgb(204, 204, 204);">"; path=/"</code> (y al cambiar el nombre del objeto), esto se volverá un <code>sessionStorage</code> <em>polyfill</em> en vez de un <code>localStorage</code> <em>polyfill</em>. Sin embargo, esta implementación compartirá valores almacenados a través de pestañas y ventanas del navegador (y sólo se borrará cuando todas las ventanas del navegador hayan sido cerradas), mientras que una implementación <span style="font-family: 'Courier New','Andale Mono',monospace; line-height: normal;">sessionStorage</span><span style="line-height: 1.5em;"> completamente compatible sólo restringirá los valores guardados al contexto actual del navegador.</span></div> + +<h4 id="Compatibilidad_y_relación_con_globalStorage" style="line-height: 18px; font-size: 1.28571428571429rem;">Compatibilidad y relación con globalStorage</h4> + +<p class="note"><code>localStorage</code> es lo mismo que <code>globalStorage[location.hostname]</code>, con la excepción de que tiene un ámbito de origen HTML5 (<em>esquema </em>+ <em>nombre del host </em>+ <em>puerto no estandar</em>), y <code>localStorage</code> es una instancia de <code>Storage</code>, al contrario que <code>globalStorage[location.hostname]</code>, que es una instancia de <code>StorageObsolete</code>, como se explica más adelante. Por ejemplo, <a class="external" href="http://example.com" rel="freelink">http://ejemplo.com</a> no puede acceder al mismo objeto <code>localStorage</code> que <a class="link-https" href="https://example.com" rel="freelink">https://ejemplo.com,</a> pero los dos pueden acceder al mismo elemento de <code>globalStorage</code>. --<code>localStorage</code> es una interfaz estándar mientras que <code>globalStorage</code> no lo es, así que no se debe depender de ella.</p> + +<p>Nótese que al establecer una propiedad en <code>globalStorage[location.hostname]</code> <strong>no</strong> la establece en <code>localStorage</code>, y al extender <code>Storage.prototype</code> no afecta a los elementos de <code>globalStorage</code>; sólo al extender <code>StorageObsolete.prototype</code> los afecta.</p> + +<h4 id="El_formato_de_Storage">El formato de Storage</h4> + +<p>Las claves y valores de <code>Storage</code> se guardan en el formato UTF-16 <a href="/en-US/docs/Web/API/DOMString">DOMString</a>, que usa 2 bytes por carácter.</p> diff --git a/files/es/web/api/storage/removeitem/index.html b/files/es/web/api/storage/removeitem/index.html new file mode 100644 index 0000000000..f597bd4d5a --- /dev/null +++ b/files/es/web/api/storage/removeitem/index.html @@ -0,0 +1,142 @@ +--- +title: Storage.removeItem() +slug: Web/API/Storage/removeItem +tags: + - API + - Almacenamiento + - Almacenamiento web + - Referencia + - Storage + - Web Storage + - metodo +translation_of: Web/API/Storage/removeItem +--- +<p>{{APIRef("Web Storage API")}}</p> + +<p>El método <code>removeItem()</code> de la interfaz {{domxref("Storage")}} elimina la clave cuyo nombre recibe por parámetro del almacenamiento. La interfaz <code>Storage</code> de la <a href="/es/docs/Web/API/API_de_almacenamiento_web">API de almacenamiento web</a> provee acceso al almacenamiento de la sesión (<code>sessionStorage</code>) o al almacenamiento local (<code>localStorage</code>).</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox notranslate"><em>storage</em>.removeItem(<em>keyName</em>);</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><em><u>keyName</u></em></dt> + <dd>Una {{domxref("DOMString")}} que contiene el nombre de la clave que se desea eliminar.</dd> +</dl> + +<h3 id="Devuelve">Devuelve</h3> + +<p><em>Ningún valor.</em></p> + +<h2 id="Ejemplos">Ejemplos</h2> + +<p>La siguiente función crea 3 elementos dentro del almacenamiento local y después elimina el elemento <code>image</code>.</p> + +<pre class="brush: js notranslate">function populateStorage() { + localStorage.setItem('bgcolor', 'red'); + localStorage.setItem('font', 'Helvetica'); + localStorage.setItem('image', 'myCat.png'); + + localStorage.removeItem('image'); +}</pre> + +<p>De la misma manera se podría manipular el almacenamiento de sesión:</p> + +<pre class="brush: js notranslate">function populateSessionStorage() { + sessionStorage.setItem('bgcolor', 'red'); + sessionStorage.setItem('font', 'Helvetica'); + sessionStorage.setItem('image', 'myCat.png'); + + sessionStorage.removeItem('image'); +}</pre> + +<div class="note"> +<p><strong>Nota</strong>: Para ver esto en un ejemplo real, vea nuestra <a href="https://github.com/mdn/web-storage-demo">Demo de Web Storage</a>.</p> +</div> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentarios</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', 'webstorage.html#dom-storage-removeitem', 'Storage.removeItem')}}</td> + <td>{{Spec2('Web Storage')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>localStorage</td> + <td>4</td> + <td>3.5</td> + <td>8</td> + <td>10.50</td> + <td>4</td> + </tr> + <tr> + <td>sessionStorage</td> + <td>5</td> + <td>2</td> + <td>8</td> + <td>10.50</td> + <td>4</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>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>2.1</td> + <td>{{ CompatUnknown }}</td> + <td>8</td> + <td>11</td> + <td>iOS 3.2</td> + </tr> + </tbody> +</table> +</div> + +<p>Todos los navegadores tienen diferentes niveles de capacidad tanto para localStorage como para sessionStorage. Aquí hay un <a href="http://dev-test.nemikor.com/web-storage/support-test/" title="http://dev-test.nemikor.com/web-storage/support-test/">resumen detallado de la capacidad de almacenamiento para diversos navegadores</a>.</p> + +<div class="note"> +<p><strong>Nota: </strong>desde iOS 5.1, Safari Mobile almacena los datos de localStorage en la carpeta de cache, que está sujeta a borrados ocasionales a petición del sistema operativo, típicamente cuando queda poco espacio.</p> +</div> + +<h2 id="Vea_también">Vea también</h2> + +<p><a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API">Utilizando la API de Web Storage</a></p> diff --git a/files/es/web/api/storage/setitem/index.html b/files/es/web/api/storage/setitem/index.html new file mode 100644 index 0000000000..f9d4ee0237 --- /dev/null +++ b/files/es/web/api/storage/setitem/index.html @@ -0,0 +1,136 @@ +--- +title: Storage.setItem() +slug: Web/API/Storage/setItem +tags: + - API + - Almacenamiento + - Almacenamiento web + - Storage + - Web Storage + - metodo +translation_of: Web/API/Storage/setItem +--- +<p>{{APIRef("Web Storage API")}}</p> + +<p>El método <code>setItem()</code> de la interfaz {{domxref("Storage")}}, cuando reciba una clave y un valor, añadirá estos al almacén, o actualizará el valor si la clave ya existe.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><em>storage</em>.setItem(<em>keyName</em>, <em>keyValue</em>);</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><em>keyName</em></dt> + <dd>Un {{domxref("DOMString")}} conteniendo la clave que se quiere crear/actualizar.</dd> + <dt><em>keyValue</em></dt> + <dd>Un {{domxref("DOMString")}} conteniendo el valor que se le quiere dar a la clave que se está creando/actualizando.</dd> +</dl> + +<h3 id="Devuelve">Devuelve</h3> + +<p><em>No devuelve valor.</em></p> + +<h3 id="Excepciones">Excepciones</h3> + +<p><code>setItem()</code> puede lanzar una excepción si el almacén esta lleno. Particularmente, en Safari Mobile (desde iOS 5) siempre lo hará cuando el usuario ingresa en modo privado (Safari determina una cuota de 0 bytes en modo privado, al contrario de otros navegadores, que permiten almacenamiento en modo privado, usando contenedores de información separados).<br> + Por lo tanto, los desarrolladores deben asegurarse de <strong>capturar siempre las posibles excepciones de <code>setItem()</code></strong>.</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>La siguiente función crea tres ítems dentro del almacenamiento local.</p> + +<pre class="brush: js">function populateStorage() { + localStorage.setItem('bgcolor', 'red'); + localStorage.setItem('font', 'Helvetica'); + localStorage.setItem('image', 'myCat.png'); +}</pre> + +<div class="note"> +<p><strong>Nota</strong>: Para ver un ejemplo real, vea nuestro <a href="https://github.com/mdn/web-storage-demo">Web Storage Demo</a>.</p> +</div> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('Web Storage', '#dom-storage-setitem', 'setItem()')}}</td> + <td>{{Spec2('Web Storage')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_navegadores">Compatibilidad en navegadores</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidad</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>localStorage</td> + <td>4</td> + <td>3.5</td> + <td>8</td> + <td>10.50</td> + <td>4</td> + </tr> + <tr> + <td>sessionStorage</td> + <td>5</td> + <td>2</td> + <td>8</td> + <td>10.50</td> + <td>4</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidad</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>2.1</td> + <td>{{ CompatUnknown }}</td> + <td>8</td> + <td>11</td> + <td>iOS 3.2</td> + </tr> + </tbody> +</table> +</div> + +<p>Todos los navegadores tienen niveles de capacidad variados para localStorage y sessionStorage. Aquí hay un <a class="external" href="http://dev-test.nemikor.com/web-storage/support-test/" title="http://dev-test.nemikor.com/web-storage/support-test/">análisis detallado de todas las capacidades de almacenamiento para varios navegadores</a>.</p> + +<div class="note"> +<p><strong>Nota: </strong>desde iOS 5.1, Safari Mobile almacena los datos de localStorage en la carpeta de caché, que está sujeta a limpieza ocasional a petición del sistema operativo, típicamente cuando el espacio es reducido.</p> +</div> + +<h2 id="Vea_también">Vea también</h2> + +<p><a href="/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API">Usando la Web Storage API</a></p> diff --git a/files/es/web/api/storagemanager/estimate/index.html b/files/es/web/api/storagemanager/estimate/index.html new file mode 100644 index 0000000000..b2c0ee4df6 --- /dev/null +++ b/files/es/web/api/storagemanager/estimate/index.html @@ -0,0 +1,90 @@ +--- +title: StorageManager.estimate() +slug: Web/API/StorageManager/estimate +tags: + - API + - Almacenamiento + - Contexto seguro + - Cuota + - Referencia + - Storage API + - StorageManager + - Uso + - estimación + - estimate + - metodo +translation_of: Web/API/StorageManager/estimate +--- +<p>{{securecontext_header}}{{APIRef("Storage")}}</p> + +<p>El método <strong><code>estimate()</code></strong> de la interfaz {{domxref("StorageManager")}} solicita al Gestor de Almacenamiento la información de cuota y uso para el origen actual. Este método opera de forma asíncrona, por lo que devuelve una {{jsxref("Promise")}} que se resuelve una vez que la información esté disponible. La función que controla el cumplimiento de la promesa recibe un {{domxref("StorageEstimate")}} como entrada con la informción de uso y cuota.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var <em>estimatePromise</em> = <em>StorageManager</em>.estimate();</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<p>Ninguno.</p> + +<h3 id="Valor_devuelto">Valor devuelto</h3> + +<p>Una {{jsxref('Promise')}} que se resuelve como un objeto que se ajusta al diccionario {{domxref('StorageEstimate')}}. Este diccionario contiene estimaciones sobre la cantidad de espacio disponible para el origen o aplicación (en {{domxref("StorageEstimate.quota")}}, así como la cantidad que se usa en ese momento (in {{domxref("StorageEstimate.usage")}}). Estos no son números exactos; entre la compresión, la deduplicación y la ofuscación por razones de seguridad, no serán precisos.</p> + +<p>Es posible que la <code>quota</code> varíe de una aplicación a otra en función de factores como la frecuencia con la que el usuario la visita, los datos de popularidad del sitio, etc.</p> + +<h2 id="Ejemplo" name="Ejemplo">Ejemplo</h2> + +<p>En este ejemplo, obtenemos las estimaciones de uso y presentamos el porcentaje de la capacidad de almacenamiento utilizada actualmente al usuario.</p> + +<h3 id="HTML">HTML</h3> + +<pre class="brush: html"><p> + You're currently using about <span id="percent"> + </span>% of your available storage. +</p> +</pre> + +<h3 id="JavaScript">JavaScript</h3> + +<pre class="brush: js">navigator.storage.estimate().then(function(estimate) { + document.getElementById("percent").innerHTML = + (estimate.usage / estimate.quota).toFixed(2); +}); +</pre> + +<h3 id="Resultado">Resultado</h3> + +<p>{{ EmbedLiveSample('Example', 600, 40) }}</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('Storage','#dom-storagemanager-estimate','estimate()')}}</td> + <td>{{Spec2('Storage')}}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + + + +<p>{{Compat("api.StorageManager.estimate")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>Storage API</li> + <li>{{domxref("Storage")}}, el objeto devuelto por {{domxref("Window.localStorage")}}</li> + <li>{{domxref("StorageManager")}}</li> + <li>{{domxref("navigator.storage")}}</li> +</ul> diff --git a/files/es/web/api/storagemanager/index.html b/files/es/web/api/storagemanager/index.html new file mode 100644 index 0000000000..afc0bd77ad --- /dev/null +++ b/files/es/web/api/storagemanager/index.html @@ -0,0 +1,55 @@ +--- +title: StorageManager +slug: Web/API/StorageManager +tags: + - API + - Interface + - NeedsTranslation + - Persistence + - Quotas + - Reference + - Secure context + - Storage + - Storage API + - StorageManager + - TopicStub + - Usage +translation_of: Web/API/StorageManager +--- +<p>{{securecontext_header}}{{SeeCompatTable}}{{APIRef("Storage")}}</p> + +<p>The <strong><code>StorageManager</code></strong> interface of the the <a href="/en-US/docs/Web/API/Storage_API">Storage API</a> provides an interface for managing persistance permissions and estimating available storage. You can get a reference to this interface using either {{domxref("navigator.storage")}} or {{domxref("WorkerNavigator.storage")}}.</p> + +<h2 id="Methods">Methods</h2> + +<dl> + <dt>{{domxref("StorageManager.estimate()")}} {{securecontext_inline}}</dt> + <dd>Returns a {{domxref("StorageEstimate")}} object containing usage and quota numbers for your origin.</dd> + <dt>{{domxref("StorageManager.persist()")}} {{securecontext_inline}}</dt> + <dd>Returns a {{jsxref('Promise')}} that resolves to <code>true</code> if the user agent is able to persist your site's storage.</dd> + <dt>{{domxref("StorageManager.persisted()")}} {{securecontext_inline}}</dt> + <dd>Returns a {{jsxref('Promise')}} that resolves to <code>true</code> if persistence has already been granted for your site's storage.</dd> +</dl> + +<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('Storage','#storagemanager','StorageManger')}}</td> + <td>{{Spec2('Storage')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("api.StorageManager")}}</p> diff --git a/files/es/web/api/storagemanager/persist/index.html b/files/es/web/api/storagemanager/persist/index.html new file mode 100644 index 0000000000..bb42fbeac4 --- /dev/null +++ b/files/es/web/api/storagemanager/persist/index.html @@ -0,0 +1,59 @@ +--- +title: StorageManager.persist() +slug: Web/API/StorageManager/persist +tags: + - Contexto seguro + - Referencia + - Storage API + - metodo + - persist() +translation_of: Web/API/StorageManager/persist +--- +<p>{{securecontext_header}}{{APIRef("Storage")}}{{SeeCompatTable}}</p> + +<p><span class="seoSummary">El método <strong><code>persist()</code></strong> de la interfaz {{domxref("StorageManager")}} solicita permiso para usar el almacenamiento persistente, y devuelve una {{jsxref('Promise')}} que se resuelve como <code>true</code> si se concede el permiso y <em>box mode</em> es persistente, y <code>false</code> en cualquier otro caso.</span></p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">navigator.storage.persist().then(function(persistent) { ... })</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<p>Ninguno.</p> + +<h3 id="Valor_devuelto">Valor devuelto</h3> + +<p>Una {{jsxref('Promise')}} que se resuelve en un {{jsxref('Boolean')}}.</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush: js">if (navigator.storage && navigator.storage.persist) + navigator.storage.persist().then(function(persistent) { + if (persistent) + console.log("Storage will not be cleared except by explicit user action"); + else + console.log("Storage may be cleared by the UA under storage pressure."); + });</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('Storage','#dom-storagemanager-persist','persist')}}</td> + <td>{{Spec2('Storage')}}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + + + +<p>{{Compat("api.StorageManager.persist")}}</p> diff --git a/files/es/web/api/storagemanager/persisted/index.html b/files/es/web/api/storagemanager/persisted/index.html new file mode 100644 index 0000000000..bce6970649 --- /dev/null +++ b/files/es/web/api/storagemanager/persisted/index.html @@ -0,0 +1,59 @@ +--- +title: StorageManager.persisted() +slug: Web/API/StorageManager/persisted +tags: + - Contexto seguro + - Referencia + - Storage API + - metodo + - persisted() +translation_of: Web/API/StorageManager/persisted +--- +<p>{{securecontext_header}}{{APIRef("Storage")}}{{SeeCompatTable}}</p> + +<p><span class="seoSummary">La propiedad <strong><code>persisted</code></strong> de la interfaz {{domxref("StorageManager")}} devuelve una {{jsxref('Promise')}} que se resuelve como <code>true</code> si <em>box mode</em> es</span> persistente <span class="seoSummary">para el alamacenamiento de su sitio.</span></p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">navigator.storage.persisted().then(function(persistent) { ... })</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<p>Ninguno.</p> + +<h3 id="Devuelve">Devuelve</h3> + +<p>Una {{jsxref('Promise')}} que se resuelve como {{jsxref('Boolean')}}.</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush: js"><code>if (navigator.storage && navigator.storage.persist) + navigator.storage.persisted().then(function(persistent) { + if (persistent) + console.log("Storage will not be cleared except by explicit user action"); + else + console.log("Storage may be cleared by the UA under storage pressure."); + });</code></pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('Storage','#dom-storagemanager-persisted','persisted')}}</td> + <td>{{Spec2('Storage')}}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + + + +<p>{{Compat("api.StorageManager.persisted")}}</p> diff --git a/files/es/web/api/stylesheet/disabled/index.html b/files/es/web/api/stylesheet/disabled/index.html new file mode 100644 index 0000000000..470283c9dc --- /dev/null +++ b/files/es/web/api/stylesheet/disabled/index.html @@ -0,0 +1,20 @@ +--- +title: Stylesheet.disabled +slug: Web/API/StyleSheet/disabled +translation_of: Web/API/StyleSheet/disabled +--- +<p>{{ ApiRef() }}</p> +<h3 id="Summary" name="Summary">Resumen</h3> +<p>Esta propiedad indica si es se aplica o no, la hoja de estilo actual.</p> +<h3 id="Syntax" name="Syntax">Sintaxis</h3> +<pre class="eval"><em>bool</em> = stylesheet.disabled +</pre> +<h3 id="Example" name="Example">Ejemplo</h3> +<pre>// si la hoja de estilo está deshabilitada... +if (stylesheet.disabled) { + // apply style in-line +} +</pre> +<h3 id="Specification" name="Specification">Especificación</h3> +<p><a class="external" href="http://www.w3.org/TR/2000/REC-DOM-Level-2-Style-20001113/stylesheets.html#StyleSheets-StyleSheet-disabled">disabled </a></p> +<p>{{ languages( { "pl": "pl/DOM/stylesheet.disabled" } ) }}</p> diff --git a/files/es/web/api/stylesheet/href/index.html b/files/es/web/api/stylesheet/href/index.html new file mode 100644 index 0000000000..0f4a42dd0c --- /dev/null +++ b/files/es/web/api/stylesheet/href/index.html @@ -0,0 +1,38 @@ +--- +title: stylesheet.href +slug: Web/API/StyleSheet/href +translation_of: Web/API/StyleSheet/href +--- +<p>{{ ApiRef() }}</p> +<h3 id="Summary" name="Summary">Resumen</h3> +<p>Devuelve la localización de la hoja de estilo.</p> +<h3 id="Syntax" name="Syntax">Sintaxis</h3> +<pre class="eval"><em>uri</em> = stylesheet.href +</pre> +<h3 id="Parameters" name="Parameters">Parámetros</h3> +<ul> + <li><code>uri</code> es una cadena que contiene la URI de la hoja de estilo.</li> +</ul> +<h3 id="Example" name="Example">Ejemplo</h3> +<pre> // en una máquina local: + <html> + <head> + <link rel="StyleSheet" href="example.css" type="text/css" /> + <script> + function sref() { + alert(document.styleSheets[0].href); + } + </script> + </head> + <body> + <div class="thunder">Thunder</div> + <button onclick="sref()">ss</button> + </body> + </html> +// returns "file:////C:/Windows/Desktop/example.css +</pre> +<h3 id="Notes" name="Notes">Notas</h3> +<p>Si la hoja de estilo es un enlace, el valor de este atributo es su localización. Para las hojas de estilo in-line, el valor del atributo es NULL.</p> +<p> </p> +<h3 id="Specification" name="Specification">Specification</h3> +<p><a class="external" href="http://www.w3.org/TR/2000/REC-DOM-Level-2-Style-20001113/stylesheets.html#StyleSheets-StyleSheet-href">href </a></p> diff --git a/files/es/web/api/stylesheet/index.html b/files/es/web/api/stylesheet/index.html new file mode 100644 index 0000000000..3344780e21 --- /dev/null +++ b/files/es/web/api/stylesheet/index.html @@ -0,0 +1,50 @@ +--- +title: objeto Stylesheet +slug: Web/API/StyleSheet +translation_of: Web/API/StyleSheet +--- +<p>{{ ApiRef("CSSOM") }}</p> + +<p>Esta sección describe el objeto <a class="external" href="http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleSheet">CSSStyleSheet</a>, que representa una única hoja de estilos CSS.</p> + +<p>Una hoja de estilos CSS consiste en reglas CSS que pueden, cada una de ellas, ser manipuladas a través del objeto <a href="/Es/DOM/CssRule" title="es/DOM/cssRule">CSSRule</a>. El objeto de la hoja de estilo en sí mismo, te permite examinar y modificar la hoja de estilos, incluyendo su lista de reglas.</p> + +<p>Puedes tomar la lista de estilos de un documento determinado mediante el uso de la propiedad <a href="/es/DOM/document.styleSheets" title="es/DOM/document.styleSheets">document.styleSheets</a>.</p> + +<h3 id="Properties" name="Properties">Propiedades</h3> + +<dl> + <dt><a href="/Es/DOM/Stylesheet.cssRules" title="es/DOM/stylesheet.cssRules">stylesheet.cssRules</a></dt> + <dd>Devuelve todas las reglas CSS que hay en la hoja de estilo, en forma de arreglo.</dd> + <dt><a href="/es/DOM/stylesheet.disabled" title="es/DOM/stylesheet.disabled">stylesheet.disabled</a></dt> + <dd>Esta propiedad indica si se ha aplicado o no, la hoja de estilo actual.</dd> + <dt><a href="/es/DOM/stylesheet.href" title="es/DOM/stylesheet.href">stylesheet.href</a></dt> + <dd>Devuelve la localización de la hoja de estilo.</dd> + <dt><a href="/es/DOM/stylesheet.media" title="es/DOM/stylesheet.media">stylesheet.media</a></dt> + <dd>Especifica el medio al que se tiene intención de aplicar la hoja de estilo.</dd> + <dt><a href="/es/DOM/stylesheet.ownerNode" title="es/DOM/stylesheet.ownerNode">stylesheet.ownerNode</a></dt> + <dd>el nodo que asocia la hoja de estilo con el documento.</dd> + <dt><a href="/es/DOM/stylesheet.ownerRule" title="es/DOM/stylesheet.ownerRule">stylesheet.ownerRule</a></dt> + <dd>Si la hoja de estilo tiene una regla marcada con @import, la propiedad ownerRule contendrá la CSSImportRule.</dd> + <dt><a href="/es/DOM/stylesheet.parentStyleSheet" title="es/DOM/stylesheet.parentStyleSheet">stylesheet.parentStyleSheet</a></dt> + <dd>Devuelve la hoja de estilo que que está incluida en esta, si existe.</dd> + <dt><a href="/es/DOM/stylesheet.title" title="es/DOM/stylesheet.title">stylesheet.title</a></dt> + <dd>Devuelve el título de la hoja de estilo actual.</dd> + <dt><a href="/es/DOM/stylesheet.type" title="es/DOM/stylesheet.type">stylesheet.type</a></dt> + <dd>Especifica el lenguaje de la hoja de estilo.</dd> +</dl> + +<h3 id="Methods" name="Methods">Métodos</h3> + +<dl> + <dt><a href="/es/DOM/stylesheet.deleteRule" title="es/DOM/stylesheet.deleteRule">stylesheet.deleteRule</a></dt> + <dd>Elimina una regla de la hoja de estilo.</dd> + <dt><a href="/es/DOM/stylesheet.insertRule" title="es/DOM/stylesheet.insertRule">stylesheet.insertRule</a></dt> + <dd>Agrega una nueva regla de estilo a la hoja de estilo actualmente usada.</dd> +</dl> + +<h3 id="Specification" name="Specification">Especificación</h3> + +<p><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Style/stylesheets.html#StyleSheets-StyleSheet">DOM Level 2 Style Sheets: StyleSheet</a></p> + +<p><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleSheet">DOM Level 2 CSS: CSSStyleSheet</a></p> diff --git a/files/es/web/api/stylesheet/media/index.html b/files/es/web/api/stylesheet/media/index.html new file mode 100644 index 0000000000..47e36011cd --- /dev/null +++ b/files/es/web/api/stylesheet/media/index.html @@ -0,0 +1,24 @@ +--- +title: Stylesheet.media +slug: Web/API/StyleSheet/media +translation_of: Web/API/StyleSheet/media +--- +<p>{{ ApiRef() }}</p> +<h3 id="Summary" name="Summary">Resumen</h3> +<p><strong>media</strong> Especifica el medio al que se tiene intención de aplicar la hoja de estilo.</p> +<h3 id="Syntax" name="Syntax">Sintaxis</h3> +<pre class="eval"><em>medium</em> = stylesheet.media +stylesheet.media = <em>medium</em> +</pre> +<h3 id="Parameters" name="Parameters">Parámetros</h3> +<ul> + <li><code>medium</code> es una cadena que describe un medio único o una lista de valores separados por comas.</li> +</ul> +<h3 id="Example" name="Example">Ejemplo</h3> +<pre><link rel="StyleSheet" href="document.css" type="text/css" media="screen" /> +</pre> +<h3 id="Notes" name="Notes">Notas</h3> +<p>El valor por defecto para media es "screen."</p> +<h3 id="Specification" name="Specification">Especificación</h3> +<p>DOM Level 2 Styles - STYLESHEET</p> +<p>{{ languages( { "pl": "pl/DOM/stylesheet.media" } ) }}</p> diff --git a/files/es/web/api/stylesheet/ownernode/index.html b/files/es/web/api/stylesheet/ownernode/index.html new file mode 100644 index 0000000000..e7a14fb528 --- /dev/null +++ b/files/es/web/api/stylesheet/ownernode/index.html @@ -0,0 +1,35 @@ +--- +title: Stylesheet.ownerNode +slug: Web/API/StyleSheet/ownerNode +translation_of: Web/API/StyleSheet/ownerNode +--- +<p>{{ ApiRef() }}</p> +<h3 id="Summary" name="Summary">Resumen</h3> +<p><strong>ownerNode</strong> devuelve el nodo que asocia la hoja de estilo con el documento.</p> +<h3 id="Syntax" name="Syntax">Sintaxis</h3> +<pre class="eval"><em>objRef</em> = stylesheet.ownerNode +</pre> +<h3 id="Example" name="Example">Ejemplo</h3> +<pre class="eval"><html> + <head> + <link rel="StyleSheet" href="example.css" type="text/css" /> + <script> + function stilo() { + alert(document.styleSheets[0].ownerNode); + } + </script> + </head> + <body> +</pre> +<div class="thunder"> + Thunder</div> +<pre class="eval"> <button onclick="stilo()">ss</button> + </body> +</html> +// displays "object HTMLLinkElement" +</pre> +<h3 id="Notes" name="Notes">Notas</h3> +<p>Para el HTML, <strong>ownerNode</strong> correspondería a un elemento <a href="/es/LINK" title="es/LINK">LINK</a> o <a href="/Es/DOM/Element.style" title="es/DOM/element.style">STYLE</a>. Para XML, serían las instrucciones del proceso de enlace. Para las hojas de estilo que están incluidas en otras hojas de estilo, este valor es NULL.</p> +<h3 id="Specification" name="Specification">Especificación</h3> +<p>DOM Level 2 Styles - STYLESHEET</p> +<p>{{ languages( { "pl": "pl/DOM/stylesheet.ownerNode" } ) }}</p> diff --git a/files/es/web/api/stylesheet/parentstylesheet/index.html b/files/es/web/api/stylesheet/parentstylesheet/index.html new file mode 100644 index 0000000000..118aedd82a --- /dev/null +++ b/files/es/web/api/stylesheet/parentstylesheet/index.html @@ -0,0 +1,24 @@ +--- +title: Stylesheet.parentStyleSheet +slug: Web/API/StyleSheet/parentStyleSheet +translation_of: Web/API/StyleSheet/parentStyleSheet +--- +<p>{{ ApiRef() }}</p> +<h3 id="Summary" name="Summary">Resumen</h3> +<p>Devuelve la hoja de estilo que incluye a la que está en curso, si existe.</p> +<h3 id="Syntax" name="Syntax">Sintaxis</h3> +<pre class="eval"><em>objRef</em> = stylesheet.parentStyleSheet +</pre> +<h3 id="Example" name="Example">Ejemplo</h3> +<pre class="eval">// encuentra la hoja de estilo de alto nivel +if (stylesheet.parentStyleSheet) { + sheet = stylesheet.parentStyleSheet; +} +else +{ sheet = stylesheet; } +</pre> +<h3 id="Notes" name="Notes">Notas</h3> +<p>Esta propiedad devuelve NULL si la hoja de estilo actual es una hoja de estilo de alto nivel o si la inclusión de hojas de estilo no está implementada.</p> +<h3 id="Specification" name="Specification">Specification</h3> +<p><a class="external" href="http://www.w3.org/TR/2000/REC-DOM-Level-2-Style-20001113/stylesheets.html#StyleSheets-StyleSheet-parentStyleSheet">parentStyleSheet </a></p> +<p>{{ languages( { "pl": "pl/DOM/stylesheet.parentStyleSheet" } ) }}</p> diff --git a/files/es/web/api/stylesheet/title/index.html b/files/es/web/api/stylesheet/title/index.html new file mode 100644 index 0000000000..e6c61082d7 --- /dev/null +++ b/files/es/web/api/stylesheet/title/index.html @@ -0,0 +1,13 @@ +--- +title: Stylesheet.title +slug: Web/API/StyleSheet/title +translation_of: Web/API/StyleSheet/title +--- +<p>{{ ApiRef() }}</p> +<h3 id="Summary" name="Summary">Resumen</h3> +<p><strong>title</strong> devuelve el título de la hoja de estilo que se está usando.</p> +<h3 id="Notes" name="Notes">Notas</h3> +<p>El título es a menudo especificado en el <a href="/es/DOM/stylesheet.ownerNode" title="es/DOM/stylesheet.ownerNode">ownerNode</a>.</p> +<h3 id="Specification" name="Specification">Especificación</h3> +<p><a class="external" href="http://www.w3.org/TR/2000/REC-DOM-Level-2-Style-20001113/stylesheets.html#StyleSheets-StyleSheet-title">title </a></p> +<p>{{ languages( { "pl": "pl/DOM/stylesheet.title" } ) }}</p> diff --git a/files/es/web/api/stylesheet/type/index.html b/files/es/web/api/stylesheet/type/index.html new file mode 100644 index 0000000000..fa60372cc0 --- /dev/null +++ b/files/es/web/api/stylesheet/type/index.html @@ -0,0 +1,17 @@ +--- +title: Stylesheet.type +slug: Web/API/StyleSheet/type +translation_of: Web/API/StyleSheet/type +--- +<p>{{ ApiRef() }}</p> +<h3 id="Summary" name="Summary">Resumen</h3> +<p>type especifica el lenguaje de la hoja de estilo.</p> +<h3 id="Syntax" name="Syntax">Sintaxis</h3> +<pre class="eval"><em>string</em> = stylesheet.type +</pre> +<h3 id="Example" name="Example">Ejemplo</h3> +<pre> ss.type = "text/css"; +</pre> +<h3 id="Specification" name="Specification">Especificación</h3> +<p><a class="external" href="http://www.w3.org/TR/2000/REC-DOM-Level-2-Style-20001113/stylesheets.html#StyleSheets-StyleSheet-type">type </a></p> +<p>{{ languages( { "pl": "pl/DOM/stylesheet.type" } ) }}</p> diff --git a/files/es/web/api/subtlecrypto/digest/index.html b/files/es/web/api/subtlecrypto/digest/index.html new file mode 100644 index 0000000000..48669844b6 --- /dev/null +++ b/files/es/web/api/subtlecrypto/digest/index.html @@ -0,0 +1,135 @@ +--- +title: SubtleCrypto.digest() +slug: Web/API/SubtleCrypto/digest +translation_of: Web/API/SubtleCrypto/digest +--- +<div>{{APIRef("Web Crypto API")}}</div> + +<p>El método <code><strong>digest()</strong></code> de la interfaz {{domxref("SubtleCrypto")}} genera un digest de los datos proveidos. Un {{domxref("digest")}} es un valor corto de longitud fija derivado de alguna entrada de longitud variable. Los digest criptográficos deben mostrar resistencia a colisiones, lo que significa que es difícil encontrar dos entradas diferentes que tengan el mismo valor de digest.</p> + +<p>Toma como argumento un identificador para el algoritmo digest a utilizar y los datos a codificar. Devuelve un <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" title="The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value."><code>Promise</code></a> que se completará con el digest.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">const digest = <em>crypto</em><code>.subtle.digest(<em>algorithm</em>, <em>data</em>)</code>; +</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<ul> + <li><em><code>algorithm</code></em> es un {{domxref("DOMString")}} definiendo la función hash a utilizar. Los valores admitidos son: + + <ul> + <li><code>SHA-1</code> (pero no debe utilizarse en aplicaciones criptográficas)</li> + <li><code>SHA-256</code></li> + <li><code>SHA-384</code></li> + <li><code>SHA-512</code></li> + </ul> + </li> + <li><em><code>data</code></em> es un {{jsxref("ArrayBuffer")}} o {{domxref("ArrayBufferView")}} que contiene los datos a ser digitalizados.</li> +</ul> + +<h3 id="Valor_de_retorno">Valor de retorno</h3> + +<ul> + <li><code><em>digest</em></code> es un <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" title="The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value."><code>Promise</code></a> que se completa con un <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" title="The ArrayBuffer object is used to represent a generic, fixed-length raw binary data buffer. You cannot directly manipulate the contents of an ArrayBuffer; instead, you create one of the typed array objects or a DataView object which represents the buffer in a specific format, and use that to read and write the contents of the buffer."><code>ArrayBuffer</code></a> conteniendo el digest.</li> +</ul> + +<h2 id="Algoritmos_soportados">Algoritmos soportados</h2> + +<p>Los argoritmos digest, también conocidos como <a href="/en-US/docs/Glossary/Cryptographic_hash_function">funciones criptográficas hash</a>, transforman un bloque de datos arbitrariamente grande en una salida de tamaño fijo, normalmente mucho más corta que la entrada. Tienen una variedad de aplicaciones en criptografía.</p> + +<h3 id="SHA-1">SHA-1</h3> + +<p>Este algoritmo se especifica en <a href="https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf">FIPS 180-4</a>, sección 6.1, y produce una salida de 160 bits de largo.</p> + +<div class="blockIndicator warning"> +<p><strong>Advertencia</strong>: Este algoritmo se considera ahora vulnerable y no debe utilizarse para aplicaciones criptográficas.</p> +</div> + +<h3 id="SHA-256">SHA-256</h3> + +<p>Este algoritmo se especifica en <a href="https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf">FIPS 180-4</a>, sección 6.2, y produce una salida de 256 bits de largo.</p> + +<h3 id="SHA-384">SHA-384</h3> + +<p>Este algoritmo se especifica en <a href="https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf">FIPS 180-4</a>, sección 6.5, y produce una salida de 384 bits de largo.</p> + +<h3 id="SHA-512">SHA-512</h3> + +<p>Este algoritmo se especifica en <a href="https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf">FIPS 180-4</a>, sección 6.4, y produce una salida de 512 bits de largo.</p> + +<div class="blockIndicator note"> +<p>Sugerencia: Si estás buscando aquí cómo crear un código de autenticación de mensajes "keyed-hash" (<a href="/en-US/docs/Glossary/HMAC">HMAC</a>), necesitas usar <a href="/en-US/docs/Web/API/SubtleCrypto/sign#HMAC">SubtleCrypto.sign()</a> en su lugar.</p> +</div> + +<h2 id="Ejemplos">Ejemplos</h2> + +<h3 id="Ejemplo_básico">Ejemplo básico</h3> + +<p>Este ejemplo codifica un mensaje, luego calcula su digest SHA-256 y muestra la longitud del mismo:</p> + +<pre class="brush: js">const text = 'An obscure body in the S-K System, your majesty. The inhabitants refer to it as the planet Earth.'; + +async function digestMessage(message) { + const encoder = new TextEncoder(); + const data = encoder.encode(message); + const hash = await crypto.subtle.digest('SHA-256', data); + return hash; +} + +const digestBuffer = await digestMessage(text); +console.log(digestBuffer.byteLength); +</pre> + +<h3 id="Convirtiendo_un_digest_a_una_cadena_hexadecimal">Convirtiendo un digest a una cadena hexadecimal</h3> + +<p>El resumen se devuelve como un <code>ArrayBuffer</code>, pero para la comparación y visualización los digests se representan a menudo como cadenas hexadecimales. Este ejemplo calcula un digest, y luego convierte el <code>ArrayBuffer</code> a un string hexadecimal:</p> + +<pre class="brush: js">const text = 'An obscure body in the S-K System, your majesty. The inhabitants refer to it as the planet Earth.'; + +async function digestMessage(message) { + const msgUint8 = new TextEncoder().encode(message); // encode as (utf-8) Uint8Array + const hashBuffer = await crypto.subtle.digest('SHA-256', msgUint8); // hash the message + const hashArray = Array.from(new Uint8Array(hashBuffer)); // convert buffer to byte array + const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join(''); // convert bytes to hex string + return hashHex; +} + +const digestHex = await digestMessage(text); +console.log(digestHex); +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('Web Crypto API', '#dfn-SubtleCrypto-method-digest', 'SubtleCrypto.digest()')}}</td> + <td>{{Spec2('Web Crypto API')}}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_del_navegador">Compatibilidad del navegador</h2> + +<div class="hidden">La tabla de compatibilidad de esta página se genera a partir de datos estructurados. Si desea contribuir a los datos, por favor, revise <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> y envíenos un pull request.</div> + +<p>{{Compat("api.SubtleCrypto.digest")}}</p> + +<div class="blockIndicator note"> +<p>En Chrome 60, se añadió una característica que deshabilita crypto.subtle para conexiones no TLS.</p> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="https://www.chromium.org/Home/chromium-security/prefer-secure-origins-for-powerful-new-features">Chromium especificación de origines seguro</a></li> + <li><a href="https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf" rel="noopener">FIPS 180-4</a> especifica la familia de algoritmos de digest SHA.</li> +</ul> diff --git a/files/es/web/api/subtlecrypto/encrypt/index.html b/files/es/web/api/subtlecrypto/encrypt/index.html new file mode 100644 index 0000000000..8f35030d35 --- /dev/null +++ b/files/es/web/api/subtlecrypto/encrypt/index.html @@ -0,0 +1,142 @@ +--- +title: SubtleCrypto.digest() +slug: Web/API/SubtleCrypto/encrypt +tags: + - API + - Encriptación + - Referencia + - SubtleCrypto + - Web Crypto API + - encrypt +translation_of: Web/HTTP/Headers/Digest +--- +<div>{{APIRef("Web Crypto API")}}</div> + +<p>El método <code><strong>digest()</strong></code> de la interfaz {{domxref("SubtleCrypto")}} genera un digest de los datos proveidos. Un {{domxref("digest")}} es un valor corto de longitud fija derivado de alguna entrada de longitud variable. Los digest criptográficos deben mostrar resistencia a colisiones, lo que significa que es difícil encontrar dos entradas diferentes que tengan el mismo valor de digest.</p> + +<p>Toma como argumento un identificador para el algoritmo digest a utilizar y los datos a codificar. Devuelve un <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" title="The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value."><code>Promise</code></a> que se completará con el digest.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">const digest = <em>crypto</em><code>.subtle.digest(<em>algorithm</em>, <em>data</em>)</code>; +</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<ul> + <li><em><code>algorithm</code></em> es un {{domxref("DOMString")}} definiendo la función hash a utilizar. Los valores admitidos son: + + <ul> + <li><code>SHA-1</code> (pero no debe utilizarse en aplicaciones criptográficas)</li> + <li><code>SHA-256</code></li> + <li><code>SHA-384</code></li> + <li><code>SHA-512</code></li> + </ul> + </li> + <li><em><code>data</code></em> es un {{jsxref("ArrayBuffer")}} o {{domxref("ArrayBufferView")}} que contiene los datos a ser digitalizados.</li> +</ul> + +<h3 id="Valor_de_retorno">Valor de retorno</h3> + +<ul> + <li><code><em>digest</em></code> es un <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" title="The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value."><code>Promise</code></a> que se completa con un <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" title="The ArrayBuffer object is used to represent a generic, fixed-length raw binary data buffer. You cannot directly manipulate the contents of an ArrayBuffer; instead, you create one of the typed array objects or a DataView object which represents the buffer in a specific format, and use that to read and write the contents of the buffer."><code>ArrayBuffer</code></a> conteniendo el digest.</li> +</ul> + +<h2 id="Algoritmos_soportados">Algoritmos soportados</h2> + +<p>Los argoritmos digest, también conocidos como <a href="/en-US/docs/Glossary/Cryptographic_hash_function">funciones criptográficas hash</a>, transforman un bloque de datos arbitrariamente grande en una salida de tamaño fijo, normalmente mucho más corta que la entrada. Tienen una variedad de aplicaciones en criptografía.</p> + +<h3 id="SHA-1">SHA-1</h3> + +<p>Este algoritmo se especifica en <a href="https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf">FIPS 180-4</a>, sección 6.1, y produce una salida de 160 bits de largo.</p> + +<div class="blockIndicator warning"> +<p><strong>Advertencia</strong>: Este algoritmo se considera ahora vulnerable y no debe utilizarse para aplicaciones criptográficas.</p> +</div> + +<h3 id="SHA-256">SHA-256</h3> + +<p>Este algoritmo se especifica en <a href="https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf">FIPS 180-4</a>, sección 6.2, y produce una salida de 256 bits de largo.</p> + +<h3 id="SHA-384">SHA-384</h3> + +<p>Este algoritmo se especifica en <a href="https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf">FIPS 180-4</a>, sección 6.5, y produce una salida de 384 bits de largo.</p> + +<h3 id="SHA-512">SHA-512</h3> + +<p>Este algoritmo se especifica en <a href="https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf">FIPS 180-4</a>, sección 6.4, y produce una salida de 512 bits de largo.</p> + +<div class="blockIndicator note"> +<p>Sugerencia: Si estás buscando aquí cómo crear un código de autenticación de mensajes "keyed-hash" (<a href="/en-US/docs/Glossary/HMAC">HMAC</a>), necesitas usar <a href="/en-US/docs/Web/API/SubtleCrypto/sign#HMAC">SubtleCrypto.sign()</a> en su lugar.</p> +</div> + +<h2 id="Ejemplos">Ejemplos</h2> + +<h3 id="Ejemplo_básico">Ejemplo básico</h3> + +<p>Este ejemplo codifica un mensaje, luego calcula su digest SHA-256 y muestra la longitud del mismo:</p> + +<pre class="brush: js">const text = 'An obscure body in the S-K System, your majesty. The inhabitants refer to it as the planet Earth.'; + +async function digestMessage(message) { + const encoder = new TextEncoder(); + const data = encoder.encode(message); + const hash = await crypto.subtle.digest('SHA-256', data); + return hash; +} + +const digestBuffer = await digestMessage(text); +console.log(digestBuffer.byteLength); +</pre> + +<h3 id="Convirtiendo_un_digest_a_una_cadena_hexadecimal">Convirtiendo un digest a una cadena hexadecimal</h3> + +<p>El resumen se devuelve como un <code>ArrayBuffer</code>, pero para la comparación y visualización los digests se representan a menudo como cadenas hexadecimales. Este ejemplo calcula un digest, y luego convierte el <code>ArrayBuffer</code> a un string hexadecimal:</p> + +<pre class="brush: js">const text = 'An obscure body in the S-K System, your majesty. The inhabitants refer to it as the planet Earth.'; + +async function digestMessage(message) { + const msgUint8 = new TextEncoder().encode(message); // encode as (utf-8) Uint8Array + const hashBuffer = await crypto.subtle.digest('SHA-256', msgUint8); // hash the message + const hashArray = Array.from(new Uint8Array(hashBuffer)); // convert buffer to byte array + const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join(''); // convert bytes to hex string + return hashHex; +} + +const digestHex = await digestMessage(text); +console.log(digestHex); +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('Web Crypto API', '#dfn-SubtleCrypto-method-digest', 'SubtleCrypto.digest()')}}</td> + <td>{{Spec2('Web Crypto API')}}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_del_navegador">Compatibilidad del navegador</h2> + +<div class="hidden">La tabla de compatibilidad de esta página se genera a partir de datos estructurados. Si desea contribuir a los datos, por favor, revise <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> y envíenos un pull request.</div> + +<p>{{Compat("api.SubtleCrypto.digest")}}</p> + +<div class="blockIndicator note"> +<p>En Chrome 60, se añadió una característica que deshabilita crypto.subtle para conexiones no TLS.</p> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="https://www.chromium.org/Home/chromium-security/prefer-secure-origins-for-powerful-new-features">Chromium especificación de origines seguro</a></li> + <li><a href="https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf" rel="noopener">FIPS 180-4</a> especifica la familia de algoritmos de digest SHA.</li> +</ul> diff --git a/files/es/web/api/subtlecrypto/index.html b/files/es/web/api/subtlecrypto/index.html new file mode 100644 index 0000000000..429f0c080e --- /dev/null +++ b/files/es/web/api/subtlecrypto/index.html @@ -0,0 +1,290 @@ +--- +title: SubtleCrypto +slug: Web/API/SubtleCrypto +tags: + - API + - Interfaz + - Referencia + - SubtleCrypto + - Web Crypto API +translation_of: Web/API/SubtleCrypto +--- +<div>{{APIRef("Web Crypto API")}}</div> + +<p>La interfaz <code><strong>SubtleCrypto</strong></code> de la <a href="/en-US/docs/Web/API/Web_Crypto_API">Web Crypto API</a> provee una serie de funciones criptográficas de bajo nivel. Se accede a ella a través de las propiedades {{domxref("Crypto.subtle")}} disponible en un contexto de la ventana (via {{domxref("Window.crypto")}}).</p> + +<div class="warning"> +<p><strong>Advertencia:</strong> Esta API proporciona una serie de primitivos criptográficos de bajo nivel. Es muy fácil hacer un mal uso de ellos, y las trampas involucradas pueden ser muy sutiles.</p> + +<p>Incluso suponiendo que se utilicen correctamente las funciones criptográficas básicas, la gestión segura de las claves y el diseño general del sistema de seguridad son extremadamente difíciles de conseguir correctamente, y generalmente son el dominio de expertos en seguridad especializados.</p> + +<p>Los errores en el diseño e implementación del sistema de seguridad pueden hacer que la seguridad del sistema sea completamente ineficaz.</p> + +<p><strong>Si no estás seguro de saber lo que estás haciendo, probablemente no deberías usar esta API.</strong></p> +</div> + +<h2 id="Descripción_general">Descripción general</h2> + +<p>Podemos dividir las funciones implementadas por esta API en dos grupos: funciones criptográficas y funciones de administración de claves.</p> + +<h3 id="Funciones_criptográficas">Funciones criptográficas</h3> + +<p>Estas son las funciones que puedes utilizar para implementar características de seguridad como la privacidad y la autenticación en un sistema. El API de <code>SubtleCrypto</code> proporciona las siguientes funciones criptográficas:</p> + +<p>* {{DOMxRef("SubtleCrypto.sign","sign()")}} y {{DOMxRef("SubtleCrypto.verify","verify()")}}: crea y verifica las firmas digitales.<br> + * {{DOMxRef("SubtleCrypto.encrypt","encrypt()")}} y {{DOMxRef("SubtleCrypto.decrypt","decrypt()")}}: encripta y desencripta datos.<br> + * {{DOMxRef("SubtleCrypto.digest","digest()")}}: crea un digest de longitud fija y resistente a colisiones de algunos datos.</p> + +<h3 id="Funciones_de_gestión_clave">Funciones de gestión clave</h3> + +<p>Excepto para {{DOMxRef("SubtleCrypto.digest","digest()")}}, todas las funciones de criptografía de la API utilizan claves criptográficas. En la API <code>SubtleCrypto</code> una clave criptográfica se representa usando un objeto {{DOMxRef("CryptoKey","CryptoKey")}}. Para realizar operaciones como firmado y encriptación, provee un objeto {{DOMxRef("CryptoKey","CryptoKey")}} a la función {{DOMxRef("SubtleCrypto.sign","sign()")}} o {{DOMxRef("SubtleCrypto.encrypt","encrypt()")}}.</p> + +<h4 id="Generando_y_derivando_claves">Generando y derivando claves</h4> + +<p>Las funciones {{DOMxRef("SubtleCrypto.generateKey","generateKey()")}} y {{DOMxRef("SubtleCrypto.deriveKey","deriveKey()")}} ambos crean un nuevo objeto {{DOMxRef("CryptoKey")}}.</p> + +<p>La diferencia es que <code>generateKey()</code> generará un nuevo valor clave distinto cada vez que lo llames, mientras que <code>deriveKey()</code> deriva una llave de algún material inicial de claves. Si proporcionas el mismo material de claves a dos llamadas separadas a <code>deriveKey()</code>, obtendrás dos objetos <code>CryptoKey</code> que tienen el mismo valor de base. Esto es útil si, por ejemplo, se quiere derivar una clave de cifrado de una contraseña y luego derivar la misma clave de la misma contraseña para descifrar los datos.</p> + +<h4 id="Importación_y_exportación_de_claves">Importación y exportación de claves</h4> + +<p>Para hacer que las claves estén disponibles fuera de tu aplicación, necesitas exportar la clave, y para eso sirve {{DOMxRef("SubtleCrypto.exportKey","exportKey()")}}.Puedes elegir uno de varios formatos de exportación.</p> + +<p>El inverso de <code>exportKey()</code> es {{DOMxRef("SubtleCrypto.importKey","importKey()")}}. Puedes importar claves de otros sistemas, y la compatibilidad con formatos estándar como <a href="https://tools.ietf.org/html/rfc5208">PKCS #8</a> y <a href="https://tools.ietf.org/html/rfc7517">JSON Web Key</a> te ayudan a hacer esto. La función <code>exportKey()</code> exporta la clave en un formato no codificado.</p> + +<p>Si la clave es sensible, deberías usar {{DOMxRef("SubtleCrypto.wrapKey","wrapKey()")}}, que exporta la clave y luego la encripta usando otra clave; el API llama a una "llave de envoltura".</p> + +<p>El inverso de <code>wrapKey()</code> es {{DOMxRef("SubtleCrypto.unwrapKey","unwrapKey()")}}, que descifra y luego importa la llave.</p> + +<h4 id="Almacenamiento_de_claves">Almacenamiento de claves</h4> + +<p>Epecification objetos <code>CryptoKey</code> pueden ser almacenados usando el <a href="/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm">structured clone algorithm</a>, lo que significa que puedes almacenarlos y recuperarlos usando las API de almacenamiento web estándar. La especificación espera que la mayoría de los desarrolladores usen el <a href="/en-US/docs/Web/API/IndexedDB_API">IndexedDB API</a> para almacenar objetos <code>CryptoKey</code>.</p> + +<h3 id="Algoritmos_Suportados">Algoritmos Suportados</h3> + +<p>Las funciones criptográficas que proporciona la Web Crypto API pueden ser realizadas por uno o más <em>algoritmos criptográficos </em>diferentes: El argumento <code>algorithm</code> de la función indica el algoritmo a utilizar. Algunos algoritmos necesitan parámetros adicionales: en estos casos el argumento <code>algorithm</code> es un objeto de diccionario que incluye los parámetros adicionales.</p> + +<p>En el cuadro que figura a continuación se resume qué algoritmos son adecuados para cada operación criptográfica:</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="row"></th> + <th scope="col"> + <p><a href="/en-US/docs/Web/API/SubtleCrypto/sign">sign()</a></p> + + <p><a href="/en-US/docs/Web/API/SubtleCrypto/verify">verify()</a></p> + </th> + <th scope="col"> + <p><a href="/en-US/docs/Web/API/SubtleCrypto/encrypt">encrypt()</a></p> + + <p><a href="/en-US/docs/Web/API/SubtleCrypto/decrypt">decrypt()</a></p> + </th> + <th scope="col"><a href="/en-US/docs/Web/API/SubtleCrypto/digest">digest()</a></th> + <th scope="col"> + <p><a href="/en-US/docs/Web/API/SubtleCrypto/deriveBits">deriveBits()</a></p> + + <p><a href="/en-US/docs/Web/API/SubtleCrypto/deriveKey">deriveKey()</a></p> + </th> + <th scope="col"> + <p><a href="/en-US/docs/Web/API/SubtleCrypto/wrapKey">wrapKey()</a></p> + + <p><a href="/en-US/docs/Web/API/SubtleCrypto/unwrapKey">unwrapKey()</a></p> + </th> + </tr> + </thead> + <tbody> + <tr> + <th scope="row">RSASSA-PKCS1-v1_5</th> + <td>✓</td> + <td></td> + <td></td> + <td></td> + <td></td> + </tr> + <tr> + <th scope="row">RSA-PSS</th> + <td>✓</td> + <td></td> + <td></td> + <td></td> + <td></td> + </tr> + <tr> + <th scope="row">ECDSA</th> + <td>✓</td> + <td></td> + <td></td> + <td></td> + <td></td> + </tr> + <tr> + <th scope="row">HMAC</th> + <td>✓</td> + <td></td> + <td></td> + <td></td> + <td></td> + </tr> + <tr> + <th scope="row">RSA-OAEP</th> + <td></td> + <td>✓</td> + <td></td> + <td></td> + <td>✓</td> + </tr> + <tr> + <th scope="row">AES-CTR</th> + <td></td> + <td>✓</td> + <td></td> + <td></td> + <td>✓</td> + </tr> + <tr> + <th scope="row">AES-CBC</th> + <td></td> + <td>✓</td> + <td></td> + <td></td> + <td>✓</td> + </tr> + <tr> + <th scope="row">AES-GCM</th> + <td></td> + <td>✓</td> + <td></td> + <td></td> + <td>✓</td> + </tr> + <tr> + <th scope="row">SHA-1</th> + <td></td> + <td></td> + <td>✓</td> + <td></td> + <td></td> + </tr> + <tr> + <th scope="row">SHA-256</th> + <td></td> + <td></td> + <td>✓</td> + <td></td> + <td></td> + </tr> + <tr> + <th scope="row">SHA-384</th> + <td></td> + <td></td> + <td>✓</td> + <td></td> + <td></td> + </tr> + <tr> + <th scope="row">SHA-512</th> + <td></td> + <td></td> + <td>✓</td> + <td></td> + <td></td> + </tr> + <tr> + <th scope="row">ECDH</th> + <td></td> + <td></td> + <td></td> + <td>✓</td> + <td></td> + </tr> + <tr> + <th scope="row">HKDF</th> + <td></td> + <td></td> + <td></td> + <td>✓</td> + <td></td> + </tr> + <tr> + <th scope="row">PBKDF2</th> + <td></td> + <td></td> + <td></td> + <td>✓</td> + <td></td> + </tr> + <tr> + <th scope="row">AES-KW</th> + <td></td> + <td></td> + <td></td> + <td></td> + <td>✓</td> + </tr> + </tbody> +</table> + +<h2 id="Propiedades">Propiedades</h2> + +<p><em>Esta interfaz no hereda ni implementa ninguna propiedad.</em></p> + +<h2 id="Métodos">Métodos</h2> + +<p><em>Esta interfaz no hereda ningún método.</em></p> + +<dl> + <dt>{{domxref("SubtleCrypto.encrypt()")}}</dt> + <dd>Retorna un {{jsxref("Promise")}} que se completa con los datos codificados correspondientes al texto sin cifrar, el algoritmo y la clave dados como parámetros.</dd> + <dt>{{domxref("SubtleCrypto.decrypt()")}}</dt> + <dd>Retorna un {{jsxref("Promise")}} que se completa con los datos claros correspondientes al texto encriptado, el algoritmo y la clave dados como parámetros.</dd> + <dt>{{domxref("SubtleCrypto.sign()")}}</dt> + <dd>Retorna un {{jsxref("Promise")}} que se completa con la firma correspondiente al texto, algoritmo y clave dados como parámetros.</dd> + <dt>{{domxref("SubtleCrypto.verify()")}}</dt> + <dd>Retorna un {{jsxref("Promise")}} que se completa con un valor {{jsxref("Boolean")}} indicando si la firma dada como parámetro coincide con el texto, el algoritmo y la clave que también se dan como parámetros.</dd> + <dt>{{domxref("SubtleCrypto.digest()")}}</dt> + <dd>Retorna un {{jsxref("Promise")}} que se completa con digest generado a partir del algoritmo y el texto dados como parámetros.</dd> + <dt>{{domxref("SubtleCrypto.generateKey()")}}</dt> + <dd>Retorna un {{jsxref("Promise")}} que se completa con un recién generado {{domxref("CryptoKey")}}, para algoritmos simétricos, o un {{domxref("CryptoKeyPair")}}, que contiene dos claves recién generadas, para algoritmos asimétricos. Estas coincidirán con el algoritmo, usos y extraíbles dados como parámetros.</dd> + <dt>{{domxref("SubtleCrypto.deriveKey()")}}</dt> + <dd>Retorna un {{jsxref("Promise")}} que se completa con un recién generado {{domxref("CryptoKey")}} derivado de la clave maestra y el algoritmo específico dados como parámetros.</dd> + <dt>{{domxref("SubtleCrypto.deriveBits()")}}</dt> + <dd>Retorna un {{jsxref("Promise")}} que se completa con un recién generado buffer de bits pseudo-aleatorios derivado de la clave maestra y el algoritmo específico dados como parámetros.</dd> + <dt>{{domxref("SubtleCrypto.importKey()")}}</dt> + <dd>Retorna un {{jsxref("Promise")}} que se completa con un {{domxref("CryptoKey")}} correspondiente al formato, el algoritmo, los datos clave en bruto, los usos y la extraíbilidad dados como parámetros.</dd> + <dt>{{domxref("SubtleCrypto.exportKey()")}}</dt> + <dd>Retorna un {{jsxref("Promise")}} que se completa con un buffer que contiene la clave en el formato solicitado.</dd> + <dt>{{domxref("SubtleCrypto.wrapKey()")}}</dt> + <dd>Retorna un {{jsxref("Promise")}} que se completa con una llave simétrica envuelta para su uso (transferencia y almacenamiento) en entornos inseguros. La llave envuelta coincide con el formato especificado en los parámetros dados, y la envoltura se hace con la llave envuelta dada, usando el algoritmo especificado.</dd> + <dt>{{domxref("SubtleCrypto.unwrapKey()")}}</dt> + <dd>Retorna un {{jsxref("Promise")}} que se completa con un {{domxref("CryptoKey")}} correspondiente a la llave envuelta dada en el parámetro.</dd> +</dl> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{ SpecName('Web Crypto API', '#subtlecrypto-interface', 'SubtleCrypto') }}</td> + <td>{{ Spec2('Web Crypto API') }}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_del_navegador">Compatibilidad del navegador</h2> + + + +<p>{{Compat("api.SubtleCrypto")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("Crypto")}} and {{domxref("Crypto.subtle")}}.</li> + <li><a href="https://www.crypto101.io/">Crypto 101</a>: un curso de introducción a la criptografía (en inglés).</li> +</ul> diff --git a/files/es/web/api/svgpoint/index.html b/files/es/web/api/svgpoint/index.html new file mode 100644 index 0000000000..9709061af4 --- /dev/null +++ b/files/es/web/api/svgpoint/index.html @@ -0,0 +1,13 @@ +--- +title: SVGPoint +slug: Web/API/SVGPoint +tags: + - SVGPoint + - createSVGPoint + - getScreenCTM + - matrixTransform +translation_of: Web/API/SVGPoint +--- +<div>{{APIRef("SVG")}}</div> + +<p>Crea un nuevo elemento SVGPoint que se inicializa en el origen ( 0,0) del sistema de coordenadas. El elemento no es visible ni es agregado al DOM</p> diff --git a/files/es/web/api/texttrack/cuechange_event/index.html b/files/es/web/api/texttrack/cuechange_event/index.html new file mode 100644 index 0000000000..4a667535fc --- /dev/null +++ b/files/es/web/api/texttrack/cuechange_event/index.html @@ -0,0 +1,109 @@ +--- +title: 'TextTrack: evento cuechange' +slug: Web/API/TextTrack/cuechange_event +tags: + - API + - Audio + - Event + - Media + - Reference + - TextTrack + - Video + - WebVTT + - cuechange + - events + - oncuechange + - track +translation_of: Web/API/TextTrack/cuechange_event +--- +<div>{{APIRef}}</div> + +<p><span class="seoSummary">El evento <strong><code>cuechange</code></strong> se activa cuando un {{domxref("TextTrack")}} ha cambiado las anotaciones que se estan mostrando.</span> El evento es activado tanto en <code>TextTrack</code> <em>y</em> en el {{domxref("HTMLTrackElement")}} donde esta siendo mostrado, si lo hay.</p> + +<table class="properties"> + <tbody> + <tr> + <th scope="row">Burbujas</th> + <td>No</td> + </tr> + <tr> + <th scope="row">Cancelable</th> + <td>No</td> + </tr> + <tr> + <th scope="row">Interfaz</th> + <td>{{domxref("Event")}}</td> + </tr> + <tr> + <th scope="row">Propiedad del controlador de eventos</th> + <td>{{domxref("GlobalEventHandlers.oncuechange")}}</td> + </tr> + </tbody> +</table> + +<h2 id="Ejemplos">Ejemplos</h2> + +<h3 id="En_el_TextTrack">En el TextTrack</h3> + +<p>Tu puedes preparar una escucha para el evento <code>cuechange</code> en un <code>TextTrack</code> usando el método {{domxref("EventTarget.addEventListener", "addEventListener()")}}:</p> + +<pre class="brush: js notranslate">track.addEventListener('cuechange', function () { + let cues = track.activeCues; // array de las anotaciones actuales +}); +</pre> + +<p>O puedes solo preparar la propiedad del controlador de eventos {{domxref("GlobalEventHandlers.oncuechange", "oncuechange")}}:</p> + +<pre class="brush: js notranslate">track.oncuechange = function () { + let cues = track.activeCues; // array of current cues +}</pre> + +<h3 id="En_el_elemento_track">En el elemento track</h3> + +<p>El subyacente {{domxref("TextTrack")}}, indicado por la propiedad {{domxref("HTMLTrackElement.track", "track")}}, recive un evento {{domxref("TextTrack.cuechange_event", "cuechange")}} cada vez que la anotación que esta siendo actualmente presentada cambia. Est sucede incluso si la pista de texto no está asociada cun un elemento multimedia.</p> + +<p>Si la pista de texto <em>está</em> asociada con el elemento multimedia, usando el elemento {{HTMLElement("track")}} como hijo del elemento {{HTMLElement("audio")}} o del elemento {{HTMLElement("video")}}, el evento <code>cuechange</code> es también enviado al {{domxref("HTMLTrackElement")}}.</p> + +<pre class="brush: js notranslate">let textTrackElem = document.getElementById("texttrack"); + +textTrackElem.addEventListener("cuechange", (event) => { + let cues = event.target.track.activeCues; +}); +</pre> + +<p>Además, puedes utilizar el controlador de eventos <code>oncuechange</code>:</p> + +<pre class="brush: js notranslate">let textTrackElem = document.getElementById("texttrack"); + +textTrackElem.oncuechange = (event) => { + let cues = event.target.track.activeCues; +});</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('HTML WHATWG', '#event-media-cuechange', 'cuechange')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_los_navegadores">Compatibilidad de los navegadores</h2> + +<div class="hidden">La tabla de compatibilidad en esta página está generada desde datos estructurados. Si quieres contribuir a los datos, por favor visita <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> y envíanos una pull request.</div> + +<p>{{Compat("api.TextTrack.cuechange_event")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{glossary("WebVTT")}}</li> +</ul> diff --git a/files/es/web/api/texttrack/index.html b/files/es/web/api/texttrack/index.html new file mode 100644 index 0000000000..17c32575fa --- /dev/null +++ b/files/es/web/api/texttrack/index.html @@ -0,0 +1,102 @@ +--- +title: TextTrack +slug: Web/API/TextTrack +tags: + - API + - Interface + - Media + - NeedsTranslation + - Reference + - TextTrack + - TopicStub + - Web + - WebVTT +translation_of: Web/API/TextTrack +--- +<div>{{APIRef("WebVTT")}}</div> + +<div id="interface_description"> +<p>The <code>TextTrack</code> interface—part of the API for handling WebVTT (text tracks on media presentations)—describes and controls the text track associated with a particular {{HTMLElement("track")}} element.</p> +</div> + +<h2 id="Properties">Properties</h2> + +<p class="properties also_inherits"><em>This interface also inherits properties from {{domxref("EventTarget")}}.</em></p> + +<dl id="property_definitions"> + <dt>{{domxref("TextTrack.activeCues")}} {{readonlyInline}}</dt> + <dd>A {{domxref("TextTrackCueList")}} object listing the currently active set of text track cues. Track cues are active if the current playback position of the media is between the cues' start and end times. Thus, for displayed cues such as captions or subtitles, the active cues are currently being displayed.</dd> + <dt>{{domxref("TextTrack.cues")}} {{readonlyInline}}</dt> + <dd>A {{domxref("TextTrackCueList")}} which contains all of the track's cues.</dd> + <dt>{{domxref("TextTrack.id")}} {{readonlyInline}}</dt> + <dd>A {{domxref("DOMString")}} which identifies the track, if it has one. If it doesn't have an ID, then this value is an empty string (<code>""</code>). If the <code>TextTrack</code> is associated with a {{HTMLElement("track")}} element, then the track's ID matches the element's ID.</dd> + <dt>{{domxref("TextTrack.inBandMetadataTrackDispatchType")}} {{readonlyInline}}</dt> + <dd>Returns a {{domxref("DOMString")}} which indicates the track's in-band metadata track dispatch type. <em><strong>needs details</strong></em></dd> + <dt>{{domxref("TextTrack.kind")}} {{readonlyInline}}</dt> + <dd>Returns a {{domxref("DOMString")}} indicating what kind of text track the <code>TextTrack</code> describes. The value must be one of those in the TextTrackKind enum.</dd> + <dt>{{domxref("TextTrack.label")}} {{readonlyInline}}</dt> + <dd>A human-readable {{domxref("DOMString")}} which contains the text track's label, if one is present; otherwise, this is an empty string (<code>""</code>), in which case a custom label may need to be generated by your code using other attributes of the track, if the track's label needs to be exposed to the user.</dd> + <dt>{{domxref("TextTrack.language")}} {{readonlyInline}}</dt> + <dd>A {{domxref("DOMString")}} which specifies the text language in which the text track's contents is written. The value must adhere to the format specified in the <a href="https://tools.ietf.org/html/bcp47">Tags for Identifying Languages</a> (<a href="https://tools.ietf.org/html/bcp47">BCP 47</a>) document from the IETF, just like the HTML {{htmlattrxref("lang")}} attribute. For example, this can be <code>"en-US"</code> for United States English or <code>"pt-BR"</code> for Brazilian Portuguese.</dd> + <dt>{{domxref("TextTrack.mode")}}</dt> + <dd>A {{domxref("DOMString")}} specifying the track's current mode. Changing this property's value changes the track's current mode to match. Permitted values are listed under <a href="/en-US/docs/Web/API/TextTrack/mode#Text_track_mode_constants">Text track mode constants</a>. The default is <code>disabled</code>, unless the {{HTMLElement("track")}} element's {{htmlattrxref("default", "track")}} Boolean attribute is specified, in which case the default mode is <code>started</code>.</dd> +</dl> + +<h2 id="Events">Events</h2> + +<dl id="event_handler_property_definitions"> + <dt><code><a href="/en-US/docs/Web/API/TextTrack/cuechange_event">cuechange</a></code></dt> + <dd>Fired when cues are entered and exited. A given text cue appears when the cue is entered and disappears when the cue is exited.<br> + Also available via the <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/oncuechange">oncuechange</a></code> property.</dd> +</dl> + +<h2 id="methods" name="methods">Methods</h2> + +<p class="methods also_inherits"><em>This interface also inherits methods from {{domxref("EventTarget")}}.</em></p> + +<dl id="method_definitions"> + <dt>{{domxref("TextTrack.addCue()")}}</dt> + <dd>Adds a cue (specified as a {{domxref("TextTrackCue")}} object to the track's list of cues.</dd> + <dt>{{domxref("TextTrack.removeCue()")}}</dt> + <dd>Removes a cue (specified as a {{domxref("TextTrackCue")}} object from the track's list of cues.</dd> +</dl> + +<dl id="method_definitions_obsolete"> +</dl> + +<h2 id="Example" name="Example">Example</h2> + +<p>tbd</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', '#texttrack', 'TextTrack') }}</td> + <td>{{ Spec2('HTML WHATWG') }}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("api.TextTrack")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/WebVTT_API">WebVTT</a></li> + <li>{{domxref("TextTrackCueList")}}</li> + <li>{{domxref("VTTCue")}}</li> + <li>{{HTMLElement("track")}}</li> + <li>{{domxref("HTMLTrackElement")}}</li> +</ul> diff --git a/files/es/web/api/touchevent/index.html b/files/es/web/api/touchevent/index.html new file mode 100644 index 0000000000..c18c737064 --- /dev/null +++ b/files/es/web/api/touchevent/index.html @@ -0,0 +1,190 @@ +--- +title: TouchEvent +slug: Web/API/TouchEvent +translation_of: Web/API/TouchEvent +--- +<p>{{ APIRef("Touch Events") }}</p> + +<p>La interfaz <strong><code>TouchEvent</code></strong> representa un evento enviado cuando cambia el estado de los contactos con una superficie sensible al tacto. Esta superficie puede ser una pantalla táctil o un trackpad, por ejemplo. El evento puede describir uno o mas puntos de contacto con la pantalla e incluye soporte para detectar el movimiento, adición y remoción de puntos de contacto, etc.</p> + +<p>Los toques pueden ser representados por el objeto {{ domxref("Touch") }}, cada toque es descrito por una posición, tamaño y forma, cantidad de presión, y el elemento que se presiona. Los toques son almacenados en el objeto {{ domxref("TouchList") }}</p> + +<p>Constructor</p> + +<dl> + <dt>{{domxref("TouchEvent.TouchEvent", "TouchEvent()")}}</dt> + <dd>Crea un objeto Touch<code>Event</code>.</dd> +</dl> + +<h2 id="Propiedades">Propiedades</h2> + +<p><em>Esta interfaz hereda propiedades de sus padres {{domxref("UIEvent")}} y {{domxref("Event")}}.</em></p> + +<dl> + <dt>{{ domxref("TouchEvent.altKey") }} {{readonlyInline}}</dt> + <dd>Un valor Booleano indicando si la tecla alt estaba pulsada cuando el evento touch fue lanzado.</dd> + <dt>{{ domxref("TouchEvent.changedTouches") }} {{readonlyInline}}</dt> + <dd>Una lista {{ domxref("TouchList") }} objetos {{ domxref("Touch") }} representan puntos de contacto individuales cuyos estados cambiaron entre el evento touch previo y este. </dd> + <dt>{{ domxref("TouchEvent.ctrlKey") }} {{readonlyInline}}</dt> + <dd>Un valor booleano que indica si la tecla de control estaba pulsada o no cuando el evento touch se disparó.</dd> + <dt>{{ domxref("TouchEvent.metaKey") }} {{readonlyInline}}</dt> + <dd>Un valor Boleano que indica si la tecla meta estaba apagada o no cuando el evento touch se disparó.</dd> + <dt>{{ domxref("TouchEvent.shiftKey") }} {{readonlyInline}}</dt> + <dd>Un valor Boleano que indica si la techa shift estaba apagado(presionada) cuando el evento touch se disparó.</dd> + <dt>{{ domxref("TouchEvent.targetTouches") }}{{readonlyInline}}</dt> + <dd>A {{ domxref("TouchList") }} of all the {{ domxref("Touch") }} objects that are both currently in contact with the touch surface <strong>and</strong> were also started on the same element that is the target of the event.</dd> + <dt>{{ domxref("TouchEvent.touches") }} {{readonlyInline}}</dt> + <dd>A {{ domxref("TouchList") }} of all the {{ domxref("Touch") }} objects representing all current points of contact with the surface, regardless of target or changed status.</dd> +</dl> + +<h2 id="Tipos_de_evento_táctiles">Tipos de evento táctiles</h2> + +<p>Hay varios tipos de eventos que pueden ser disparados (activados) para indicar que han ocurrido cambios relacionados con el contacto. Puede determinar cuál de estos ha ocurrido mirando la propiedad {{domxref ("event.type", "TouchEvent.type")}} del evento.</p> + +<div class="note"><strong>Nota:</strong> Es importante observar que en muchos casos, Los eventos táctiles y de mouse se envían (para permitir que el código no táctil específico aún interactúe con el usuario). Si usa eventos táctiles, debe llamar a {{domxref ("event.preventDefault ()")}} para evitar que también se envíe el evento del mouse.</div> + +<h3 id="event(touchstart)">{{event("touchstart")}}</h3> + +<p>Sent when the user places a touch point on the touch surface. The event's target will be the {{ domxref("element") }} in which the touch occurred.</p> + +<h3 id="event(touchend)">{{event("touchend")}}</h3> + +<p>Sent when the user removes a touch point from the surface (that is, when they lift a finger or stylus from the surface). This is also sent if the touch point moves off the edge of the surface; for example, if the user's finger slides off the edge of the screen.</p> + +<p>The event's target is the same {{ domxref("element") }} that received the <code>touchstart</code> event corresponding to the touch point, even if the touch point has moved outside that element.</p> + +<p>The touch point (or points) that were removed from the surface can be found in the {{ domxref("TouchList") }} specified by the <code>changedTouches</code> attribute.</p> + +<h3 id="event(touchmove)">{{event("touchmove")}}</h3> + +<p>Sent when the user moves a touch point along the surface. The event's target is the same {{ domxref("element") }} that received the <code>touchstart</code> event corresponding to the touch point, even if the touch point has moved outside that element.</p> + +<p>This event is also sent if the values of the radius, rotation angle, or force attributes of a touch point change.</p> + +<div class="note"><strong>Note:</strong> The rate at which <code>touchmove</code> events is sent is browser-specific, and may also vary depending on the capability of the user's hardware. You must not rely on a specific granularity of these events.</div> + +<h3 id="event(touchcancel)">{{event("touchcancel")}}</h3> + +<p>Sent when a touch point has been disrupted in some way. There are several possible reasons why this might happen (and the exact reasons will vary from device to device, as well as browser to browser):</p> + +<ul> + <li>An event of some kind occurred that canceled the touch; this might happen if a modal alert pops up during the interaction.</li> + <li>The touch point has left the document window and moved into the browser's UI area, a plug-in, or other external content.</li> + <li>The user has placed more touch points on the screen than can be supported, in which case the earliest {{ domxref("Touch") }} in the {{ domxref("TouchList") }} gets canceled.</li> +</ul> + +<h2 id="GlobalEventHandlers">GlobalEventHandlers</h2> + +<p>{{SeeCompatTable}}</p> + +<dl> + <dt>{{ domxref("GlobalEventHandlers.ontouchstart") }} {{experimental_inline}}</dt> + <dd>A {{domxref("GlobalEventHandlers","global event handler")}} for the {{event("touchstart")}} event.</dd> + <dt>{{ domxref("GlobalEventHandlers.ontouchend") }} {{experimental_inline}}</dt> + <dd>A {{domxref("GlobalEventHandlers","global event handler")}} for the {{event("touchend")}} event.</dd> + <dt>{{ domxref("GlobalEventHandlers.ontouchmove") }} {{experimental_inline}}</dt> + <dd>A {{domxref("GlobalEventHandlers","global event handler")}} for the {{event("touchmove")}} event.</dd> + <dt>{{ domxref("GlobalEventHandlers.ontouchcancel") }} {{experimental_inline}}</dt> + <dd>A {{domxref("GlobalEventHandlers","global event handler")}} for the {{event("touchcancel")}} event.</dd> +</dl> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>See the <a href="/en/DOM/Touch_events#Example" title="en/DOM/Touch events#Example">example on the main Touch events article</a>.</p> + +<h2 id="Especificaciones">Especificaciones</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('Touch Events 2','#touchevent-interface', 'TouchEvent')}}</td> + <td>{{Spec2('Touch Events 2')}}</td> + <td>Added <code>ontouchstart</code>, <code>ontouchend</code>, <code>ontouchmove</code>, <code>ontouchend</code> global attribute handlers</td> + </tr> + <tr> + <td>{{SpecName('Touch Events', '#touchevent-interface', 'TouchEvent')}}</td> + <td>{{Spec2('Touch Events')}}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_navegadores">Compatibilidad en navegadores</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 (WebKit)</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatChrome("22.0")}}</td> + <td>{{CompatGeckoDesktop("18.0")}}</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>Android Webview</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("6.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>11</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>TouchEvent()</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{domxref("Touch_events","Touch Events Overview")}}</li> + <li>{{domxref("GestureEvent")}}</li> + <li>{{domxref("MSGestureEvent")}}</li> +</ul> diff --git a/files/es/web/api/uievent/index.html b/files/es/web/api/uievent/index.html new file mode 100644 index 0000000000..8d896924eb --- /dev/null +++ b/files/es/web/api/uievent/index.html @@ -0,0 +1,158 @@ +--- +title: UIEvent +slug: Web/API/UIEvent +tags: + - API +translation_of: Web/API/UIEvent +--- +<p>{{APIRef("DOM Events")}}</p> + +<p>The <strong><code>UIEvent</code></strong> interface represents simple user interface events.</p> + +<p><code>UIEvent</code> derives from {{domxref("Event")}}. Though the {{domxref("UIEvent.initUIEvent()")}} method is kept for backward compatibility, creating of a <code>UIEvent</code> object should be done using the {{domxref("UIEvent.UIEvent", "UIEvent()")}} constructor.</p> + +<p>Several interfaces are direct or indirect descendants of this one: {{domxref("MouseEvent")}}, {{domxref("FocusEvent")}}, {{domxref("KeyboardEvent")}}, {{domxref("WheelEvent")}}, {{domxref("InputEvent")}}, and {{domxref("CompositionEvent")}}.</p> + +<h2 id="Constructors">Constructors</h2> + +<dl> + <dt>{{domxref("UIEvent.UIEvent()", "UIEvent()")}}</dt> + <dd>Creates a <code>UIEvent</code> object.</dd> +</dl> + +<h2 id="Properties">Properties</h2> + +<p><em>This interface also inherits properties of its parent, {{domxref("Event")}}.</em></p> + +<dl> + <dt>{{domxref("UIEvent.cancelBubble")}} {{Deprecated_inline}}{{Non-standard_inline}}</dt> + <dd>Is a {{jsxref("Boolean")}} indicating whether the bubbling of the event has been canceled or not.</dd> +</dl> + +<dl> + <dt>{{domxref("UIEvent.detail")}}{{readonlyinline}}</dt> + <dd>Returns a <code>long</code> that gives some detail about the event, depending on the type of event.</dd> + <dt>{{domxref("UIEvent.isChar")}} {{Non-standard_inline}} {{readonlyinline}}</dt> + <dd>Returns a {{jsxref("Boolean")}} indicating whether the event produced a key character or not.</dd> + <dt>{{domxref("UIEvent.layerX")}} {{Non-standard_inline}} {{readonlyinline}}</dt> + <dd>Returns the horizontal coordinate of the event relative to the current layer.</dd> + <dt>{{domxref("UIEvent.layerY")}} {{Non-standard_inline}} {{readonlyinline}}</dt> + <dd>Returns the vertical coordinate of the event relative to the current layer.</dd> + <dt>{{domxref("UIEvent.pageX")}} {{Non-standard_inline}} {{readonlyinline}}</dt> + <dd>Returns the horizontal coordinate of the event relative to the whole document.</dd> + <dt>{{domxref("UIEvent.pageY")}} {{Non-standard_inline}} {{readonlyinline}}</dt> + <dd>Returns the vertical coordinate of the event relative to the whole document.</dd> + <dt>{{domxref("UIEvent.view")}}{{readonlyinline}}</dt> + <dd>Returns a {{domxref("WindowProxy")}} that contains the view that generated the event.</dd> + <dt>{{domxref("UIEvent.which")}} {{Non-standard_inline}} {{readonlyinline}}</dt> + <dd>Returns the numeric <code>keyCode</code> of the key pressed, or the character code (<code>charCode</code>) for an alphanumeric key pressed.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<p><em>This interface also inherits methods of its parent, {{domxref("Event")}}.</em></p> + +<dl> + <dt>{{domxref("UIEvent.initUIEvent()")}} {{deprecated_inline}}</dt> + <dd>Initializes a <code>UIEvent</code> object. If the event has already being dispatched, this method does nothing.</dd> +</dl> + +<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('DOM3 Events', '#interface-UIEvent', 'UIEvent')}}</td> + <td>{{Spec2('DOM3 Events')}}</td> + <td>From {{SpecName('DOM2 Events')}}: + <ul> + <li>added the <code>UIEvent()</code> constructor,</li> + <li>deprecated the <code>initUIEvent()</code> method,</li> + <li>and changed the type of <code>view</code> from <code>AbstractView</code> to <code>WindowProxy</code>.</li> + </ul> + </td> + </tr> + <tr> + <td>{{SpecName('DOM2 Events', '#Events-UIEvent', 'UIEvent')}}</td> + <td>{{Spec2('DOM2 Events')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="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>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + </tr> + <tr> + <td><code>UIEvent()</code></td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatGeckoDesktop(11)}}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatUnknown() }}</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() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + </tr> + <tr> + <td><code>UIEvent()</code></td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatGeckoMobile(11)}}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<h2 class="editable" id="See_also"><span>See also</span></h2> + +<ul> + <li>{{ domxref("Event") }}</li> +</ul> diff --git a/files/es/web/api/uievent/pagex/index.html b/files/es/web/api/uievent/pagex/index.html new file mode 100644 index 0000000000..fbd75e26f8 --- /dev/null +++ b/files/es/web/api/uievent/pagex/index.html @@ -0,0 +1,102 @@ +--- +title: event.pageX +slug: Web/API/UIEvent/pageX +tags: + - DOM + - Referencia_DOM_de_Gecko + - Todas_las_Categorías +translation_of: Web/API/UIEvent/pageX +--- +<p>{{ ApiRef() }}</p> +<h3 id="Sumario" name="Sumario">Sumario</h3> +<p>Retorna la coordena horizontal del evento, relativo al documento completo.</p> +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> +<pre class="eval"><i>pageX</i> =<i>event</i>.pageX; +</pre> +<p><code>pageX</code> es un valor entero expresado en pixels para la corrdenada X del puntero del ratón, relativo al documento entero, cuando se produjo el evento. Esta propiedad toma en cuenta la barra de desplazamiento horizontal de la página.</p> +<h3 id="Ejemplo" name="Ejemplo">Ejemplo</h3> +<pre><html> +<head> +<title>pageX\pageY & layerX\layerY example</title> + +<script type="text/javascript"> + +function showCoords(evt){ + var form = document.forms.form_coords; + var parent_id = evt.target.parentNode.id; + form.parentId.value = parent_id; + form.pageXCoords.value = evt.pageX; + form.pageYCoords.value = evt.pageY; + form.layerXCoords.value = evt.layerX; + form.layerYCoords.value = evt.layerY; +} + +</script> + +<style type="text/css"> + + #d1 { + border: solid blue 1px; + padding: 20px; + } + + #d2 { + position: absolute; + top: 180px; + left: 80%; + right:auto; + width: 40%; + border: solid blue 1px; + padding: 20px; + } + + #d3 { + position: absolute; + top: 240px; + left: 20%; + width: 50%; + border: solid blue 1px; + padding: 10px; + } + +</style> +</head> + +<body onmousedown="showCoords(event)"> + +<p>To display the mouse coordinates please click anywhere on the page.</p> + +<div id="d1"> +<span>This is an un-positioned div so clicking it will return +layerX/layerY values almost the same as pageX/PageY values.</span> +</div> + +<div id="d2"> +<span>This is a positioned div so clicking it will return layerX/layerY +values that are relative to the top-left corner of this positioned +element. Note the pageX\pageY properties still return the +absolute position in the document, including page scrolling.</span> + +<span>Make the page scroll more! This is a positioned div so clicking it +will return layerX/layerY values that are relative to the top-left +corner of this positioned element. Note the pageX\pageY properties still +return the absolute position in the document, including page +scrolling.</span> +</div> + +<div id="d3"> +<form name="form_coords"> + Parent Element id: <input type="text" name="parentId" size="7" /><br /> + pageX:<input type="text" name="pageXCoords" size="7" /> + pageY:<input type="text" name="pageYCoords" size="7" /><br /> + layerX:<input type="text" name="layerXCoords" size="7" /> + layerY:<input type="text" name="layerYCoords" size="7" /> +</form> +</div> + +</body> +</html> +</pre> +<h3 id="Specificaci.C3.B3n" name="Specificaci.C3.B3n">Specificación</h3> +<p>No es parte del estándar público.</p> +<p>{{ languages( { "pl": "pl/DOM/event.pageX", "en": "en/DOM/event.pageX" } ) }}</p> diff --git a/files/es/web/api/url/createobjecturl/index.html b/files/es/web/api/url/createobjecturl/index.html new file mode 100644 index 0000000000..9a6b6841b4 --- /dev/null +++ b/files/es/web/api/url/createobjecturl/index.html @@ -0,0 +1,148 @@ +--- +title: URL.createObjectURL() +slug: Web/API/URL/createObjectURL +tags: + - API + - Experimental + - Method + - URL + - URL API + - createObjectURL +translation_of: Web/API/URL/createObjectURL +--- +<p>{{ApiRef("URL")}}{{SeeCompatTable}}</p> + +<p>El método estático <strong><code>URL.createObjectURL()</code></strong> crea un {{domxref("DOMString")}} que contiene una URL que representa al objeto pasado como parámetro. La vida de la URL está ligado al {{domxref("document")}} de la ventana en la que fue creada. El nuevo objeto URL representa al objeto {{domxref("File")}} especificado o al objeto {{domxref("Blob")}}.</p> + +<div class="note"> +<p>El uso de un objeto {{domxref("MediaStream")}} como entrada a este método está en proceso de ser obsoleto. Las discusiones están en curso sobre si o no debe ser quitado totalmente. Como tal, <em>se debe de evitar usar este método con {{domxref("MediaStream")}}s, y se debería usar {{domxref("HTMLMediaElement.srcObject", "HTMLMediaElement.srcObject()")}}</em>.</p> +</div> + +<p>{{AvailableInWorkers}}</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><em>objectURL</em> = URL.createObjectURL(<em>object</em>); +</pre> + +<h2 id="Parámetros">Parámetros</h2> + +<dl> + <dt><code>object</code></dt> + <dd>Un objeto {{domxref("File")}} o un objeto {{domxref("Blob")}} para el que se creará la URL.</dd> +</dl> + +<ul> +</ul> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>Ver <a href="/en-US/docs/Using_files_from_web_applications#Example_Using_object_URLs_to_display_images" title="https://developer.mozilla.org/en/Using_files_from_web_applications#Example:_Using_object_URLs_to_display_images">Usando objetos URL para representar imágenes</a>.</p> + +<h2 id="Notas">Notas</h2> + +<p>Cada vez que se llama a <code>createObjectURL()</code>, un nuevo objeto URL es creado, incluso si ya creaste uno para el mismo objeto. Cada uno de estos objetos puede ser liberado usando {{domxref("URL.revokeObjectURL()")}} cuándo ya no lo necesitas. Los navegadores liberan estos objetos cuando el documento es cerrado; de todas formas, para obtener un rendimiento óptimo y un óptimo uso de memoria, si hay momentos seguros en los que puedes liberar estos objetos deberías hacerlo. Por ejemplo: No liberar los recursos cuando se ha creado una URL a partir de un {{domxref('MediaStream')}} puede dejar la luz de la cámara del navegador encendida más tiempo del necesario.</p> + +<div class="note"> +<p>Notese que no es necesario crear URLs a partir de un {{domxref('MediaStream')}}, ya que los objetos de streams deberían asignarse directamente a elementos de reproducción con {{domxref("HTMLMediaElement.srcObject")}}. La posibilidad de usar un <code>MediaStream</code> como valor de un objeto está obsoleta.</p> +</div> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('File API', '#dfn-createObjectURL', 'URL')}}</td> + <td>{{Spec2('File API')}}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>8 [1]<br> + {{CompatChrome(23)}}</td> + <td>{{CompatGeckoDesktop(2)}}</td> + <td>{{CompatIE(10)}}</td> + <td>{{CompatOpera(15)}}</td> + <td>{{CompatSafari(6)}} [1]<br> + {{CompatSafari(7)}}</td> + </tr> + <tr> + <td>In a {{ domxref("Worker", "Web Worker") }}</td> + <td>10 [1]<br> + {{CompatChrome(23)}}</td> + <td>{{CompatGeckoDesktop(21)}}</td> + <td>{{CompatIE(11)}}</td> + <td>{{CompatOpera(15)}}</td> + <td>{{CompatSafari(6)}} [1]<br> + {{CompatSafari(7)}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome para Android</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>18 [1]</td> + <td>4.0 [1]</td> + <td>{{CompatGeckoMobile(14)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatOpera(15)}} [1]</td> + <td>6.0 [1]</td> + </tr> + <tr> + <td>In a {{ domxref("Worker", "Web Worker") }}</td> + <td>18 [1]</td> + <td>{{CompatVersionUnknown}} [1]</td> + <td>{{CompatGeckoMobile(14)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatOpera(15)}} [1]</td> + <td>6.0 [1]</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Con <code><a href="/en-US/docs/Web/API/URL">URL</a></code> prefijado como <code>webkitURL</code></p> + +<h2 id="Mirar_también">Mirar también</h2> + +<ul> + <li>{{domxref("URL.revokeObjectURL()")}}</li> + <li>{{domxref("HTMLMediaElement.srcObject")}}</li> + <li><a href="/en-US/docs/Using_files_from_web_applications" title="Using files from web applications">Usando archivos desde aplicaciones web</a></li> +</ul> diff --git a/files/es/web/api/url/host/index.html b/files/es/web/api/url/host/index.html new file mode 100644 index 0000000000..f18934e6a6 --- /dev/null +++ b/files/es/web/api/url/host/index.html @@ -0,0 +1,62 @@ +--- +title: Estabilidad +slug: Web/API/URL/Host +translation_of: Web/API/URL/host +--- +<div>{{ApiRef("URL API")}}</div> + +<p>The <strong><code>host</code></strong> property of the {{domxref("URL")}} interface is a {{domxref("USVString")}} containing the host, that is the {{domxref("URL.hostname", "hostname")}}, and then, if the {{glossary("port")}} of the URL is nonempty, a <code>':'</code>, followed by the {{domxref("URL.port", "port")}} of the URL.</p> + +<p>{{AvailableInWorkers}}</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox">const <em>host</em> = <em>url</em>.host +<em>url.<code>host</code></em> = <em>newHost</em> +</pre> + +<h3 id="Value">Value</h3> + +<p>A {{domxref("USVString")}}.</p> + +<h2 id="Examples">Examples</h2> + +<pre class="brush: js">let url = new URL('https://developer.mozilla.org/en-US/docs/Web/API/URL/host'); +console.log(url.host); // "developer.mozilla.org" + +url = new URL('https://developer.mozilla.org:443/en-US/docs/Web/API/URL/host'); +console.log(url.host); // "developer.mozilla.org" +// The port number is not included because 443 is the scheme's default port + +url = new URL('https://developer.mozilla.org:4097/en-US/docs/Web/API/URL/host'); +console.log(url.host); // "developer.mozilla.org:4097" +</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('URL', '#dom-url-host', 'URL.host')}}</td> + <td>{{Spec2('URL')}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("api.URL.host")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>The {{domxref("URL")}} interface it belongs to.</li> +</ul> diff --git a/files/es/web/api/url/index.html b/files/es/web/api/url/index.html new file mode 100644 index 0000000000..c107b21511 --- /dev/null +++ b/files/es/web/api/url/index.html @@ -0,0 +1,217 @@ +--- +title: URL +slug: Web/API/URL +tags: + - API + - Experimental + - Expérimental(2) + - NeedsTranslation + - TopicStub + - URL API +translation_of: Web/API/URL +--- +<div>{{ApiRef("URL API")}} {{SeeCompatTable}}</div> + +<p>La interfaz <strong><code>URL</code></strong> representa a un objeto que provee métodos estáticos para crear objetos URL.</p> + +<p>When using a user agent where no constructor has been implemented yet, it is possible to access such an object using the {{domxref("Window.URL")}} properties (prefixed with Webkit-based browser as <code>Window.webkitURL</code>).</p> + +<p>{{AvailableInWorkers}}</p> + +<h2 id="Properties">Properties</h2> + +<dl> + <dt>{{domxref("URL.href")}}</dt> + <dd>Is a {{domxref("DOMString")}} containing the whole URL.</dd> + <dt>{{domxref("URL.protocol")}}</dt> + <dd>Is a {{domxref("DOMString")}} containing the protocol scheme of the URL, including the final <code>':'</code>.</dd> + <dt>{{domxref("URL.host")}}</dt> + <dd>Is a {{domxref("DOMString")}} containing the host, that is the <em>hostname</em>, a <code>':'</code>, and the <em>port</em> of the URL.</dd> + <dt>{{domxref("URL.hostname")}}</dt> + <dd>Is a {{domxref("DOMString")}} containing the domain of the URL.</dd> + <dt>{{domxref("URL.port")}}</dt> + <dd>Is a {{domxref("DOMString")}} containing the port number of the URL.</dd> + <dt>{{domxref("URL.pathname")}}</dt> + <dd>Is a {{domxref("DOMString")}} containing an initial <code>'/'</code> followed by the path of the URL.</dd> + <dt>{{domxref("URL.search")}}</dt> + <dd>Is a {{domxref("DOMString")}} containing a <code>'?'</code> followed by the parameters of the URL.</dd> + <dt>{{domxref("URL.hash")}}</dt> + <dd>Is a {{domxref("DOMString")}} containing a <code>'#'</code> followed by the fragment identifier of the URL.</dd> + <dt>{{domxref("URL.username")}}</dt> + <dd>Is a {{domxref("DOMString")}} containing the username specified before the domain name.</dd> + <dt>{{domxref("URL.password")}}</dt> + <dd>Is a {{domxref("DOMString")}} containing the password specified before the domain name.</dd> + <dt>{{domxref("URL.origin")}} {{readonlyInline}}</dt> + <dd>Returns a {{domxref("DOMString")}} containing the origin of the URL, that is its scheme, its domain and its port.</dd> +</dl> + +<dl> + <dt>{{domxref("URL.searchParams")}}</dt> + <dd>Returns a {{domxref("URLSearchParams")}} object allowing to access the GET query arguments contained in the URL.</dd> +</dl> + +<h2 id="Constructor">Constructor</h2> + +<dl> + <dt>{{domxref("URL.URL", "URL()")}}</dt> + <dd>Creates and return a <code>URL</code> object composed from the given parameters.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<p><em>The <code>URL</code> interface implements methods defined in {{domxref("URLUtils")}}.</em></p> + +<dl> + <dt>{{domxref("URLUtils.toString()")}}</dt> + <dd>Returns a {{domxref("DOMString")}} containing the whole URL. It is a synonym for {{domxref("URLUtils.href")}}, though it can't be used to modify the value.</dd> +</dl> + +<h2 id="Static_methods">Static methods</h2> + +<dl> + <dt>{{domxref("URL.createObjectURL()")}}</dt> + <dd>Returns a {{domxref("DOMString")}} containing a unique blob URL, that is a URL with <code>blob:</code> as its scheme, followed by an opaque string uniquely identifying the object in the browser.</dd> + <dt>{{domxref("URL.revokeObjectURL()")}}</dt> + <dd>Revokes an object URL previously created using {{domxref("URL.createObjectURL()")}}.</dd> +</dl> + +<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('File API', '#creating-revoking', 'URL')}}</td> + <td>{{Spec2('File API')}}</td> + <td>Added the static methods <code>URL.createObjectURL()</code> and <code>URL.revokeObjectURL</code><code>()</code>.</td> + </tr> + <tr> + <td>{{SpecName('URL', '#api', 'Node')}}</td> + <td>{{Spec2('URL')}}</td> + <td>Initial definition (implements <code>URLUtils</code>).</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>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>8.0<sup>[2]</sup><br> + 32</td> + <td>In Development<sup>[5]</sup></td> + <td>{{CompatGeckoDesktop("2.0")}}<sup>[1][3]</sup><br> + {{CompatGeckoDesktop("19.0")}}</td> + <td>{{CompatNo}}<sup>[4]</sup></td> + <td>15.0<sup>[2]</sup><br> + 19</td> + <td>6.0<sup>[2]</sup><br> + 7.0</td> + </tr> + <tr> + <td><code>username</code>, <code>password</code>, and <code>origin</code></td> + <td>32</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("26.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>19</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>searchParams</code></td> + <td>{{CompatChrome(49)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("29.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>36</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>4<sup>[2]</sup><br> + 4.4</td> + <td>8.0<sup>[2]</sup><br> + 32</td> + <td>{{CompatGeckoMobile("14.0")}}<sup>[1][3]</sup><br> + {{CompatGeckoMobile("19.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>15.0<sup>[2]</sup></td> + <td>6.0<sup>[2]</sup></td> + </tr> + <tr> + <td><code>username</code>, <code>password</code>, and <code>origin</code></td> + <td>4.4</td> + <td>32</td> + <td>{{CompatGeckoDesktop("26.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>searchParams</code></td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(49)}}</td> + <td>{{CompatGeckoMobile("29.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] From Gecko 2 (Firefox 4) to Gecko 18 included, Gecko supported this interface with the non-standard <code>nsIDOMMozURLProperty</code> internal type. As the only to access such an object was through {{domxref("window.URL")}}, in practice, this didn't make any difference.</p> + +<p>[2] This feature is implemented under the non-standard name <code>webkitURL</code>.</p> + +<p>[3] For Firefox, to use from chrome code, JSM and Bootstrap scope, you have to import it like this:</p> + +<pre class="brush: js">Cu.importGlobalProperties(['URL']); +</pre> + +<p><code>URL</code> is available in Worker scopes.</p> + +<p>[4] As of IE11, instantiating new URL objects is not supported - ie. new URL() does not work. </p> + +<p>[5] Edge in development: see https://developer.microsoft.com/en-us/microsoft-edge/platform/status/urlapi/ and https://wpdev.uservoice.com/forums/257854-microsoft-edge-developer/suggestions/6263638-url-api</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>Property allowing to get such an object: {{domxref("Window.URL")}}.</li> + <li><a href="/en-US/docs/Components.utils.importGlobalProperties">Components.utils.importGlobalProperties</a></li> +</ul> diff --git a/files/es/web/api/url/port/index.html b/files/es/web/api/url/port/index.html new file mode 100644 index 0000000000..fea61df62a --- /dev/null +++ b/files/es/web/api/url/port/index.html @@ -0,0 +1,55 @@ +--- +title: URL.port +slug: Web/API/URL/port +translation_of: Web/API/URL/port +--- +<div>{{ApiRef("URL API")}}</div> + +<p>La propiedad <strong><code>port</code></strong> de la interfaz {{domxref("URL")}} es un {{domxref("USVString")}} que contiene el número de puerto de la URL. Si la URL no contiene un número de puerto explícito, se establecerá <code>''</code>.</p> + +<p>{{AvailableInWorkers}}</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><em>string</em> = <em>object</em>.port; +<em>object</em>.port = <em>string</em>; +</pre> + +<h3 id="Valor">Valor</h3> + +<p>Un {{domxref("USVString")}}.</p> + +<h2 id="Ejemplos">Ejemplos</h2> + +<pre class="brush: js">var url = new URL('<span class="message-body-wrapper"><span class="message-flex-body"><span class="devtools-monospace message-body"><span class="cm-string">https://mydomain.com:80/svn/Repos/</span></span></span></span>'); +var result = url.port; // Devuelve:'80' +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('URL', '#dom-url-port', 'URL.port')}}</td> + <td>{{Spec2('URL')}}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_del_navegador">Compatibilidad del navegador</h2> + +<div class="hidden">La tabla de compatibilidad en esta página se genera a partir de datos estructurados. Si desea contribuir con los datos, consulte https://github.com/mdn/browser-compat-data y envíenos una solicitud de extracción.</div> + +<p>{{Compat("api.URL.port")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>La interfaz {{domxref("URL")}} a la que pertenece.</li> +</ul> diff --git a/files/es/web/api/url/url/index.html b/files/es/web/api/url/url/index.html new file mode 100644 index 0000000000..978a7de9f9 --- /dev/null +++ b/files/es/web/api/url/url/index.html @@ -0,0 +1,99 @@ +--- +title: URL() +slug: Web/API/URL/URL +translation_of: Web/API/URL/URL +--- +<div>{{APIRef("URL API")}}</div> + +<p><code><font face="Arial, x-locale-body, sans-serif"><span style="background-color: #ffffff;">El constructor </span></font><strong>URL()</strong></code> devuelve un objeto {{domxref("URL")}} recién creado que representa la URL definida por los parámetros.</p> + +<p>Si la URL base dada o la URL resultante no son URL válidas, se lanza un {{domxref("DOMException")}} de tipo <code>SYNTAX_ERROR</code>.</p> + +<p>{{AvailableInWorkers}}</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><em>url</em> = new URL(<em>url</em>, [<em>base</em>]) +</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code>url</code></dt> + <dd>Un {{domxref("USVString")}} que representa una URL absoluta o relativa. Si <em>url</em> es una URL relativa, se requiere <em>base</em>, y se usará como URL base. Si url es una URL absoluta, se ignorará una <em>base</em> determinada.</dd> + <dt><code>base</code><em> </em>{{optional_inline}}</dt> + <dd>Un {{domxref("USVString")}} representa la URL base a usar en caso de que la URL sea una URL relativa. Si no se especifica, el valor predeterminado es <code>''</code>.</dd> +</dl> + +<div class="note"> +<p><strong>Nota</strong>: Aún puede usar un objeto {{domxref("URL")}} existente para la base, que se enchufa al atributo {{domxref("DOMString.href","href")}} del objeto.</p> +</div> + +<h3 id="Excepciones">Excepciones</h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Excepción</th> + <th scope="col">Explicación</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>TypeError</code></td> + <td><em>url</em> (en el caso de URL absolutas) o <em>base</em> + <em>url</em> (en el caso de URL relativas) no es una URL válida.</td> + </tr> + </tbody> +</table> + +<h2 id="Ejemplos">Ejemplos</h2> + +<pre class="brush: js">// Urls base +var m = 'https://developer.mozilla.org'; +var a = new URL("/", m); // => 'https://developer.mozilla.org/' +var b = new URL(m); // => 'https://developer.mozilla.org/' + + new URL('en-US/docs', b); // => 'https://developer.mozilla.org/en-US/docs' +var d = new URL('/en-US/docs', b); // => 'https://developer.mozilla.org/en-US/docs' + new URL('/en-US/docs', d); // => 'https://developer.mozilla.org/en-US/docs' + new URL('/en-US/docs', a); // => 'https://developer.mozilla.org/en-US/docs' + + new URL('/en-US/docs', "https://developer.mozilla.org/fr-FR/toto"); + // => 'https://developer.mozilla.org/en-US/docs' + + new URL('/en-US/docs', ''); // Provoca una excepción TypeError ya que '' no es una URL válida + new URL('/en-US/docs'); // Provoca una excepción TypeError ya que '/en-US/docs' no es una URL válida + new URL('http://www.example.com', ); // => 'http://www.example.com/' + new URL('http://www.example.com', b); // => 'http://www.example.com/' + + new URL("//foo.com", "https://example.com") // => 'https://foo.com' (ver URL relativas) +</pre> + +<h2 id="Especificación">Especificación</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('URL', '#constructors', 'URL.URL()')}}</td> + <td>{{Spec2('URL')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_del_navegador">Compatibilidad del navegador</h2> + +<div class="hidden">La tabla de compatibilidad en esta página se genera a partir de datos estructurados. Si desea contribuir con los datos, consulte https://github.com/mdn/browser-compat-data y envíenos una solicitud de extracción.</div> + +<p>{{Compat("api.URL.URL")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>La interfaz a la que pertenece: {{domxref("URL")}}.</li> +</ul> diff --git a/files/es/web/api/urlsearchparams/index.html b/files/es/web/api/urlsearchparams/index.html new file mode 100644 index 0000000000..ec3433af72 --- /dev/null +++ b/files/es/web/api/urlsearchparams/index.html @@ -0,0 +1,204 @@ +--- +title: URLSearchParams +slug: Web/API/URLSearchParams +translation_of: Web/API/URLSearchParams +--- +<p>{{ApiRef("URL API")}}</p> + +<p>La interfaz <strong><code>URLSearchParams</code></strong> define métodos útiles para trabajar con los parámetros de búsqueda de una URL.</p> + +<p>Un objeto implementando <code>URLSearchParams</code> puede directamente ser usado en una {{jsxref("Statements/for...of", "for...of")}} estructura, en lugar de {{domxref('URLSearchParams.entries()', 'entries()')}}: <code>for (var p of mySearchParams)</code> la cual es equivalente a <code>for (var p of mySearchParams.entries())</code>.</p> + +<h2 id="Constructor">Constructor</h2> + +<dl> + <dt>{{domxref("URLSearchParams.URLSearchParams", 'URLSearchParams()')}}</dt> + <dd>El Constructor returna un objeto de tipo <code>URLSearchParams</code>.</dd> +</dl> + +<h2 id="Propiedades">Propiedades</h2> + +<p><em>Esta interfaz no hereda ninguna propiedad.</em></p> + +<h2 id="Métodos">Métodos</h2> + +<p><em>Esta interfaz no hereda ningún método.</em></p> + +<dl> + <dt>{{domxref("URLSearchParams.append()")}}</dt> + <dd>Agrega el par de llave/valor especificado como un nuevo parámetro de búsqueda.</dd> + <dt>{{domxref("URLSearchParams.delete()")}}</dt> + <dd>Elimina el parámetro de búsqueda especificado, y su valor asociado, de la lista de todos los parámetros de búsqueda.</dd> + <dt>{{domxref("URLSearchParams.entries()")}}</dt> + <dd>Returna un {{jsxref("Iteration_protocols","iterator")}} que permite iterar a traves de todos los pares de llave/valor que contiene el objeto.</dd> + <dt>{{domxref("URLSearchParams.get()")}}</dt> + <dd>Returna el primer valor asociado al parámetro de búsqueda especificado.</dd> + <dt>{{domxref("URLSearchParams.getAll()")}}</dt> + <dd>Returna todas los valores asociados con el parámetro de búsqueda especificado.</dd> + <dt>{{domxref("URLSearchParams.has()")}}</dt> + <dd>Returna un {{jsxref("Boolean")}} que indica si el parametro de búsqueda especificado existe.</dd> + <dt>{{domxref("URLSearchParams.keys()")}}</dt> + <dd>Returna un {{jsxref("Iteration_protocols", "iterator")}} que permite iterar a través de todas las <strong>llaves </strong>de los pares de llave/valor que contiene un objeto.</dd> + <dt>{{domxref("URLSearchParams.set()")}}</dt> + <dd>Establece el valor al parámetro de búsqueda asociado con el valor dado. Si hay varios valores, elimina los demás.</dd> + <dt>{{domxref("URLSearchParams.sort()")}}</dt> + <dd>Organiza todos los pares de llave/valor, si existen, por sus llaves.</dd> + <dt>{{domxref("URLSearchParams.toString()")}}</dt> + <dd>Returna una cadena de texto que contiene un parámetro de consulta adecuado para utilizar en una URL.</dd> + <dt>{{domxref("URLSearchParams.values()")}}</dt> + <dd>Returna un {{jsxref("Iteration_protocols", "iterator")}} que permite iterar a través de todos los <strong>valores </strong>de los pares de llave/valor que contiene un objeto.</dd> +</dl> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush: js">var paramsString = "q=URLUtils.searchParams&topic=api" +var searchParams = new URLSearchParams(paramsString); + +//Itera los parámetros de búsqueda. +for (let p of searchParams) { + console.log(p); +} + +searchParams.has("topic") === true; // true +searchParams.get("topic") === "api"; // true +searchParams.getAll("topic"); // ["api"] +searchParams.get("foo") === null; // true +searchParams.append("topic", "webdev"); +searchParams.toString(); // "q=URLUtils.searchParams&topic=api&topic=webdev" +searchParams.set("topic", "More webdev"); +searchParams.toString(); // "q=URLUtils.searchParams&topic=More+webdev" +searchParams.delete("topic"); +searchParams.toString(); // "q=URLUtils.searchParams" +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificaciones</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('URL', '#urlsearchparams', "URLSearchParams")}}</td> + <td>{{Spec2('URL')}}</td> + <td>Definición Inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatChrome(49)}}</td> + <td>{{CompatGeckoDesktop("29.0")}}</td> + <td>{{CompatNo}}</td> + <td>36</td> + <td>10.1</td> + </tr> + <tr> + <td><code>entries()</code>, <code>keys()</code>, <code>values()</code>, and support of <code>for...of</code></td> + <td>{{CompatChrome(49)}}</td> + <td>{{CompatGeckoDesktop("44.0")}}</td> + <td>{{CompatNo}}</td> + <td>36</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>USVString</code> for constructor <code>init</code> object</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("53.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Record for constructor <code>init</code> object</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop("54.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android Webview</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>Soporte básico</td> + <td>{{CompatChrome(49)}}</td> + <td>{{CompatChrome(49)}}</td> + <td>{{CompatGeckoMobile("29.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>entries()</code>, <code>keys()</code>, <code>values()</code>, and support of <code>for...of</code></td> + <td>{{CompatChrome(49)}}</td> + <td>{{CompatChrome(49)}}</td> + <td>{{CompatGeckoMobile("44.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>USVString</code> for constructor <code>init</code> object</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("53.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Record for constructor <code>init</code> object</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("54.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Vea_también">Vea también</h2> + +<ul> + <li>Otras interfaces relacionadas con URL: {{domxref("URL")}}, {{domxref("URLUtils")}}.</li> + <li><a href="https://developers.google.com/web/updates/2016/01/urlsearchparams?hl=en">Google Developers: Fácil manipulación de una URL con URLSearchParams</a></li> +</ul> + +<dl> +</dl> diff --git a/files/es/web/api/urlsearchparams/urlsearchparams/index.html b/files/es/web/api/urlsearchparams/urlsearchparams/index.html new file mode 100644 index 0000000000..0cfe5f28df --- /dev/null +++ b/files/es/web/api/urlsearchparams/urlsearchparams/index.html @@ -0,0 +1,78 @@ +--- +title: URLSearchParams() +slug: Web/API/URLSearchParams/URLSearchParams +tags: + - API + - API URL + - Constructor + - Referencia + - URLSearchParams +translation_of: Web/API/URLSearchParams/URLSearchParams +--- +<p>{{ApiRef("URL API")}}</p> + +<p>El constructor <code><strong>URLSearchParams()</strong></code> crea y retorna un nuevo objeto {{domxref("URLSearchParams")}}. Si se incluye el caracter <code>'?'</code> al comienzo, éste es ignorado.</p> + +<p>{{availableinworkers}}</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var <em>URLSearchParams</em> = new URLSearchParams(<em>init</em>);</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><em><code>init</code></em> {{optional_inline}}</dt> + <dd>Una instancia de {{domxref("USVString")}}, una secuencia de {{domxref("USVString")}}s, o un registro conteniendo dos {{domxref("USVString")}}s.</dd> +</dl> + +<h3 id="Valor_retornado">Valor retornado</h3> + +<p>Un objeto instancia de {{domxref("URLSearchParams")}}.</p> + +<h2 id="Ejemplos">Ejemplos</h2> + +<p>El siguiente ejemplo muestra cómo crear un objeto {{domxref("URLSearchParams")}} desde un string que representa una URL.</p> + +<pre class="brush: js">// Pasar un literal string +var url = new URL('https://example.com?foo=1&bar=2'); +// Obtener la URL actual desde window.location +var url2 = new URL(window.location); + +// Obtener parámetros de url.search y pasarlos al constructor +var params = new URLSearchParams(url.search); +var params2 = new URLSearchParams(url2.search); + +// Pasar una secuencia +var params3 = new URLSearchParams([["foo", 1],["bar", 2]]); + +// Pasar un registro +var params4 = new URLSearchParams({"foo" : 1 , "bar" : 2}); +</pre> + +<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('URL', '#dom-urlsearchparams-urlsearchparams', "URLSearchParams()")}}</td> + <td>{{Spec2('URL')}}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_browsers">Compatibilidad de browsers</h2> + +<div> +<div class="hidden">La tabla de compatibilidad en esta página es generada desde datos estructurados. Si te gustaría contribuir a estos datos, por favor clona el repositorio <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> y envíanos un pull request.</div> + +<p>{{Compat("api.URLSearchParams.URLSearchParams")}}</p> +</div> diff --git a/files/es/web/api/using_the_browser_api/index.html b/files/es/web/api/using_the_browser_api/index.html new file mode 100644 index 0000000000..31fb24d2fb --- /dev/null +++ b/files/es/web/api/using_the_browser_api/index.html @@ -0,0 +1,159 @@ +--- +title: Using the browser API +slug: Web/API/Using_the_Browser_API +translation_of: Mozilla/Gecko/Chrome/API/Browser_API/Using +--- +<p>{{ non-standard_header() }}</p> +<p>{{ B2GOnlyHeader2('privileged') }}</p> +<h2 id="Summary">Summary</h2> +<p>The HTML Browser API is an extension of the HTML {{HTMLElement("iframe")}} element that allows web apps to implement browsers or browser-like applications. This entails two major aspects:</p> +<ul> + <li>Make the <code>iframe</code> appear like a top-level browser window to the embedded content. This means that <span id="summary_alias_container"><span id="short_desc_nonedit_display"><a href="/en-US/docs/DOM/window.top" title="/en-US/docs/DOM/window.top"><code>window.top</code></a>, <a href="/en-US/docs/DOM/window.parent" title="/en-US/docs/DOM/window.parent"><code>window.parent</code></a>, <a href="/en-US/docs/DOM/window.frameElement" title="/en-US/docs/DOM/window.frameElement"><code>window.frameElement</code></a>, etc. should <em>not</em> reflect the frame hierarchy.</span></span> Optionally, the notion that the embedded is an Open Web App can be expressed as well.</li> + <li>An API to manipulate and listen for changes to the embedded content's state.</li> +</ul> +<p>In addition to that, it's also possible to express the notion that the embedded content is an <a href="/en-US/docs/Apps" title="/en-US/docs/Apps">Open Web App</a>. In that case the content is loaded within the appropriate app context (such as permissions).</p> +<h2 id="Usage">Usage</h2> +<p>An {{HTMLElement("iframe")}} is turned into a browser frame by setting the {{htmlattrxref("mozbrowser","iframe")}} attribute:</p> +<pre class="brush: html"><iframe src="http://hostname.tld" mozbrowser></pre> +<p>In order to embed an Open Web App, the {{htmlattrxref("mozapp","iframe")}} attribute must also be supplied, with the path to the app's manifest:</p> +<pre><iframe src="http://hostname.tld" mozapp='http://path/to/manifest.webapp' mozbrowser></pre> +<p>At last the content of the {{HTMLElement("iframe")}} can be loaded in its own child process, separate to the page embedding this frame by using the {{htmlattrxref("remote","iframe")}} attribute.</p> +<pre><iframe src="http://hostname.tld" mozbrowser remote></pre> +<div class="warning"> + <p><strong>Warning:</strong> That last attribute is necessary for security reasons if you plan to load content from an untrusted/unknown origin. If you don't use it, you take the risk of your application being compromised by a malicious web site.</p> +</div> +<h2 id="Permissions">Permissions</h2> +<p>Any application that wants to embed a browser frame must have the <code>browser</code> permission within its <a href="/en-US/docs/Web/Apps/Manifest" title="/en-US/docs/Web/Apps/Manifest">app manifest</a>.</p> +<pre class="brush: json">{ + "permissions": { + "browser": {} + } +}</pre> +<p>Additionally, to embed an Open Web App, the app must have the <code>embed-apps</code> permission.</p> +<pre class="brush: json">{ + "permissions": { + "browser": {}, + "embed-apps": {} + } +}</pre> +<h2 id="Extra_methods">Extra methods</h2> +<p>To support the requirement of a browser {{HTMLElement("iframe")}}, Firefox OS extends the {{domxref("HTMLIFrameElement")}} DOM interface. Those new methods gives the {{HTMLElement("iframe")}} some super powers:</p> +<h3 id="Navigation_methods">Navigation methods</h3> +<p>Those methods allow navigating through the browsing history of the {{HTMLElement("iframe")}}. They are necessary to be able to implement back, forward, stop, and reload buttons.</p> +<ul> + <li>{{domxref("HTMLIFrameElement.reload","reload()")}}: Allows reloading the content of the {{HTMLElement("iframe")}}.</li> + <li>{{domxref("HTMLIFrameElement.stop","stop()")}}: Allows stopping the loading of the {{HTMLElement("iframe")}}'s content.</li> + <li>{{domxref("HTMLIFrameElement.getCanGoBack","getCanGoBack()")}}: Allows knowing if it's possible to navigate backward.</li> + <li>{{domxref("HTMLIFrameElement.goBack","goBack()")}}: Changes the location of the {{HTMLElement("iframe")}} for the previous location in its browsing history.</li> + <li>{{domxref("HTMLIFrameElement.getCanGoForward","getCanGoForward()")}}: Allows knowing if it's possible to navigate forward.</li> + <li>{{domxref("HTMLIFrameElement.goForward","goForward()")}}: Changes the location of the {{HTMLElement("iframe")}} for the next location in its browsing history.</li> +</ul> +<h3 id="Performance_methods">Performance methods</h3> +<p>Those methods are used to manage the resources used by a browser {{HTMLElement("iframe")}}. This is especially useful for implementing tabbed browser application.</p> +<ul> + <li>{{domxref("HTMLIFrameElement.setVisible","setVisible()")}}: Changes the visibility state of a browser {{HTMLElement("iframe")}}. This can influence resources allocation and some function usage such as {{domxref("window.requestAnimationFrame","requestAnimationFrame")}}.</li> + <li>{{domxref("HTMLIFrameElement.getVisible","getVisible()")}}: Allows knowing the current visibility state of the browser {{HTMLElement("iframe")}}.</li> + <li>{{domxref("HTMLIFrameElement.purgeHistory","purgeHistory()")}}: Allows clearing all the resources (cookies, localStorage, cache, etc.) associated with the browser {{HTMLElement("iframe")}}.</li> +</ul> +<h3 id="Event_methods">Event methods</h3> +<p>In order to manage the browser {{HTMLElement("iframe")}}'s content, many new events were added (see below). The following methods are used to deal with those events:</p> +<ul> + <li>The {{HTMLElement("iframe")}} gains support for the methods of the {{domxref("EventTarget")}} interface: {{domxref("EventTarget.addEventListener","addEventListener()")}}, {{domxref("EventTarget.removeEventListener","removeEventListener()")}}, and {{domxref("EventTarget.dispatchEvent","dispatchEvent()")}}.</li> + <li>{{domxref("HTMLIFrameElement.sendMouseEvent","sendMouseEvent()")}}: Allows sending a {{domxref("MouseEvent")}} to the {{HTMLElement("iframe")}}'s content.</li> + <li>{{domxref("HTMLIFrameElement.sendTouchEvent","sendTouchEvent()")}}: Allows sending a {{domxref("TouchEvent")}} to the {{HTMLElement("iframe")}}'s content. Note that this method is available for touch enabled devices only.</li> + <li>{{domxref("HTMLIFrameElement.addNextPaintListener","addNextPaintListener()")}}: Allows defining a handler to listen for the next {{event("MozAfterPaint")}} event in the browser {{HTMLElement("iframe")}}.</li> + <li>{{domxref("HTMLIFrameElement.removeNextPaintListener","removeNextPaintListener()")}}: Allows removing a handler previously set with {{domxref("HTMLIFrameElement.addNextPaintListener","addNextPaintListener()")}}.</li> +</ul> +<h3 id="Miscellaneous_methods">Miscellaneous methods</h3> +<p>Those methods are utilities, useful for apps that host a browser {{HTMLElement("iframe")}}.</p> +<ul> + <li>{{domxref("HTMLIFrameElement.getScreenshot","getScreenshot()")}}: Allows taking a screenshot of the browser {{HTMLElement("iframe")}}'s content. This is particularly useful to get thumbnails of tabs in a tabbed browser app.</li> + <li>{{domxref("HTMLIFrameElement.zoom","zoom()")}}: Change the zoom factor of the browser {{HTMLElement("iframe")}}'s content. This is particularly useful to perform zoom in/out on non-touch-enabled devices.</li> +</ul> +<h2 id="Events">Events</h2> +<p>In order to allow an application to manage the browser {{HTMLElement("iframe")}}, the application can listen for new events about what's happening within the browser {{HTMLElement("iframe")}}. The following new events can be listened for:</p> +<ul> + <li>{{event("mozbrowserasyncscroll")}}: Sent when the scroll position within a browser {{HTMLElement("iframe")}} changes.</li> + <li>{{event("mozbrowserclose")}}: Sent when {{domxref("window.close()")}} is called within a browser {{HTMLElement("iframe")}}.</li> + <li>{{event("mozbrowsercontextmenu")}}: Sent when a browser {{HTMLElement("iframe")}} tries to open a context menu. This allows handling {{HTMLElement("menuitem")}} element available within the browser {{HTMLElement("iframe")}}'s content.</li> + <li>{{event("mozbrowsererror")}}: Sent when an error occurred while trying to load content within a browser {{HTMLElement("iframe")}}.</li> + <li>{{event("mozbrowsericonchange")}}: Sent when the favicon of a browser {{HTMLElement("iframe")}} changes.</li> + <li>{{event("mozbrowserloadend")}}: Sent when the browser {{HTMLElement("iframe")}} has finished loading all its assets.</li> + <li>{{event("mozbrowserloadstart")}}: Sent when the browser {{HTMLElement("iframe")}} starts to load a new page.</li> + <li>{{event("mozbrowserlocationchange")}}: Sent when a browser {{HTMLElement("iframe")}}'s location changes.</li> + <li>{{event("mozbrowseropenwindow")}}: Sent when {{domxref("window.open()")}} is called within a browser {{HTMLElement("iframe")}}.</li> + <li>{{event("mozbrowsersecuritychange")}}: Sent when the SSL state changes within a browser {{HTMLElement("iframe")}}.</li> + <li>{{event("mozbrowsershowmodalprompt")}}: Sent when {{domxref("window.alert","alert()")}}, {{domxref("window.confirm","confirm()")}}, or {{domxref("window.prompt","prompt()")}} is called within a browser {{HTMLElement("iframe")}}.</li> + <li>{{event("mozbrowsertitlechange")}}: Sent when the document.title changes within a browser {{HTMLElement("iframe")}}.</li> + <li>{{event("mozbrowserusernameandpasswordrequired")}}: Sent when an HTTP authentification is requested.</li> + <li>{{event("mozbrowseropensearch")}}: Sent when a link to a search engine is found.</li> +</ul> +<h2 id="Example">Example</h2> +<p>In this example we'll see how to implement a very basic browser app.</p> +<h3 id="HTML">HTML</h3> +<p>In the HTML we just add a URL bar, a "Go" and "Stop" button, and a browser {{HTMLElement("iframe")}}.</p> +<pre class="brush: html"><header> + <input id="url"> + <button id="go">Go</button> + <button id="stop">Stop</button> +</header> + +<iframe src="about:blank" mozbrowser remote></iframe> +</pre> +<h3 id="CSS">CSS</h3> +<p>We switch between the go and stop button with a little css trick.</p> +<pre class="brush: css">button:disabled { + display: none; +}</pre> +<h3 id="JavaScript">JavaScript</h3> +<p>Now we can add the required functionalities:</p> +<pre class="brush: js">document.addEventListener("DOMContentLoaded", function () { + var url = document.getElementById("url"); + var go = document.getElementById("go"); + var stop = document.getElementById("stop"); + + var browser = document.getElementsByTagName("iframe")[0]; + + // This function is used to switch the Go and Stop button + // If the browser is loading content, "Go" is disabled and "Stop" is enabled + // Otherwise, "Go" is enabled and "Stop" is disabled + function uiLoading(isLoading) { + go.disabled = isLoading; + stop.disabled = !isLoading; + } + + go.addEventListener("touchend", function () { + browser.setAttribute("src", url.value); + }); + + stop.addEventListener("touchend", function () { + browser.stop(); + }); + + // When the browser starts loading content, we switch the "Go" and "Stop" buttons + browser.addEventListener('mozbrowserloadstart', function () { + uiLoading(true); + }); + + // When the browser finishes loading content, we switch back the "Go" and "Stop" buttons + browser.addEventListener('mozbrowserloadend', function () { + uiLoading(false); + }); + + // In case of error, we also switch back the "Go" and "Stop" buttons + browser.addEventListener('mozbrowsererror', function (event) { + uiLoading(false); + alert("Loading error: " + event.detail); + }); + + // When a user follows a link, we make sure the new location is displayed in the address bar + browser.addEventListener('mozbrowserlocationchange', function (event) { + url.value = event.detail; + }); +});</pre> +<h2 id="See_also">See also</h2> +<ul> + <li>{{HTMLElement("iframe")}}</li> + <li>{{domxref("HTMLIFrameElement")}}</li> + <li>Stat of <a href="https://wiki.mozilla.org/WebAPI/BrowserAPI" title="https://wiki.mozilla.org/WebAPI/BrowserAPI">implementation on WikiMo</a></li> +</ul> diff --git a/files/es/web/api/web_crypto_api/checking_authenticity_with_password/index.html b/files/es/web/api/web_crypto_api/checking_authenticity_with_password/index.html new file mode 100644 index 0000000000..f2e2ef65fd --- /dev/null +++ b/files/es/web/api/web_crypto_api/checking_authenticity_with_password/index.html @@ -0,0 +1,30 @@ +--- +title: Verificando la autenticidad usando contraseña +slug: Web/API/Web_Crypto_API/Checking_authenticity_with_password +translation_of: Web/API/Web_Crypto_API/Checking_authenticity_with_password +--- +<p>{{APIRef("Web Crypto API")}}{{draft}}</p> + +<p>La autenticidad del mensaje puede ser verificada usando el API Crypto Web. En este artículo mostrarémos como crear y controlar una firma digital utilizando una contraseña y una función hash.</p> + +<p>Un algoritmo HMAC toma una llave y genera un código digerido de la llave y los datos a firmar. Posteriormente, cualquiera con la llave puede volver a generar el mismo código digerido para verificar si los datos han sido alterados. Además, mediante el conocimiento de una clave secreta, permite almacenar juntos el código digerido y los datos: un atacante no podrá generar un código digerido sobre datos manipulados si no conoce la clave secreta.</p> + +<p>Note that this algorithm doesn't carry any information about the person owning the data, nor its unicity: the mere knowledge of the key is enough to alter the data.</p> + +<p>Let's assume that the data is stored on the computer. To access it, both for writing and reading, we will use <code>localforage.js</code> a small library wrapping the different storages capabilities of a browser in the same interface. This library is not an essential component of this use case and is used here for convenience, to keep focused on what really matter, the cryptographic part.</p> + +<p>The data we want to access is of the form:</p> + +<p> </p> + +<p>where <code>data</code><em> </em>is the information to guarantee the integrity and <code>signature</code> the information used to verify it.</p> + +<p>Cryptographic keys can't be remembered by heart by human, and passwords, or passphrases, make bad, that is unsecure, cryptographic key. To solve this problem, cryptographers have designed algorithms generating cryptographically-sound keys from password. Knowing the password allowed to regenerate the same key and to use it.</p> + +<p>We ask the user for a password, and we use it to generate the key:</p> + +<pre> </pre> + +<p>With that key, we will be able to compute the <em>mac</em> of the data.</p> + +<pre> </pre> diff --git a/files/es/web/api/web_crypto_api/index.html b/files/es/web/api/web_crypto_api/index.html new file mode 100644 index 0000000000..d8d0069fe4 --- /dev/null +++ b/files/es/web/api/web_crypto_api/index.html @@ -0,0 +1,85 @@ +--- +title: Web Crypto API +slug: Web/API/Web_Crypto_API +tags: + - Referencia + - Vista general + - Web Crypto API +translation_of: Web/API/Web_Crypto_API +--- +<p>{{DefaultAPISidebar("Web Crypto API")}}{{SeeCompatTable}}{{draft}}</p> + +<p>La <strong>Web Crypto API</strong> es una interfaz que permite a un script usar primitivos criptográficos con el fin de construir sistemas utilizando criptografía.</p> + +<div class="blockIndicator warning"> +<p><strong>Advertencia:</strong> Esta API proporciona una serie de primitivos criptográficos de bajo nivel. Es muy fácil hacer un mal uso de ellos, y las trampas involucradas pueden ser muy sutiles.</p> + +<p>Incluso suponiendo que se utilicen correctamente las funciones criptográficas básicas, la gestión segura de las claves y el diseño general del sistema de seguridad son extremadamente difíciles de conseguir correctamente, y generalmente son el dominio de expertos en seguridad especializados.</p> + +<p>Los errores en el diseño e implementación del sistema de seguridad pueden hacer que la seguridad del sistema sea completamente ineficaz.</p> + +<p><strong>Si no estás seguro de saber lo que estás haciendo, probablemente no deberías usar esta API.</strong></p> +</div> + +<p>Una de las principales características de esta API es que permite la manipulación y almacenamiento de claves privadas y secretas sin la capa de bits de la clave para poder usarlo con Javascript.</p> + +<p>Esta interfaz permite el acceso a las siguientes primitivos:</p> + +<ul> + <li><strong><em>digest</em></strong>, la capacidad para calcular un hash de un bloque arbitrario de datos, con el fin de detectar cualquier cambio en él.</li> + <li><strong><em>mac</em></strong>, la capacidad de calcular un código de mensaje de autenticación.</li> + <li><strong><em>sign</em></strong> and <strong><em>verify</em></strong>, la capacidad de firmar digitalmente un documento, y de verificar una firma.</li> + <li><strong><em>encrypt</em></strong> and <strong><em>decrypt</em></strong>, la capacidad de codificar o descodificar un documento.</li> + <li><strong><em>import</em></strong> and <strong><em>export</em></strong>, la capacidad de importar o exportar una clave.</li> + <li><strong><em>key generation</em></strong>, la capacidad de crear una llave criptográfica segura o un par de llaves (llave pública y llave privada), sin el uso de una clave base, pero usando la entropía disponible en el sistema local.</li> + <li><strong><em>key wrapping</em></strong> and <strong><em>unwrapping</em></strong>, la capacidad de transmitir y recibir una llave de un tercero, codificada usando otra llave sin exponer dicha llave a JavaScript.</li> + <li><strong><em>random</em></strong>, la capacidad de generar criptográficamente números pseudo-aleatorios fuertes.</li> +</ul> + +<p>La Web Crypto API no resuelve todos los problemas criptográficos a los que un sitio web o una aplicación puedan encontrarse:</p> + +<ul> + <li>No flexibiliza el modelo de <a href="/en-US/docs/Web/Security/Same-origin_policy">same-origin security model</a> del navegador, como los casos en que las claves son emitidas por entidades centralizadas utilizadas por varios sitios web.</li> + <li>No interactúa con hardware dedicado, tal y como smart cards, pendrives, o generadores aleatorios.</li> +</ul> + +<div class="warning"> +<p><strong>¡Atención!</strong></p> + +<ul> + <li>El simple hecho de hacer uso de la criptografía no hace a tu sistema seguro. La Seguridad es un <strong>proceso</strong> que constamentemente evalua el riesgo de un sistema en el contexto de uso. The context and the risks experienced evolve over time.</li> + <li>Al aplicar seguridad, todo el <strong>sistema</strong> debe considerarse. En el caso de la Web Crypto API, los desarrolladores Web no sólo deben considerar la seguridad del script, sino también la seguridad de la conexión al servidor y los datos que éste podría comunicar sin encriptar. La seguridad en general será tan débil como la parte más débil de todo el sistema.</li> +</ul> +</div> + +<h2 id="Interfaces">Interfaces</h2> + +<p>Algunos navegadores implementan una interfaz llamada {{domxref("Crypto")}} sin tenerla bien definida o criptográficamente siendo llamada. Con el fin de evitar conclusiones, los métodos y propiedades de esta interfaz van a ir implementados en la Web Crypto API, y todos los métodos de la Web Crypto API están disponibles en una nueva interfaz: {{domxref("SubtleCrypto")}}.<br> + La propiedad {{domxref("Crypto.subtle")}} da acceso a un objeto para implementarla.</p> + +<h2 id="Casos_de_uso">Casos de uso</h2> + +<p>La Web Crypto API puede ser usada para:</p> + +<ul> + <li>Verificar que los datos no han sido alterados por terceros. Incluso si los datos se almacenan de forma clara, el almacenamiento de una firma, generada a partir de una contraseña, permite a las personas que conocen la contraseña saber que es auténtica.</li> +</ul> + +<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("Web Crypto API")}}</td> + <td>{{Spec2("Web Crypto API")}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> diff --git a/files/es/web/api/web_speech_api/index.html b/files/es/web/api/web_speech_api/index.html new file mode 100644 index 0000000000..0a8de49da3 --- /dev/null +++ b/files/es/web/api/web_speech_api/index.html @@ -0,0 +1,121 @@ +--- +title: Web Speech API +slug: Web/API/Web_Speech_API +tags: + - API + - Experimental + - Landing + - NeedsTranslation + - Reference + - TopicStub + - Web Speech API + - recognition + - speech + - synthesis +translation_of: Web/API/Web_Speech_API +--- +<div>{{DefaultAPISidebar("Web Speech API")}}{{seecompattable}}</div> + +<div class="summary"> +<p>The Web Speech API enables you to incorporate voice data into web apps. The Web Speech API has two parts: SpeechSynthesis (Text-to-Speech), and SpeechRecognition (Asynchronous Speech Recognition.)</p> +</div> + +<h2 id="Web_Speech_Concepts_and_Usage">Web Speech Concepts and Usage</h2> + +<p>The Web Speech API makes web apps able to handle voice data. There are two components to this API:</p> + +<ul> + <li>Speech recognition is accessed via the {{domxref("SpeechRecognition")}} interface, which provides the ability to recognize voice context from an audio input (normally via the device's default speech recognition service) and respond appropriately. Generally you'll use the interface's constructor to create a new {{domxref("SpeechRecognition")}} object, which has a number of event handlers available for detecting when speech is input through the device's microphone. The {{domxref("SpeechGrammar")}} interface represents a container for a particular set of grammar that your app should recognise. Grammar is defined using <a href="http://www.w3.org/TR/jsgf/">JSpeech Grammar Format</a> (<strong>JSGF</strong>.)</li> + <li>Speech synthesis is accessed via the {{domxref("SpeechSynthesis")}} interface, a text-to-speech component that allows programs to read out their text content (normally via the device's default speech synthesiser.) Different voice types are represented by {{domxref("SpeechSynthesisVoice")}} objects, and different parts of text that you want to be spoken are represented by {{domxref("SpeechSynthesisUtterance")}} objects. You can get these spoken by passing them to the {{domxref("SpeechSynthesis.speak()")}} method.</li> +</ul> + +<p>For more details on using these features, see <a href="/en-US/docs/Web/API/Web_Speech_API/Using_the_Web_Speech_API">Using the Web Speech API</a>.</p> + +<h2 id="Web_Speech_API_Interfaces">Web Speech API Interfaces</h2> + +<h3 id="Speech_recognition">Speech recognition</h3> + +<dl> + <dt>{{domxref("SpeechRecognition")}}</dt> + <dd>The controller interface for the recognition service; this also handles the {{domxref("SpeechRecognitionEvent")}} sent from the recognition service.</dd> + <dt>{{domxref("SpeechRecognitionAlternative")}}</dt> + <dd>Represents a single word that has been recognised by the speech recognition service.</dd> + <dt>{{domxref("SpeechRecognitionError")}}</dt> + <dd>Represents error messages from the recognition service.</dd> + <dt>{{domxref("SpeechRecognitionEvent")}}</dt> + <dd>The event object for the {{event("result")}} and {{event("nomatch")}} events, and contains all the data associated with an interim or final speech recognition result.</dd> + <dt>{{domxref("SpeechGrammar")}}</dt> + <dd>The words or patterns of words that we want the recognition service to recognize.</dd> + <dt>{{domxref("SpeechGrammarList")}}</dt> + <dd>Represents a list of {{domxref("SpeechGrammar")}} objects.</dd> + <dt>{{domxref("SpeechRecognitionResult")}}</dt> + <dd>Represents a single recognition match, which may contain multiple {{domxref("SpeechRecognitionAlternative")}} objects.</dd> + <dt>{{domxref("SpeechRecognitionResultList")}}</dt> + <dd>Represents a list of {{domxref("SpeechRecognitionResult")}} objects, or a single one if results are being captured in {{domxref("SpeechRecognition.continuous","continuous")}} mode.</dd> +</dl> + +<h3 id="Speech_synthesis">Speech synthesis</h3> + +<dl> + <dt>{{domxref("SpeechSynthesis")}}</dt> + <dd>The controller interface for the speech service; this can be used to retrieve information about the synthesis voices available on the device, start and pause speech, and other commands besides.</dd> + <dt>{{domxref("SpeechSynthesisErrorEvent")}}</dt> + <dd>Contains information about any errors that occur while processing {{domxref("SpeechSynthesisUtterance")}} objects in the speech service.</dd> + <dt>{{domxref("SpeechSynthesisEvent")}}</dt> + <dd>Contains information about the current state of {{domxref("SpeechSynthesisUtterance")}} objects that have been processed in the speech service.</dd> + <dt>{{domxref("SpeechSynthesisUtterance")}}</dt> + <dd>Represents a speech request. It contains the content the speech service should read and information about how to read it (e.g. language, pitch and volume.)</dd> +</dl> + +<dl> + <dt>{{domxref("SpeechSynthesisVoice")}}</dt> + <dd>Represents a voice that the system supports. Every <code>SpeechSynthesisVoice</code> has its own relative speech service including information about language, name and URI.</dd> + <dt>{{domxref("Window.speechSynthesis")}}</dt> + <dd>Specced out as part of a <code>[NoInterfaceObject]</code> interface called <code>SpeechSynthesisGetter</code>, and Implemented by the <code>Window</code> object, the <code>speechSynthesis</code> property provides access to the {{domxref("SpeechSynthesis")}} controller, and therefore the entry point to speech synthesis functionality.</dd> +</dl> + +<h2 id="Examples">Examples</h2> + +<p>The <a href="https://github.com/mdn/web-speech-api/">Web Speech API repo</a> on GitHub contains demos to illustrate speech recognition and synthesis.</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('Web Speech API')}}</td> + <td>{{Spec2('Web Speech API')}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<h3 id="SpeechRecognition"><code>SpeechRecognition</code></h3> + +<div> + + +<p>{{Compat("api.SpeechRecognition", 0)}}</p> + +<h3 id="SpeechSynthesis"><code>SpeechSynthesis</code></h3> + +<div class="hidden">The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</div> + +<p>{{Compat("api.SpeechSynthesis", 0)}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Web_Speech_API/Using_the_Web_Speech_API">Using the Web Speech API</a></li> + <li><a href="http://www.sitepoint.com/talking-web-pages-and-the-speech-synthesis-api/">SitePoint article</a></li> + <li><a href="http://updates.html5rocks.com/2014/01/Web-apps-that-talk---Introduction-to-the-Speech-Synthesis-API">HTML5Rocks article</a></li> + <li><a href="http://aurelio.audero.it/demo/speech-synthesis-api-demo.html">Demo</a> [aurelio.audero.it]</li> +</ul> +</div> diff --git a/files/es/web/api/web_speech_api/uso_de_la_web_speech_api/index.html b/files/es/web/api/web_speech_api/uso_de_la_web_speech_api/index.html new file mode 100644 index 0000000000..407de0e10d --- /dev/null +++ b/files/es/web/api/web_speech_api/uso_de_la_web_speech_api/index.html @@ -0,0 +1,301 @@ +--- +title: Uso de la Web Speech API +slug: Web/API/Web_Speech_API/Uso_de_la_Web_Speech_API +translation_of: Web/API/Web_Speech_API/Using_the_Web_Speech_API +--- +<p class="summary">La API Web Speech API proporciona dos funcionalidades distintas — reconocimiento de voz, y síntesis de voz (también conocido como texto a voz o tts) — lo que nos ofrece nuevas e interesantes posibilidades para accesibilidad y otros mecanismos. Este artículo ofrece una breve introducción en las dos áreas, así como unas demos.</p> + +<h2 id="Reconocimiento_de_voz">Reconocimiento de voz</h2> + +<p>El reconocimiento de voz implica recibir voz a través del micrófono de un dispositivo, luego es verificado por un servicio de reconocimiento de voz contra una lista de palabras o frases 'grammar' (esta lista básicamente es el vocabulario a reconocer en una app particular). Cuando se reconoce con éxito una palabra o frase, esta se devuelve como una cadena de texto y así poder iniciar otras acciones.</p> + +<p>La API Web Speech tiene una interfaz principal de control para el - {{domxref ("SpeechRecognition")}} -, además de una serie de interfaces estrechamente relacionadas para representar la gramática, los resultados, etc. Normalmente, el sistema de reconocimiento de voz predeterminado que dispone el dispositivo se utilizará para el reconocimiento de voz: la mayoría de los sistemas operativos modernos tienen un sistema de reconocimiento de voz para emitir comandos de voz. Piense en Dictado en macOS, Siri en iOS, Cortana en Windows 10, Android Speech, etc.</p> + +<div class="note"> +<p><strong>Note</strong>: En algunos navegadores como Chrome, el uso del reconocimiento de voz implica el uso de un motor de reconocimiento basado en un servidor. Tu audio se envía a un servicio de reconocimiento web para ser procesado, por lo que no funcionará offline.</p> +</div> + +<h3 id="Demo">Demo</h3> + +<p>Para mostrar un uso sencillo del reconocimiento de voz Web, hemos escrito una demo llamada <a href="https://github.com/mdn/web-speech-api/tree/master/speech-color-changer">Speech color changer</a>. Cuando se toca o hace click en la pantalla, se puede decir un color HTML, y el color de fondo de la aplicación cambiará a ese color.</p> + +<p><img alt="The UI of an app titled Speech Color changer. It invites the user to tap the screen and say a color, and then it turns the background of the app that colour. In this case it has turned the background red." src="https://mdn.mozillademos.org/files/11975/speech-color-changer.png" style="border: 1px solid black; display: block; height: 533px; margin: 0px auto; width: 300px;"></p> + +<p>Para ejecutar la demo, se puede clonar (o <a href="https://github.com/mdn/web-speech-api/archive/master.zip">directamente descargar</a>) el repositorio Github donde se encuentra, abrir el fichero index HTML en un navegador de escritorio compatible, o navegar a través del enlace <a href="https://mdn.github.io/web-speech-api/speech-color-changer/">live demo URL</a> en un navegador de móvil compatible como Chrome.</p> + +<h3 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h3> + +<p>Actualmente, la compatibilidad de la Web Speech API para el reconocimiento de voz se limita a Chrome para escritorio y Android — Chrome tiene soporte desde la versión 33 pero con interfaces 'prefixed', por lo que se deben incluir ese tipo de interfaces 'prefixed', por ejemplo <code>webkitSpeechRecognition</code>.</p> + +<h3 id="HTML_y_CSS">HTML y CSS</h3> + +<p>El HTML y el CSS para esta app no son importantes. Solo tenemos un título, instrucciones en un párrafo, y un div dentro del cual visualizaremos los mensajes de diagnósticos.</p> + +<pre class="brush: html"><h1>Speech color changer</h1> +<p>Tap/click then say a color to change the background color of the app.</p> +<div> + <p class="output"><em>...diagnostic messages</em></p> +</div></pre> + +<p>El CSS proporciona un estilo responsive muy simple para que se visualice bien en todos los dispositivos.</p> + +<h3 id="JavaScript">JavaScript</h3> + +<p>Miremos el JavaScript con un poco más de detalle.</p> + +<h4 id="Compatibilidad_con_Chrome">Compatibilidad con Chrome </h4> + +<p>Como se ha mencionado anteriormente, Chrome actualmente admite el reconocimiento de voz con propiedades 'prefixed', por lo tanto, al principio de nuestro código incluiremos las siguientes líneas para usar los objetos que correspondan a Chrome, y así cualquier implementación en el futuro pueda admitir estas características sin ningún 'prefixed':</p> + +<pre class="brush: js">var SpeechRecognition = SpeechRecognition || webkitSpeechRecognition +var SpeechGrammarList = SpeechGrammarList || webkitSpeechGrammarList +var SpeechRecognitionEvent = SpeechRecognitionEvent || webkitSpeechRecognitionEvent</pre> + +<h4 id="La_gramática_-grammar-">La gramática -grammar-</h4> + +<p>Las siguientes líneas de código definen la gramática que queremos que reconozca nuestra app. Se define una variable para contener nuestra gramática:</p> + +<pre class="brush: js">var colors = [ 'aqua' , 'azure' , 'beige', 'bisque', 'black', 'blue', 'brown', 'chocolate', 'coral' ... ]; +var grammar = '#JSGF V1.0; grammar colors; public <color> = ' + colors.join(' | ') + ' ;'</pre> + +<p>El formato usado para 'grammar' es <a class="external external-icon" href="http://www.w3.org/TR/jsgf/">JSpeech Grammar Format</a> (<strong>JSGF</strong>) — Se puede encontrar más sobre las especificaciones de este formato en el anterior enlace. Sin embargo y por ahora vamos a echarle un vistazo rápidamente:</p> + +<ul> + <li>Las líneas se separan con punto y coma como en JavaScript.</li> + <li>La primera línea — <code>#JSGF V1.0;</code> — establece el formato y versión utilizados. Esto siempre se debe incluir primero.</li> + <li>La segunda línea indica el tipo de términos que queremos que se reconozcan. <code>public</code> declara que es una regla pública, la cadena entre los paréntesis angulares definen el nombre reconocido para éste término (<code>color</code>), y la lista de elementos que siguen al signo igual son los valores alternativos que se reconocerán y aceptaran como valores apropiados al término. Observar como cada elemento se separa con el carácter pipe ' | ' .</li> + <li>Se pueden definir tantos términos como se desee en líneas separadas siguiendo la estructura anterior, e incluir definiciones gramaticales complejas. Esta demostración básica la mantenemos lo más simple posible.</li> +</ul> + +<h4 id="Conectando_la_gramática_a_nuestro_reconocimiento_de_voz">Conectando la gramática a nuestro reconocimiento de voz</h4> + +<p>Lo siguiente que tenemos que hacer es definir una instancia de reconocimiento de voz para el control en nuestra aplicación. Esto se hace usando el constructor {{domxref("SpeechRecognition.SpeechRecognition()", "SpeechRecognition()")}}. También creamos una lista de gramática de voz para contener nuestra gramática usando el constructor {{domxref("SpeechGrammarList.SpeechGrammarList()","SpeechGrammarList()")}}.</p> + +<pre class="brush: js">var recognition = new SpeechRecognition(); +var speechRecognitionList = new SpeechGrammarList();</pre> + +<p>Añadimos nuestra <code>grammar</code> a la lista anterior usando el método {{domxref("SpeechGrammarList.addFromString()")}}. Este método acepta como parámetro la cadena que queremos añadir, así como opcionalmente, un valor que especifique la importancia de esta gramática en relación a otras gramáticas disponibles en la lista (el rango del valor va desde 0 hasta 1 inclusive). La gramática agregada está disponible en la lista como una instancia del objeto {{domxref("SpeechGrammar")}}.</p> + +<pre class="brush: js">speechRecognitionList.addFromString(grammar, 1);</pre> + +<p>Después añadimos la lista {{domxref("SpeechGrammarList")}} a la instancia del reconocimiento de voz estableciéndola en la propiedad {{domxref("SpeechRecognition.grammars")}}. También establecemos algunas otras propiedades a la instancia de reconocimiento antes de continuar:</p> + +<ul> + <li>{{domxref("SpeechRecognition.continuous")}}: Controla si se capturan los resultados de forma continua (<code>true</code>), o solo un resultado cada vez que se inicia el reconocimiento (<code>false</code>).</li> + <li>{{domxref("SpeechRecognition.lang")}}: Establece el idioma del reconocimiento. Esto es una buena práctica y, por lo tanto, recomendable.</li> + <li>{{domxref("SpeechRecognition.interimResults")}}: Define si el sistema de reconocimiento de voz debe devolver resultados provisionales o solo resultados finales. Para nuestra demo es suficiente con los resultados finales.</li> + <li>{{domxref("SpeechRecognition.maxAlternatives")}}: Establece el número de posibles coincidencias alternativas que se deben devolver por resultado. Esto a veces puede ser útil, por ejemplo, si un resultado no está completamente claro y desea mostrar una lista de alternativas para que el usuario elija la correcta. Esta opción no es necesaria para la demo, por lo que solo especificamos una (la cual es la predeterminada).</li> +</ul> + +<pre class="brush: js">recognition.grammars = speechRecognitionList; +recognition.continuous = false; +recognition.lang = 'en-US'; +recognition.interimResults = false; +recognition.maxAlternatives = 1;</pre> + +<h4 id="Comenzando_el_reconocimiento_de_voz">Comenzando el reconocimiento de voz</h4> + +<p>Tomamos las referencias de la salida {{htmlelement("div")}} y del elemento HTML (para que podamos enviar mensajes de diagnostico y actualizar el color de fondo de la aplicación más adelante), e implementamos un manejador onclick para que cuando se haga click o se toque la pantalla, se inicie el reconocimiento de voz. Esto se logra llamando al método {{domxref("SpeechRecognition.start()")}}. El método <code>forEach()</code> se usa para visualizar indicadores de colores que muestran qué colores intenta decir.</p> + +<pre class="brush: js">var diagnostic = document.querySelector('.output'); +var bg = document.querySelector('html'); +var hints = document.querySelector('.hints'); + +var colorHTML= ''; +colors.forEach(function(v, i, a){ + console.log(v, i); + colorHTML += '<span style="background-color:' + v + ';"> ' + v + ' </span>'; +}); +hints.innerHTML = 'Tap/click then say a color to change the background color of the app. Try ' + colorHTML + '.'; + +document.body.onclick = function() { + recognition.start(); + console.log('Ready to receive a color command.'); +}</pre> + +<h4 id="Recepción_y_manejo_de_resultados">Recepción y manejo de resultados</h4> + +<p>Una vez que comienza el reconocimiento de voz, hay muchos manejadores de eventos que se pueden usar para recuperar los resultados, así como otros elementos de información adicional (ver <a href="https://developer.mozilla.org/en-US/docs/Web/API/SpeechRecognition#Event_handlers"><code>SpeechRecognition</code> event handlers list</a>.) El más común que probablemente usarás es {{domxref("SpeechRecognition.onresult")}}, el cual es lanzado cuando se recibe el resultado con éxito:</p> + +<pre class="brush: js">recognition.onresult = function(event) { + var color = event.results[0][0].transcript; + diagnostic.textContent = 'Result received: ' + color + '.'; + bg.style.backgroundColor = color; + console.log('Confidence: ' + event.results[0][0].confidence); +}</pre> + +<p>La tercera línea es un poco más compleja, así que vamos a explicarla paso a paso. La propiedad {{domxref("SpeechRecognitionEvent.results")}} devuelve un objeto {{domxref("SpeechRecognitionResultList")}} que contiene los objetos {{domxref("SpeechRecognitionResult")}}. Tiene un getter para que pueda ser accesible como si fuera un array — así el primer <code>[0]</code> devuelve el <code>SpeechRecognitionResult</code> en la posición 0. Cada objeto <code>SpeechRecognitionResult</code> contiene objetos {{domxref("SpeechRecognitionAlternative")}} que contienen palabras individuales reconocidas. Estos también tienen getters para que se puedan acceder a ellos como arrays — por lo tanto el segundo <code>[0]</code> devuelve <code>SpeechRecognitionAlternative</code> en la posición 0. Luego devolvemos su propiedad <code>transcript</code> para obtener una cadena que contenga el resultado individual reconocido como un string, estableciendo el color de fondo a ese color, e informando del color reconocido como un mensaje de diagnóstico en el IU.</p> + +<p>También usamos el manejador {{domxref("SpeechRecognition.onspeechend")}} para parar el servicio de reconocimiento de voz (usando {{domxref("SpeechRecognition.stop()")}}) cuando se ha reconocido una sola palabra y se ha finalizado de hablar:</p> + +<pre class="brush: js">recognition.onspeechend = function() { + recognition.stop(); +}</pre> + +<h4 id="Manejo_de_errores_y_voz_no_reconocida">Manejo de errores y voz no reconocida</h4> + +<p>Los dos últimos manejadores son para controlar los casos donde no se reconoce ninguna de las palabras definidas en la gramática, o cuando ocurre un error. {{domxref("SpeechRecognition.onnomatch")}} maneja el primer caso mencionado, pero tenga en cuenta que de momento no parece que se dispare correctamente; solo devuelve lo que ha reconocido:</p> + +<pre class="brush: js">recognition.onnomatch = function(event) { + diagnostic.textContent = 'I didnt recognise that color.'; +}</pre> + +<p>{{domxref("SpeechRecognition.onerror")}} maneja los casos donde se ha producido en error en el reconocimiento — la propiedad {{domxref("SpeechRecognitionError.error")}} contiene el error devuelto:</p> + +<pre class="brush: js">recognition.onerror = function(event) { + diagnostic.textContent = 'Error occurred in recognition: ' + event.error; +}</pre> + +<h2 id="Síntesis_de_voz">Síntesis de voz</h2> + +<p>La síntesis de voz (también conocida como texto a voz o tts) implica recibir contenido en forma de texto dentro de una aplicación y convertirla en voz a través del altavoz del dispositivo o de la conexión de salida del audio.</p> + +<p>La Web Speech API tiene una interface principal controladora — {{domxref("SpeechSynthesis")}} — además de una serie de interfaces estrechamente relacionadas para representar el texto que se va a sintetizar (conocido como dictados 'utterances'), voces que se usarán para los dictados, etc. De nuevo, la mayoría de sistemas operativos disponen de algún sistema de síntesis de voz que pueden serán usados por la API si están disponibles.</p> + +<h3 id="Demo_2">Demo</h3> + +<p>Para mostrar un uso sencillo de la síntesis de voz Web, tenemos la demo llamada <a href="https://mdn.github.io/web-speech-api/speak-easy-synthesis/">Speak easy synthesis</a>. Esta incluye un juego de controles de formulario para introducir texto a sintetizar, configurar el tono, velocidad de reproducción y la voz a usar cuando el texto sea pronunciado. Después de introducir el texto se puede presionar <kbd>Enter</kbd>/<kbd>Return</kbd> para escucharlo.</p> + +<p><img alt="UI of an app called speak easy synthesis. It has an input field in which to input text to be synthesised, slider controls to change the rate and pitch of the speech, and a drop down menu to choose between different voices." src="https://mdn.mozillademos.org/files/11977/speak-easy-synthesis.png" style="border: 1px solid black; display: block; height: 533px; margin: 0px auto; width: 300px;"></p> + +<p>Para ejecutar la demo, se puede clonar (o <a href="https://github.com/mdn/web-speech-api/archive/master.zip">directamente descargar</a>) el repositorio Github donde se encuentra, abrir el fichero index HTML en un navegador de escritorio compatible, o navegar a través del enlace <a href="https://mdn.github.io/web-speech-api/speech-color-changer/">live demo URL</a> en un navegador de móvil compatible como Chrome.</p> + +<h3 id="Compatibilidad_de_navegadores_2">Compatibilidad de navegadores</h3> + +<p>El soporte para la síntesis de voz Web Speech API solo ha llegado a los navegadores más importantes y actualmente se limita a los siguientes:</p> + +<ul> + <li> + <p>Firefox para escritorio y dispositivos móviles en Gecko 42+ (Windows)/44+, sin prefijos, y se puede activar configurando el flag <code>media.webspeech.synth.enabled</code> a <code>true</code> en <code>about:config</code>.</p> + </li> + <li> + <p>Firefox OS 2.5+ lo soporta por defecto y sin ser necesario ningún permiso.</p> + </li> + <li> + <p>Chrome para escritorio y Android tienen soporte desde la versión 33, sin prefijos.</p> + </li> +</ul> + +<h3 id="HTML_y_CSS_2">HTML y CSS</h3> + +<p>El HTML y CSS de nuevo no son fundamentales, simplemente contiene un titulo, algunas instrucciones de uso y un formulario con algunos controles sencillos. El elemento {{htmlelement("select")}} inicialmente está vacío pero se rellena con {{htmlelement("option")}} mediante JavaScript (ver más adelante.)</p> + +<pre class="brush: html"><h1>Speech synthesiser</h1> + +<p>Enter some text in the input below and press return to hear it. change voices using the dropdown menu.</p> + +<form> + <input type="text" class="txt"> + <div> + <label for="rate">Rate</label><input type="range" min="0.5" max="2" value="1" step="0.1" id="rate"> + <div class="rate-value">1</div> + <div class="clearfix"></div> + </div> + <div> + <label for="pitch">Pitch</label><input type="range" min="0" max="2" value="1" step="0.1" id="pitch"> + <div class="pitch-value">1</div> + <div class="clearfix"></div> + </div> + <select> + + </select> +</form></pre> + +<h3 id="JavaScript_2">JavaScript</h3> + +<p>Analicemos el JavaScript usado en esta app.</p> + +<h4 id="Configurar_variables">Configurar variables</h4> + +<p>En primer lugar, capturamos las referencias de todos los elementos DOM involucrados en la IU, pero lo más importante es capturar una referencia a {{domxref("Window.speechSynthesis")}}. Este es el punto de entrada a la API — devuelve una instancia a {{domxref("SpeechSynthesis")}}, la interface controladora para la síntesis de voz en la web.</p> + +<pre class="brush: js">var synth = window.speechSynthesis; + +var inputForm = document.querySelector('form'); +var inputTxt = document.querySelector('.txt'); +var voiceSelect = document.querySelector('select'); + +var pitch = document.querySelector('#pitch'); +var pitchValue = document.querySelector('.pitch-value'); +var rate = document.querySelector('#rate'); +var rateValue = document.querySelector('.rate-value'); + +var voices = []; +</pre> + +<h4 id="Rellenar_el_elemento_select">Rellenar el elemento select </h4> + +<p>Para rellenar el elemento {{htmlelement("select")}} con las diferentes opciones de voz del que dispone el dispositivo, hemos escrito la función <code>populateVoiceList()</code>. Primero invocamos {{domxref("SpeechSynthesis.getVoices()")}}, que devuelve una lista de todas las voces disponibles representadas por objetos {{domxref("SpeechSynthesisVoice")}}. Después recorremos esa lista — para cada voz creamos un elemento {{htmlelement("option")}}, establecemos su contenido con el nombre de la voz (desde {{domxref("SpeechSynthesisVoice.name")}}), y el lenguaje de la misma (desde {{domxref("SpeechSynthesisVoice.lang")}}), y <code>-- DEFAULT</code> si la voz es la predeterminada para el motor de síntesis (verificando si {{domxref("SpeechSynthesisVoice.default")}} devuelve <code>true</code>.)</p> + +<p>Para cada opción también creamos atributos <code>data-</code>, conteniendo el nombre y lenguaje de la voz asociada, para que más tarde podamos usarlos fácilmente, y después añadimos las opciones 'option' como hijos del select.</p> + +<pre class="brush: js">function populateVoiceList() { + voices = synth.getVoices(); + + for(i = 0; i < voices.length ; i++) { + var option = document.createElement('option'); + option.textContent = voices[i].name + ' (' + voices[i].lang + ')'; + + if(voices[i].default) { + option.textContent += ' -- DEFAULT'; + } + + option.setAttribute('data-lang', voices[i].lang); + option.setAttribute('data-name', voices[i].name); + voiceSelect.appendChild(option); + } +}</pre> + +<p>Cuando vamos a ejecutar la función hacemos lo siguiente debido a que Firefox no soporta {{domxref("SpeechSynthesis.onvoiceschanged")}}, y sólo devolverá una lista de voces cuando se ejecute {{domxref("SpeechSynthesis.getVoices()")}}. Sin embargo con Chrome solo hay que esperar a que se active el evento antes de rellenar la lista, de ahí la siguiente parte de código.</p> + +<pre class="brush: js">populateVoiceList(); +if (speechSynthesis.onvoiceschanged !== undefined) { + speechSynthesis.onvoiceschanged = populateVoiceList; +}</pre> + +<h4 id="Reproduciendo_el_texto_introducido">Reproduciendo el texto introducido</h4> + +<p>A continuación, creamos un manejador de eventos para comenzar a reproducir el texto introducido en el campo de texto. Usamos un manejador <a href="/en-US/docs/Web/API/GlobalEventHandlers/onsubmit">onsubmit</a> en el formulario para que la acción ocurra cuando se presione <kbd>Enter</kbd>/<kbd>Return</kbd>. Primero creamos una nueva instancia de {{domxref("SpeechSynthesisUtterance.SpeechSynthesisUtterance()", "SpeechSynthesisUtterance()")}} usando su constructor — a este se le pasa el valor de la entrada de texto como parámetro.</p> + +<p>A continuación, debemos obtener la voz que queremos utilizar. Usamos la propiedad {{domxref("HTMLSelectElement")}} <code>selectedOptions</code> para devolver el elemento seleccionado {{htmlelement("option")}}. Entonces usamos el atributo de este elemento <code>data-name</code>, encontrando el objeto {{domxref("SpeechSynthesisVoice")}} cuyo nombre coincida con el valor del atributo. Y configuramos la propiedad de {{domxref("SpeechSynthesisUtterance.voice")}} con el valor que coincida con la opción seleccionada.</p> + +<p>Por último, configuramos {{domxref("SpeechSynthesisUtterance.pitch")}} y {{domxref("SpeechSynthesisUtterance.rate")}} con los valores de los elementos del formulario correspondientes. Entonces y ya configurado todo lo necesario, comenzamos la reproducción invocando {{domxref("SpeechSynthesis.speak()")}}, y pasándolo a la instancia {{domxref("SpeechSynthesisUtterance")}} como parámetro.</p> + +<pre class="brush: js">inputForm.onsubmit = function(event) { + event.preventDefault(); + + var utterThis = new SpeechSynthesisUtterance(inputTxt.value); + var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name'); + for(i = 0; i < voices.length ; i++) { + if(voices[i].name === selectedOption) { + utterThis.voice = voices[i]; + } + } + utterThis.pitch = pitch.value; + utterThis.rate = rate.value; + synth.speak(utterThis);</pre> + +<p>Al final del manejador incluimos un manejador {{domxref("SpeechSynthesisUtterance.onpause")}} para mostrar cómo usar {{domxref("SpeechSynthesisEvent")}}. Cuando se invoca a {{domxref("SpeechSynthesis.pause()")}},este devuelve un mensaje informando del número y nombre del carácter en el que se detuvo la reproducción.</p> + +<pre class="brush: js"> utterThis.onpause = function(event) { + var char = event.utterance.text.charAt(event.charIndex); + console.log('Speech paused at character ' + event.charIndex + ' of "' + + event.utterance.text + '", which is "' + char + '".'); + }</pre> + +<p>Por último, llamamos a <a href="/en-US/docs/Web/API/HTMLElement/blur">blur()</a> en la entrada de texto. Esto permite ocultar la entrada de texto en Firefox OS.</p> + +<pre class="brush: js"> inputTxt.blur(); +}</pre> + +<h4 id="Actualizando_los_valores_de_tono_y_velocidad_mostrados">Actualizando los valores de tono y velocidad mostrados</h4> + +<p>La última parte del código simplemente actualiza los valores <code>pitch</code>/<code>rate</code> mostrados en la IU, cada vez que el slider cambia de posición.</p> + +<pre class="brush: js">pitch.onchange = function() { + pitchValue.textContent = pitch.value; +} + +rate.onchange = function() { + rateValue.textContent = rate.value; +}</pre> diff --git a/files/es/web/api/web_workers_api/index.html b/files/es/web/api/web_workers_api/index.html new file mode 100644 index 0000000000..3a055af3ca --- /dev/null +++ b/files/es/web/api/web_workers_api/index.html @@ -0,0 +1,226 @@ +--- +title: Web Workers API +slug: Web/API/Web_Workers_API +translation_of: Web/API/Web_Workers_API +--- +<p>{{DefaultAPISidebar("Web Workers API")}}</p> + +<p class="summary"><strong>Los Web Workers</strong> hacen posible ejecutar la operación de un script en un hilo en segundo plano separado de la ejecución el hilo principal de la aplicación web. La ventaja de esto es que un proceso laborioso puede actuar en un hilo separado, permitiendo al hilo principal (normlamente la UI) ejecutarse sin ser bloqueado o ralentizado.</p> + +<h2 id="Web_Workers_conceptos_y_uso">Web Workers conceptos y uso</h2> + +<p>Un worker es un objeto que se crea a través del constructor ( {{domxref("Worker.Worker", "Worker()")}}) este ejecuta un archivo javascript — este fichero contiene los scripts que se van a ejecutan en el hilo del worker; los workers se ejecutan en un contexto global diferente al actual del navegador {{domxref("window")}}. Este contexto está representado por el objeto {{domxref("DedicatedWorkerGlobalScope")}} en el caso de los workers dedicados (los workers standard utilizan un solo script; y los shared workers usan {{domxref("SharedWorkerGlobalScope")}}).</p> + +<p>Podemos ejecutar los script que necesitemos dentro del hilo del worker, pero con algunas excepciones. Por ejemplo no se puede manipular directamente el DOM, ni usar algunos métodos y propiedades por defecto del objeto {{domxref("window")}}. Pero puede usar un gran número de elementos que están dentro de <code>window</code>, incluyendo <a href="/en-US/docs/WebSockets">WebSockets</a>, y data storage formas de almacenamiento como <a href="/en-US/docs/Web/API/IndexedDB_API">IndexedDB</a> y solo en Firefox OS <a href="/en-US/docs/Web/API/Data_Store_API">Data Store API</a>. Mira <a href="/en-US/docs/Web/API/Worker/Functions_and_classes_available_to_workers">Funciones y clases disponibles para workers</a> para saber más.</p> + +<p>Los datos se comunican entre los workers y el hilo principal a través de un sistema de mensajes — tanto del hilo principal como del worker para enviar un mensaje se invoca al método <code>postMessage()</code> , y a través del listener del evento <code>onmessage</code> se pueden escuchar los mensajes (El mensaje está dentro de la propiedad <code>data</code> del evento) . Los datos se copian en lugar de compartirse.</p> + +<p>Los workers también pueden generar nuevos workers, siempre que los workers estén en la misma página que el principal. Además, los workers pueden usar <a class="internal" href="/en-US/docs/Web/API/XMLHttpRequest"><code>XMLHttpRequest</code></a> para la network I/O, con la excepción de que los atributos <code>responseXML</code> y <code>channel</code> de <code>XMLHttpRequest</code> siempre retornan valor <code>null</code>.</p> + +<p>Ademas de los workers dedicados, hay otro tipo de workers:</p> + +<ul> + <li>Los Shared workers son workers que pueden ser utilizados por multiples scripts corriendo en diferenes ventanas, IFrames, etc., esto siempre que estén en el mismo dominio que el worker. Son un poco más complejos que los workers dedicados— los scripts deben comunicarse a través de un puerto activo. Mira {{domxref("SharedWorker")}} para mas detalles.</li> + <li><a href="/en-US/docs/Web/API/ServiceWorker_API">ServiceWorkers</a> esencialmente actuan como servidores proxy que se ubican entre las aplicaciones web, el navegador y la red (cuando están disponibles). Están destinados (entre otras cosas) para poder manejar experiencias y comportamientos offline, interceptando peticiones de red y tomando la acción apropiada tomando en cuenta si la conexión está disponible y actualizando los assets desde el servidor. También notificaciones push y sincronización desde la API en segundo plano.</li> + <li>Chrome Workers es un worker solo de Firefox puedes utilizar si estás desarrollando complementos se puede tener acceso a <a href="https://developer.mozilla.org/en/js-ctypes">js-ctypes</a> en el worker. Mira {{domxref("ChromeWorker")}} para mas detalles. </li> + <li><a href="/en-US/docs/Web/API/Web_Audio_API#Audio_Workers">Audio Workers</a> nos dan la capacidad de procesar audio directamente dentro del contexto del worker.</li> +</ul> + +<div class="note"> +<p><strong>Note</strong>: Según el <a href="https://html.spec.whatwg.org/multipage/workers.html#runtime-script-errors-2">Web workers Spec</a>, los errores del worker no deberían bubujear (mira {{bug(1188141)}}. Esto está implementado en Firefox 42.</p> +</div> + +<h2 id="Web_Worker_interfaces">Web Worker interfaces</h2> + +<dl> + <dt>{{domxref("AbstractWorker")}}</dt> + <dd>Abstrae todas las propiedades y métodos comunes a toda clase de workers (i.e. {{domxref("Worker")}} or {{domxref("SharedWorker")}}).</dd> + <dt>{{domxref("Worker")}}</dt> + <dd>Representa el hilo del worker en ejecución, pudiendo pasar mensajes a este.</dd> + <dt>{{domxref("WorkerLocation")}}</dt> + <dd>Define la ruta absoluta del script que ejecuta el <a href="https://developer.mozilla.org/en-US/docs/Web/API/Worker" title="The Worker interface of the Web Workers API represents a background task that can be easily created and can send messages back to its creator. Creating a worker is as simple as calling the Worker() constructor and specifying a script to be run in the worker thread."><code>Worker</code></a>.</dd> +</dl> + +<dl> + <dt>{{domxref("SharedWorker")}}</dt> + <dd>Representa un tipo de worker al que se puede acceder desde distintos contextos de navegación, tanto de varias ventanas, iframes, y otros workers.</dd> + <dt>{{domxref("WorkerGlobalScope")}}</dt> + <dd>Representa el ámbito genérico de cualquier worker (similar a {{domxref("Window")}} en un contenido web normal). Los diferentes tipos de workers tienen objetos de ámbito que heredan de esta interfaz y añade características más específicas.</dd> + <dt>{{domxref("DedicatedWorkerGlobalScope")}}</dt> + <dd>Representa el ámbito de un worker dedicado, hereda de {{domxref("WorkerGlobalScope")}} y añade algunas características.</dd> + <dt>{{domxref("SharedWorkerGlobalScope")}}</dt> + <dd>Representa el ámbito de un shared worke, hereda de {{domxref("WorkerGlobalScope")}} y añade algunas características.</dd> + <dt>{{domxref("WorkerNavigator")}}</dt> + <dd>Representa la identidad y estado del user agent (El cliente):</dd> +</dl> + +<h2 id="Examples">Examples</h2> + +<p>Hemos creado un par de demostraciones para ver su uso básico:</p> + +<ul> + <li><a href="https://github.com/mdn/simple-web-worker">Basic dedicated worker example</a> (<a href="http://mdn.github.io/simple-web-worker/">run dedicated worker</a>).</li> + <li><a href="https://github.com/mdn/simple-shared-worker">Basic shared worker example</a> (<a href="http://mdn.github.io/simple-shared-worker/">run shared worker</a>).</li> +</ul> + +<p>You can find out more information on how these demos work in <a href="/en-US/docs/Web/API/Web_Workers_API/Using_web_workers">Using web workers</a>.</p> + +<h2 id="Especificaciones">Especificaciones</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', '#workers')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td></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>Característica</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>soporte básico</td> + <td>4</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(1.9.1)}}</td> + <td>10.0</td> + <td>10.6</td> + <td>4</td> + </tr> + <tr> + <td>Shared workers</td> + <td>4</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop(29)}}</td> + <td>{{CompatNo}}</td> + <td>10.6</td> + <td>4</td> + </tr> + <tr> + <td>Paso de datos usando structured cloning</td> + <td>13</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(8)}}</td> + <td>10.0</td> + <td>11.5</td> + <td>6</td> + </tr> + <tr> + <td>Paso de datos usando transferable objects</td> + <td>17 {{property_prefix("webkit")}}<br> + 21</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop(18)}}</td> + <td>{{CompatNo}}</td> + <td>15</td> + <td>6</td> + </tr> + <tr> + <td>Global {{domxref("window.URL", "URL")}}</td> + <td>10<sup>[1]</sup><br> + 23</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(21)}}</td> + <td>11</td> + <td>15</td> + <td>6<sup>[1]</sup></td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Edge</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>Soporte básico</td> + <td>4.4</td> + <td>4</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile(1.9.1)}}</td> + <td>1.0.1</td> + <td>10.0</td> + <td>11.5</td> + <td>5.1</td> + </tr> + <tr> + <td>Shared workers</td> + <td>{{CompatNo}}</td> + <td>4</td> + <td>{{CompatNo}}</td> + <td>29</td> + <td>1.4</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>Pasando datos usando structured cloning</td> + <td>{{CompatNo}}</td> + <td>4</td> + <td>{{CompatVersionUnknown}}</td> + <td>8</td> + <td>1.0.1</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>Pasando datos usando transferable objects</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>18</td> + <td>1.0.1</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] As <code>webkitURL</code>.</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Web_Workers_API/basic_usage">Using Web Workers</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Worker">Worker Interface</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/SharedWorker">SharedWorker interface</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker_API">ServiceWorker API</a></li> + <li><a href="/en-US/docs/Web/API/Worker/Functions_and_classes_available_to_workers">Functions and classes available to workers</a></li> + <li><a href="/en-US/docs/Web/API/Web_Workers_API/Advanced_concepts_and_examples">Advanced concepts and examples</a></li> + <li><a href="/en-US/docs/Web/API/ChromeWorker">ChromeWorker</a>: for using workers in privileged/chrome code</li> +</ul> diff --git a/files/es/web/api/webgl_api/index.html b/files/es/web/api/webgl_api/index.html new file mode 100644 index 0000000000..28d94c22d4 --- /dev/null +++ b/files/es/web/api/webgl_api/index.html @@ -0,0 +1,98 @@ +--- +title: WebGL +slug: Web/API/WebGL_API +tags: + - WebGL +translation_of: Web/API/WebGL_API +--- +<div>{{WebGLSidebar}}</div> + +<p class="summary"><span class="goog-gtc-unit" id="goog-gtc-unit-3"><span class="goog-gtc-from-human goog-gtc-translatable" dir="ltr">WebGL trae gráficos en 3D para la Web mediante la introducción de una API que cumple estrictamente la OpenGL ES 2.0 que se puede utilizar en elementos </span></span><a href="/en/HTML/Canvas" title="En/html/canvas"><code>canvas</code></a><span class="goog-gtc-unit" id="goog-gtc-unit-3"><span class="goog-gtc-from-human goog-gtc-translatable" dir="ltr"><a> HTML5.</a></span></span><a> <span class="goog-gtc-unit" id="goog-gtc-unit-4"><span class="goog-gtc-from-human goog-gtc-translatable" dir="ltr">La compatibilidad para WebGL viene en </span></span></a><a href="/es/Firefox_4_para_desarrolladores" title="es/Firefox 4 para desarrolladores">Firefox 4</a> y se puede probar en las <a class="external" href="http://firefox.com/beta" title="http://firefox.com/beta">betas de Firefox 4</a> o en <a class="external" href="http://nightly.mozilla.org/" title="http://nightly.mozilla.org/">trunk builds.</a> .</p> + +<div class="note"><span class="goog-gtc-unit" id="goog-gtc-unit-5"><span class="goog-gtc-from-human goog-gtc-translatable" dir="ltr"><strong>Nota:</strong> La especificación para WebGL se encuentra todavía en fase de borrador y sujeta a cambios.</span></span></div> + +<table class="mainpage-table"> + <tbody> + <tr> + <td> + <h2 id="Temas_sobre_desarrollo"><span class="goog-gtc-unit" id="goog-gtc-unit-6"><span class="goog-gtc-from-human goog-gtc-translatable" dir="ltr">Temas sobre desarrollo</span></span></h2> + + <dl> + <dt><a href="/en/WebGL/Getting_started_with_WebGL" title="en/WebGL/Getting started with WebGL"><span class="goog-gtc-unit" id="goog-gtc-unit-7"><span class="goog-gtc-from-mt goog-gtc-translatable" dir="ltr">Primeros pasos con WebGL</span></span></a></dt> + <dd><span class="goog-gtc-unit" id="goog-gtc-unit-8"><span class="goog-gtc-from-human goog-gtc-translatable" dir="ltr">Cómo crear un contexto WebGL.</span></span></dd> + <dt><a href="/en/WebGL/Adding_2D_content_to_a_WebGL_context" title="en/WebGL/Adding 2D content to a WebGL context"><span class="goog-gtc-unit" id="goog-gtc-unit-9"><span class="goog-gtc-from-mt goog-gtc-translatable" dir="ltr">Adición de contenido 2D a un contexto WebGL</span></span></a></dt> + <dd><span class="goog-gtc-unit" id="goog-gtc-unit-10"><span class="goog-gtc-from-human goog-gtc-translatable" dir="ltr">Cómo representar formas planas sencillas utilizando WebGL.</span></span></dd> + <dt><a href="/en/WebGL/Using_shaders_to_apply_color_in_WebGL" title="en/WebGL/Using shaders to apply color in WebGL"><span class="goog-gtc-unit" id="goog-gtc-unit-11"><span class="goog-gtc-from-human goog-gtc-translatable" dir="ltr">Uso de sombreadores para aplicar color en WebGL</span></span></a></dt> + <dd><span class="goog-gtc-unit" id="goog-gtc-unit-12"><span class="goog-gtc-from-human goog-gtc-translatable" dir="ltr">Muestra cómo agregar color a las formas mediante sombreadores.</span></span></dd> + <dt><a href="/en/WebGL/Animating_objects_with_WebGL" title="en/WebGL/Animating objects with WebGL"><span class="goog-gtc-unit" id="goog-gtc-unit-13"><span class="goog-gtc-from-mt goog-gtc-translatable" dir="ltr">Animación de objetos con WebGL</span></span></a></dt> + <dd><span class="goog-gtc-unit" id="goog-gtc-unit-14"><span class="goog-gtc-from-human goog-gtc-translatable" dir="ltr">Muestra cómo rotar y trasladar los objetos para crear animaciones sencillas.</span></span></dd> + <dt><a href="/en/WebGL/Creating_3D_objects_using_WebGL" title="en/WebGL/Creating 3D objects using WebGL"><span class="goog-gtc-unit" id="goog-gtc-unit-15"><span class="goog-gtc-from-mt goog-gtc-translatable" dir="ltr">Creación de objetos 3D utilizando WebGL</span></span></a></dt> + <dd><span class="goog-gtc-unit" id="goog-gtc-unit-16"><span class="goog-gtc-from-mt goog-gtc-translatable" dir="ltr">Muestra cómo crear y animar un objeto 3D (en este caso, un cubo).</span></span></dd> + <dt><a href="/en/WebGL/Using_textures_in_WebGL" title="en/WebGL/Using textures in WebGL"><span class="goog-gtc-unit" id="goog-gtc-unit-17"><span class="goog-gtc-from-mt goog-gtc-translatable" dir="ltr">Uso de texturas en WebGL</span></span></a></dt> + <dd><span class="goog-gtc-unit" id="goog-gtc-unit-18"><span class="goog-gtc-from-human goog-gtc-translatable" dir="ltr">Muestra cómo asignar texturas a las caras de un objeto.</span></span></dd> + <dt><a href="/en/WebGL/Lighting_in_WebGL" title="en/WebGL/Lighting in WebGL"><span class="goog-gtc-unit" id="goog-gtc-unit-19"><span class="goog-gtc-from-mt goog-gtc-translatable" dir="ltr">Iluminación en WebGL</span></span></a></dt> + <dd><span class="goog-gtc-unit" id="goog-gtc-unit-20"><span class="goog-gtc-from-human goog-gtc-translatable" dir="ltr">Cómo simular efectos de iluminación en tu contexto WebGL.</span></span></dd> + <dt><a href="/en/WebGL/Animating_textures_in_WebGL" title="en/WebGL/Animating textures in WebGL"><span class="goog-gtc-unit" id="goog-gtc-unit-21"><span class="goog-gtc-from-mt goog-gtc-translatable" dir="ltr">Animación de texturas en WebGL</span></span></a></dt> + <dd><span class="goog-gtc-unit" id="goog-gtc-unit-22"><span class="goog-gtc-from-human goog-gtc-translatable" dir="ltr">Se muestra cómo animar texturas, en este caso, mediante la asignación de un vídeo Ogg a las caras de un cubo que gira.</span></span></dd> + </dl> + </td> + <td> + <h2 id="Recursos"><span class="goog-gtc-unit" id="goog-gtc-unit-23"><span class="goog-gtc-from-human goog-gtc-translatable" dir="ltr">Recursos</span></span></h2> + + <dl> + <dt><a class="link-https" href="https://cvs.khronos.org/svn/repos/registry/trunk/public/webgl/doc/spec/WebGL-spec.html" title="https://cvs.khronos.org/svn/repos/registry/trunk/public/webgl/doc/spec/WebGL-spec.html"><span class="goog-gtc-unit" id="goog-gtc-unit-24"><span class="goog-gtc-from-human goog-gtc-translatable" dir="ltr">Especificación WebGL (Borrador de trabajo)</span></span></a></dt> + <dd><span class="goog-gtc-unit" id="goog-gtc-unit-25"><span class="goog-gtc-from-mt goog-gtc-translatable" dir="ltr">El borrador de la especificación WebGL.</span></span></dd> + <dt><a class="external" href="http://www.khronos.org/webgl/" title="http://www.khronos.org/webgl/"><span class="goog-gtc-unit" id="goog-gtc-unit-26"><span class="goog-gtc-from-human goog-gtc-translatable" dir="ltr">Sitio de Khronos WebGL</span></span></a></dt> + <dd><span class="goog-gtc-unit" id="goog-gtc-unit-27"><span class="goog-gtc-from-mt goog-gtc-translatable" dir="ltr">El sitio web principal de WebGL en el Grupo Khronos.</span></span></dd> + <dt><a class="external" href="http://learningwebgl.com/blog/" title="http://learningwebgl.com/blog/"><span class="goog-gtc-unit" id="goog-gtc-unit-28"><span class="goog-gtc-from-human goog-gtc-translatable" dir="ltr">Aprender WebGL</span></span></a></dt> + <dd><span class="goog-gtc-unit" id="goog-gtc-unit-29"><span class="goog-gtc-from-mt goog-gtc-translatable" dir="ltr">Un sitio con tutoriales sobre cómo usar WebGL.</span></span></dd> + <dt><a class="external" href="http://learningwebgl.com/cookbook/index.php/" title="http://learningwebgl.com/cookbook/index.php/"><span class="goog-gtc-unit" id="goog-gtc-unit-30"><span class="goog-gtc-from-human goog-gtc-translatable" dir="ltr">La guía práctica de WebGL</span></span></a></dt> + <dd><span class="goog-gtc-unit" id="goog-gtc-unit-31"><span class="goog-gtc-from-human goog-gtc-translatable" dir="ltr">Un sitio web con recetas muy útiles para escribir código WebGL.</span></span></dd> + <dt><a class="external" href="http://sylvester.jcoglan.com/" title="http://sylvester.jcoglan.com/"><span class="goog-gtc-unit" id="goog-gtc-unit-32"><span class="goog-gtc-from-mt goog-gtc-translatable" dir="ltr">Sylvester</span></span></a></dt> + <dd><span class="goog-gtc-unit" id="goog-gtc-unit-33"><span class="goog-gtc-from-mt goog-gtc-translatable" dir="ltr">Una biblioteca de código abierto para la manipulación de vectores y matrices.</span></span></dd> + <dt><a class="external" href="http://planet-webgl.org/" title="http://planet-webgl.org/"><span class="goog-gtc-unit" id="goog-gtc-unit-34"><span class="goog-gtc-from-mt goog-gtc-translatable" dir="ltr">Planeta WebGL</span></span></a></dt> + <dd><span class="goog-gtc-unit" id="goog-gtc-unit-35"><span class="goog-gtc-from-human goog-gtc-translatable" dir="ltr">Un agregador de RSS para las personas que pertenecen a la comunidad WebGL.</span></span></dd> + </dl> + </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_los_navegadores"><span class="goog-gtc-unit" id="goog-gtc-unit-36"><span class="goog-gtc-from-human goog-gtc-translatable" dir="ltr">Compatibilidad de los navegadores</span></span></h2> + +<table class="standard-table"> + <tbody> + <tr> + <th><span class="goog-gtc-unit" id="goog-gtc-unit-37"><span class="goog-gtc-from-tm goog-gtc-from-tm-score-100 goog-gtc-translatable" dir="ltr">Navegador</span></span></th> + <th><span class="goog-gtc-unit" id="goog-gtc-unit-38"><span class="goog-gtc-from-tm goog-gtc-from-tm-score-99 goog-gtc-translatable" dir="ltr">Compatibilidad básica</span></span></th> + <th><code>.getContext(<em>context</em>)</code></th> + </tr> + <tr> + <td><span class="goog-gtc-unit" id="goog-gtc-unit-39"><span class="goog-gtc-from-tm goog-gtc-from-tm-score-100 goog-gtc-translatable" dir="ltr">Internet Explorer</span></span></td> + <td><span class="goog-gtc-unit" id="goog-gtc-unit-40"><span class="goog-gtc-from-mt goog-gtc-translatable" dir="ltr">---</span></span></td> + <td><span class="goog-gtc-unit" id="goog-gtc-unit-41"><span class="goog-gtc-from-mt goog-gtc-translatable" dir="ltr">---</span></span></td> + </tr> + <tr> + <td><span class="goog-gtc-unit" id="goog-gtc-unit-42"><span class="goog-gtc-from-mt goog-gtc-translatable" dir="ltr">Firefox (Gecko)</span></span></td> + <td><span class="goog-gtc-unit" id="goog-gtc-unit-43"><span class="goog-gtc-from-human goog-gtc-ph-missing goog-gtc-translatable" dir="ltr">4.0 (2)</span></span></td> + <td><span class="goog-gtc-unit" id="goog-gtc-unit-44"><span class="goog-gtc-from-human goog-gtc-translatable" dir="ltr">experimental-webgl</span></span></td> + </tr> + <tr> + <td><span class="goog-gtc-unit" id="goog-gtc-unit-45"><span class="goog-gtc-from-tm goog-gtc-from-tm-score-100 goog-gtc-translatable" dir="ltr">Opera</span></span></td> + <td><span class="goog-gtc-unit" id="goog-gtc-unit-46"><span class="goog-gtc-from-mt goog-gtc-translatable" dir="ltr">---</span></span></td> + <td><span class="goog-gtc-unit" id="goog-gtc-unit-47"><span class="goog-gtc-from-mt goog-gtc-translatable" dir="ltr">---</span></span></td> + </tr> + <tr> + <td><span class="goog-gtc-unit" id="goog-gtc-unit-48"><span class="goog-gtc-from-tm goog-gtc-from-tm-score-100 goog-gtc-translatable" dir="ltr">Chrome</span></span></td> + <td><span class="goog-gtc-unit" id="goog-gtc-unit-49"><span class="goog-gtc-from-tm goog-gtc-from-tm-score-100 goog-gtc-translatable" dir="ltr">9</span></span></td> + <td><span class="goog-gtc-unit" id="goog-gtc-unit-50"><span class="goog-gtc-from-human goog-gtc-translatable" dir="ltr">experimental-webgl</span></span></td> + </tr> + <tr> + <td><span class="goog-gtc-unit" id="goog-gtc-unit-51"><span class="goog-gtc-from-tm goog-gtc-from-tm-score-100 goog-gtc-translatable" dir="ltr">Safari</span></span></td> + <td><span class="goog-gtc-unit" id="goog-gtc-unit-52"><span class="goog-gtc-from-human goog-gtc-translatable" dir="ltr">6 (en Safari nightlies)</span></span></td> + <td><span class="goog-gtc-unit" id="goog-gtc-unit-53"><span class="goog-gtc-from-human goog-gtc-translatable" dir="ltr">experimental-webgl</span></span></td> + </tr> + </tbody> +</table> + +<p> </p> diff --git a/files/es/web/api/webgl_api/tutorial/adding_2d_content_to_a_webgl_context/index.html b/files/es/web/api/webgl_api/tutorial/adding_2d_content_to_a_webgl_context/index.html new file mode 100644 index 0000000000..595b0f57f1 --- /dev/null +++ b/files/es/web/api/webgl_api/tutorial/adding_2d_content_to_a_webgl_context/index.html @@ -0,0 +1,276 @@ +--- +title: Agregando Contenido 2D en el Contexto WebGL +slug: Web/API/WebGL_API/Tutorial/Adding_2D_content_to_a_WebGL_context +translation_of: Web/API/WebGL_API/Tutorial/Adding_2D_content_to_a_WebGL_context +--- +<div>{{WebGLSidebar("Tutorial")}} {{PreviousNext("Web/API/WebGL_API/Tutorial/Getting_started_with_WebGL", "Web/API/WebGL_API/Tutorial/Using_shaders_to_apply_color_in_WebGL")}}</div> + +<p>Una vez que has logrado <a href="/en-US/docs/Web/API/WebGL_API/Tutorial/Getting_started_with_WebGL">crear el contexto WebGL</a>, estás listo para crear objetos dentro del mismo. Algo sencillo que podemos hacer es pintar un simple cuadrado plano sin texturas, así que vamos a empezar desde ahí, creando el código para dibujar el cuadrado plano.</p> + +<h2 id="Dibujando_la_Escena">Dibujando la Escena</h2> + +<p>Lo mas importante que tenemos que entender antes de empezar, es que aún cuando dibujaremos un cuadrado plano en este ejemplo, estaremos trabajando en un espacio 3D. Lo que estaremos haciendo es dibujar un cuadrado plano y posicionándolo frente de la camara de forma perpendicular. Necesitaremos definir los Shaders que definirán el color para nuestra escena además de dibujar nuestro objeto. Esto establecerá cómo aparece el cuadrado plano en nuestra pantalla.</p> + +<h3 id="Los_Shaders">Los Shaders </h3> + +<p>Los shaders usan especificamente <a href="https://www.khronos.org/files/opengles_shading_language.pdf">OpenGL ES Shading Language</a>. Los detalles de la forma de trabajar de los shaders estan fuera del alcance de este articulo, como tambien la sintaxis del lenguaje de los shaders sin embargo la version corta es que hay 2 tipos de shaders (funciones que se ejecutan en la GPU) que necesitas escribir. shaders de vertices y shaders de fragmentos. Estos son pasados al WebGL como una cadena y compilados para ejecutarse en el GPU.</p> + +<h4 id="Shaders_de_Vértices">Shaders de Vértices</h4> + +<p>La responsabilidad de los Shaders de Vértices es asignar un valor a una variable especial <code>gl_Position</code> para crear los valores del espacio de trabajo (valores entre -1 y +1) en toda la zona del canvas. En nuestro Shader de Vértices de abajo estamos recibiendo valores de un atributo que definiremos como <code>aVertexPosition</code>. Estamos entonces multiplicando esa posición por dos matrices 4x4 que definimos como <code>uProjectionMatrix</code> y <code>uModelMatrix</code> e igualando <code>gl_Position</code> al resultado. Para más información sobre proyección y otras matrices <a href="https://webglfundamentals.org/webgl/lessons/webgl-3d-perspective.html">puedes encontrar útil este artículo</a>.</p> + +<pre class="brush: html"> // Vertex shader program + + const vsSource = ` + attribute vec4 aVertexPosition; + + uniform mat4 uModelViewMatrix; + uniform mat4 uProjectionMatrix; + + void main() { + gl_Position = uProjectionMatrix * uModelViewMatrix * aVertexPosition; + } + `; +</pre> + +<h4 id="Shaders_de_Fragmentos">Shaders de Fragmentos</h4> + +<p>Cada vez que el Shader de Vértices escribe de 1 a 3 valores al <code>gl_Position</code> este también dibujará un punto, una linea o un triángulo. Mientras éste esta dibujando, llamará al Shader de Fragmentos y preguntará: ¿De qué color debería dibujar este pixel? En este caso, simplemente retornaremos blanco cada vez.</p> + +<p><code>gl_FragColor</code> es una variable built-in de GL que es usada para el color del fragmento. Al definir su valor se establece el color del pixel, como se ve a continuación:</p> + +<pre class="brush: html"> const fsSource = ` + void main() { + gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0); + } + `; +</pre> + +<h3 id="Inicializando_los_shaders">Inicializando los shaders</h3> + +<p>Ahora que hemos definido los dos shaders, necesitamos pasarlos a WebGL, compilarlos y enlazarlos juntos. El código de abajo crea dos shaders al llamar <code>loadShader</code>, pasando el tipo y la fuente para el shader. Entonces crea un programa, adjunta los shaders y los enlaza juntos. Si la compilación o el enlace fallan, el código muestra una alerta.</p> + +<pre class="brush: js">// +// Initialize a shader program, so WebGL knows how to draw our data +// +function initShaderProgram(gl, vsSource, fsSource) { + const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource); + const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource); + + // Create the shader program + + const shaderProgram = gl.createProgram(); + gl.attachShader(shaderProgram, vertexShader); + gl.attachShader(shaderProgram, fragmentShader); + gl.linkProgram(shaderProgram); + + // If creating the shader program failed, alert + + if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) { + alert('Unable to initialize the shader program: ' + gl.getProgramInfoLog(shaderProgram)); + return null; + } + + return shaderProgram; +} + +// +// creates a shader of the given type, uploads the source and +// compiles it. +// +function loadShader(gl, type, source) { + const shader = gl.createShader(type); + + // Send the source to the shader object + + gl.shaderSource(shader, source); + + // Compile the shader program + + gl.compileShader(shader); + + // See if it compiled successfully + + if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { + alert('An error occurred compiling the shaders: ' + gl.getShaderInfoLog(shader)); + gl.deleteShader(shader); + return null; + } + + return shader; +} +</pre> + +<p>Para usar este código lo llamamos así:</p> + +<pre class="brush: js"> const shaderProgram = initShaderProgram(gl, vsSource, fsSource); +</pre> + +<p>Después de haber creado el programa de sombreado necesitaremos buscar las ubicaciones que WebGL asignó a nuestras entradas (inputs). En este caso tenemos un attribute y 2 uniforms. Los attribute reciben valores de los buffers. Cada iteración del Shader de Vértices recibe el siguiente valor desde el buffer asignado al attribute. Los uniforms son similares a variables globales en Javascript, estos mantienen el mismo valor para todas las iteraciones de un shader. Como las ubicaciones attribute y uniform son específicas de un solo programa de sombreado, los almacenamos juntos para que sean fáciles de pasar.</p> + +<pre class="brush: js"> const programInfo = { + program: shaderProgram, + attribLocations: { + vertexPosition: gl.getAttribLocation(shaderProgram, 'aVertexPosition'), + }, + uniformLocations: { + projectionMatrix: gl.getUniformLocation(shaderProgram, 'uProjectionMatrix'), + modelViewMatrix: gl.getUniformLocation(shaderProgram, 'uModelViewMatrix'), + }, + }; +</pre> + +<h2 id="Creando_el_cuadrado_plano">Creando el cuadrado plano</h2> + +<p>Antes de que podamos renderizar nuestro cuadrado plano, necesitamos crear el buffer que contenga sus posiciones de vértice y poner las posiciones de vértice en él. Lo haremos usando una función que llamaremos <code>initBuffers()</code>. Mientras vayamos explorando conceptos WebGL más avanzados, esta rutina crecerá para crear objetos 3D más y más complejos.</p> + +<pre class="brush: js">function initBuffers(gl) { + + // Create a buffer for the square's positions. + + const positionBuffer = gl.createBuffer(); + + // Select the positionBuffer as the one to apply buffer + // operations to from here out. + + gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer); + + // Now create an array of positions for the square. + + const positions = [ + 1.0, 1.0, + -1.0, 1.0, + 1.0, -1.0, + -1.0, -1.0, + ]; + + // Now pass the list of positions into WebGL to build the + // shape. We do this by creating a Float32Array from the + // JavaScript array, then use it to fill the current buffer. + + gl.bufferData(gl.ARRAY_BUFFER, + new Float32Array(positions), + gl.STATIC_DRAW); + + return { + position: positionBuffer, + }; +} +</pre> + +<p>Esta rutina es muy sencilla dada la naturaleza de la escena en este ejemplo. Empieza llamando el método {{domxref("WebGLRenderingContext.createBuffer()", "createBuffer()")}} del objeto <code>gl</code> para obtener un buffer dentro del cual almacenaremos las posiciones del vértice. Este es ligado al contexto al llamar el método {{domxref("WebGLRenderingContext.bindBuffer()", "bindBuffer()")}}.</p> + +<p>Una vez terminado, creamos un array de Javascript almacenando la posición de cada vértice en el cuadrado plano. Este es convertido entonces en un array de flotantes y es pasado al método {{domxref("WebGLRenderingContext.bufferData()", "bufferData()")}} del objeto <code>gl</code> para establecer las posiciones de vértice para el objeto.</p> + +<h2 id="Renderizando_la_escena">Renderizando la escena</h2> + +<p>Una vez que los shaders estan establecidos, se buscan las ubicaciones, y las posiciones de vértice del cuadrado plano puestas en un buffer, podemos renderizar la escena. Como no estamos animando nada en este ejemplo, nuestra función <code>drawScene()</code> es muy simple. Esta usa unas rutinas de utilidad que cubriremos en breve.</p> + +<pre class="brush: js">function drawScene(gl, programInfo, buffers) { + gl.clearColor(0.0, 0.0, 0.0, 1.0); // Clear to black, fully opaque + gl.clearDepth(1.0); // Clear everything + gl.enable(gl.DEPTH_TEST); // Enable depth testing + gl.depthFunc(gl.LEQUAL); // Near things obscure far things + + // Clear the canvas before we start drawing on it. + + gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); + + // Create a perspective matrix, a special matrix that is + // used to simulate the distortion of perspective in a camera. + // Our field of view is 45 degrees, with a width/height + // ratio that matches the display size of the canvas + // and we only want to see objects between 0.1 units + // and 100 units away from the camera. + + const fieldOfView = 45 * Math.PI / 180; // in radians + const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight; + const zNear = 0.1; + const zFar = 100.0; + const projectionMatrix = mat4.create(); + + // note: glmatrix.js always has the first argument + // as the destination to receive the result. + mat4.perspective(projectionMatrix, + fieldOfView, + aspect, + zNear, + zFar); + + // Set the drawing position to the "identity" point, which is + // the center of the scene. + const modelViewMatrix = mat4.create(); + + // Now move the drawing position a bit to where we want to + // start drawing the square. + + mat4.translate(modelViewMatrix, // destination matrix + modelViewMatrix, // matrix to translate + [-0.0, 0.0, -6.0]); // amount to translate + + // Tell WebGL how to pull out the positions from the position + // buffer into the vertexPosition attribute. + { + const numComponents = 2; // pull out 2 values per iteration + const type = gl.FLOAT; // the data in the buffer is 32bit floats + const normalize = false; // don't normalize + const stride = 0; // how many bytes to get from one set of values to the next + // 0 = use type and numComponents above + const offset = 0; // how many bytes inside the buffer to start from + gl.bindBuffer(gl.ARRAY_BUFFER, buffers.position); + gl.vertexAttribPointer( + programInfo.attribLocations.vertexPosition, + numComponents, + type, + normalize, + stride, + offset); + gl.enableVertexAttribArray( + programInfo.attribLocations.vertexPosition); + } + + // Tell WebGL to use our program when drawing + + gl.useProgram(programInfo.program); + + // Set the shader uniforms + + gl.uniformMatrix4fv( + programInfo.uniformLocations.projectionMatrix, + false, + projectionMatrix); + gl.uniformMatrix4fv( + programInfo.uniformLocations.modelViewMatrix, + false, + modelViewMatrix); + + { + const offset = 0; + const vertexCount = 4; + gl.drawArrays(gl.TRIANGLE_STRIP, offset, vertexCount); + } +} + +</pre> + +<p>El primer paso es limpiar el canvas de nuestro color de fondo; establecemos la perspectiva de la cámara. Configuramos un campo de 45º, con una relación ancho/alto que coincide con las dimensiones de nuestro canvas. También especificamos que queremos objetos entre 0.1 y 100 unidades de la cámara para ser renderizados.</p> + +<p>Entonces establecemos la posición del cuadrado plano al cargar la posición de identidad y alejando la cámara en 6 unidades. Déspues de eso, enlazamos el buffer del vértice del cuadrado al atributo que el shader estaba usando para <code>aVertexPosition</code> y le decimos a WebGL como jalar los datos fuera de este. Finalmente dibujamos el objeto al llamar el método {{domxref("WebGLRenderingContext.drawArrays()", "drawArrays()")}}.</p> + +<p>{{EmbedGHLiveSample('webgl-examples/tutorial/sample2/index.html', 670, 510) }}</p> + +<p><a href="https://github.com/mdn/webgl-examples/tree/gh-pages/tutorial/sample2">Ver código completo</a> | <a href="http://mdn.github.io/webgl-examples/tutorial/sample2/">Abrir esta demostración en una nueva página</a></p> + +<h2 id="Utilidades_para_operaciones_de_Matrices">Utilidades para operaciones de Matrices</h2> + +<p>Las operaciones de matrices pueden parecer complicadas pero <a href="https://webglfundamentals.org/webgl/lessons/webgl-2d-matrices.html">en realidad son muy fáciles si las tomas un paso a la vez</a>. Generalmente la gente usa una librería de matrices antes que escribir la suya. En nuestro caso estamos usando la popular <a href="http://glmatrix.net/">librería glMatrix</a>.</p> + +<p>Ver también</p> + +<ul> + <li><a href="https://webglfundamentals.org/webgl/lessons/webgl-2d-matrices.html">Matrices</a> en WebGLFundamentals</li> + <li><a class="external" href="http://mathworld.wolfram.com/Matrix.html">Matrices</a> en Wolfram MathWorld</li> + <li><a class="external" href="http://en.wikipedia.org/wiki/Matrix_(mathematics)">Matriz</a> en Wikipedia</li> +</ul> + +<p>{{PreviousNext("Web/API/WebGL_API/Tutorial/Getting_started_with_WebGL", "Web/API/WebGL_API/Tutorial/Using_shaders_to_apply_color_in_WebGL")}}</p> diff --git a/files/es/web/api/webgl_api/tutorial/animating_objects_with_webgl/index.html b/files/es/web/api/webgl_api/tutorial/animating_objects_with_webgl/index.html new file mode 100644 index 0000000000..ad9b98310a --- /dev/null +++ b/files/es/web/api/webgl_api/tutorial/animating_objects_with_webgl/index.html @@ -0,0 +1,119 @@ +--- +title: Animación de Objetos con WebGL +slug: Web/API/WebGL_API/Tutorial/Animating_objects_with_WebGL +tags: + - WebGL +translation_of: Web/API/WebGL_API/Tutorial/Animating_objects_with_WebGL +--- +<p>{{WebGLSidebar("Tutorial")}} {{PreviousNext("Web/API/WebGL_API/Tutorial/Using_shaders_to_apply_color_in_WebGL", "Web/API/WebGL_API/Tutorial/Creating_3D_objects_using_WebGL") }}</p> + +<p>Our existing code from the previous examples is already configured to redraw our WebGL scene every 15 milliseconds. Until now, it's simply redrawing everything exactly the same way every time. It's time to change that, so that our square actually moves.</p> + +<p>In this example, we'll actually rotate and move our 2D square in all three dimensions; this will prove that even though we're only creating a 2D object, it still exists in 3D space.</p> + +<h2 id="Making_the_square_rotate">Making the square rotate</h2> + +<p>Let's start by making the square rotate. The first thing we'll need is a variable in which to track the current rotation of the square:</p> + +<pre class="brush: js">var squareRotation = 0.0; +</pre> + +<p>Now we need to update the <code>drawScene()</code> function to apply the current rotation to the square when drawing it. After translating to the initial drawing position for the square, we apply the rotation like this:</p> + +<pre class="brush: js">mvPushMatrix(); +mvRotate(squareRotation, [1, 0, 1]); +</pre> + +<p>This saves the current model-view matrix, then rotates the matrix by the current value of <code>squareRotation</code>, around the X and Z axes.</p> + +<p>After drawing, we need to restore the original matrix:</p> + +<pre class="brush: js"> mvPopMatrix(); +</pre> + +<p>We save and restore the original matrix to avoid having this rotation applied to other objects we might draw.</p> + +<p>To actually animate, we need to add code that changes the value of <code>squareRotation</code> over time. We can do that by creating a new variable to track the time at which we last animated (let's call it <code>lastSquareUpdateTime</code>), then adding the following code to the end of the <code>drawScene()</code> function:</p> + +<pre class="brush: js"> var currentTime = (new Date).getTime(); + if (lastSquareUpdateTime) { + var delta = currentTime - lastSquareUpdateTime; + + squareRotation += (30 * delta) / 1000.0; + } + + lastSquareUpdateTime = currentTime; +</pre> + +<p>This code uses the amount of time that's passed since the last time we updated the value of <code>squareRotation</code> to determine how far to rotate the square.</p> + +<h2 id="Making_the_square_move">Making the square move</h2> + +<p>We can also move the square around by translating to a different position before drawing it. This example is going to do some very basic animation; obviously in the real world you'd want to do something less insane.</p> + +<p>Let's track offsets to each axis for our translation in new variables:</p> + +<pre class="brush: js">var squareXOffset = 0.0; +var squareYOffset = 0.0; +var squareZOffset = 0.0; +</pre> + +<p>And the amount by which to change our position on each axis in these variables:</p> + +<pre class="brush: js">var xIncValue = 0.2; +var yIncValue = -0.4; +var zIncValue = 0.3; +</pre> + +<p>Now we can simply add this code to the previous code that updates the rotation:</p> + +<pre class="brush: js"> squareXOffset += xIncValue * ((30 * delta) / 1000.0); + squareYOffset += yIncValue * ((30 * delta) / 1000.0); + squareZOffset += zIncValue * ((30 * delta) / 1000.0); + + if (Math.abs(squareYOffset) > 2.5) { + xIncValue = -xIncValue; + yIncValue = -yIncValue; + zIncValue = -zIncValue; + } +</pre> + +<p>This causes our square to zoom around, moving haphazardly around the context as well as toward and away from the viewer, all while rotating. It looks rather like a screen saver.</p> + +<p>If your browser supports WebGL, <a href="/samples/webgl/sample4/index.html" title="https://developer.mozilla.org/samples/webgl/sample4/index.html">click here to take a look at this example</a> in action.</p> + +<h2 id="More_matrix_operations">More matrix operations</h2> + +<p>This example uses a few additional matrix operations, including two routines to push and pop matrices from a stack to preserve them, and one that rotates a matrix a given number of degrees. These follow, for your reference:</p> + +<pre class="brush: js">var mvMatrixStack = []; + +function mvPushMatrix(m) { + if (m) { + mvMatrixStack.push(m.dup()); + mvMatrix = m.dup(); + } else { + mvMatrixStack.push(mvMatrix.dup()); + } +} + +function mvPopMatrix() { + if (!mvMatrixStack.length) { + throw("Can't pop from an empty matrix stack."); + } + + mvMatrix = mvMatrixStack.pop(); + return mvMatrix; +} + +function mvRotate(angle, v) { + var inRadians = angle * Math.PI / 180.0; + + var m = Matrix.Rotation(inRadians, $V([v[0], v[1], v[2]])).ensure4x4(); + multMatrix(m); +} +</pre> + +<p>These routines were borrowed from a sample previously written by Vlad Vukićević.</p> + +<p>{{PreviousNext("Web/API/WebGL_API/Tutorial/Using_shaders_to_apply_color_in_WebGL", "Web/API/WebGL_API/Tutorial/Creating_3D_objects_using_WebGL") }}</p> diff --git a/files/es/web/api/webgl_api/tutorial/animating_textures_in_webgl/index.html b/files/es/web/api/webgl_api/tutorial/animating_textures_in_webgl/index.html new file mode 100644 index 0000000000..0274f91187 --- /dev/null +++ b/files/es/web/api/webgl_api/tutorial/animating_textures_in_webgl/index.html @@ -0,0 +1,106 @@ +--- +title: Animating textures in WebGL +slug: Web/API/WebGL_API/Tutorial/Animating_textures_in_WebGL +translation_of: Web/API/WebGL_API/Tutorial/Animating_textures_in_WebGL +--- +<p>{{WebGLSidebar("Tutorial") }} {{Previous("Web/API/WebGL_API/Tutorial/Lighting_in_WebGL")}}</p> + +<p>En esta demostración nos basamos en el ejemplo anterior, solo que ahora reemplazaremos nuestra textura estática con los fotogramas de un video Ogg.</p> + +<p>Esto es de hecho muy fácil de entender y de hacer, así que vamos a empezar. </p> + +<p>Podemos utilizar un código similar para usar, como fuente para las texturas, otros tipos de datos tales como {{ HTMLElement("canvas") }}.</p> + +<h2 id="Obteniendo_acceso_al_video">Obteniendo acceso al video</h2> + +<p>El primer paso es añadir el HTML para crear el elemento {{ HTMLElement("video") }} que usaremos para obtener los fotogramas de video:</p> + +<pre class="brush: js"><video id="video"> + Parece ser que tu navegador no soporta el elemento HTML5. <code>&lt;video&gt;</code> +</video> +</pre> + +<p>Esto simplemente crea un elemento para reproducir el archivo de video "Firefox.ogv". Usaremos CSS para ocultar el video</p> + +<pre class="brush: css">video { + display: none; +} +</pre> + +<p>Ahora pasamos al código JavasScript, empezando por añadir una línea de código a la función start() para obtener la referencia al elemento de video:</p> + +<pre class="brush: js">videoElement = document.getElementById("video"); +</pre> + +<p>Y reemplazamos el código que configura las llamadas de "interval-driven" en drawScecene() por esto:</p> + +<pre class="brush: js">videoElement.addEventListener("canplaythrough", startVideo, true); +videoElement.addEventListener("ended", videoDone, true); +</pre> + +<p>Finalmente configuramos el atributo src para empezar a cargar el video. FIXME (bjacob): También se debe configurar preload="auto" o si no, el video nunca ejecuta canplaythrough en Firefox. En Chrome se debería cargar el video aun sin usar preload="auto".</p> + +<pre class="brush: js">video.preload = "auto"; +videoElement.src = "Firefox.ogv";</pre> + +<p>El objetivo aquí es no empezar la animación hasta que una parte suficiente del video se haya cargado de modo que pueda ser reproducido sin interrupciones. Para esto añadimos un event listener para esperar a que el elemento de video nos diga que ya ha cargado los suficientes datos como para reproducir el video puede ser reproducido sin pausas.</p> + +<p>The <code>startVideo()</code> quedará así:</p> + +<pre class="brush: js">function startVideo() { + videoElement.play(); + intervalID = setInterval(drawScene, 15); +} +</pre> + +<p>Esto simplemente reproduce el video, entonces establece las llamadas "interval-driven" a drawScene() para gestionar el renderizado del cubo.</p> + +<p>Añadiremos también un segundo event listener en el "ended" del video de modo que cuando el video haya finalizado de reproducirse nosotros podamos parar la animación.</p> + +<pre class="brush: js">function videoDone() { + clearInterval(intervalID); +}</pre> + +<p>La función de videoDone() simplemente llama a {{ domxref("window.clearInterval()") }} para terminar de llamar a la función de actualizar la animación.</p> + +<h2 id="Usando_los_fotogramas_del_video_como_textura">Usando los fotogramas del video como textura</h2> + +<p>El siguiente paso es initTexture(), el cual se ha vuelto mucho más simple desde que no es necesario cargar un archivo de imagen. En lugar de esto, todo lo que vamos a hacer es crear un objeto de textura vacío para configurar el filtering cuando lo usemos más tarde:</p> + +<pre class="brush: js">function initTextures() { + cubeTexture = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, cubeTexture); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); +} +</pre> + +<div>La función updateTexture() quedaría así; Aquí es donde se realiza el trabajo real.</div> + +<pre class="brush: js">function updateTexture() { + gl.bindTexture(gl.TEXTURE_2D, cubeTexture); + gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, + gl.UNSIGNED_BYTE, videoElement); +} +</pre> + +<p>Has visto este código antes. Es prácticamente idéntico a la rutina de handleTextureLoaded() en el ejemplo anterior, excepto que cuando llamamos a texImage2D() en lugar de pasarle un objeto Image, lo pasamos en el elemento {{ HTMLElement("video") }}. Ya que WebGL sabe como obtener el fotograma actual y usarlo como textura.</p> + +<p><code>updateTexture()</code> se llama cada vez que estamos preparados para que la función drawScene() redibuje la escena. La única diferencia es que añadimos la llamada de updateTexture() antes de hacer nada más.</p> + +<p>¡Esto es todo al respecto!</p> + +<p>{{EmbedGHLiveSample('webgl-examples/tutorial/sample8/index.html', 670, 510) }}</p> + +<p><a href="https://github.com/mdn/webgl-examples/tree/gh-pages/tutorial/sample8">Ver el código completo</a> | <a href="http://mdn.github.io/webgl-examples/tutorial/sample8/">Abrir esta demo en una nueva página</a></p> + +<h2 id="Artículos_relacionados">Artículos relacionados</h2> + +<ul> + <li><a href="/es/Using_HTML5_audio_and_video">Usar audio y video en Firefox</a></li> +</ul> + +<p>{{Previous("Web/API/WebGL_API/Tutorial/Lighting_in_WebGL")}}</p> diff --git a/files/es/web/api/webgl_api/tutorial/getting_started_with_webgl/index.html b/files/es/web/api/webgl_api/tutorial/getting_started_with_webgl/index.html new file mode 100644 index 0000000000..a56004e010 --- /dev/null +++ b/files/es/web/api/webgl_api/tutorial/getting_started_with_webgl/index.html @@ -0,0 +1,106 @@ +--- +title: Primeros pasos con WebGL +slug: Web/API/WebGL_API/Tutorial/Getting_started_with_WebGL +tags: + - Intro + - Tutorial + - WebGL +translation_of: Web/API/WebGL_API/Tutorial/Getting_started_with_WebGL +--- +<p>{{WebGLSidebar("Tutorial")}} {{Next("Web/API/WebGL_API/Tutorial/Adding_2D_content_to_a_WebGL_context")}}</p> + +<p>WebGL <span id="result_box" lang="es"><span>permite que el contenido web </span></span>utilice una API basada en <a class="external" href="http://www.khronos.org/opengles/" hreflang="en" title="http://www.khronos.org/opengles/">OpenGL ES</a> 2.0 para llevar a cabo la representación 2D y 3D en un elemento <a href="https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API">canvas</a> HTML en los navegadores que lo soporten sin el uso de plug-ins. WebGL consiste en código de control escrito en JavaScript y código de efectos especiales (código shader) que se ejecuta en la unidad de procesamiento gráfico de una computadora (GPU). Los elementos WebGL se pueden mezclar con otros elementos HTML y componerse con otras partes de la página o el fondo de la misma.</p> + +<p>Este artículo le dará a conocer los conceptos básicos de WebGL. Se asume que ya tiene una comprensión de las matemáticas implicadas en gráficos 3D, y este artículo no pretende tratar de enseñar OpenGL en sí.</p> + +<h2 id="Preparando_el_renderizado_en_3D">Preparando el renderizado en 3D</h2> + +<p>Lo primero que necesitas para poder usar WebGL para renderizar en 3D es un HTML <a href="https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API">canvas</a>. El fragmento HTML a continuación establece un <a href="https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API">canvas</a> y configura un controlador de eventos <code>onload</code> que se utilizarán para inicializar nuestro contexto WebGL.</p> + +<pre class="brush: html"><body onload="start()"> + <canvas id="glcanvas" width="640" height="480"> + Tu navegador parece no soportar el elemento HTML5 <code>&lt;canvas&gt;</code>. + </canvas> +</body> +</pre> + +<h3 id="Preparando_el_contexto_de_WebGL">Preparando el contexto de WebGL</h3> + +<p>La función <code>start()</code>, en nuestro código JavaScript, es llamada después de que el documento fue cargado. Su misión es establecer el contexto WebGL y empezar a renderizar contenido.</p> + +<pre class="brush: js">var gl; // Un variable global para el contexto WebGL + +function start() { + var canvas = document.getElementById("glcanvas"); + + gl = initWebGL(canvas); // Inicializar el contexto GL + + // Solo continuar si WebGL esta disponible y trabajando + + if (gl) { + gl.clearColor(0.0, 0.0, 0.0, 1.0); // Establecer el color base en negro, totalmente opaco + gl.enable(gl.DEPTH_TEST); // Habilitar prueba de profundidad + gl.depthFunc(gl.LEQUAL); // Objetos cercanos opacan objetos lejanos + gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT); // Limpiar el buffer de color asi como el de profundidad + } +} +</pre> + +<p>La primer cosa que hacemos aqui es obtener una referencia al <a href="https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API">canvas</a>, ocultándolo en una variable llamada <code>canvas</code>. Obviamente si no necesitas referenciar repetidamente, deberías evitar guardar este valor globalmente, y solo guardarlo en una variable local o miembro de un objeto.</p> + +<p>Una vez tenemos el canvas, llamamos a la función llamada <code>initWebGL()</code>; esta es una función que definiremos momentaneamente; su trabajo es inicializar el contexto WebGL.</p> + +<p>Si el contexto es exitosamente inicializado, <code>gl</code> sera una referencia a este. En este caso, establecemos el color base a negro, después limpiamos el contexto a ese color. Después, el contexto es configurado estableciendo parametros. En este caso, estamos habilitando la prueba de profundidad y especificando que los objetos cercanos opacaran a los objetos lejanos.</p> + +<p>Para los propositos de esta introducción al código, eso sera todo lo que haremos. Empezaremos a ver como crear algo después.</p> + +<h3 id="Crear_el_contexto_de_WebGL">Crear el contexto de WebGL</h3> + +<p>La función <code>initWebGL()</code>se ve como esto:</p> + +<pre class="brush: js">function initWebGL(canvas) { + gl = null; + + try { + // Tratar de tomar el contexto estandar. Si falla, retornar al experimental. + gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl"); + } + catch(e) {} + + // Si no tenemos ningun contexto GL, date por vencido ahora + if (!gl) { + alert("Imposible inicializar WebGL. Tu navegador puede no soportarlo."); + gl = null; + } + + return gl; +} + +</pre> + +<p>Para obtener el contexto WebGL de un canvas, pedimo el contexto llamado "webgl" del canvas. Si este falla, intentamos con el nombre "experimental-webgl". Si este igualmente, falla, mostramos una alerta permitiendo al usuario conocer que parece no tener soporte WebGL. Eso es todo al respecto. En este punto, <code>gl</code> es nulo (no hay ningun contexto WebGL disponible) o es una referencia al contexto WebGL en donde renderizaremos.</p> + +<div class="note"><strong>Nota:</strong> El nombre de contexto "experimental-webgl" es nombre temporal para usar durante el desarrollo de las especificaciones; el nombre "webgl" sera usado una vez se termine el desarrollo.</div> + +<p>En este punto, tienes suficiente código para que el contexto WebGL, inicialice exitosamente, y deberias terminar con una gran cuadro negro y vacio, listo y esperando a recibir contenido .</p> + +<p><a href="/samples/webgl/sample1/index.html" title="https://developer.mozilla.org/samples/webgl/sample1/index.html">Prueba este ejemplo</a> si estas usando un navegador compatible con WebGL.</p> + +<h3 id="Cambiando_el_tamaño_del_contexto_WebGL">Cambiando el tamaño del contexto WebGL</h3> + +<p>Un nuevo contexto WebGL establecera el tamaño de su ventana a la altura y anchura del elemento canvas, sin CSS, al instante el contexto fue obtenido. Editando el estilo del elemento canvas cambiara su tamaño mostrado pero no cambiara la resolución de renderizado. Editando los atributos de anchura y altura de un elemento canvas después de crear el contexto tampoco cambiara el numero de pixeles a ser renderizados. Para cambiar la resolución en la cual WebGL renderiza, como cuando el usuario cambia el tamaño de ventana de un canvas de documento completo o quieres proveer ajustes graficos ajustables dentro de la aplicación, necesitaras llamar a la función del contexto WebGL llamada <code>viewport()</code> para hacer efectivo el cambio.</p> + +<p>Para modificar la resolución renderizada de un contexto WebGL con las variables <code>gl</code> y <code>canvas</code> como fue usado en el ejemplo de arriba:</p> + +<pre class="brush: js">gl.viewport(0, 0, canvas.width, canvas.height);</pre> + +<p>Un lienzo experimentara escalado cuando es renderizado en una resolución diferente a la establecida en el estilo CSS . Cambiar el tamaño con CSS es muy util para salvar recursos renderizando a una baja resolución y permitiendo que el navegador aumente la escala; bajar la escala es posible, lo que producira un efecto de Super Sample AntiAliasing (SSAA) (con resultados sencillos y un costo alto de rendimiento). Es mejor usar el <abbr style="line-height: 24px;" title='"Multisample'>MSAA (Multi Sample AntiAliasing)</abbr> e implementar un filtrado de texturas en el navegador del usuario, si es que esta disponible y es apropiado, en lugar de hacerlo por medio de la fuerza bruta, esperando que el algoritmo de reducción de la imagen del navegador produzca un resultado limpio.</p> + +<h2 id="También_podría_interesarte">También podría interesarte</h2> + +<ul> + <li><a href="https://dev.opera.com/articles/introduction-to-webgl-part-1/">Una introducción a WebGL - </a>Escrito por Luz Caballero, publicado en dev.opera.com. Este articulo cita que es WebGL, explica como funciona WebGL (incluyendo el concepto del proceso de renderizado), e introduce algunas librerias WebGL</li> + <li><a href="http://duriansoftware.com/joe/An-intro-to-modern-OpenGL.-Table-of-Contents.html">Una introducción al OpenGL moderno</a> - Una serie de articulos escritos por Joe Groff. Joe da una limpia introducción sobre OpenGL desde su historia al importante concepto del proceso de graficos y provee algunos ejemplos sobre como OpenGL trabaja. Si no tienes ninguna idea sobre OpenGL, este es un buen lugar para comenzar.</li> +</ul> + +<p>{{Next("Web/API/WebGL_API/Tutorial/Adding_2D_content_to_a_WebGL_context")}}</p> diff --git a/files/es/web/api/webgl_api/tutorial/index.html b/files/es/web/api/webgl_api/tutorial/index.html new file mode 100644 index 0000000000..47a0aceb5e --- /dev/null +++ b/files/es/web/api/webgl_api/tutorial/index.html @@ -0,0 +1,42 @@ +--- +title: Tutoral de WebGL +slug: Web/API/WebGL_API/Tutorial +tags: + - Tutorial + - WebGL +translation_of: Web/API/WebGL_API/Tutorial +--- +<div>{{WebGLSidebar}}</div> + +<div class="summary"> +<p><a class="external" href="http://www.khronos.org/webgl/" title="http://www.khronos.org/webgl/">WebGL</a> enables web content to use an API based on <a class="external" href="http://www.khronos.org/opengles/" title="http://www.khronos.org/opengles/">OpenGL ES</a> 2.0 to perform 3D rendering in an HTML {{HTMLElement("canvas")}} in browsers that support it without the use of plug-ins. WebGL programs consist of control code written in JavaScript and special effects code(shader code) that is executed on a computer's Graphics Processing Unit (GPU). WebGL elements can be mixed with other HTML elements and composited with other parts of the page or page background.</p> +</div> + +<p><span class="seoSummary">This tutorial describes how to use the <code><canvas></code> element to draw WebGL graphics, starting with the basics. The examples provided should give you some clear ideas what you can do with WebGL and will provide code snippets that may get you started in building your own content.</span></p> + +<p><strong>Antes de que inicies</strong></p> + +<p>Using the <code><canvas></code> element is not very difficult, but you do need a basic understanding of <a href="/en-US/docs/Web/HTML" title="HTML">HTML</a> and <a href="/en-US/docs/Web/JavaScript" title="JavaScript">JavaScript</a>. The <code><canvas></code> element and WebGL are not supported in some older browsers, but are supported in recent versions of all major browsers. In order to draw graphics on the canvas we use a JavaScript context object, which creates graphics on the fly.</p> + +<p> </p> + +<h2 id="En_este_tutorial">En este tutorial</h2> + +<dl> + <dt><a href="/en-US/docs/Web/API/WebGL_API/Tutorial/Getting_started_with_WebGL">Getting started with WebGL</a></dt> + <dd>How to set up a WebGL context.</dd> + <dt><a href="/en-US/docs/Web/API/WebGL_API/Tutorial/Adding_2D_content_to_a_WebGL_context">Adding 2D content to a WebGL context</a></dt> + <dd>How to render simple flat shapes using WebGL.</dd> + <dt><a href="/en-US/docs/Web/API/WebGL_API/Tutorial/Using_shaders_to_apply_color_in_WebGL">Using shaders to apply color in WebGL</a></dt> + <dd>Demonstrates how to add color to shapes using shaders.</dd> + <dt><a href="/en-US/docs/Web/API/WebGL_API/Tutorial/Animating_objects_with_WebGL">Animating objects with WebGL</a></dt> + <dd>Shows how to rotate and translate objects to create simple animations.</dd> + <dt><a href="/en-US/docs/Web/API/WebGL_API/Tutorial/Creating_3D_objects_using_WebGL">Creating 3D objects using WebGL</a></dt> + <dd>Shows how to create and animate a 3D object (in this case, a cube).</dd> + <dt><a href="/en-US/docs/Web/API/WebGL_API/Tutorial/Using_textures_in_WebGL">Using textures in WebGL</a></dt> + <dd>Demonstrates how to map textures onto the faces of an object.</dd> + <dt><a href="/en-US/docs/Web/API/WebGL_API/Tutorial/Lighting_in_WebGL">Lighting in WebGL</a></dt> + <dd>How to simulate lighting effects in your WebGL context.</dd> + <dt><a href="/en-US/docs/Web/API/WebGL_API/Tutorial/Animating_textures_in_WebGL">Animating textures in WebGL</a></dt> + <dd>Shows how to animate textures; in this case, by mapping an Ogg video onto the faces of a rotating cube.</dd> +</dl> diff --git a/files/es/web/api/webgl_api/tutorial/objetos_3d_utilizando_webgl/index.html b/files/es/web/api/webgl_api/tutorial/objetos_3d_utilizando_webgl/index.html new file mode 100644 index 0000000000..91e6bf3d37 --- /dev/null +++ b/files/es/web/api/webgl_api/tutorial/objetos_3d_utilizando_webgl/index.html @@ -0,0 +1,133 @@ +--- +title: Creación de objetos 3D utilizando WebGL +slug: Web/API/WebGL_API/Tutorial/Objetos_3D_utilizando_WebGL +tags: + - Cubo 3D + - Objetos 3D + - Tutorial + - WebGL +translation_of: Web/API/WebGL_API/Tutorial/Creating_3D_objects_using_WebGL +--- +<p>{{WebGLSidebar("Tutorial")}} {{PreviousNext("Web/API/WebGL_API/Tutorial/Animating_objects_with_WebGL", "Web/API/WebGL_API/Tutorial/Using_textures_in_WebGL")}}</p> + +<p>Vamos a llevar nuestro cuadrado hacia la tercera dimensión agregando cinco caras más para crear el cubo. Para hacer esto de manera eficiente, vamos a cambiar el dibujado por medio de vertices utilizando el método {{domxref("WebGLRenderingContext.drawArrays()", "gl.drawArrays()")}}<code> </code>por el uso de un arreglo de vértices como tabla, esto por medio del llamado hacia {{domxref("WebGLRenderingContext.drawElements()", "gl.drawElements()")}}.</p> + +<p>Considerar: cada cara cuatro vértices para su definición, pero cada vértice es compartido por 3 caras. Realizando una lista con los 24 vértices es como nosotros haremos un menor intercambio de datos, después haremos referencia hacia cada vértic por medio se su índice en la lista en lugar de pasar el juego entero de coordenadas. Si te preguntas por qué necesitamos 24 vértices, y no solo 8, es porque cada esquina pertenece a tres caras de diferente color, y un solo vértice necesita tener un solo color específico, por lo tanto crearemos 3 copias de cada vértice en tres colores diferentes, uno por cada cara.</p> + +<h2 id="Definir_la_posición_de_los_vértices_del_cubo">Definir la posición de los vértices del cubo</h2> + +<p>Primero, construiremos el buffer para la posición de los vértices actualizando el código en <code>initBuffers()</code>. Esto es muy parecido a lo como si fuera para el cuadraro, pero más lardo debido a que ahora son 24 vértices (4 por lado):</p> + +<pre class="brush: js">var vertices = [ + // Cara delantera + -1.0, -1.0, 1.0, + 1.0, -1.0, 1.0, + 1.0, 1.0, 1.0, + -1.0, 1.0, 1.0, + + // Cara trasera + -1.0, -1.0, -1.0, + -1.0, 1.0, -1.0, + 1.0, 1.0, -1.0, + 1.0, -1.0, -1.0, + + // Top face + -1.0, 1.0, -1.0, + -1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, + 1.0, 1.0, -1.0, + + // Bottom face + -1.0, -1.0, -1.0, + 1.0, -1.0, -1.0, + 1.0, -1.0, 1.0, + -1.0, -1.0, 1.0, + + // Right face + 1.0, -1.0, -1.0, + 1.0, 1.0, -1.0, + 1.0, 1.0, 1.0, + 1.0, -1.0, 1.0, + + // Left face + -1.0, -1.0, -1.0, + -1.0, -1.0, 1.0, + -1.0, 1.0, 1.0, + -1.0, 1.0, -1.0 +]; +</pre> + +<h2 id="Definir_los_colores_de_los_vértices">Definir los colores de los vértices</h2> + +<p>Necesitamos construir un arreglo de colores por cada uno de los 24 vertices. Este código comienza por definir un color para cada cara, después utiliza un ciclo para ensamblar el arreglo de colores por cada uno de los vértices.</p> + +<pre class="brush: js">var colors = [ + [1.0, 1.0, 1.0, 1.0], // Cara delantera: blanco + [1.0, 0.0, 0.0, 1.0], // Cara trasera: rojo + [0.0, 1.0, 0.0, 1.0], // Cara superior: verde + [0.0, 0.0, 1.0, 1.0], // Cara inferior: azul + [1.0, 1.0, 0.0, 1.0], // Cara derecha: amarillo + [1.0, 0.0, 1.0, 1.0] // Cara izquierda: morado +]; + +var generatedColors = []; + +for (j=0; j<6; j++) { + var c = colors[j]; + + for (var i=0; i<4; i++) { + generatedColors = generatedColors.concat(c); + } +} + +var cubeVerticesColorBuffer = gl.createBuffer(); +gl.bindBuffer(gl.ARRAY_BUFFER, cubeVerticesColorBuffer); +gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(generatedColors), gl.STATIC_DRAW); +</pre> + +<h2 id="Definir_el_elemento_arreglo">Definir el elemento arreglo</h2> + +<p>Una ves que el vértice es generado, nosotros necesitamos contruir el elemento arreglo.</p> + +<pre class="brush: js">var cubeVerticesIndexBuffer = gl.createBuffer(); +gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVerticesIndexBuffer); + +// Este arrelgo define cada cara como 2 triángulos utilizando +// los índices dentro de cada arreglo de vértices +// para especificar cada posición en los tríangulos. + +var cubeVertexIndices = [ + 0, 1, 2, 0, 2, 3, // enfrente + 4, 5, 6, 4, 6, 7, // atrás + 8, 9, 10, 8, 10, 11, // arriba + 12, 13, 14, 12, 14, 15, // fondo + 16, 17, 18, 16, 18, 19, // derecha + 20, 21, 22, 20, 22, 23 // izquierda +]; + +// Ahora enviamos el elemento arreglo a GL + +gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, + new Uint16Array(cubeVertexIndices), gl.STATIC_DRAW); +</pre> + +<p>El arreglo <code>cubeVertexIndices</code> define cada cara como un par de triángulos, especificando cada vértice del triángulo como un índice dentro del arreglo de vértices en el cubo. Así el cubo es descrito como una colección de 12 triángulos. </p> + +<h2 id="Dibujando_el_cubo">Dibujando el cubo</h2> + +<p>Para continuar necesitaremos agregar el código a nuestra función <code>drawScene()</code> esto para poder dibujar utilizando el buffer índice del cubo, agregaremos un nuevo llamado a {{domxref("WebGLRenderingContext.bindBuffer()", "gl.bindBuffer()")}} y {{domxref("WebGLRenderingContext.drawElements()", "gl.drawElements()")}}como se muestra a continuación:</p> + +<pre class="brush: js">gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVerticesIndexBuffer); +setMatrixUniforms(); +gl.drawElements(gl.TRIANGLES, 36, gl.UNSIGNED_SHORT, 0); +</pre> + +<p>Desde que cada cara de nuestro cubo está compuesto de dos triángulos, tenemos 6 vértices en el cubo, se podría pensar que algunos de ellos son duplicados. Sin embargo, desde que nuestro arreglo índice se encuentra compuesto de enteros simples, esto no es una cantidad excesiva de intercambio de datos para pasar por cada cuadro de la animación.</p> + +<p>En este punto ahora tenemos un cubo animado rebotando y rotando, cuenta con seis caras coloreadas vívidamente.</p> + +<p>{{EmbedGHLiveSample('webgl-examples/tutorial/sample5/index.html', 670, 510) }}</p> + +<p><a href="https://github.com/mdn/webgl-examples/tree/gh-pages/tutorial/sample5">Ver el Código completo</a> | <a href="http://mdn.github.io/webgl-examples/tutorial/sample5/">Abrir esta demostración en una página nueva</a></p> + +<p>{{PreviousNext("Web/API/WebGL_API/Tutorial/Animating_objects_with_WebGL", "Web/API/WebGL_API/Tutorial/Using_textures_in_WebGL")}}</p> diff --git a/files/es/web/api/webgl_api/tutorial/using_shaders_to_apply_color_in_webgl/index.html b/files/es/web/api/webgl_api/tutorial/using_shaders_to_apply_color_in_webgl/index.html new file mode 100644 index 0000000000..25192a8281 --- /dev/null +++ b/files/es/web/api/webgl_api/tutorial/using_shaders_to_apply_color_in_webgl/index.html @@ -0,0 +1,91 @@ +--- +title: Utilizar los shaders para aplicar color en WebGL +slug: Web/API/WebGL_API/Tutorial/Using_shaders_to_apply_color_in_WebGL +translation_of: Web/API/WebGL_API/Tutorial/Using_shaders_to_apply_color_in_WebGL +--- +<p>{{WebGLSidebar("Tutorial")}} {{PreviousNext("Web/API/WebGL_API/Tutorial/Adding_2D_content_to_a_WebGL_context", "Web/API/WebGL_API/Tutorial/Animating_objects_with_WebGL")}}</p> + +<p>Habiendo creado un cuadrado en la <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Tutorial/Adding_2D_content_to_a_WebGL_context">demostración anterior</a>, el siguiente paso es agregar algo de color. Nosotros podemos hacer esto a través de los shaders.</p> + +<h2 id="Aplicando_color_a_los_vértices">Aplicando color a los vértices</h2> + +<p>En WebGL, los objetos son construidos utilizando conjuntos de vértices, donde cada uno de ellos posee una posición y un color. Por defecto, los colores de los otros pixeles (y todos sus atributos, incluyendo la posición) son procesados utilizando interpolación, creando automáticamente gradientes suaves. Anteriormente, nuestro sombreador de vértices (vertex shader) no aplicaba ningún color específico a los vértices. Entre éste y el fragmento sombreado que asigna el color blanco fijo a cada pixel, todo el cuadrado se renderizó como blanco sólido.</p> + +<p>Vamos a suponer que queremos desplegar un gradiente donde cada una de las esquinas tiene diferente color: rojo, azul, verde, y blanco. La primera tarea es establecer estos colores en los cuatro vértices. Para hacer esto, primero necesitamos crear una matriz de colores de vértices, después la guardaremos dentro del buffer WebGL. Podemos realizarlo agregando el siguiente código a nuestra función initBuffers(): </p> + +<pre class="brush: js"> var colors = [ + 1.0, 1.0, 1.0, 1.0, // blanco + 1.0, 0.0, 0.0, 1.0, // rojo + 0.0, 1.0, 0.0, 1.0, // verde + 0.0, 0.0, 1.0, 1.0 // azul + ]; + + squareVerticesColorBuffer = gl.createBuffer(); + gl.bindBuffer(gl.ARRAY_BUFFER, squareVerticesColorBuffer); + gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW); +} +</pre> + +<p>El código comienza por crear una matriz JavaScript que contenga cuatro vectores de 4 valores, para cada uno de los colores del vértice. Entonces se reserva un nuevo buffer WebGL para almacenar esos colores y la matriz se convierte en floats (Números de tipo flotante) y se almacena dentro del buffer.</p> + +<p>Para designar los colores a utilizar, el vertex shader necesita ser actualizado para extraer el color apropiado del buffer de color:</p> + +<pre class="brush: html"> <script id="shader-vs" type="x-shader/x-vertex"> + attribute vec3 aVertexPosition; + attribute vec4 aVertexColor; + + uniform mat4 uMVMatrix; + uniform mat4 uPMatrix; + + varying lowp vec4 vColor; + + void main(void) { + gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0); + vColor = aVertexColor; + } + </script> +</pre> + +<p>La diferencia principal aquí es que, por cada vértice, vamos a establecer su color usando <code>varying</code> en el fragmento de sombreado.</p> + +<h2 id="Coloreando_los_fragments">Coloreando los fragments</h2> + +<p>Anteriormente utilizábamos el fragment shader como un actualizador:</p> + +<pre class="brush: html"> <script id="shader-fs" type="x-shader/x-fragment"> + void main(void) { + gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0); + } + </script> +</pre> + +<p>Según vayamos tomando el color interpolado para cada pixel, nosotros simplemente necesitamos cambiar esto para obtener el valor de la variable vColor:</p> + +<pre class="brush: html"> <script id="shader-fs" type="x-shader/x-fragment"> + varying lowp vec4 vColor; + + void main(void) { + gl_FragColor = vColor; + } + </script> +</pre> + +<p>Es un cambio simple; cada fragmento simplemente recibe el color interpolado basado en su posición relativa a los vértices, en lugar que de un valor establecido.</p> + +<h2 id="Dibujando_usando_los_colores">Dibujando usando los colores</h2> + +<p>Como siguiente, es necesario agregar código hacia la rutina <code>initShaders() esto para inicializar el atributo de color para el shader program:</code></p> + +<pre class="brush: js"> vertexColorAttribute = gl.getAttribLocation(shaderProgram, "aVertexColor"); + gl.enableVertexAttribArray(vertexColorAttribute); +</pre> + +<p>Then, drawScene() puede ser revisado para que utilice dichos colores cuando dibuje el cuadrado:</p> + +<p>gl.bindBuffer(gl.ARRAY_BUFFER, squareVerticesColorBuffer); gl.vertexAttribPointer(vertexColorAttribute, 4, gl.FLOAT, false, 0, 0);</p> + +<p>{{EmbedGHLiveSample('webgl-examples/tutorial/sample3/index.html', 670, 510) }}</p> + +<p><a href="https://github.com/mdn/webgl-examples/tree/gh-pages/tutorial/sample3">Ver el código completo</a> | <a href="http://mdn.github.io/webgl-examples/tutorial/sample3/">Abrir demostración en una nueva página</a></p> + +<p>{{PreviousNext("Web/API/WebGL_API/Tutorial/Adding_2D_content_to_a_WebGL_context", "Web/API/WebGL_API/Tutorial/Animating_objects_with_WebGL")}}</p> diff --git a/files/es/web/api/webgl_api/tutorial/wtilizando_texturas_en_webgl/index.html b/files/es/web/api/webgl_api/tutorial/wtilizando_texturas_en_webgl/index.html new file mode 100644 index 0000000000..9d2be2d61b --- /dev/null +++ b/files/es/web/api/webgl_api/tutorial/wtilizando_texturas_en_webgl/index.html @@ -0,0 +1,209 @@ +--- +title: Utilizando texturas en WebGL +slug: Web/API/WebGL_API/Tutorial/Wtilizando_texturas_en_WebGL +tags: + - Texturas + - Tutorial + - WebGL +translation_of: Web/API/WebGL_API/Tutorial/Using_textures_in_WebGL +--- +<p>{{WebGLSidebar("Tutorial")}} {{PreviousNext("Web/API/WebGL_API/Tutorial/Creating_3D_objects_using_WebGL", "Web/API/WebGL_API/Tutorial/Lighting_in_WebGL")}}</p> + +<p>Ahora que nuestro programa de prueba tiene un cubo, asignemos una textura en lugar de tener sus caras de un color solido.</p> + +<h2 id="Cargando_texturas">Cargando texturas</h2> + +<p>La primera cosa que debemos hacer es añadir el codigo para cargar nuestra textura. en nuestro caso, estaremos usando una unica textura, asignada en las seis caras de nuestro cubo rotador, pero la misma tecnica puede ser utilizada para cualquier cantidad de texturas.</p> + +<div class="note"><strong>Note:</strong> Es importante señalar que la carga de texturas sigue <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS">reglas de dominio-cruzado</a>; Es decir, sólo puede cargar texturas de sitios para los que su contenido tiene aprobación de CORS. Vea las texturas entre dominios a continuación para más detalles.</div> + +<p>El codigo que carga la textura se ve como esto:</p> + +<pre class="brush: js">function initTextures() { + cubeTexture = gl.createTexture(); + cubeImage = new Image(); + cubeImage.onload = function() { handleTextureLoaded(cubeImage, cubeTexture); } + cubeImage.src = 'cubetexture.png'; +} + +function handleTextureLoaded(image, texture) { + gl.bindTexture(gl.TEXTURE_2D, texture); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST); + gl.generateMipmap(gl.TEXTURE_2D); + gl.bindTexture(gl.TEXTURE_2D, null); +} +</pre> + +<p><code><font face="Open Sans, Arial, sans-serif">La rutina </font>initTextures()</code> comienza por crear el GL texture cubeTexture llamando la rutina GL {{domxref("WebGLRenderingContext.createTexture()", "createTexture()")}}. Para cargar la textura desde un archivo de imagen, este luego crea un Objeto Imagen y carga en él el archivo de imagen que deseamos utilizar como nuestra textura. La rutina <code>handleTextureLoaded()</code> corre cuando la textura ha terminado de cargar.</p> + +<p>Para realmente crear la textura, especificamos que la nueva textura es la textura actual en la que queremos operar vinculándola a gl.TEXTURE_2D. Despues de esto, la imagen cargada es pasada a {{domxref("WebGLRenderingContext.texImage2D()", "texImage2D()")}} para escribir la informacion de la imagen en la textura.</p> + +<div class="note"><strong>Nota: El alto y hancho de las texturas deben, en la mayoría de las circunstancias, ser una potencia de dos píxeles (es decir, 1, 2, 4, 8, 16, etc.) en cada dimensión. Para la excepción, vea la sección: <a href="https://developer.mozilla.org/en-US/docs/Web/WebGL/Using_textures_in_WebGL#Non_power-of-two_textures">"Texturas no potencia de dos"</a>, a continuación.</strong></div> + +<p>Las siguientes dos líneas setean el filtrado para la textura; Esto controla cómo se filtra la imagen mientras se escala. En este caso estamos usando linear filtering cuando escala la imagen, y mipmap cuando se hace mas pequeña. Entonces el mipmap es generado llamando {{domxref("WebGLRenderingContext.generateMipMap()", "generateMipMap()")}}, Y terminamos diciéndole a WebGL que hemos terminado de manipular la textura vinculando null a gl.TEXTURE_2D.</p> + +<h3 id="Texturas_no_potencia-de-dos">Texturas no potencia-de-dos</h3> + +<p>Generalmente hablando, Utilizar texturas cuyos lados son una potencia de dos es ideal. Están almacenadas eficientemente en la memoria de video y no están restringidas en cómo podrían ser utilizadas. Las texturas creadas por el artista deben ser escaladas hacia arriba o hacia abajo a una potencia cercana a dos y, realmente, debería haber sido creada en potencia-de-dos para empezar. Cada lado debe ser: 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024 ó 2048 píxeles. Muchos dispositivos, pero no todos, pueden soportar 4096 píxeles; Algunos pueden soportar 8192 e incluso más.</p> + +<p>Ocasionalmente, es difícil utilizar texturas en potencia-de-dos dada una circunstancia especifica. Si la fuente es alguna tercera parte, A menudo los mejores resultados vienen de modificar las imágenes usando canvas HTML5 en tamaños de potencia-de-dos antes de que se pasen a WebGL; Las coordenadas UV también pueden requerir ajuste si el estiramiento es notorio.</p> + +<p>Pero, Si tiene que tener una textura no-potencia-de-dos (NPOT = no-power-of-two), WebGL incluye un limitado soporte nativo. Las texturas NPOT son en su mayoría útiles si las dimensiones de la textura debe ser la misma resolución que otra cosa, como la resolución de tu monitor, o si no vale la pena molestarse por las sugerencias anteriores. Resumiendo: estas texturas no se pueden usar con mipmapping y no deben repetirse (tile o wrap).</p> + +<p>Un ejemplo de una textura es tilear una imagen de unos ladrillos para cubrir una pared de ladrillos.</p> + +<p>Mipmapping y "UV tiling" pueden ser desactivados utilizando {{domxref("WebGLRenderingContext.texParameter()", "texParameteri()")}} y cuando creas tu textura utilizando {{domxref("WebGLRenderingContext.bindTexture()", "bindTexture()")}}. Ésto permitirá las texturas NPOT a expensas de mipmapping, UV wrapping, UV tiling, y tu control sobre cómo el dispositivo procederá a manejar tu textura.</p> + +<pre class="brush: js">// gl.NEAREST is also allowed, instead of gl.LINEAR, as neither mipmap. +gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); +// Prevents s-coordinate wrapping (repeating). +gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); +// Prevents t-coordinate wrapping (repeating). +gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);</pre> + +<p>Una vez más, con estos parámetros, los dispositivos compatibles con WebGL aceptarán automáticamente cualquier resolución para esa textura (hasta sus dimensiones máximas). Sin realizar la configuración anterior, WebGL requiere que todas las muestras de texturas NPOT fallen al devolver el color "negro sólido": rgba (0,0,0,1).</p> + +<h2 id="Mapeando_la_textura_en_las_caras">Mapeando la textura en las caras</h2> + +<p>A este punto, la textura esta cargada y lista para usar. pero antes de utilizarla, Necesitamos asignar el mapeo de las coordenadas de textura a los vértices de las caras de nuestro cubo. Esto reemplaza todo el código previamente existente para configurar colores para cada una de las caras del cubo en initBuffers().</p> + +<pre class="brush: js">cubeVerticesTextureCoordBuffer = gl.createBuffer(); +gl.bindBuffer(gl.ARRAY_BUFFER, cubeVerticesTextureCoordBuffer); + +var textureCoordinates = [ + // Front + 0.0, 0.0, + 1.0, 0.0, + 1.0, 1.0, + 0.0, 1.0, + // Back + 0.0, 0.0, + 1.0, 0.0, + 1.0, 1.0, + 0.0, 1.0, + // Top + 0.0, 0.0, + 1.0, 0.0, + 1.0, 1.0, + 0.0, 1.0, + // Bottom + 0.0, 0.0, + 1.0, 0.0, + 1.0, 1.0, + 0.0, 1.0, + // Right + 0.0, 0.0, + 1.0, 0.0, + 1.0, 1.0, + 0.0, 1.0, + // Left + 0.0, 0.0, + 1.0, 0.0, + 1.0, 1.0, + 0.0, 1.0 +]; + +gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(textureCoordinates), + gl.STATIC_DRAW); +</pre> + +<p>Primeramente, este codigo crea un GL buffer en el cual almacenaremos las coordenadas de la textura para cada cara, luego enlazamos ese buffer como el array en el cual escribiremos.</p> + +<p>El array textureCoordinates define las coordenadas de textura correspondientes a cada vértice de cada cara. Tenga en cuenta que las coordenadas de textura van de 0,0 a 1,0; Las dimensiones de las texturas se normalizan a un rango de 0,0 a 1,0 independientemente de su tamaño real, con el propósito de mapeo de textura.</p> + +<p>Una vez que hemos seteado la matriz de mapeo de textura, pasamos la matriz al búfer, de modo que GL tiene esos datos listos para su uso.</p> + +<h2 id="Actualizando_los_shaders">Actualizando los shaders</h2> + +<p>El shader -- y el código que inicializa los shaders -- también necesita ser actualizado para utilizar la textura en vez de un color solido.</p> + +<p>Primero, echemos un vistazo a un cambio muy sencillo que se necesita en initShaders():</p> + +<pre class="brush: js">textureCoordAttribute = gl.getAttribLocation(shaderProgram, 'aTextureCoord'); +gl.enableVertexAttribArray(textureCoordAttribute); +gl.vertexAttribPointer(texCoordAttribute, 2, gl.FLOAT, false, 0, 0); +</pre> + +<p>Esto reemplaza el código que setea el atributo "vertex color" (color del vertice) con uno que contiene la coordenada de textura para cada vértice.</p> + +<h3 id="El_vertex_shader">El vertex shader</h3> + +<p>A continuación, necesitamos reemplazar el "vertex shader" de modo que en lugar de buscar datos de color, busque los datos de coordenadas de textura.</p> + +<pre class="brush: html"><script id="shader-vs" type="x-shader/x-vertex"> + attribute vec3 aVertexPosition; + attribute vec2 aTextureCoord; + + uniform mat4 uMVMatrix; + uniform mat4 uPMatrix; + + varying highp vec2 vTextureCoord; + + void main(void) { + gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0); + vTextureCoord = aTextureCoord; + } +</script> +</pre> + +<p>El cambio clave aquí es que en lugar de buscar el color del vértice (vertex color), estamos estableciendo las coordenadas de textura; Esto indicará la ubicación dentro de la textura correspondiente al vértice.</p> + +<h3 id="El_fragment_shader">El fragment shader</h3> + +<p>El fragment shader también debe actualizarse:</p> + +<pre class="brush: html"><script id="shader-fs" type="x-shader/x-fragment"> + varying highp vec2 vTextureCoord; + + uniform sampler2D uSampler; + + void main(void) { + gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t)); + } +</script> +</pre> + +<p>En lugar de asignar un valor de color al fragment color, el fragment color se calcula recolectando el texel (es decir, el píxel dentro de la textura) que el muestreador dice que se corresponde mejor con la posición del fragment.</p> + +<h2 id="Dibujando_el_cubo_texturado">Dibujando el cubo texturado</h2> + +<p>El cambio a la función drawScene() es simple (excepto que por razones de claridad, he eliminado el código que hace que el cubo se traslade a través del espacio mientras se anima, en vez de eso, solo gira).</p> + +<p>El código para mapear colores a la textura se ha ido, sustituido por esto:</p> + +<pre class="brush: js">gl.activeTexture(gl.TEXTURE0); +gl.bindTexture(gl.TEXTURE_2D, cubeTexture); +gl.uniform1i(gl.getUniformLocation(shaderProgram, 'uSampler'), 0); +</pre> + +<p>GL proporciona 32 registros de textura; La primera de ellas es gl.TEXTURE0. Vincularemos nuestra textura previamente cargada a ese registro, a continuación, establecremos el shader sampler uSampler (especificado en el shader) para utilizar esa textura.</p> + +<p>En este punto, el cubo giratorio debe estar listo.</p> + +<p>{{EmbedGHLiveSample('webgl-examples/tutorial/sample6/index.html', 670, 510) }}</p> + +<p><a href="https://github.com/mdn/webgl-examples/tree/gh-pages/tutorial/sample6">Ver el código completo</a> | <a href="http://mdn.github.io/webgl-examples/tutorial/sample6/">Abrir esta demo en una nueva pestaña</a></p> + +<h2 id="Texturas_entre_dominios">Texturas entre dominios</h2> + +<p>La carga de texturas WebGL esta sujeta a controles de acceso entre dominios. Para que su contenido cargue una textura de otro dominio, La aprobacion CORS debe ser obtenida. Ver <a href="/en-US/docs/Web/HTTP/Access_control_CORS">control de acceso HTTP</a> para mas detalles sobre CORS.</p> + +<p>Ver este articulo <a class="external" href="http://hacks.mozilla.org/2011/11/using-cors-to-load-webgl-textures-from-cross-domain-images/">hacks.mozilla.org</a> para una explicacion de como usar imágenes CORS-approved como texturas WebGL , con un <a class="external" href="http://people.mozilla.org/~bjacob/webgltexture-cors-js.html">ejemplo auto-contenido</a>.</p> + +<div class="note"> +<p><strong>Nota: </strong>El soporte CORS para texturas WebGL y el atributo crossOrigin para elementos de imagen se implementan en {{Gecko ("8.0")}}.</p> +</div> + +<p>Canvas 2D contaminados (Solo lectura) no pueden ser utilizados como texturas WebGL. una 2D {{ HTMLElement("canvas") }} se convierte en contaminada, por ejemplo, cuando una imagen de dominio cruzado (cross-domain) es dibujada en el.</p> + +<div class="note"> +<p><strong>Nota: </strong>El soporte de CORS para Canvas 2D drawImage se implementa en {{Gecko ("9.0")}}. Esto significa que el uso de una imagen de dominio cruzado con aprobación de CORS ya no pinta el lienzo 2D, por lo que el lienzo 2D sigue siendo utilizable como fuente de una textura WebGL. </p> +</div> + +<div class="note"> +<p><strong>Nota:</strong> El soporte de CORS para videos de dominio cruzado y el atributo de crossorigin para elementos {{HTMLElement("video")}} se implementa en {{Gecko ("12.0")}}.</p> +</div> + +<p>{{PreviousNext("Web/API/WebGL_API/Tutorial/Creating_3D_objects_using_WebGL", "Web/API/WebGL_API/Tutorial/Lighting_in_WebGL")}}</p> diff --git a/files/es/web/api/webrtc_api/index.html b/files/es/web/api/webrtc_api/index.html new file mode 100644 index 0000000000..d4de66d803 --- /dev/null +++ b/files/es/web/api/webrtc_api/index.html @@ -0,0 +1,126 @@ +--- +title: API de WebRTC +slug: Web/API/WebRTC_API +tags: + - API + - WebRTC +translation_of: Web/API/WebRTC_API +--- +<p>{{WebRTCSidebar}}</p> + +<p><span class="seoSummary"><strong>WebRTC</strong> (<em>Web real-time communications</em> o comunicaciones web en tiempo real) es una tecnología que permite a aplicaciones y sitios web capturar y opcionalmente retransmitir audio/vídeo, así como intercambiar datos arbitrarios entre navegadores sin necesidad de un intermediario.</span> El conjunto de estándares que comprende WebRTC hace posible compartir datos y realizar teleconferencias de igual-a-igual (<em>peer-to-peer</em>), sin requerir que el usuario instale complementos (<em>plug-ins</em>) o cualquier otro software de terceros.</p> + +<p>WebRTC consta de varias API y protocolos interrelacionados que trabajan juntos para lograr esto. La documentación que encontrará aquí le ayudará a entender los fundamentos de WebRTC, cómo configurarlo y usar tanto datos como conexiones de medios, etc.</p> + +<h2 id="Referencia">Referencia</h2> + +<div class="index"> +<ul> + <li>{{domxref("RTCPeerConnection")}}</li> + <li>{{domxref("RTCSessionDescription")}}</li> + <li>{{domxref("RTCIceCandidate")}}</li> + <li>{{domxref("RTCPeerConnectionIceEvent")}}</li> + <li>{{domxref("MessageEvent")}}</li> + <li>{{domxref("MediaStream")}}</li> + <li>{{domxref("RTCStatsReport")}}</li> + <li>{{domxref("RTCIdentityEvent")}}</li> + <li>{{domxref("RTCIdentityErrorEvent")}}</li> + <li>{{domxref("MediaStreamEvent")}}</li> + <li>{{domxref("MediaStreamTrack")}}</li> + <li>{{domxref("MediaDevices")}}</li> +</ul> +</div> + +<h2 id="Guías">Guías</h2> + +<dl> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Architecture">Visión general de la arquitectura de WebRTC</a></dt> + <dd>Debajo de las API que los desarrolladores usan para crear y usar conexiones WebRTC se encuentran varios protocolos de red y estándares de conectividad. Esta breve descripción cubre estos estándares.</dd> + <dt><a href="/en-US/docs/Web/API/WebRTC_API/WebRTC_basics">Lo esencial de WebRTC</a></dt> + <dd>Este artículo le muestra la creación de una aplicación RTC a través del navegador. Al final, debe tener un canal de datos punto a punto y un canal de medios en funcionamiento.</dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Protocols">Protocolos de WebRTC</a></dt> + <dd>Este artículo presenta los protocolos sobre los cuales se construye la API WebRTC.</dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Connectivity">Conectividad de WebRTC</a></dt> + <dd>Este artículo describe cómo los diversos protocolos relacionados con WebRTC interactúan entre sí para crear una conexión y transferir datos y / o medios entre pares.</dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Overview">Nociones sobre la API WebRTC</a></dt> + <dd>WebRTC consta de varias API y protocolos interrelacionados que trabajan juntos para admitir el intercambio de datos y medios entre dos o más pares. Este artículo proporciona una breve descripción de cada una de estas API y para qué sirve.</dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Session_lifetime">Duración de una sesión de WebRTC</a></dt> + <dd>WebRTC le permite construir una comunicación punto a punto de datos arbitrarios, audio o video, o cualquier combinación de los mismos, en una aplicación de navegador. En este artículo, veremos la duración de una sesión de WebRTC, desde establecer la conexión hasta cerrarla cuando ya no sea necesaria.</dd> +</dl> + +<h2 id="Tutoriales">Tutoriales</h2> + +<dl> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/adapter.js">Improving compatibility using WebRTC adapter.js</a></dt> + <dd>The WebRTC organization <a href="https://github.com/webrtc/adapter/">provides on GitHub the WebRTC adapter</a> to work around compatibility issues in different browsers' WebRTC implementations. The adapter is a JavaScript shim which lets your code to be written to the specification so that it will "just work" in all browsers with WebRTC support.</dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Taking_still_photos">Taking still photos with WebRTC</a></dt> + <dd>This article shows how to use WebRTC to access the camera on a computer or mobile phone with WebRTC support and take a photo with it.</dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Simple_RTCDataChannel_sample">A simple RTCDataChannel sample</a></dt> + <dd>The {{domxref("RTCDataChannel")}} interface is a feature which lets you open a channel between two peers over which you may send and receive arbitrary data. The API is intentionally similar to the <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSocket_API">WebSocket API</a>, so that the same programming model can be used for each.</dd> +</dl> + +<h2 class="Related_Topics" id="Related_Topics" name="Related_Topics">Recursos</h2> + +<h3 id="Protocolos">Protocolos</h3> + +<h4 id="WebRTC-proper_protocols">WebRTC-proper protocols</h4> + +<ul> + <li><a href="http://datatracker.ietf.org/doc/draft-ietf-rtcweb-alpn/"><cite>Application Layer Protocol Negotiation for Web Real-Time Communications</cite></a></li> + <li><a href="http://datatracker.ietf.org/doc/draft-ietf-rtcweb-audio/"><cite>WebRTC Audio Codec and Processing Requirements</cite></a></li> + <li><a href="http://datatracker.ietf.org/doc/draft-ietf-rtcweb-data-channel/"><cite>RTCWeb Data Channels</cite></a></li> + <li><a href="http://datatracker.ietf.org/doc/draft-ietf-rtcweb-data-protocol/"><cite>RTCWeb Data Channel Protocol</cite></a></li> + <li><a href="http://datatracker.ietf.org/doc/draft-ietf-rtcweb-rtp-usage/"><cite>Web Real-Time Communication (WebRTC): Media Transport and Use of RTP</cite></a></li> + <li><a href="http://datatracker.ietf.org/doc/draft-ietf-rtcweb-security-arch/"><cite>WebRTC Security Architecture</cite></a></li> + <li><a href="http://datatracker.ietf.org/doc/draft-ietf-rtcweb-transports/"><cite>Transports for RTCWEB</cite></a></li> +</ul> + +<h4 id="Related_supporting_protocols">Related supporting protocols</h4> + +<ul> + <li><a href="https://tools.ietf.org/html/rfc5245">Interactive Connectivity Establishment (ICE): A Protocol for Network Address Translator (NAT) Traversal for Offer/Answer Protocol</a></li> + <li><a href="https://tools.ietf.org/html/rfc5389"><cite>Session Traversal Utilities for NAT (STUN)</cite></a></li> + <li><a href="https://tools.ietf.org/html/rfc7064"><cite>URI Scheme for the Session Traversal Utilities for NAT (STUN) Protocol</cite></a></li> + <li><a href="https://tools.ietf.org/html/rfc7065"><cite>Traversal Using Relays around NAT (TURN) Uniform Resource Identifiers</cite></a></li> + <li><a href="https://tools.ietf.org/html/rfc3264"><cite>An Offer/Answer Model with Session Description Protocol (SDP)</cite></a></li> + <li><a href="https://datatracker.ietf.org/doc/draft-ietf-tram-turn-third-party-authz/"><cite>Session Traversal Utilities for NAT (STUN) Extension for Third Party Authorization</cite></a></li> +</ul> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('WebRTC 1.0')}}</td> + <td>{{Spec2('WebRTC 1.0')}}</td> + <td>The initial definition of the API of WebRTC.</td> + </tr> + <tr> + <td>{{SpecName('Media Capture')}}</td> + <td>{{Spec2('Media Capture')}}</td> + <td>The initial definition of the object conveying the stream of media content.</td> + </tr> + <tr> + <td>{{SpecName('Media Capture DOM Elements')}}</td> + <td>{{Spec2('Media Capture DOM Elements')}}</td> + <td>The initial definition on how to obtain stream of content from DOM Elements</td> + </tr> + </tbody> +</table> + +<p class="Related_Topics">In additions to these specifications defining the API needed to use WebRTC, there are several protocols, listed under <a href="#Protocols">resources</a>.</p> + +<h2 class="Related_Topics" id="Related_Topics" name="Related_Topics">Ver también</h2> + +<ul> + <li><a href="https://hacks.mozilla.org/2015/06/firefox-multistream-and-renegotiation-for-jitsi-videobridge/">Firefox multistream and renegotiation for Jitsi Videobridge</a></li> + <li><a href="https://hacks.mozilla.org/2015/04/peering-through-the-webrtc-fog-with-socketpeer/">Peering Through the WebRTC Fog with SocketPeer</a></li> + <li><a href="https://hacks.mozilla.org/2014/04/inside-the-party-bus-building-a-web-app-with-multiple-live-video-streams-interactive-graphics/">Inside the Party Bus: Building a Web App with Multiple Live Video Streams + Interactive Graphics</a></li> +</ul> diff --git a/files/es/web/api/webrtc_api/protocols/index.html b/files/es/web/api/webrtc_api/protocols/index.html new file mode 100644 index 0000000000..efa90077fa --- /dev/null +++ b/files/es/web/api/webrtc_api/protocols/index.html @@ -0,0 +1,38 @@ +--- +title: WebRTC protocols +slug: Web/API/WebRTC_API/Protocols +translation_of: Web/API/WebRTC_API/Protocols +--- +<p>{{WebRTCSidebar}}</p> + +<p>Este artículo presenta los protocolos sobre los cuales se construye la API WebRTC.</p> + +<h2 id="ICE">ICE</h2> + +<p><a href="http://en.wikipedia.org/wiki/Interactive_Connectivity_Establishment">Interactive Connectivity Establishment (ICE)</a> es un marco para permitir que su navegador web se conecte con sus compañeros. Hay muchas razones por las que una conexión directa de un par a otro simplemente no funcionará. Debe evitar los firewalls que evitarían abrir conexiones, darle una dirección única si, como en la mayoría de las situaciones, su dispositivo no tiene una dirección IP pública y transmitir datos a través de un servidor si su enrutador no le permite conectarse directamente con sus pares. ICE utiliza algunas de las siguientes técnicas que se describen a continuación para lograr esto:</p> + +<h2 id="STUN">STUN</h2> + +<p><a href="http://en.wikipedia.org/wiki/STUN">Session Traversal Utilities for <u>NAT</u> (STU<u>N</u>)</a> (acrónimo dentro de un acrónimo) es un protocolo para descubrir su dirección pública y determinar cualquier restricción en su enrutador que impida una conexión directa con un par.</p> + +<p>El cliente enviará una solicitud a un servidor STUN en Internet que responderá con la dirección pública del cliente y si el cliente está accesible detrás del NAT del enrutador.</p> + +<p><img alt="An interaction between two users of a WebRTC application involving a STUN server." src="https://mdn.mozillademos.org/files/6115/webrtc-stun.png" style="display: block; height: 378px; margin: 0px auto; width: 259px;"></p> + +<h2 id="NAT">NAT</h2> + +<p><a href="http://en.wikipedia.org/wiki/NAT">Network Address Translation (NAT)</a> se usa para dar a su dispositivo una dirección IP pública. Un enrutador tendrá una dirección IP pública y cada dispositivo conectado al enrutador tendrá una dirección IP privada. Las solicitudes se traducirán de la IP privada del dispositivo a la IP pública del enrutador con un puerto único. De esa manera, no necesita una IP pública única para cada dispositivo, pero aún puede descubrirse en Internet.</p> + +<p>Algunos enrutadores tendrán restricciones sobre quién puede conectarse a dispositivos en la red. Esto puede significar que aunque tengamos la dirección IP pública encontrada por el servidor STUN, nadie puede crear una conexión. En esta situación, debemos recurrir a TURN.</p> + +<h2 id="TURN">TURN</h2> + +<p>Algunos enrutadores que utilizan NAT emplean una restricción llamada "NAT simétrica". Esto significa que el enrutador solo aceptará conexiones de pares a los que se haya conectado previamente.</p> + +<p><a href="http://en.wikipedia.org/wiki/TURN">Traversal Using Relays around NAT (TURN)</a> está destinado a eludir la restricción NAT simétrica al abrir una conexión con un servidor TURN y transmitir toda la información a través de ese servidor. Crearía una conexión con un servidor TURN y le diría a todos los pares que envíen paquetes al servidor que luego se le reenviarán. Obviamente, esto conlleva algunos gastos generales, por lo que solo se usa si no hay otras alternativas.</p> + +<p><img alt="An interaction between two users of a WebRTC application involving STUN and TURN servers." src="https://mdn.mozillademos.org/files/6117/webrtc-turn.png" style="display: block; height: 297px; margin: 0px auto; width: 295px;"></p> + +<h2 id="SDP">SDP</h2> + +<p><a href="http://en.wikipedia.org/wiki/Session_Description_Protocol">Session Description Protocol (SDP)</a> es un estándar para describir el contenido multimedia de la conexión, como la resolución, los formatos, los códecs, el cifrado, etc., de modo que ambos pares puedan entenderse una vez que se transfieren los datos. Esto es, en esencia, los metadatos que describen el contenido y no el contenido de los medios en sí.</p> diff --git a/files/es/web/api/websocket/close_event/index.html b/files/es/web/api/websocket/close_event/index.html new file mode 100644 index 0000000000..da70792cdc --- /dev/null +++ b/files/es/web/api/websocket/close_event/index.html @@ -0,0 +1,72 @@ +--- +title: close +slug: Web/API/WebSocket/close_event +translation_of: Web/API/WebSocket/close_event +--- +<p>El manejador <code>close</code> es ejecutado cuando una conexión con un websocket es cerrada.</p> + +<h2 id="General_info">General info</h2> + +<dl> + <dt style="float: left; text-align: right; width: 120px;">Specification</dt> + <dd style="margin: 0 0 0 120px;"><a class="external" href="http://www.w3.org/TR/websockets/">WebSocket</a></dd> + <dt style="float: left; text-align: right; width: 120px;">Interface</dt> + <dd style="margin: 0 0 0 120px;">Event</dd> + <dt style="float: left; text-align: right; width: 120px;">Bubbles</dt> + <dd style="margin: 0 0 0 120px;">No</dd> + <dt style="float: left; text-align: right; width: 120px;">Cancelable</dt> + <dd style="margin: 0 0 0 120px;">No</dd> + <dt style="float: left; text-align: right; width: 120px;">Target</dt> + <dd style="margin: 0 0 0 120px;"><a href="/en-US/docs/WebSockets/WebSockets_reference/WebSocket" title="/en-US/docs/WebSockets/WebSockets_reference/WebSocket">WebSocket</a></dd> + <dt style="float: left; text-align: right; width: 120px;">Default Action</dt> + <dd style="margin: 0 0 0 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>El objetivo del evento (el objetivo superior en el árbol DOM).</td> + </tr> + <tr> + <td><code>type</code> {{readonlyInline}}</td> + <td>{{domxref("DOMString")}}</td> + <td>El tipo de evento.</td> + </tr> + <tr> + <td><code>bubbles</code> {{readonlyInline}}</td> + <td>{{jsxref("Boolean")}}</td> + <td>Si el evento normalmente burbujea o no.</td> + </tr> + <tr> + <td><code>cancelable</code> {{readonlyInline}}</td> + <td>{{jsxref("Boolean")}}</td> + <td>Si el evento es cancelable o no.</td> + </tr> + </tbody> +</table> + +<h2 id="Related_Events">Related Events</h2> + +<ul> + <li>{{event("open")}}</li> + <li>{{event("close")}}</li> + <li>{{event("error")}}</li> + <li>{{event("message")}}</li> +</ul> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/WebSockets/Writing_WebSocket_client_applications">Writing WebSocket client applications</a></li> +</ul> diff --git a/files/es/web/api/websocket/index.html b/files/es/web/api/websocket/index.html new file mode 100644 index 0000000000..b281258e99 --- /dev/null +++ b/files/es/web/api/websocket/index.html @@ -0,0 +1,356 @@ +--- +title: WebSocket +slug: Web/API/WebSocket +translation_of: Web/API/WebSocket +--- +<div>{{APIRef("Web Sockets API")}}{{SeeCompatTable}}</div> + +<div> </div> + +<div>El objeto WebSocket provee la API para la creación y administración de una conexión <a href="/en-US/docs/Web/API/WebSockets_API">WebSocket </a>a un servidor, así como también para enviar y recibir datos en la conexión.</div> + +<div> </div> + +<div>El constructor de WebSocket acepta un parámetro requerido y otro opcional.</div> + +<p> </p> + +<pre class="syntaxbox">WebSocket WebSocket( + in DOMString url, + in optional DOMString protocols +); + +WebSocket WebSocket( + in DOMString url, + in optional DOMString[] protocols +); +</pre> + +<p> </p> + +<dl> + <dt><code>url</code></dt> + <dd><code>La URL a la cual se conecta, debe ser la URL con la cual el servidor WebSocket debe responder.</code></dd> + <dt><code>protocols</code> {{optional_inline}}</dt> + <dd>Permite cualquier caso, desde un simple protocolo o un arreglo de cadenas de texto. Estas cadenas de texto son usadas para indicar subprotocolos, en los cuales un único servidor puede implementar múltiples subprotocolos para el WebSocket (por ejemplo, tu podrías esperar que un servido gestione diferentes tipos de interacciones dependiendo de un tipo específico de protocolo). Si no especificas un subprotocolo, se asume una cadena de texto vacía.</dd> + <dd> </dd> +</dl> + +<p>El constructor puede levantar excepciones:</p> + +<dl> + <dt><code>SECURITY_ERR</code></dt> + <dd>El puerto en el cual la conexión se realiza se encuentra bloqueado.</dd> +</dl> + +<h2 id="Revisión_de_Métodos">Revisión de Métodos</h2> + +<table class="standard-table"> + <tbody> + <tr> + <td><code>void <a href="#close()">close</a>(in optional unsigned long code, in optional DOMString reason);</code></td> + </tr> + <tr> + <td><code>void <a href="#send()">send</a>(in DOMString data);</code></td> + </tr> + </tbody> +</table> + +<h2 id="Atributos">Atributos</h2> + +<table class="standard-table"> + <tbody> + <tr> + <td class="header">Atributo</td> + <td class="header">Tipo</td> + <td class="header">Descricción</td> + </tr> + <tr> + <td><code>binaryType</code></td> + <td>{{DOMXref("DOMString")}}</td> + <td> + <p>Una cadena de texto indicando el tipo de dato binario que es transmitido por la conexión. Debe ser de cualquier manera "blob" si es se unas objetos DOM {{domxref("Blob")}} o bien "arraybuffer" {{jsxref("ArrayBuffer")}} si se usan otro tipo de objetos</p> + </td> + </tr> + <tr> + <td><code>bufferedAmount</code></td> + <td><code>unsigned long</code></td> + <td> + <p>La cantidad de bytes de data que pueden ser almacenadas en cola utilizando llamadas a {{manch("send")}} pero que aún no se han transmitido a la red. Este valor se reestablece a cero una vez que toda la información ha sido enviada. Este valor no vuelve a cero cuando la conexión es cerrada; si mantientes llamando {{manch("send")}}, continuará acumulandose. <strong>Solo de lectura.</strong></p> + </td> + </tr> + <tr> + <td><code>extensions</code></td> + <td>{{DOMXref("DOMString")}}</td> + <td> + <p>Las extensiones seleccionadas por el servidor. Esto solamente puede ser un string vacío o bien una lista de extensiones que es negociada por la conexión.</p> + </td> + </tr> + <tr> + <td><code>onclose</code></td> + <td>{{domxref("EventListener")}}</td> + <td> + <p>Un monitor de eventos que atiende una llamada cuando la conexión del WebSocket cambia a un estado CERRADO (CLOSED). El monitor recibe un <a href="/en-US/docs/Web/API/CloseEvent"><code>CloseEvent</code></a> llamado "cerrado".</p> + </td> + </tr> + <tr> + <td><code>onerror</code></td> + <td>{{domxref("EventListener")}}</td> + <td> + <p>Un monitor de eventos que es llamado cuando un error ocurre. Esto es un evento simple llamado "error"</p> + </td> + </tr> + <tr> + <td><code>onmessage</code></td> + <td>{{domxref("EventListener")}}</td> + <td> + <p>Un monitor de eventos que es llamado cuando un mensaje es recibido desde un servidor. El monitor recibe un objeto <a href="/en-US/docs/Web/API/MessageEvent"><code>MessageEvent </code></a>llamado "mensaje".</p> + </td> + </tr> + <tr> + <td><code>onopen</code></td> + <td>{{domxref("EventListener")}}</td> + <td>Un monitor de eventos que es llamado cuando el estado <code>readyState </code>de la conexión<code> Websocket </code>cambia a <code>OPEN. </code>Esto indica que la conexión está lista para enviar y recibir datos. El evento es uno simple con el nombre "open".</td> + </tr> + <tr> + <td><code>protocol</code></td> + <td>{{DOMXref("DOMString")}}</td> + <td>Una cadena indicando el nombre del sub-protocolo que el servidor ha seleccionado. Este puede ser una de las cadenas especificadas en el parámetro <code>protocols</code> cuando se ha creado el objeto Websocket.</td> + </tr> + <tr> + <td><code>readyState</code></td> + <td><code>unsigned short</code></td> + <td>El estado actual de la conexión. Este es uno de {{anch("Ready state constants")}}. <strong>Solo lectura.</strong></td> + </tr> + <tr> + <td><code>url</code></td> + <td>{{DOMXref("DOMString")}}</td> + <td>La URL como la resuelve el constructor. Esto siempre es una URL absoluta. <strong>Solo lectura.</strong></td> + </tr> + </tbody> +</table> + +<h2 id="Constantes">Constantes</h2> + +<h3 id="Ready_state_constants">Ready state constants</h3> + +<p>Estas constantes son usadas por el atributo <code>readyState</code> para describir el estado de la conexión <code>WebSocket</code>.</p> + +<table class="standard-table"> + <tbody> + <tr> + <td class="header">Constante</td> + <td class="header">Valor</td> + <td class="header">Descripción</td> + </tr> + <tr> + <td><code>CONNECTING</code></td> + <td><code>0</code></td> + <td>La conexión no está aún abierta.</td> + </tr> + <tr> + <td><code>OPEN</code></td> + <td><code>1</code></td> + <td>La conexión está abierta y lista para comunicar.</td> + </tr> + <tr> + <td><code>CLOSING</code></td> + <td><code>2</code></td> + <td>La conexión está siendo cerrada.</td> + </tr> + <tr> + <td><code>CLOSED</code></td> + <td><code>3</code></td> + <td>La conexión está cerrada o no puede ser abierta.</td> + </tr> + </tbody> +</table> + +<h2 id="Métodos">Métodos</h2> + +<h3 id="close()">close()</h3> + +<p>Cierra la conexión o intento de conexión del WebSocket si lo hay. Si la conexión ya está cerrada, no hace nada.</p> + +<pre class="syntaxbox">void close( + in optional unsigned short code, + in optional DOMString reason +); +</pre> + +<h4 id="Parámetros">Parámetros</h4> + +<dl> + <dt><code>code</code> {{optional_inline}}</dt> + <dd>Un valor numérico indicando el código de estado que explica porqué la conexión está siendo cerrada. Si no se especifica este parámetro, se asume un valor por defecto de 1000 (que indica un cierre normal por "transacción completa") . Ver <a href="/en-US/docs/Web/API/CloseEvent#Status_codes">códigos de estado</a> en la página de <a href="/en-US/docs/Web/API/CloseEvent">CloseEvent</a> para la lista de valores permitidos.</dd> + <dt><code>reason</code> {{optional_inline}}</dt> + <dd>Una cadena legible explicando porqué la conexión está siendo cerrada. Esta cadena no puede ser mayor que 123 bytes de texto UTF-8 (<strong>no</strong> caracteres)</dd> +</dl> + +<h4 id="Exceptions_thrown">Exceptions thrown</h4> + +<dl> + <dt><code>INVALID_ACCESS_ERR</code></dt> + <dd>Se ha especificado un código erróneo.</dd> + <dt><code>SYNTAX_ERR</code></dt> + <dd>La <code>reason</code> cadena es demasiado larga o continene caracteres no validos.</dd> +</dl> + +<div class="note"> +<p><strong>Note:</strong> En Gecko, este métido no soporta ningun parámetro antes de Gecko 8.0 {{geckoRelease("8.0")}}.</p> +</div> + +<h3 id="send()">send()</h3> + +<p>Transmite datos al servidor sobre la conexión WebSocket.</p> + +<pre class="syntaxbox">void send( + in DOMString data +); + +void send( + in ArrayBuffer data +); + +void send( + in Blob data +); +</pre> + +<h4 id="Parametros">Parametros</h4> + +<dl> + <dt><code>data</code></dt> + <dd>Una cadena de texto que enviar al servidor.</dd> +</dl> + +<h4 id="Excepciones">Excepciones</h4> + +<dl> + <dt><code>INVALID_STATE_ERR</code></dt> + <dd>La conexión no está abierta en este momento.</dd> + <dt><code>SYNTAX_ERR</code></dt> + <dd>La data tiene caracteres no válidos que no se pueden decodificar.</dd> +</dl> + +<div class="note"> +<p><strong>Note: </strong>La implementación del método <code>send() </code>en el motor de renderizado Gecko puede cambiar de la especificación en {{Gecko("6.0")}}; Gecko devuelve un <code>boolean </code>indicando si la conexión esta todavía abierta (y, por extensión, que los datos son encolados o trasmitidos satisfactoriamente). Esto ha sido corregido en {{Gecko("8.0")}}.</p> + +<p>A partir de {{Gecko("11.0")}}, implementa {{jsxref("ArrayBuffer")}} pero no tipos de datos {{domxref("Blob")}}.</p> +</div> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush: js">// Crea una nueva conexión. +const socket = new WebSocket('ws://localhost:8080'); + +// Abre la conexión +socket.addEventListener('open', function (event) { + socket.send('Hello Server!'); +}); + +// Escucha por mensajes +socket.addEventListener('message', function (event) { + console.log('Message from server', event.data); +});</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th>Specification</th> + <th>Status</th> + <th>Comment</th> + </tr> + <tr> + <td>{{SpecName("Websockets", "#the-websocket-interface", "WebSocket")}}</td> + <td>{{Spec2("Websockets")}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("2.0")}}<sup>[1]</sup></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Sub-protocol support</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("6.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Edge</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>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("7.0")}}<sup>[1]</sup></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Sub-protocol support</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("7.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Starting in Gecko 6.0 {{geckoRelease("6.0")}}, the constructor is prefixed; you will need to use <code>MozWebSocket()</code>: <code>var mySocket = new MozWebSocket("http://www.example.com/socketserver");</code></p> + +<p>The <code>extensions</code> attribute was not supported in Gecko until Gecko 8.0.</p> + +<p>Prior to Gecko 11.0 {{geckoRelease("11.0")}}, outbound messages sent using the <a href="#send()">send()</a> method were limited to 16 MB. They can now be up to 2 GB in size.</p> + +<h2 id="Referencias_adicionales">Referencias adicionales</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications">Writing WebSocket client applications</a></li> +</ul> diff --git a/files/es/web/api/websocket/onerror/index.html b/files/es/web/api/websocket/onerror/index.html new file mode 100644 index 0000000000..69a523b1b6 --- /dev/null +++ b/files/es/web/api/websocket/onerror/index.html @@ -0,0 +1,50 @@ +--- +title: WebSocket.onerror +slug: Web/API/WebSocket/onerror +tags: + - API + - Error + - Propiedad + - Referencia + - Web API + - WebSocket +translation_of: Web/API/WebSocket/onerror +--- +<p>{{APIRef("Web Sockets API")}}</p> + +<p>La propiedad <strong><code>WebSocket.onerror</code></strong>, del tipo {{domxref("EventHandler")}}, será llamada cuando se dé un error. Esta llamada recibirá un tipo {{domxref("Event")}} como argumento.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><em>aWebSocket</em>.onerror = function(event) { + console.error("Error en el WebSocket detectado:", event); +};</pre> + +<h2 id="Valor">Valor</h2> + +<p>Un {{domxref("EventListener")}}.</p> + +<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">Comentarios</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('HTML WHATWG', '#handler-websocket-onerror', 'WebSocket: onerror')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + + + +<p>{{Compat("api.WebSocket.onerror")}}</p> diff --git a/files/es/web/api/websockets_api/escribiendo_servidor_websocket/index.html b/files/es/web/api/websockets_api/escribiendo_servidor_websocket/index.html new file mode 100644 index 0000000000..333e8e8830 --- /dev/null +++ b/files/es/web/api/websockets_api/escribiendo_servidor_websocket/index.html @@ -0,0 +1,244 @@ +--- +title: Escribiendo un servidor WebSocket en C# +slug: Web/API/WebSockets_API/Escribiendo_servidor_WebSocket +tags: + - HTML5 + - Tutorial + - WebSockets +translation_of: Web/API/WebSockets_API/Writing_WebSocket_server +--- +<h2 id="Introducción">Introducción</h2> + +<p>Si deseas utilizar la API WebSocket, es conveniente si tienes un servidor. En este artículo te mostraré como puedes escribir uno en C#. Tú puedes hacer esto en cualquier lenguaje del lado del servidor, pero para mantener las cosas simples y más comprensibles, elegí el lenguaje de Microsoft<span style="line-height: 1.5;">.</span></p> + +<p>Este servidor se ajusta a <a href="http://tools.ietf.org/html/rfc6455" title="http://tools.ietf.org/html/rfc6455">RFC 6455</a> por lo que solo manejará las conexiones de Chrome version 16, Firefox 11, IE 10 and superiores.</p> + +<h2 id="Primeros_pasos">Primeros pasos</h2> + +<p>WebSocket se comunica a través de conexiones <a href="https://es.wikipedia.org/wiki/Transmission_Control_Protocol" title="https://es.wikipedia.org/wiki/Transmission_Control_Protocol">TCP (Transmission Control Protocol)</a>, afortunadamente C# tiene una clase <a href="http://msdn.microsoft.com/es-es/library/system.net.sockets.tcplistener.aspx" title="http://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener.aspx">TcpListener</a> la cual hace lo que su nombre sugiere. Esta se encuentra en el namespace <em>System.Net.Sockets</em>.</p> + +<div class="note"> +<p><span style="line-height: 1.572;">Es una buena idea usar la instrucción <code>using</code></span><span style="line-height: 1.572;"> para escribir menos. Eso significa que no tendrás que re escribir el namespace de nuevo en cada ocasión.</span></p> +</div> + +<h3 id="TcpListener">TcpListener</h3> + +<p>Constructor:</p> + +<pre class="brush: cpp">TcpListener(System.Net.IPAddress localaddr, int port)</pre> + +<p><code>localaddr</code> especifica la IP a escuchar y <code>port</code> especifica el puerto.</p> + +<div class="note"> +<p>Para crear un objeto <code>IPAddress</code> desde un <code>string</code>, usa el método estático <code>Parse</code> de <code>IPAddres.</code></p> +</div> + +<p><span style="line-height: 1.572;">Métodos</span><span style="line-height: 1.572;">:</span></p> + +<ul> + <li><code><span style="line-height: 1.572;">Start()</span></code></li> + <li><span style="line-height: 1.572;">S<code>ystem.Net.Sockets.<a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx" title="http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx">TcpClient</a> AcceptTcpClient()</code><br> + Espera por una conexión TCP, la acepta y la devuelve como un objeto TcpClient.</span></li> +</ul> + +<p><span style="line-height: 1.572;">Aquí está como utilizar lo que hemos aprendido:</span></p> + +<pre class="brush: cpp">using System.Net.Sockets; +using System.Net; +using System; + +class Server { + public static void Main() { + TcpListener server = new TcpListener(IPAddress.Parse("127.0.0.1"), 80); + + server.Start(); + Console.WriteLine("El server se ha iniciado en 127.0.0.1:80.{0}Esperando una conexión...", Environment.NewLine); + + TcpClient client = server.AcceptTcpClient(); + + Console.WriteLine("Un cliente conectado."); + } +} +</pre> + +<h3 id="TcpClient"><span style="line-height: 1.572;">TcpClient</span></h3> + +<p>Métodos:</p> + +<ul> + <li><code>System.Net.Sockets.<a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.aspx" title="http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.aspx">NetworkStream</a> GetStream()</code><br> + Obtiene el stream del canal de comunicación. Ambos lados del canal tienen capacidad de lectura y escritura.</li> +</ul> + +<p>Propiedades:</p> + +<ul> + <li><code>int Available</code><br> + Este es el número de bytes de datos que han sido enviados. El valor es cero hasta que <code><em>NetworkStream.DataAvailable</em></code> es <code><em>true</em></code>.</li> +</ul> + +<h3 id="NetworkStream">NetworkStream</h3> + +<p>Métodos:</p> + +<pre class="brush: cpp">Write(Byte[] buffer, int offset, int size)</pre> + +<p>Escribe bytes desde el <em>buffer;</em> el <em>offset</em> y el <em>size</em> determinan la longitud del mensaje.</p> + +<pre><span class="brush: cpp" style="line-height: 1.572;">Read(Byte[] buffer, int offset, int size)</span></pre> + +<p>Lee bytes al <em>buffer;</em> el <em>offset</em> y el <em>size </em>determinan la longitud del mensaje.</p> + +<p>Ampliemos nuestro ejemplo anterior.</p> + +<pre class="brush: cpp">TcpClient client = server.AcceptTcpClient(); + +Console.WriteLine("Un cliente conectado."); + +NetworkStream stream = client.GetStream(); + +//enter to an infinite cycle to be able to handle every change in stream +while (true) { + while (!stream.DataAvailable); + + Byte[] bytes = new Byte[client.Available]; + + stream.Read(bytes, 0, bytes.Length); +}</pre> + +<h2 id="Handshaking">Handshaking</h2> + +<p>Cuando un cliente se conecta al servidor, envía una solicitud GET para actualizar la conexión al WebSocket desde una simple petición HTTP. Esto es conocido como <em>handshaking</em>.</p> + +<p>Este código de ejemplo detecta el GET desde el cliente. Nota que esto bloqueará hasta los 3 primeros bytes del mensaje disponible. Soluciones alternativas deben ser investigadas para ambientes de producción.</p> + +<pre><code>using System.Text; +using System.Text.RegularExpressions; + +while(client.Available < 3) +{ + // wait for enough bytes to be available +} + +Byte[] bytes = new Byte[client.Available]; + +stream.Read(bytes, 0, bytes.Length); + +//translate bytes of request to string +String data = Encoding.UTF8.GetString(bytes); + +if (Regex.IsMatch(data, "^GET")) { + +} else { + +}</code></pre> + +<p>Esta respuesta es fácil de construir, pero puede ser un poco díficil de entender. La explicación completa del <em>handshake </em>al servidor puede encontrarse en <a href="https://developer.mozilla.org/es/docs/WebSockets-840092-dup/RFC%206455,%20section%204.2.2">RFC 6455, section 4.2.2</a>. Para nuestros propósitos, solo construiremos una respuesta simple.</p> + +<p>Debes:</p> + +<ol> + <li>Obtener el valor de "<em>Sec-WebSocket-Key" </em>sin espacios iniciales ni finales de el encabezado de la solicitud</li> + <li>Concatenarlo con "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"</li> + <li>Calcular el código SHA-1 y Base64</li> + <li>Escribe el valor <em>Sec-WebSocket-Accept</em> en el encabezado como parte de la respuesta HTTP.</li> +</ol> + +<pre class="brush: cpp">if (new Regex("^GET").IsMatch(data)) { + Byte[] response = Encoding.UTF8.GetBytes("HTTP/1.1 101 Switching Protocols" + Environment.NewLine + + "Connection: Upgrade" + Environment.NewLine + + "Upgrade: websocket" + Environment.NewLine + + "Sec-WebSocket-Accept: " + Convert.ToBase64String ( + SHA1.Create().ComputeHash ( + Encoding.UTF8.GetBytes ( + new Regex("Sec-WebSocket-Key: (.*)").Match(data).Groups[1].Value.Trim() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" + ) + ) + ) + Environment.NewLine + + Environment.NewLine); + + stream.Write(response, 0, response.Length); +} +</pre> + +<h2 id="Decoding_messages">Decoding messages</h2> + +<p>Luego de un <em>handshake</em> exitoso el cliente puede enviar mensajes al servidor, pero estos serán codificados.</p> + +<p>Si nosotros enviamos "MDN", obtendremos estos bytes:</p> + +<table> + <tbody> + <tr> + <td>129</td> + <td>131</td> + <td>61</td> + <td>84</td> + <td>35</td> + <td>6</td> + <td>112</td> + <td>16</td> + <td>109</td> + </tr> + </tbody> +</table> + +<p>- 129:</p> + +<table> + <thead> + <tr> + <th scope="col">FIN (¿Es el mensaje completo?)</th> + <th scope="col">RSV1</th> + <th scope="col">RSV2</th> + <th scope="col">RSV3</th> + <th scope="col">Opcode</th> + </tr> + </thead> + <tbody> + <tr> + <td>1</td> + <td>0</td> + <td>0</td> + <td>0</td> + <td>0x1=0001</td> + </tr> + </tbody> +</table> + +<p>FIN: Puedes enviar tu mensaje en marcos, pero ahora debe mantener las cosas simples.<br> + <span style="line-height: 1.572;">Opcode </span><em>0x1</em><span style="line-height: 1.572;"> significa que es un texto. </span><a href="http://tools.ietf.org/html/rfc6455#section-5.2" style="line-height: 1.572;" title="http://tools.ietf.org/html/rfc6455#section-5.2">Lista completa de Opcodes</a></p> + +<p>- 131:</p> + +<p>Si el segundo byte menos 128 se encuentra entre 0 y 125, esta es la longitud del mensaje. Si es 126, los siguientes 2 bytes (entero sin signo de 16 bits), si es 127, los siguientes 8 bytes (entero sin signo de 64 bits) son la longitud.</p> + +<div class="note"> +<p>Puedo tomar 128, porque el primer bit siempre es 1.</p> +</div> + +<p>- 61, 84, 35 y 6 son los bytes de la clave a decodificar. Cambian en cada oportunidad.</p> + +<p>- Los bytes codificados restantes son el mensaje<span style="line-height: 1.572;">.</span></p> + +<h3 id="Algoritmo_de_decodificación">Algoritmo de decodificación</h3> + +<p>byte decodificado = byte codificado XOR (posición del byte codificado Mod 4) byte de la clave</p> + +<p>Ejemplo en C#:</p> + +<pre class="brush: cpp">Byte[] decoded = new Byte[3]; +Byte[] encoded = new Byte[3] {112, 16, 109}; +Byte[] key = Byte[4] {61, 84, 35, 6}; + +for (int i = 0; i < encoded.Length; i++) { + decoded[i] = (Byte)(encoded[i] ^ key[i % 4]); +}</pre> + +<h2 id="Relacionado">Relacionado</h2> + +<ul> + <li><a href="/es/docs/WebSockets/Writing_WebSocket_servers">Escribiendo servidores WebSocket</a></li> +</ul> + +<div id="cke_pastebin" style="position: absolute; top: 2209.23px; width: 1px; height: 1px; overflow: hidden; left: -1000px;"> </div> diff --git a/files/es/web/api/websockets_api/escribiendo_servidores_con_websocket/index.html b/files/es/web/api/websockets_api/escribiendo_servidores_con_websocket/index.html new file mode 100644 index 0000000000..1261f75bec --- /dev/null +++ b/files/es/web/api/websockets_api/escribiendo_servidores_con_websocket/index.html @@ -0,0 +1,246 @@ +--- +title: Escribir servidores WebSocket +slug: Web/API/WebSockets_API/Escribiendo_servidores_con_WebSocket +translation_of: Web/API/WebSockets_API/Writing_WebSocket_servers +--- +<p>{{gecko_minversion_header("2")}}</p> + +<h2 id="Introducción">Introducción</h2> + +<p>Un servidor WebSocket es simplemente una aplicación TCP que escucha en cualquier puerto de un servidor que sigue un protocolo específico. La tarea de crear un servidor propio personalizado suele asustar a los desarrolladores, sin embargo puede resultar muy fácil implementar un servidor WebSocket en la plataforma que elijas.</p> + +<p>Un servidor WebSocket puede ser escrito en cualquier lenguaje de programación Server-Side que sea soporte <a href="https://en.wikipedia.org/wiki/Berkeley_sockets">Berkeley Sockets</a>, como por ejemplo C++ o Python o inclusive PHP y JavaScript para servidores. Este no va a ser un tutorial para ningún lenguaje espefícamente sino que te ayudará a escribir tu propio servidor.<br> + <br> + Necesitarás conocer como trabaja el protocolo HTTP y una experiencia intermedia en programación. Dependiendo de las capacidades de tu lenguaje puede ser necesario tener conocimientos en sockets TCP. Esta guía te dará el conocimiento necesario para escribir un servidor con WebSocket.</p> + +<div class="note"> +<p>Lea las últimas especificaciones oficiales de WebSocket <a href="http://datatracker.ietf.org/doc/rfc6455/?include_text=1">RFC 6455</a>. Las secciones 1 y 4-7 son especialmente interesantes para personas que deseen implementar servidores. La sección 10 abarca temas de seguridad y definitivamente deberías leerla antes de exponer tu servidor a la red.</p> +</div> + +<p>Un servidor WebSocket es explicado a un muy bajo nivel aquí. Los servidores WebSocket usualmente estan separados y especializados (por una cuestión de balance de cargas y otra razones prácticas), por lo tanto deberías usar un <a href="https://en.wikipedia.org/wiki/Reverse_proxy">Reverse Proxy</a> (semejante a un servidor HTTP común) casi siempre para detectar los Handshakes de WebSocket, preprocesarlos, y reenviar los datos de los clientes al servidor WebSocket real.<br> + </p> + +<h2 id="Paso_1_El_Handshake_del_WebSocket"><a name="Handshake">Paso 1: El Handshake del WebSocket </a></h2> + +<p>Antes que nada, el servidor debe escuchar las conexiones entrantes usando un socket TCP estandar. Dependiendo de tu plataforma, esto puede ser manejado por tí. Por ejemplo asumamos que tu servidor esta escuchando la dirección example.com en el puerto 8000, y tu socket en el servidor responde a la petición GET con /chat.</p> + +<div class="warning"> +<p><strong>Advertencia: </strong>El servidor puede escuchar cualquier puerto que elijas, pero si elijes un puerto diferente al 80 o 443 podría haber problemas con los firewalls y proxies. Suele suceder con el puerto 443 tambien pero para eso se necesita un conexión segura (TLS/SSL). También se debe aclarar que la mayoría de los navegadores (como Firefox 8 o superiores) no permiten conexiones a servidores WebSocket sin seguridad que se realicen desde páginas web con seguridad (HTTPS). </p> +</div> + +<p>El Handshake es el puente desde HTTP a WS. En el Handshake se negocian los detalles de la conexión y cualquier de las partes pueden abandonar el proceso antes de completar dicha conexión si los términos no son favorables. El servidor debe ser cuidadoso al analizar lo que el cliente pide, de lo contrario podrían introducirse problemas de seguridad.</p> + +<h3 id="Petición_de_Handshake_en_el_cliente">Petición de Handshake en el cliente</h3> + +<p>A pesar de que estamos creando un servidor, un cliente es quien tiene que comenzar el proceso de Handshake de WebSocket. Entonces tú tienes que saber cómo interpretar la petición del cliente. El cliente enviará una linda petición HTTP estandar que lucirá algo asi (la versión del HTTP debe ser 1.1 o mayor y el método debe ser GET):</p> + +<pre>GET /chat HTTP/1.1 +Host: example.com:8000 +<strong>Upgrade: websocket</strong> +<strong>Connection: Upgrade</strong> +Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== +Sec-WebSocket-Version: 13 + +</pre> + +<p>El cliente puede solicitar aquí extensiones y/o sub protocolos; vea <a href="#Miscellaneous">Misceláneos</a> para más detalles. También, cabeceras comunes como <code>User-Agent</code>, <code>Referer</code>, <code>Cookie</code>, or cabeceras de autenticación podrían ser incluidos. Haz lo que quieras con ellos; no pertencen a WebSocket. También puedes ignorarlos. En muchas configuraciones comunes, un proxy inverso ya ha tratado con ellos.</p> + +<p>Si alguna cabecera no se entiende o posee un valor incorrecto, el servidor debe responder "<a href="https://developer.mozilla.org/es/docs/HTTP/Response_codes#400">400 Bad Request</a>" e inmediatamente cerrar la conexión. Normalmente, también puede dar la razón porque falló el <em>handshake</em> en el cuerpo de la respuesta HTTP, pero el mensaje podría no ser mostrado (el browser no lo muestra). Si el servidor no comprende que la versión del WebSockets, debería enviar una cabecera <code>Sec-WebSocket-Version</code> que contenga la(s) versión(es) no entendidas. (Esta guía explica v13, la más nueva). Ahora, vamos a ver la cabecera más curiosa, <code>Sec-WebSocket-Key</code>.</p> + +<div class="note"> +<p><strong>Tip:</strong> Todos los <strong>navegadores</strong> deben enviar una <a href="https://developer.mozilla.org/es/docs/HTTP/Access_control_CORS#Origin"><code>cabecera Origin</code></a>. Tu puedes usar esta cabecera por seguridad (revisando por el mismo origen, listas blancas/ listas negras, etc.) y enviar un <a href="https://developer.mozilla.org/es/docs/HTTP/Response_codes#403">403 Forbidden</a> si no te gusta lo que ves. Sin embargo, se advierte que los agentes no navegadores pueden enviar un falso <code>Origin</code>. La mayoría de las aplicaciones rechazaran las solicitudes sin esta cabecera.</p> +</div> + +<div class="note"> +<p><strong>Tip:</strong> The request-uri (<code>/chat</code> here) has no defined meaning in the spec. So many people cleverly use it to let one server handle multiple WebSocket applications. For example, <code>example.com/chat</code> could invoke a multiuser chat app, while <code>/game</code> on the same server might invoke a multiplayer game.</p> +</div> + +<div class="note"> +<p><strong>Note:</strong> <a href="https://developer.mozilla.org/en-US/docs/HTTP/Response_codes">Regular HTTP status codes</a> can only be used before the handshake. After the handshake succeeds, you have to use a different set of codes (defined in section 7.4 of the spec).</p> +</div> + +<h3 id="Respuesta_de_Handshake_del_servidor">Respuesta de Handshake del servidor</h3> + +<p>Después de la petición, el servidor debería enviar una linda respuesta (aunque todavía en formato HTTP) que se verá asi (hay que recordar que la cabecera termina con \r \n y agrega un \r \n extra después del último):</p> + +<pre><strong>HTTP/1.1 101 Switching Protocols</strong> +Upgrade: websocket +Connection: Upgrade +<strong>Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= + +</strong></pre> + +<p>Adicionalmente, el servidor puede decidir respecto de las solicitudes "extension/subprotocol" en este punto (ver <a href="#Miscellaneous">Miscelláneos</a> para más detalles). La cabecera <code>Sec-WebSocket-Accept</code> es interesante. El servidor debe derivarla a partir de la cabecera <code>Sec-WebSocket-Key</code> enviada anteriormente por el cliente. Para lograr esto se deben concatenar la cabecera del cliente<span style="line-height: 1.5em;"> </span><code style="font-size: 14px;">Sec-WebSocket-Key</code><span style="line-height: 1.5em;"> y el string "</span><code style="font-size: 14px;">258EAFA5-E914-47DA-95CA-C5AB0DC85B11</code><span style="line-height: 1.5em;">" (es un "</span><a href="https://en.wikipedia.org/wiki/Magic_string" style="line-height: 1.5em;">magic string</a><span style="line-height: 1.5em;">"), calcular el </span><a href="https://en.wikipedia.org/wiki/SHA-1" style="line-height: 1.5em;">hash SHA-1</a><span style="line-height: 1.5em;"> del resultado y devolver el string codificado en</span><span style="line-height: 1.5em;"> </span><a href="https://en.wikipedia.org/wiki/Base64" style="line-height: 1.5em;">base64</a><span style="line-height: 1.5em;"> de este hash.</span></p> + +<div class="note"> +<p><strong>FYI:</strong> Este aparentemente complicado e innecesario proceso se realiza de manera que sea obvio para el cliente si el servidor soporta o noWebSockets. Esto es importante de realizar, ya que podrían crearse problemas de seguridad si el servidor acepta conexiones WebSockets pero interpreta los datos como solicitudes HTTP.</p> +</div> + +<p>Así, si la cabecera <code>Sec-WebSocket-Key</code> era "<code>dGhlIHNhbXBsZSBub25jZQ==</code>", la correspondiente respuesta <code>Sec-WebSocket-Accept</code> será "<code>s3pPLMBiTxaQ9kYGzzhZRbK+xOo=</code>". Una vez que el servidor envía estas cabeceras, el "handshake" se considera completo y puedes comenzar a intercambiar datos.</p> + +<div class="note"> +<p>El servidor puede enviar otras cabeceras como Set-Cookie, o solicitar autenticación o redirigir mediante otros status codes antes de responder al handshake.</p> +</div> + +<h3 id="Llevando_registro_de_los_clientes">Llevando registro de los clientes</h3> + +<p>Esto no está directamente relacionado con el protocolo WebSocket, pero no está de más mencionarlo: tu servidor debe llevar el registro de los sockets de los clientes, de manera de no realizar handshakes constantemente con los clientes que ya han completado este proceso. La misma dirección IP cliente puede intentar conectarse múltiples veces (pero el servidor puede denegar la conexión si se intentan demasiadas conexiones con el objetivo de evitar ataques <a href="https://en.wikipedia.org/wiki/Denial_of_service">ataques DoS</a>).</p> + +<h2 id="Paso_2_Intercambiando_Data_Frames">Paso 2: Intercambiando Data Frames</h2> + +<p>Tanto el cliente como el servidor puede decidir enviar un mensaje en cualquier momento — ese es el encanto de los WebSockets. Sin embargo, extraer información de esos denominados "frames" o tramas de datos no es una experiencia muy mágica. Aunque todos los frames siguen el mismo formato específico, los datos que van del cliente al servidor se enmascaran utilizando el <a href="https://en.wikipedia.org/wiki/XOR_cipher">cifrado XOR</a> (con una clave de 32 bits). La sección 5 de la especificación describe esto en detalle.</p> + +<h3 id="Formato">Formato</h3> + +<p>Cada trama de datos (desde el cliente al servidor o viceversa) sigue este mismo formato:</p> + +<pre style="float: left; margin-right: 20px;"> 0 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 ++-+-+-+-+-------+-+-------------+-------------------------------+ +|F|R|R|R| opcode|M| Payload len | Extended payload length | +|I|S|S|S| (4) |A| (7) | (16/64) | +|N|V|V|V| |S| | (if payload len==126/127) | +| |1|2|3| |K| | | ++-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - + +| Extended payload length continued, if payload len == 127 | ++ - - - - - - - - - - - - - - - +-------------------------------+ +| |Masking-key, if MASK set to 1 | ++-------------------------------+-------------------------------+ +| Masking-key (continued) | Payload Data | ++-------------------------------- - - - - - - - - - - - - - - - + +: Payload Data continued ... : ++ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +| Payload Data continued ... | ++---------------------------------------------------------------+</pre> + +<p>Los RSV1-3 se pueden ignorar, son para las extensiones.</p> + +<p>El bit MASK simplemente indica si el mensaje está codificado. Los mensajes del cliente deben estar enmascarados, por lo que tu servidor debe esperar que valga 1. (De hecho, la <a href="http://tools.ietf.org/html/rfc6455#section-5.1">sección 5.1 de las espeficicaciones</a> dice que tu servidor debe desconectarse de un cliente si ese cliente envía un mensaje sin enmascarar). Cuando se envía una trama al cliente, no lo ocultes y no pongas el bit de la máscara. Te explicaremos el enmascaramiento más tarde. <em>Nota: Tienes que enmascarar los mensajes incluso cuando uses un socket seguro.</em></p> + +<p>El campo opcode define cómo interpretar los datos de la carga útil:<code style="font-style: normal; line-height: 1.5;">0x0</code><span style="line-height: 1.5;"> </span><span style="line-height: 1.5;">para continuar,</span><span style="font-family: courier new,andale mono,monospace; line-height: 1.5;"> </span><code style="font-style: normal; line-height: 1.5;">0x1</code><span style="line-height: 1.5;"> para texto (que siempre se codifica con UTF-8), </span><code style="font-style: normal; line-height: 1.5;">0x2</code><span style="line-height: 1.5;"> para datos binarios, otros llamados "códigos de control" se explican más tarde. En esta versión de WebSockets, de <code>0x3</code> a <code>0x7</code> y de <code>0xB</code> a <code>0xF</code> no tienen significado.</span></p> + +<p>El bit FIN indica si este es el último mensaje de una serie. Si es 0, el servidor seguirá escuchando más partes del mensaje; de lo contrario, el servidor debería considerar el mensaje entregado. Más sobre esto después.</p> + +<h3 id="Decoding_Payload_Length">Decoding Payload Length</h3> + +<p>To read the payload data, you must know when to stop reading. That's why the payload length is important to know. Unfortunately, this is somewhat complicated. To read it, follow these steps:</p> + +<ol> + <li>Read bits 9-15 (inclusive) and interpret that as an unsigned integer. If it's 125 or less, then that's the length; you're <strong>done</strong>. If it's 126, go to step 2. If it's 127, go to step 3.</li> + <li>Read the next 16 bits and interpret those as an unsigned integer. You're <strong>done</strong>.</li> + <li>Read the next 64 bits and interpret those as an unsigned integer. You're <strong>done</strong>.</li> +</ol> + +<h3 id="Reading_and_Unmasking_the_Data">Reading and Unmasking the Data</h3> + +<p>If the MASK bit was set (and it should be, for client-to-server messages), read the next 4 octets (32 bits); this is the masking key. <span style="line-height: 1.5;">Once the payload length and masking key is decoded, you can go ahead and read that number of bytes from the socket. Let's call the data <strong>ENCODED</strong>, and the key <strong>MASK</strong>. To get <strong>DECODED</strong>, loop through the octets (bytes a.k.a. characters for text data) of <strong>ENCODED</strong> and XOR the octet with the (i modulo 4)th octet of MASK. In pseudo-code (that happens to be valid JavaScript):</span></p> + +<pre>var DECODED = ""; +for (var i = 0; i < ENCODED.length; i++) { + DECODED[i] = ENCODED[i] ^ MASK[i % 4]; +<span style="line-height: 1.5;">}</span></pre> + +<p><span style="line-height: 1.5;">Now you can figure out what <strong>DECODED</strong> means depending on your application.</span></p> + +<h3 id="Message_Fragmentation">Message Fragmentation</h3> + +<p>The FIN and opcode fields work together to send a message split up into separate frames. This is called message fragmentation. Fragmentation is only available on opcodes <code>0x0</code> to <code>0x2</code>.</p> + +<p><span style="line-height: 1.5;">Recall that the opcode tells what a frame is meant to do. If it's <code>0x1</code>, the payload is text. If it's <code>0x2</code>, the payload is binary data.</span><span style="line-height: 1.5;"> However, if it's </span><code style="font-style: normal; line-height: 1.5;">0x0,</code><span style="line-height: 1.5;"> the frame is a continuation frame. This means the server should concatenate the frame's payload to the last frame it received from that client.</span><span style="line-height: 1.5;"> Here is a rough sketch, in which a server reacts to a client sending text messages. The first message is sent in a single frame, while the second message is sent across three frames. FIN and opcode details are shown only for the client:</span></p> + +<pre style="font-size: 14px;"><strong>Client:</strong> FIN=1, opcode=0x1, msg="hello" +<strong>Server:</strong> <em>(process complete message immediately) </em>Hi. +<strong>Client:</strong> FIN=0, opcode=0x1, msg="and a" +<strong>Server:</strong> <em>(listening, new message containing text started)</em> +<strong>Client:</strong> FIN=0, opcode=0x0, msg="happy new" +<strong>Server:</strong> <em>(listening, payload concatenated to previous message)</em> +<strong>Client:</strong> FIN=1, opcode=0x0, msg="year!" +<strong>Server:</strong> <em>(process complete message) </em>Happy new year to you too!</pre> + +<p>Notice the first frame contains an entire message (has <code>FIN=1</code> and <code>opcode!=0x0</code>), so the server can process or respond as it sees fit. The second frame sent by the client has a text payload (<code>opcode=0x1</code>), but the entire message has not arrived yet (<code>FIN=0</code>). All remaining parts of that message are sent with continuation frames (<code>opcode=0x0</code>), and the final frame of the message is marked by <code>FIN=1</code>. <a href="http://tools.ietf.org/html/rfc6455#section-5.4">Section 5.4 of the spec</a> describes message fragmentation.</p> + +<h2 id="Pings_and_Pongs_The_Heartbeat_of_WebSockets">Pings and Pongs: The Heartbeat of WebSockets</h2> + +<p>At any point after the handshake, either the client or the server can choose to send a ping to the other party. When the ping is received, the recipient must send back a pong as soon as possible. You can use this to make sure that the client is still connected, for example.</p> + +<p>A ping or pong is just a regular frame, but it's a <strong>control frame</strong>. Pings have an opcode of <code>0x9</code>, and pongs have an opcode of <code>0xA</code>. When you get a ping, send back a pong with the exact same Payload Data as the ping (for pings and pongs, the max payload length is 125). You might also get a pong without ever sending a ping; ignore this if it happens.</p> + +<div class="note"> +<p>If you have gotten more than one ping before you get the chance to send a pong, you only send one pong.</p> +</div> + +<h2 id="Step_4_Closing_the_connection">Step 4: Closing the connection</h2> + +<p>To close a connection either the client or server can send a control frame with data containing a specified control sequence to begin the closing handshake (detailed in <a href="http://tools.ietf.org/html/rfc6455#section-5.5.1">Section 5.5.1</a>). Upon receiving such a frame, the other peer sends a Close frame in response. The first peer then closes the connection. Any further data received after closing of connection is then discarded. </p> + +<h2 id="Miscellaneous_2"><a name="Miscellaneous">Miscellaneous</a></h2> + +<div class="note"> +<p>WebSocket codes, extensions, subprotocols, etc. are registered at the <a href="http://www.iana.org/assignments/websocket/websocket.xml">IANA WebSocket Protocol Registry</a>.</p> +</div> + +<p>WebSocket extensions and subprotocols are negotiated via headers during <a href="#Handshake">the handshake</a>. Sometimes extensions and subprotocols seem too similar to be different things, but there is a clear distinction. Extensions control the WebSocket <strong>frame</strong> and <strong>modify</strong> the payload, while subprotocols structure the WebSocket <strong>payload</strong> and <strong>never modify</strong> anything. Extensions are optional and generalized (like compression); subprotocols are mandatory and localized (like ones for chat and for MMORPG games).</p> + +<h3 id="Extensions">Extensions</h3> + +<div class="note"> +<p><strong>This section needs expansion. Please edit if you are equipped to do so.</strong></p> +</div> + +<p>Think of an extension as compressing a file before e-mailing it to someone. Whatever you do, you're sending the <em>same</em> data in different forms. The recipient will eventually be able to get the same data as your local copy, but it is sent differently. That's what an extension does. WebSockets defines a protocol and a simple way to send data, but an extension such as compression could allow sending the same data but in a shorter format.</p> + +<div class="note"> +<p>Extensions are explained in sections 5.8, 9, 11.3.2, and 11.4 of the spec.</p> +</div> + +<p><em>TODO</em></p> + +<h3 id="Subprotocols">Subprotocols</h3> + +<p>Think of a subprotocol as a custom <a href="https://en.wikipedia.org/wiki/XML_schema">XML schema</a> or <a href="https://en.wikipedia.org/wiki/Document_Type_Definition">doctype declaration</a>. You're still using XML and its syntax, but you're additionally restricted by a structure you agreed on. WebSocket subprotocols are just like that. They do not introduce anything fancy, they just establish structure. Like a doctype or schema, both parties must agree on the subprotocol; unlike a doctype or schema, the subprotocol is implemented on the server and cannot be externally refered to by the client.</p> + +<div class="note"> +<p>Subprotocols are explained in sections 1.9, 4.2, 11.3.4, and 11.5 of the spec.</p> +</div> + +<p>A client has to ask for a specific subprotocol. To do so, it will send something like this <strong>as part of the original handshake</strong>:</p> + +<pre>GET /chat HTTP/1.1 +... +Sec-WebSocket-Protocol: soap, wamp + +</pre> + +<p>or, equivalently:</p> + +<pre>... +Sec-WebSocket-Protocol: soap +Sec-WebSocket-Protocol: wamp + +</pre> + +<p>Now the server must pick one of the protocols that the client suggested and it supports. If there are more than one, send the first one the client sent. Imagine our server can use both <code>soap</code> and <code>wamp</code>. Then, in the response handshake, it'll send:</p> + +<pre>Sec-WebSocket-Protocol: soap + +</pre> + +<div class="warning"> +<p>The server can't send more than one <code>Sec-Websocket-Protocol</code> header.<br> + <span style="line-height: 1.5;">If the server doesn't want to use a</span><span style="line-height: 1.5;">ny subprotocol, </span><strong style="line-height: 1.5;">it shouldn't send any <code>Sec-WebSocket-Protocol</code> header</strong><span style="line-height: 1.5;">. Sending a blank header is incorrect.<br> + The client may close the connection if it doesn't get the subprotocol it wants.</span></p> +</div> + +<p>If you want your server to obey certain subprotocols, then naturally you'll need extra code on the server. Let's imagine we're using a subprotocol <code>json</code>. In this subprotocol, all data is passed as <a href="https://en.wikipedia.org/wiki/JSON">JSON</a>. If the client solicits this protocol and the server wants to use it, the server will need to have a JSON parser. Practically speaking, this will be part of a library, but the server will need to pass the data around.</p> + +<div class="note"> +<p><strong>Tip:</strong> To avoid name conflict, it's recommended to make your subprotocol name part of a domain string. If you are building a custom chat app that uses a proprietary format exclusive to Example Inc., then you might use this: <code>Sec-WebSocket-Protocol: chat.example.com</code>. For different versions, a widely-used method is to add a <code>/</code> followed by the version number, like <code>chat.example.com/2.0</code>. Note that this isn't required, it's just an optional convention, and you can use any string you wish.</p> +</div> + +<h2 id="Related">Related</h2> + +<ul> + <li><a href="/en-US/docs/WebSockets/Writing_WebSocket_server" title="/en-US/docs/WebSockets/Writing_WebSocket_server">Tutorial: Websocket server in C#</a></li> + <li><a href="/en-US/docs/WebSockets/Writing_WebSocket_client_applications">Writing WebSocket client applications</a></li> + <li><a href="/en-US/docs/WebSockets/WebSocket_Server_Vb.NET">Tutorial: Websocket server in VB.NET</a></li> +</ul> diff --git a/files/es/web/api/websockets_api/index.html b/files/es/web/api/websockets_api/index.html new file mode 100644 index 0000000000..e1c339558f --- /dev/null +++ b/files/es/web/api/websockets_api/index.html @@ -0,0 +1,172 @@ +--- +title: WebSockets +slug: Web/API/WebSockets_API +translation_of: Web/API/WebSockets_API +--- +<p>{{DefaultAPISidebar("Websockets API")}}</p> + +<p><strong>WebSockets </strong>es una tecnología avanzada que hace posible abrir una sesión de comunicación interactiva entre el navegador del usuario y un servidor. Con esta API, puede enviar mensajes a un servidor y recibir respuestas controladas por eventos sin tener que consultar al servidor para una respuesta.</p> + +<h2 id="Interfaces">Interfaces</h2> + +<dl> + <dt><a href="/en-US/docs/Web/API/WebSocket" title="en/WebSockets/WebSockets reference/WebSocket"><code>WebSocket</code></a></dt> + <dd>El interfaz principal para conectar a un servidor Websocket y así enviar y recibir datos a través de la conexión.</dd> + <dt><code><a href="/en-US/docs/Web/API/CloseEvent" title="en/WebSockets/WebSockets reference/CloseEvent">CloseEvent</a></code></dt> + <dd>El evento enviado por el objeto WebSocket cuando se cierra la conexión.</dd> + <dt><a href="/en-US/docs/Web/API/MessageEvent" title="en/WebSockets/WebSockets reference/MessageEvent"><code>MessageEvent</code></a></dt> + <dd>El evento enviado por el objeto WebSocket cuando se recibe un mensaje enviado desde el servidor.</dd> +</dl> + +<div class="section"> +<h2 class="Tools" id="Tools" name="Tools">Herramientas</h2> + +<ul> + <li><a class="external" href="http://socket.io" title="http://socket.io/">Socket.IO</a>: Una poderosa API WebSocket multi-plataforma para <a class="external" href="http://nodejs.org" title="http://nodejs.org/">Node.js</a>.</li> + <li><a class="link-https" href="https://github.com/Worlize/WebSocket-Node" title="https://github.com/Worlize/WebSocket-Node">WebSocket-Node</a>: Un servidor WebSocket API implementado para <a class="external" href="http://nodejs.org" title="http://nodejs.org/">Node.js</a>.</li> + <li><a href="http://www.totaljs.com">Total.js</a>: Framework para aplicaciones web para <a href="http://www.nodejs.org">Node.js</a> (Ejemplo: <a href="https://github.com/totaljs/examples/tree/master/websocket">WebSocket chat</a>)</li> + <li><a href="https://www.npmjs.com/package/faye-websocket">Faye</a>: Un servidor y cliente <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API">WebSocket</a> (conexión bidireccional) y <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventSource/">EventSource</a> (conexión unidireccional) para <a class="external" href="http://nodejs.org" title="http://nodejs.org/">Node.js</a>.</li> +</ul> + +<h2 class="Related_Topics" id="Related_Topics" name="Related_Topics">Temas RELACIONADOS</h2> + +<ul> + <li><a href="/en-US/docs/AJAX" title="AJAX">AJAX</a>, <a href="/en-US/docs/JavaScript" title="JavaScript">JavaScript</a></li> +</ul> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a class="external" href="http://tools.ietf.org/html/rfc6455">RFC 6455 - The WebSocket Protocol</a></li> + <li><a class="external" href="http://www.w3.org/TR/websockets/">WebSocket API Specification</a></li> + <li><a href="/en-US/docs/Server-sent_events" title="Server-sent_events">Server-Sent Events</a></li> +</ul> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Versión -76 {{obsolete_inline}}</td> + <td>6</td> + <td>{{CompatGeckoDesktop("2.0")}}</td> + <td>{{CompatNo}}</td> + <td>11.00 (disabled)</td> + <td>5.0.1</td> + </tr> + <tr> + <td>Protocolo versión 7</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop("6.0")}}<br> + {{property_prefix("Moz")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>Protocolo versión 10</td> + <td>14</td> + <td>{{CompatGeckoDesktop("7.0")}}<br> + {{property_prefix("Moz")}}</td> + <td>HTML5 Labs</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>RFC 6455 (IETF Draft 17)</td> + <td>16</td> + <td>{{CompatGeckoDesktop("11.0")}}</td> + <td>10</td> + <td>12.10</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Versión -76 {{obsolete_inline}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Protocolo versión 7</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Protocolo versión 8 (IETF draft 10)</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("7.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>RFC 6455 (IETF Draft 17)</td> + <td>16</td> + <td>{{CompatGeckoDesktop("11.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>12.10</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h3 id="Notas_para_Gecko">Notas para Gecko</h3> + +<p>La compatibilidad de Firefox con WebSockets ha seguido la evolución de la especificación WebSocket. Firefox 6 implementa la versión 7 del protocolo subyacente, mientras que Firefox 7 implementa la versión 8 (como especifica IETF draft 10). Firefox mobile tuvo compatibilidad con WebSocket en Firefox mobile 7.0.</p> + +<h4 id="Gecko_6.0">Gecko 6.0</h4> + +<p>Prior to Gecko 6.0 {{geckoRelease("6.0")}}, there was, incorrectly, a <code>WebSocket</code> object that some sites were thinking implied that <code>WebSocket</code> services were not prefixed; this object has been renamed to <code>MozWebSocket</code>.</p> + +<h4 id="Gecko_7.0">Gecko 7.0</h4> + +<p>Starting in Gecko 7.0 {{geckoRelease("7.0")}}, the <code>network.websocket.max-connections</code> preference is used to determine the maximum number of WebSocket connections that can be open at a time. The default value is 200.</p> + +<h4 id="Gecko_8.0">Gecko 8.0</h4> + +<p>Starting in Gecko 8.0 {{geckoRelease("8.0")}}, the deflate-stream extension to the WebSocket protocol has been disabled, since it's been deprecated from the specification drafts. This resolves incompatibilities with some sites.</p> + +<h4 id="Gecko_11.0">Gecko 11.0</h4> + +<p>Prior to Gecko 11.0, both incoming and outgoing messages were limited to 16 MB in size. They may now be up to 2 GB in size. Note, however, that memory limitations (especially on mobile devices) make that a theoretical maximum, not a practical one. In reality, transfers of that size will fail on devices that don't have enough memory.</p> + +<p>Additionally, ArrayBuffer send and receive support for binary data has been implemented.</p> + +<p>Starting in Gecko 11.0, the WebSocket API is no longer prefixed.</p> + +<div class="warning"><strong>Warning:</strong> Among other things, a key reason WebSockets was disabled by default in Firefox 4 and 5 is the discovery of a <a class="external" href="http://www.ietf.org/mail-archive/web/hybi/current/msg04744.html" title="http://www.ietf.org/mail-archive/web/hybi/current/msg04744.html">security issue in the protocol's design</a>. This was fixed in Firefox 6 by implementing a newer version of the protocol that corrects the problem.</div> + +<div>{{HTML5ArticleTOC}}</div> diff --git a/files/es/web/api/websockets_api/writing_websocket_client_applications/index.html b/files/es/web/api/websockets_api/writing_websocket_client_applications/index.html new file mode 100644 index 0000000000..3dda33b8da --- /dev/null +++ b/files/es/web/api/websockets_api/writing_websocket_client_applications/index.html @@ -0,0 +1,197 @@ +--- +title: Escribiendo aplicaciones con WebSockets +slug: Web/API/WebSockets_API/Writing_WebSocket_client_applications +tags: + - Guía WebSocket WebSockets +translation_of: Web/API/WebSockets_API/Writing_WebSocket_client_applications +--- +<p>{{ draft() }}</p> + +<p><span style="background-clip: initial; font-family: arial,sans-serif; font-size: 10.5pt; line-height: 115%;">WebSockets es una tecnología basada en el protocolo ws, este hace posible establecer una conexión continua full-duplex, entre un cliente y servidor. Un cliente websocket podría ser el navegador del usuario, pero el protocolo es una plataforma independiente.</span></p> + +<div class="note"><strong>Nota:</strong> Tenemos un ejemplo funcional de un sistema de chat/servidor usado para ejemplos de código que estará disponible una vez nuestra infraestructura esté en posición de hospedar ejemplos de WebSocket apropiadamente.</div> + +<h2 id="Disponibilidad_de_WebSockets">Disponibilidad de WebSockets</h2> + +<p>La API de WebSocket esta disponible para el código JavaScript cuyo alcance DOM sea un objeto {{ domxref("Window") }} o cualquier objeto implementando {{ domxref("WorkerUtils") }}; si es así, puedes usarlos desde los Web Workers.</p> + +<div class="note"><strong>Nota: </strong>La API de WebSockets (y el protocolo subyacente) continúan en activo desarrollo, y existen muchos problemas de compatibilidad entre los navegadores en este momento (e inclusive entre los diferentes lanzamientos del mismo navegador).</div> + +<h2 id="Creando_un_Objeto_WebSocket">Creando un Objeto WebSocket</h2> + +<p>Para comunicarse utilizando el protocolo webSocket, necesitarás crear un objeto WebSocket; este automáticamente abrirá una conexión temporal al servidor.</p> + +<p>El constructor WebSocket requiere de un parámetro obligatorio y otro opcional:</p> + +<pre>WebSocket WebSocket( + in DOMString url, + in optional DOMString protocols +); + +WebSocket WebSocket( + in DOMString url, + in optional DOMString[] protocols +); +</pre> + +<dl> + <dt><code>url</code></dt> + <dd>La url a la que conectar; esta es la URL a la que el WebSocket responde.</dd> + <dt><code>protocols</code> {{ optional_inline() }}</dt> + <dd>Un string o array de strings con el/los protocolos a usar. Estos strings son usados para indicar sub-protocolos, para que el servidor pueda implementar multiples sub-protocolos WebSocket (por ejemplo, puede necesitar usar un servidor para manejar diferentes tipos de interacciones dependiendo del protocolo especificado). Si no se especifica el string como protocolo, se asumirá un string vacío.</dd> +</dl> + +<p>El constructor puede lanzar excepciones:</p> + +<dl> + <dt><code>SECURITY_ERR</code></dt> + <dd>El puerto de la conexión está siendo bloqueado.</dd> +</dl> + +<dl> +</dl> + +<h3 id="Errores_de_conexión">Errores de conexión</h3> + +<p>Si ocurre un error al intentar conectar, lo primero que recibiremos será un evento con el nombre de "error" en el objeto <code><a href="/en/WebSockets/WebSockets_reference/WebSocket" title="WebSocket">WebSocket</a> </code>(de este modo se invoca el manejador <code>onerror</code>), y luego <a href="/en/WebSockets/WebSockets_reference/CloseEvent" title="CloseEvent"><code>CloseEvent</code></a> es enviado al objeto <code><a href="/en/WebSockets/WebSockets_reference/WebSocket" title="WebSocket">WebSocket</a> </code>(de este modo se invoca el manejador <code>onclose</code>), para indicar la razón del cierre de la conexión.</p> + +<p>A partir de Firefox 11, es normal recibir un mensaje de error descriptivo en la consola de la plataforma Mozilla, y un código de cierre como está definido en el <a class="external" href="http://tools.ietf.org/html/rfc6455#section-7.4" title="RFC 6455 Section 7.4">RFC 6455, Section 7.4</a> a través de un <a href="/en/WebSockets/WebSockets_reference/CloseEvent" title="CloseEvent"><code>CloseEvent</code></a>.</p> + +<h3 id="Ejemplos">Ejemplos</h3> + +<p>En este ejemplo de crea un nuevo WebSocket, conectandose al servidor <code><span class="nowiki">ws://www.example.com/socketserver</span></code>. El nombre del protocolo "protocolOne" es el utilizado para la consulta del socket, aunque puede ser omitido.</p> + +<pre class="brush: js">var exampleSocket = new WebSocket("ws://www.example.com/socketserver", "protocolOne"); +</pre> + +<p>Como respuesta, <code>exampleSocket</code>.<code>readyState</code> es <code>CONNECTING</code>. El <code>readyState</code> será <code>OPEN</code> una vez que la conexión este lista para transferir información.</p> + +<p>Si se quiere establecer una conexión que soporte varios protocolos, se puede establecer un array de protocolos:</p> + +<pre class="brush: js">var exampleSocket = new WebSocket("ws://www.example.com/socketserver", ["protocolOne", "protocolTwo"]); +</pre> + +<p>Una vez que la conexión este establecida (<code>readyState</code> estará <code>OPEN</code>), <code>exampleSocket.protocol</code> te dirá qué protocolo ha seleccionado el servidor.</p> + +<p>En los ejemplos anteriores <code>ws</code> sustituye <code>http</code>, y de igual manera <code>wss</code> sustituye a <code>https</code>. Al crear un WebSocket se hace uso del mecanismo Upgrade de HTTP, por lo que la petición de actualización del protocolo está implícita cuando accedemos al servidor HTTP con <code><span class="nowiki">ws://www.example.com</span></code> o <code><span class="nowiki">wss://www.example.com</span></code>.</p> + +<h2 id="Enviando_Información_al_servidor">Enviando Información al servidor</h2> + +<p>Una vez la conexión esta abierta, se puede comenzar<span style="line-height: 1.5;"> a enviar datos al servidor. Para hacer esto, simplemente se llama al metodo</span><span style="line-height: 1.5;"> </span><a href="/en/WebSockets/WebSockets_reference/WebSocket#send()" style="line-height: 1.5;" title="en/WebSockets/WebSockets reference/WebSocket#send()"><code>send()</code></a><span style="line-height: 1.5;"> del objeto </span><code style="font-style: normal; line-height: 1.5;">WebSocket</code>, <span style="line-height: 1.5;">cada vez que se desea enviar un mensaje:</span></p> + +<pre class="brush: js">exampleSocket.send("Here's some text that the server is urgently awaiting!"); +</pre> + +<p>Puedes enviar información como un string, {{ domxref("Blob") }}, o en un <a href="/en/JavaScript_typed_arrays/ArrayBuffer" title="en/JavaScript typed arrays/ArrayBuffer"><code>ArrayBuffer</code></a>.</p> + +<div class="note"><strong>Nota:</strong> Antes de la version 11, Firefox sólo soportaba el envío de datos como una cadena.</div> + +<p>Como la conexión es asincronica y es propensa a fallar, no hay garantia de poder llamar al metodo <code>send()</code> inmediatamente despúes de haber creado el objeto WebSocket de manera exitosa. Para enviar información se debe estar seguro de que almenos una conexión ya esta abierta, usando el manejador <code>onopen</code>:</p> + +<pre class="brush: js">exampleSocket.onopen = function (event) { + exampleSocket.send("Here's some text that the server is urgently awaiting!"); +}; +</pre> + +<h3 id="Usando_JSON_para_transferir_Objetos">Usando JSON para transferir Objetos</h3> + +<p>Una forma de enviar información compleja al servidor es utilizar <a href="/en/JSON" title="en/JSON">JSON</a>. Por ejemplo, un programa para chatear puede interactuar con el servidor usando un protocolo que implementa el uso de paquetes de JSON:</p> + +<pre class="brush: js">// Envia texto a todos los usuarios através del servidor +function sendText() { + // Se construye un Objeto msg que contiene la información que el servidor necesita procesar de ese cliente. + var msg = { + type: "message", + text: document.getElementById("text").value, + id: clientID, + date: Date.now() + }; + + // Send the msg object as a JSON-formatted string. + exampleSocket.send(JSON.stringify(msg)); + + // Blank the text input element, ready to receive the next line of text from the user. + document.getElementById("text").value = ""; +} +</pre> + +<h2 id="Recibiendo_mensajes_del_servidor">Recibiendo mensajes del servidor</h2> + +<p>WebSockets<span style="line-height: 1.5;"> </span><span style="line-height: 1.5;">API</span><span style="line-height: 1.5;"> es un manejador de eventos; cuando el mensaje es recibido, un "message" el evento es pasado el manejador </span><code style="font-style: normal; line-height: 1.5;">onmessage</code><span style="line-height: 1.5;">. Para escuchar la entrada de información, se puede hacer algo como lo siguiente:</span></p> + +<pre class="brush: js">exampleSocket.onmessage = function (event) { + console.log(event.data); +} +</pre> + +<h3 id="Recibiendo_e_interpretando_objetos_JSON">Recibiendo e interpretando objetos JSON</h3> + +<p>Vamos a imaginar una aplicación de chat, donde el cliente usa JSON para transmitir objetos con información. Hay varios tipos de paquetes que el cliente recibirá:</p> + +<ul> + <li>Inicio de sesión handshake</li> + <li>Mensajes de texto</li> + <li>Actualización de Lista de usuarios</li> +</ul> + +<p>El código que interpretará los mensajes entrantes será así:</p> + +<pre class="brush: js">exampleSocket.onmessage = function(event) { + var f = document.getElementById("chatbox").contentDocument; + var text = ""; + var msg = JSON.parse(event.data); + var time = new Date(msg.date); + var timeStr = time.toLocaleTimeString(); + + switch(msg.type) { + case "id": + clientID = msg.id; + setUsername(); + break; + case "username": + text = "<b>User <em>" + msg.name + "</em> signed in at " + timeStr + "</b><br>"; + break; + case "message": + text = "(" + timeStr + ") <b>" + msg.name + "</b>: " + msg.text + "<br>"; + break; + case "rejectusername": + text = "<b>Your username has been set to <em>" + msg.name + "</em> because the name you chose is in use.</b><br>" + break; + case "userlist": + var ul = ""; + for (i=0; i < msg.users.length; i++) { + ul += msg.users[i] + "<br>"; + } + document.getElementById("userlistbox").innerHTML = ul; + break; + } + + if (text.length) { + f.write(text); + document.getElementById("chatbox").contentWindow.scrollByPages(1); + } +}; +</pre> + +<p>Se usa <code><a href="/en/JavaScript/Reference/Global_Objects/JSON/parse" title="en/JavaScript/Reference/Global Objects/JSON/parse">JSON.parse()</a></code> para convertir el objeto JSON de vuelta al original, luego se examina y se realiza la acción pertinente.</p> + +<h3 id="Formato_de_texto_de_los_datos">Formato de texto de los datos</h3> + +<p>El texto recibido a través de la conexión WebSocket está en formato UTF-8.</p> + +<p>Antes de Gecko 9.0 {{ geckoRelease("9.0") }}, algunos no-caracteres que siguen siendo texto UTF-8 válido podrían causar el cierre de la conexión. Ahora Gecko permite esos valores.</p> + +<h2 id="Cerrando_la_conexión">Cerrando la conexión</h2> + +<p>Cuando se ha terminado de usar la conexión WebSocket, se llama el método <code><a href="/en/WebSockets/WebSockets_reference/WebSocket#close()" title="en/WebSockets/WebSockets reference/WebSocket#close()">close()</a></code> del objeto <code>WebSocket</code>:</p> + +<pre class="brush: js">exampleSocket.close(); +</pre> + +<p>Puede ser de gran ayuda revisar el atributo <code>bufferedAmount</code> del socket para verificar que toda la información ha sido enviada antes de intentar cerrar el socket.</p> + +<h2 id="Consideraciones_de_Seguridad">Consideraciones de Seguridad</h2> + +<p>Los WebSockets no deben ser usados en entornos de contenido mixto; eso es, no debes abrir una conexión de WebSocket <em>no segura</em> desde una página cargada usando <em>HTTPS </em>o viceversa. De hecho, muchos navegadores solo admiten conexiones WebSocket seguras, y ya no soportan su uso en contextos no seguros.</p> + +<p>{{ languages ( {"zh-tw": "zh_tw/WebSockets/Writing_WebSocket_client_applications"} ) }}</p> diff --git a/files/es/web/api/webvr_api/index.html b/files/es/web/api/webvr_api/index.html new file mode 100644 index 0000000000..199e8f6458 --- /dev/null +++ b/files/es/web/api/webvr_api/index.html @@ -0,0 +1,256 @@ +--- +title: WebVR API +slug: Web/API/WebVR_API +tags: + - API + - Experimental + - Landing + - NeedsTranslation + - Reference + - TopicStub + - VR + - Virtual Reality + - WebVR +translation_of: Web/API/WebVR_API +--- +<div>{{SeeCompatTable}}{{APIRef("WebVR API")}}</div> + +<p class="summary">WebVR proporciona soporte para la exposición de dispositivos de realidad virtual — por ejemplo el visualizador de Oculus Rift o HTC Vive — para aplicaciones web, permitiendo a los desarrolladores traducir la información de posición y movimiento del visualizador al movimiento alrededor de una escena en 3D. Esto tiene numerosas aplicaciones interesantes, desde visitas virtuales de productos y aplicaciones de capacitación interactiva hasta juegos inmersivos en primera persona.</p> + +<h2 id="Concepts_and_usage">Concepts and usage</h2> + +<p>Any VR devices attached to your computer will be returned by the {{domxref("Navigator.getVRDisplays()")}} method; each one will be represented by a {{domxref("VRDisplay")}} object.</p> + +<p><img alt='Sketch of a person in a chair with wearing goggles labelled "Head mounted display (HMD)" facing a monitor with a webcam labelled "Position sensor"' src="https://mdn.mozillademos.org/files/11035/hw-setup.png" style="display: block; height: 78px; margin: 0px auto; width: 60%;"></p> + +<p>{{domxref("VRDisplay")}} is the central interface in the WebVR API — via its properties and methods you can access functionality to:</p> + +<ul> + <li>Retrieve useful information to allow us to identify the display, what capabilities it has, controllers associated with it, and more.</li> + <li>Retrieve {{domxref("VRFrameData", "frame data")}} for each frame of content you you want to present in a display, and submit those frames for display at a consistent rate.</li> + <li>Start and stop presenting to the display.</li> +</ul> + +<p>A typical (simple) WebVR app would work like so:</p> + +<ol> + <li>{{domxref("Navigator.getVRDisplays()")}} is used to get a reference to your VR display.</li> + <li>{{domxref("VRDisplay.requestPresent()")}} is used to start presenting to the VR display.</li> + <li>WebVR's dedicated {{domxref("VRDisplay.requestAnimationFrame()")}} method is used to run the app's rendering loop at the correct refresh rate for the display.</li> + <li>Inside the rendering loop, you grab the data required to display the current frame ({{domxref("VRDisplay.getFrameData()")}}), draw the displayed scene twice — once for the view in each eye, then submit the rendered view to the display to show to the user ({{domxref("VRDisplay.submitFrame()")}}).</li> +</ol> + +<p>In addition, WebVR 1.1 adds a number of events on the {{domxref("Window")}} object to allow JavaScript to respond to changes to the status of the display.</p> + +<div class="note"> +<p><strong>Note</strong>: You can find a lot more out about how the API works in our <a href="/en-US/docs/Web/API/WebVR_API/Using_the_WebVR_API">Using the WebVR API</a> and <a href="/en-US/docs/Web/API/WebVR_API/Concepts">WebVR Concepts</a> articles.</p> +</div> + +<h3 id="Using_controllers_Combining_WebVR_with_the_Gamepad_API">Using controllers: Combining WebVR with the Gamepad API</h3> + +<p>Many WebVR hardware setups feature controllers that go along with the headset. These can be used in WebVR apps via the <a href="/en-US/docs/Web/API/Gamepad_API">Gamepad API</a>, and specifically the <a href="/en-US/docs/Web/API/Gamepad_API#Experimental_Gamepad_extensions">Gamepad Extensions API</a> that adds API features for accessing <a href="/en-US/docs/Web/API/GamepadPose">controller pose</a>, <a href="/en-US/docs/Web/API/GamepadHapticActuator">haptic actuators</a>, and more.</p> + +<div class="note"> +<p><strong>Note</strong>: Our <a href="/en-US/docs/Web/API/WebVR_API/Using_VR_controllers_with_WebVR">Using VR controllers with WebVR</a> article explains the basics of how to use VR controllers with WebVR apps.</p> +</div> + +<h2 id="WebVR_Interfaces">WebVR Interfaces</h2> + +<dl> + <dt>{{domxref("VRDisplay")}}</dt> + <dd>Represents any VR device supported by this API. It includes generic information such as device IDs and descriptions, as well as methods for starting to present a VR scene, retrieving eye parameters and display capabilities, and other important functionality.</dd> + <dt>{{domxref("VRDisplayCapabilities")}}</dt> + <dd>Describes the capabilities of a {{domxref("VRDisplay")}} — it's features can be used to perform VR device capability tests, for example can it return position information.</dd> + <dt>{{domxref("VRDisplayEvent")}}</dt> + <dd>Represents the event object of WebVR-related events (see the {{anch("Window", "window object extensions")}} listed below).</dd> + <dt>{{domxref("VRFrameData")}}</dt> + <dd>Represents all the information needed to render a single frame of a VR scene; constructed by {{domxref("VRDisplay.getFrameData()")}}.</dd> + <dt>{{domxref("VRPose")}}</dt> + <dd>Represents the position state at a given timestamp (which includes orientation, position, velocity, and acceleration.)</dd> + <dt>{{domxref("VREyeParameters")}}</dt> + <dd>Provides access to all the information required to correctly render a scene for each given eye, including field of view information.</dd> + <dt>{{domxref("VRFieldOfView")}}</dt> + <dd>Represents a field of view defined by 4 different degree values describing the view from a center point.</dd> + <dt>{{domxref("VRLayerInit")}}</dt> + <dd>Represents a layer to be presented in a {{domxref("VRDisplay")}}.</dd> + <dt>{{domxref("VRStageParameters")}}</dt> + <dd>Represents the values describing the the stage area for devices that support room-scale experiences.</dd> +</dl> + +<h3 id="Extensions_to_other_interfaces">Extensions to other interfaces</h3> + +<p>The WebVR API extends the following APIs, adding the listed features.</p> + +<h4 id="Gamepad">Gamepad</h4> + +<dl> + <dt>{{domxref("Gamepad.displayId")}} {{readonlyInline}}</dt> + <dd><dfn>Returns the {{domxref("VRDisplay.displayId")}} of the associated {{domxref("VRDisplay")}} — the <code>VRDisplay</code> that the gamepad is controlling the displayed scene of.</dfn></dd> +</dl> + +<h4 id="Navigator">Navigator</h4> + +<dl> + <dt>{{domxref("Navigator.activeVRDisplays")}} {{readonlyInline}}</dt> + <dd>Returns an array containing every {{domxref("VRDisplay")}} object that is currently presenting ({{domxref("VRDisplay.ispresenting")}} is <code>true</code>).</dd> + <dt>{{domxref("Navigator.getVRDisplays()")}}</dt> + <dd>Returns a promise that resolves to an array of {{domxref("VRDisplay")}} objects representing any available VR displays connected to the computer.</dd> +</dl> + +<h4 id="Window_events">Window events</h4> + +<dl> + <dt>{{domxref("Window.onvrdisplaypresentchange")}}</dt> + <dd>Represents an event handler that will run when the presenting state of a VR display changes — i.e. goes from presenting to not presenting, or vice versa (when the {{event("vrdisplaypresentchange")}} event fires).</dd> + <dt>{{domxref("Window.onvrdisplayconnect")}}</dt> + <dd>Represents an event handler that will run when a compatible VR display has been connected to the computer (when the {{event("vrdisplayconnect")}} event fires).</dd> + <dt>{{domxref("Window.onvrdisplaydisconnect")}}</dt> + <dd>Represents an event handler that will run when a compatible VR display has been disconnected from the computer (when the {{event("vrdisplaydisconnect")}} event fires).</dd> + <dt>{{domxref("Window.onvrdisplayactivate")}}</dt> + <dd>Represents an event handler that will run when a display is able to be presented to (when the {{event("vrdisplayactivate")}} event fires), for example if an HMD has been moved to bring it out of standby, or woken up by being put on.</dd> + <dt>{{domxref("Window.onvrdisplaydeactivate")}}</dt> + <dd>Represents an event handler that will run when a display can no longer be presented to (when the {{event("vrdisplaydeactivate")}} event fires), for example if an HMD has gone into standby or sleep mode due to a period of inactivity.</dd> +</dl> + +<h4 id="Unimplemented_window_events">Unimplemented window events</h4> + +<p>The following events are listed in the spec, but do not currently seem to be implemented anywhere as yet.</p> + +<dl> + <dt>{{domxref("Window.onvrdisplayblur")}}</dt> + <dd>Represents an event handler that will run when presentation to a display has been paused for some reason by the browser, OS, or VR hardware (when the {{event("vrdisplayblur")}} event fires) — for example, while the user is interacting with a system menu or browser, to prevent tracking or loss of experience.</dd> + <dt>{{domxref("Window.onvrdisplayfocus")}}</dt> + <dd>Represents an event handler that will run when presentation to a display has resumed after being blurred (when the {{event("vrdisplayfocus")}} event fires).</dd> +</dl> + +<h2 id="Examples">Examples</h2> + +<p>You can find a number of examples at these locations:</p> + +<ul> + <li><a href="https://github.com/mdn/webvr-tests">webvr-tests</a> — very simple examples to accompany the MDN WebVR documentation.</li> + <li><a href="https://github.com/facebook/Carmel-Starter-Kit">Carmel starter kit</a> — nice simple, well-commented examples that go along with Carmel, Facebook's WebVR browser.</li> + <li><a href="https://webvr.info/samples/">WebVR.info samples</a> — slightly more in-depth examples plus source code</li> + <li><a href="https://webvr.rocks/firefox#demos">WebVR.rocks Firefox demos</a> — showcase examples</li> + <li><a href="https://aframe.io/">A-Frame homepage</a> — examples showing A-Frame usage</li> +</ul> + +<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("GamepadExtensions")}}</td> + <td>{{Spec2("GamepadExtensions")}}</td> + <td>Defines the <a href="/en-US/docs/Web/API/Gamepad_API#Experimental_Gamepad_extensions">Experimental Gamepad extensions</a>.</td> + </tr> + <tr> + <td>{{SpecName('WebVR 1.1')}}</td> + <td>{{Spec2('WebVR 1.1')}}</td> + <td>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>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}<sup>[1]</sup></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(55)}}<sup>[2]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>Gamepad extensions</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}<sup>[4]</sup></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>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + <th>Samsung Internet for GearVR</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoMobile(55)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}<sup>[3]</sup></td> + <td>{{CompatVersionUnknown}}<br> + </td> + </tr> + <tr> + <td>Gamepad extensions</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}<sup>[4]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] API Available on all platforms behind a flag, but currently only works on desktop in an <a href="https://webvr.info/get-chrome/">experimental version of Chrome</a> (other builds won't return any devices when {{domxref("Navigator.getVRDisplays()")}} is invoked).</p> + +<p>[2] Currently only Windows support is enabled by default. Mac support is <a href="https://hacks.mozilla.org/2017/06/announcing-webvr-on-mac/">available in Firefox Nightly</a>.</p> + +<p>[3] Currently supported only by Google Daydream.</p> + +<p>[4] Enabled in Firefox Nightly and Beta, versions 55 and above. Enabled/disabled by the <code>dom.gamepad-extensions.enabled</code> pref.</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="https://vr.mozilla.org">vr.mozilla.org</a> — The main Mozilla landing pad for WebVR, with demos, utilities, and other information.</li> + <li><a href="https://aframe.io/">A-Frame</a> — Open source web framework for building VR experiences.</li> + <li><a href="https://webvr.info">webvr.info</a> — Up-to-date information about WebVR, browser setup, and community.</li> + <li><a href="http://mozvr.com/">MozVr.com</a> — Demos, downloads, and other resources from the Mozilla VR team.</li> + <li><a href="https://github.com/MozVR/vr-web-examples/tree/master/threejs-vr-boilerplate">threejs-vr-boilerplate</a> — A useful starter template for writing WebVR apps into.</li> + <li><a href="https://github.com/googlevr/webvr-polyfill/">Web VR polyfill</a> — JavaScript implementation of WebVR.</li> +</ul> diff --git a/files/es/web/api/webvr_api/using_the_webvr_api/index.html b/files/es/web/api/webvr_api/using_the_webvr_api/index.html new file mode 100644 index 0000000000..0a4bc67e58 --- /dev/null +++ b/files/es/web/api/webvr_api/using_the_webvr_api/index.html @@ -0,0 +1,448 @@ +--- +title: Uso de la API de WebVR +slug: Web/API/WebVR_API/Using_the_WebVR_API +tags: + - '1.1' + - API + - Canvas + - Realidad Virtual + - Tutorial + - VR + - WebGL + - WebVR +translation_of: Web/API/WebVR_API/Using_the_WebVR_API +--- +<div>{{APIRef("WebVR API")}}</div> + +<p class="summary"><span id="result_box" lang="es"><span>La API WebVR es una fantástica adición al kit de herramientas del desarrollador web, permitiendo que las escenas de WebGL sean presentadas en pantallas de realidad virtual como el Oculus Rift y HTC Vive.</span> <span>Pero, ¿cómo empezar a desarrollar aplicaciones VR para la Web?</span> <span>Este artículo le guiará a través de los fundamentos.</span></span></p> + +<div class="note"> +<p><span id="result_box" lang="es"><span><strong>Nota:</strong> La versión más estable de la API de WebVR (1.1) se ha implementado recientemente en Firefox 55 (Windows en versión de lanzamiento y Mac OS X sólo en Nightly) y también está disponible en Chrome cuando se usa con hardware de Google Daydream.</span> <span>También hay una evolución posterior de la especificación 2.0, pero esto está en una etapa temprana ahora mismo.</span> <span>Puede encontrar información sobre el estado más reciente de las especificaciones en </span></span> <a href="https://w3c.github.io/webvr/">WebVR Spec Version List</a>.</p> +</div> + +<h2 id="Empezando"><span class="short_text" id="result_box" lang="es"><span>Empezando</span></span></h2> + +<p><span class="short_text" id="result_box" lang="es"><span>Para empezar, necesita:</span></span></p> + +<ul> + <li><span class="short_text" id="result_box" lang="es"><span>Soporte de hardware VR.</span></span> + + <ul> + <li><span id="result_box" lang="es"><span>La opción más barata es utilizar un dispositivo móvil, compatible con el navegador y el dispositivo montado (por ejemplo, Google Cardboard).</span> <span>Esto no será una experiencia tan buena como el hardware dedicado, pero no necesitará comprar una computadora potente o una pantalla VR dedicada.</span></span></li> + <li><span id="result_box" lang="es"><span>El hardware dedicado puede ser costoso, pero proporciona una experiencia mejor.</span> <span>El hardware más compatible con WebVR en este momento es el HTC VIVE, y The Oculus Rift.</span> <span>La primera página de</span></span> <a href="https://webvr.info/">webvr.info</a> <span id="result_box" lang="es"><span>tiene alguna otra información útil sobre hardware disponible y qué navegador los soporta.</span></span></li> + </ul> + </li> + <li><span id="result_box" lang="es"><span>Una computadora lo suficientemente potente para manejar la representación / visualización de escenas VR usando su hardware VR dedicado, si es necesario.</span> <span>Para darle una idea de lo que usted necesita, mire la guía relevante para el VR que usted está comprando</span></span> ( p. ej.<a href="https://www.vive.com/us/ready/">VIVE READY Computers</a>).</li> + <li><span class="short_text" id="result_box" lang="es"><span>Se ha instalado un navegador de soporte: el último</span></span> <a href="https://www.mozilla.org/en-US/firefox/channel/desktop/">Firefox Nightly</a> o <a href="https://www.google.com/chrome/index.html">Chrome</a> <span id="result_box" lang="es"><span>son sus mejores opciones ahora, en el escritorio o móvil.</span></span></li> +</ul> + +<p><span id="result_box" lang="es"><span>Una vez que tengas todo montado, puedes probar si tu configuración funciona con WebVR yendo a nuestro</span></span> <a href="https://mdn.github.io/webvr-tests/aframe-demo/">simple A-Frame demo</a>, <span id="result_box" lang="es"><span>y ver si la escena se procesa y si puede entrar en el modo de visualización VR pulsando el botón en la parte inferior derecha.</span></span></p> + +<p><a href="https://aframe.io/">A-Frame</a> <span id="result_box" lang="es"><span>es de lejos la mejor opción si desea crear una escena 3D compatible con WebVR rápidamente, sin necesidad de entender un montón de código nuevo de JavaScript.</span> <span>Sin embargo, no te enseña cómo funciona la API WebVR en bruto, y esto es lo que veremos a continuación.</span></span></p> + +<h2 id="Introduccion_a_nuestra_demostración"><span class="short_text" id="result_box" lang="es"><span>Introduccion a nuestra demostración</span></span></h2> + +<p><span id="result_box" lang="es"><span>Para ilustrar cómo funciona la API de WebVR, estudiaremos nuestro ejemplo raw-webgl-example, que se parece un poco a esto:</span></span></p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/15121/Capture1.png" style="display: block; height: 761px; margin: 0px auto; width: 1341px;"></p> + +<div class="note"> +<p><span id="result_box" lang="es"><span><strong>Nota:</strong> Puedes encontrar el <a href="https://github.com/mdn/webvr-tests/tree/master/raw-webgl-example">código fuente de nuestra demo</a> en </span></span> GitHub, <span id="result_box" lang="es"><span>y <a href="https://mdn.github.io/webvr-tests/raw-webgl-example/">verlo en vivo </a>también. </span></span></p> +</div> + +<div class="note"> +<p><span id="result_box" lang="es"><span><strong>Nota:</strong> Si WebVR no funciona en su navegador, es posible que deba asegurarse de que se está ejecutando a través de su tarjeta gráfica.</span> <span>Por ejemplo, para las tarjetas NVIDIA, si el panel de control de NVIDIA se ha configurado correctamente, habrá una opción de menú contextual disponible - haga clic con el botón derecho del ratón en Firefox y seleccione <em>Ejecutar con procesador gráfico</em> > <em>Procesador NVIDIA de alto rendimiento.</em></span></span></p> +</div> + +<p><span id="result_box" lang="es"><span>Nuestra demo presenta el santo grial de las demostraciones de WebGL - un cubo 3D giratorio.</span> <span>Hemos implementado esto usando raw </span></span><a href="/en-US/docs/Web/API/WebGL_API">WebGL API</a> <span id="result_box" lang="es"><span>código.</span> <span>No enseñaremos ningún JavaScript básico o WebGL, solo las partes de WebVR.</span></span></p> + +<p><span class="short_text" id="result_box" lang="es"><span>Nuestra demo también cuenta con:</span></span></p> + +<ul> + <li><span id="result_box" lang="es"><span>Un botón para iniciar (y detener) la presentación de nuestra escena en la pantalla VR.</span></span></li> + <li><span id="result_box" lang="es"><span>Un botón para mostrar (y ocultar) los datos de pose VR, es decir, la posición y orientación del auricular, actualizados en tiempo real.</span></span></li> +</ul> + +<p><span class="short_text" id="result_box" lang="es"><span>Cuando miras a través del código fuente de</span></span><a href="https://github.com/mdn/webvr-tests/blob/master/raw-webgl-example/webgl-demo.js"> nuestro archivo JavaScript principal de demostraciones</a> , <span id="result_box" lang="es"><span>puede encontrar fácilmente las partes específicas de WebVR buscando la cadena "WebVR" en comentarios anteriores.</span></span></p> + +<div class="note"> +<p><span id="result_box" lang="es"><span><strong>Nota:</strong> Para obtener más información sobre JavaScript básico y WebGL, consulte nuestro </span></span><a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript">material de aprendizaje JavaScrip</a><span lang="es"><span> </span></span>, y nuestro <a href="/en-US/docs/Web/API/WebGL_API/Tutorial">WebGL Tutorial</a>.</p> +</div> + +<h2 id="¿Como_funciona"><span class="short_text" id="result_box" lang="es"><span>¿Como funciona?</span></span></h2> + +<p><span id="result_box" lang="es"><span>En este punto, veamos cómo funcionan las partes WebVR del código.</span></span></p> + +<p><span id="result_box" lang="es"><span>Una típica (simple) aplicación WebVR funciona de esta manera:</span></span></p> + +<ol> + <li>{{domxref("Navigator.getVRDisplays()")}} <span id="result_box" lang="es"><span>se utiliza para obtener una referencia a la visualización VR.</span></span></li> + <li>{{domxref("VRDisplay.requestPresent()")}} <span id="result_box" lang="es"><span>se utiliza para iniciar la presentación en la pantalla VR.</span></span></li> + <li><span class="short_text" id="result_box" lang="es"><span>WebVR's dedicado </span></span>{{domxref("VRDisplay.requestAnimationFrame()")}} <span id="result_box" lang="es"><span>se utiliza para ejecutar el bucle de representación de la aplicación a la velocidad de actualización correcta para la pantalla.</span></span></li> + <li><span id="result_box" lang="es"><span>Dentro del bucle de procesamiento, se capturan los datos necesarios para mostrar el marco actual </span></span>({{domxref("VRDisplay.getFrameData()")}}), <span id="result_box" lang="es"><span>dibuja la escena visualizada dos veces - una vez para la vista en cada ojo -</span> <span>luego envia la vista renderizada a la pantalla para mostrar al usuario a través de </span></span>({{domxref("VRDisplay.submitFrame()")}}).</li> +</ol> + +<p><span id="result_box" lang="es"><span>En las secciones siguientes veremos en detalle nuestra demostración raw-webgl y veremos dónde se utilizan exactamente las características anteriores.</span></span></p> + +<h3 id="Comenzando_con_algunas_variables"><span class="short_text" id="result_box" lang="es"><span>Comenzando con algunas variables</span></span></h3> + +<p><span id="result_box" lang="es"><span>El primer código relacionado con WebVR que encontrarás es el siguiente bloque:</span></span></p> + +<pre class="brush: js notranslate">// WebVR variables + +var frameData = new VRFrameData(); +var vrDisplay; +var btn = document.querySelector('.stop-start'); +var normalSceneFrame; +var vrSceneFrame; + +var poseStatsBtn = document.querySelector('.pose-stats'); +var poseStatsSection = document.querySelector('section'); +poseStatsSection.style.visibility = 'hidden'; // hide it initially + +var posStats = document.querySelector('.pos'); +var orientStats = document.querySelector('.orient'); +var linVelStats = document.querySelector('.lin-vel'); +var linAccStats = document.querySelector('.lin-acc'); +var angVelStats = document.querySelector('.ang-vel'); +var angAccStats = document.querySelector('.ang-acc'); +var poseStatsDisplayed = false;</pre> + +<p><span class="short_text" id="result_box" lang="es"><span>Vamos a explicar estos </span></span><span class="short_text" lang="es"><span>brevemente :</span></span></p> + +<ul> + <li><code>frameData</code> contains a {{domxref("VRFrameData")}} <span class="short_text" id="result_box" lang="es"><span>objeto, creado con el </span></span>{{domxref("VRFrameData.VRFrameData", "VRFrameData()")}} <span id="result_box" lang="es"><span>constructor.</span> <span>Esto es inicialmente vacío, pero contendrá más adelante los datos requeridos para rendir cada marco para mostrar en la exhibición de VR, actualizado constantemente mientras que se ejecuta el ciclo de la representación.</span></span></li> + <li><code>vrDisplay</code> <span id="result_box" lang="es"><span>comienza sin inicializarse, pero más adelante se realizará una referencia a nuestro auricular VR</span></span> ({{domxref("VRDisplay")}} —<span class="short_text" id="result_box" lang="es"><span> el objeto de control central de la API).</span></span></li> + <li><code>btn</code> y <code>poseStatsBtn</code> <span id="result_box" lang="es"><span>mantenga referencias a los dos botones que estamos usando para controlar nuestra aplicación.</span></span></li> + <li><code>normalSceneFrame</code> y <code>vrSceneFrame</code> <span id="result_box" lang="es"><span>no iniciados, pero más adelante contendrán referencias a</span></span> {{domxref("Window.requestAnimationFrame()")}} y {{domxref("VRDisplay.requestAnimationFrame()")}} <span id="result_box" lang="es"><span>llamadas - esto iniciará el funcionamiento de un bucle de renderizado normal, y un bucle de renderización WebVR especial;</span> <span>explicaremos la diferencia entre estos dos más adelante.</span></span></li> + <li><span id="result_box" lang="es"><span>Las otras variables almacenan referencias a diferentes partes del cuadro de visualización de datos de pose de VR, que se puede ver en la esquina inferior derecha de la interfaz de usuario.</span></span></li> +</ul> + +<h3 id="Cómo_obtener_una_referencia_a_nuestra_pantalla_VR"><span class="short_text" id="result_box" lang="es"><span>Cómo obtener una referencia a nuestra pantalla VR</span></span></h3> + +<p><span id="result_box" lang="es"><span>Una de las principales funciones dentro de nuestro código es start () - ejecutamos esta función cuando el cuerpo ha terminado de cargar:</span></span></p> + +<pre class="brush: js notranslate">// start +// +// Called when the body has loaded is created to get the ball rolling. + +document.body.onload = start;</pre> + +<p>Para empezar, <code>start()</code> <span id="result_box" lang="es"><span>recupera un contexto de WebGL para usarlo para renderizar gráficos 3D</span></span> {{htmlelement("canvas")}} <span class="short_text" id="result_box" lang="es"><span>elemento en </span></span><a href="https://github.com/mdn/webvr-tests/blob/master/raw-webgl-example/index.html">our HTML</a>. <span class="short_text" id="result_box" lang="es"><span>A continuación verificamos si la</span></span> <code>gl</code> <span class="short_text" id="result_box" lang="es"><span>contexto está disponible</span></span> — <span id="result_box" lang="es"><span>si es así, ejecutamos una serie de funciones para configurar la escena para su visualización.</span></span></p> + +<pre class="brush: js notranslate">function start() { + canvas = document.getElementById("glcanvas"); + + initWebGL(canvas); // Initialize the GL context + + // WebGL setup code here</pre> + +<p>Next, we start the process of actually rendering the scene onto the canvas, by setting the canvas to fill the entire browser viewport, and running the rendering loop (<code>drawScene()</code>) for the first time. This is the non-WebVR — normal — rendering loop.</p> + +<pre class="brush: js notranslate"> // draw the scene normally, without WebVR - for those who don't have it and want to see the scene in their browser + + canvas.width = window.innerWidth; + canvas.height = window.innerHeight; + drawScene();</pre> + +<p>Now onto our first WebVR-specific code. First of all, we check to see if {{domxref("Navigator.getVRDisplays")}} exists — this is the entry point into the API, and therefore good basic feature detection for WebVR. You'll see at the end of the block (inside the <code>else</code> clause) that if this doesn't exist, we log a message to indicate that WebVR 1.1 isn't supported by the browser.</p> + +<pre class="brush: js notranslate"> // WebVR: Check to see if WebVR is supported + if(navigator.getVRDisplays) { + console.log('WebVR 1.1 supported');</pre> + +<p>Inside our <code>if() { ... }</code> block, we run the {{domxref("Navigator.getVRDisplays()")}} function. This returns a promise, which is fulfilled with an array containing all the VR display devices connected to the computer. If none are connected, the array will be empty.</p> + +<pre class="brush: js notranslate"> // Then get the displays attached to the computer + navigator.getVRDisplays().then(function(displays) {</pre> + +<p>Inside the promise <code>then()</code> block, we check whether the array length is more than 0; if so, we set the value of our <code>vrDisplay</code> variable to the 0 index item inside the array. <code>vrDisplay</code> now contains a {{domxref("VRDisplay")}} object representing our connected display!</p> + +<pre class="brush: js notranslate"> // If a display is available, use it to present the scene + if(displays.length > 0) { + vrDisplay = displays[0]; + console.log('Display found');</pre> + +<div class="note"> +<p><span id="result_box" lang="es"><span><strong>Nota: </strong>Es poco probable que tenga varias pantallas VR conectadas a su computadora, y esto es sólo una demostración simple, por lo que esto lo hará por ahora.</span></span></p> +</div> + +<h3 id="Starting_and_stopping_the_VR_presentation">Starting and stopping the VR presentation</h3> + +<p>Now we have a {{domxref("VRDisplay")}} object, we can use it do a number of things. The next thing we want to do is wire up functionality to start and stop presentation of the WebGL content to the display.</p> + +<p>Continuing on with the previous code block, we now add an event listener to our start/stop button (<code>btn</code>) — when this button is clicked we want to check whether we are presenting to the display already (we do this in a fairly dumb fashion, by checking what the button <code><a href="/en-US/docs/Web/API/Node/textContent">textContent</a></code> contains).</p> + +<p>If the display is not already presenting, we use the {{domxref("VRDisplay.requestPresent()")}} method to request that the browser start presenting content to the display. This takes as a parameter an array of the {{domxref("VRLayerInit")}} objects representing the layers you want to present in the display.</p> + +<p>Since the maximum number of layers you can display is currently 1, and the only required object member is the {{domxref("VRLayerInit.source")}} property (which is a reference to the {{htmlelement("canvas")}} you want to present in that layer; the other parameters are given sensible defaults — see {{domxref("VRLayerInit.leftBounds", "leftBounds")}} and {{domxref("VRLayerInit.rightBounds", "rightBounds")}})), the parameter is simply [{ source: canvas }].</p> + +<p><code>requestPresent()</code> returns a promise that is fulfilled when the presentation begins successfully.</p> + +<pre class="brush: js notranslate"> // Starting the presentation when the button is clicked: It can only be called in response to a user gesture + btn.addEventListener('click', function() { + if(btn.textContent === 'Start VR display') { + vrDisplay.requestPresent([{ source: canvas }]).then(function() { + console.log('Presenting to WebVR display');</pre> + +<p>With our presentation request successful, we now want to start setting up to render content to present to the VRDisplay. First of all we set the canvas to the same size as the VR display area. We do this by getting the {{domxref("VREyeParameters")}} for both eyes using {{domxref("VRDisplay.getEyeParameters()")}}.</p> + +<p>We then do some simple math to calculate the total width of the VRDisplay rendering area based on the eye {{domxref("VREyeParameters.renderWidth")}} and {{domxref("VREyeParameters.renderHeight")}}.</p> + +<pre class="brush: js notranslate"> // Set the canvas size to the size of the vrDisplay viewport + + var leftEye = vrDisplay.getEyeParameters('left'); + var rightEye = vrDisplay.getEyeParameters('right'); + + canvas.width = Math.max(leftEye.renderWidth, rightEye.renderWidth) * 2; + canvas.height = Math.max(leftEye.renderHeight, rightEye.renderHeight);</pre> + +<p>Next, we {{domxref("Window.cancelAnimationFrame()", "cancel the animation loop")}} previously set in motion by the {{domxref("Window.requestAnimationFrame()")}} call inside the <code>drawScene()</code> function, and instead invoke <code>drawVRScene()</code>. This function renders the same scene as before, but with some special WebVR magic going on. The loop inside here is maintained by WebVR's special {{domxref("VRDisplay.requestAnimationFrame")}} method.</p> + +<pre class="brush: js notranslate"> // stop the normal presentation, and start the vr presentation + window.cancelAnimationFrame(normalSceneFrame); + drawVRScene();</pre> + +<p><span id="result_box" lang="es"><span>Finalmente, actualizamos el texto del botón para que la próxima vez que se presione, detenga la presentación en la pantalla VR.</span></span></p> + +<pre class="brush: js notranslate"> btn.textContent = 'Exit VR display'; + });</pre> + +<p><br> + To stop the VR presentation when the button is subsequently pressed, we call {{domxref("VRDisplay.exitPresent()")}}. We also reverse the button's text content, and swap over the <code>requestAnimationFrame</code> calls. You can see here that we are using {{domxref("VRDisplay.cancelAnimationFrame")}} to stop the VR rendering loop, and starting the normal rendering loop off again by calling <code>drawScene()</code>.</p> + +<pre class="brush: js notranslate"> } else { + vrDisplay.exitPresent(); + console.log('Stopped presenting to WebVR display'); + + btn.textContent = 'Start VR display'; + + // Stop the VR presentation, and start the normal presentation + vrDisplay.cancelAnimationFrame(vrSceneFrame); + drawScene(); + } + }); + } + }); + } else { + console.log('WebVR API not supported by this browser.'); + } + } +}</pre> + +<p><span id="result_box" lang="es"><span>Una vez iniciada la presentación, podrás ver la vista estereoscópica que se muestra en el navegador:</span></span></p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/15123/Capture2.png" style="display: block; margin: 0 auto;"></p> + +<p><span id="result_box" lang="es"><span>A continuación, aprenderá cómo se produce realmente la vista estereoscópica.</span></span></p> + +<h3 id="Why_does_WebVR_have_its_own_requestAnimationFrame">Why does WebVR have its own requestAnimationFrame()?</h3> + +<p>This is a good question. The reason is that for smooth rendering inside the VR display, you need to render the content at the display's native refresh rate, not that of the computer. VR display refresh rates are greater than PC refresh rates, typically up to 90fps. The rate will be differ from the computer's core refresh rate.</p> + +<p>Note that when the VR display is not presenting, {{domxref("VRDisplay.requestAnimationFrame")}} runs identically to {{domxref("Window.requestAnimationFrame")}}, so if you wanted, you could just use a single rendering loop, rather than the two we are using in our app. We have used two because we wanted to do slightly different things depending on whether the VR display is presenting or not, and keep things separated for ease of comprehension.</p> + +<h3 id="Rendering_and_display">Rendering and display</h3> + +<p>At this point, we've seen all the code required to access the VR hardware, request that we present our scene to the hardware, and start running the rending loop. Let's now look at the code for the rendering loop, and explain how the WebVR-specific parts of it work.</p> + +<p>First of all, we begin the definition of our rendering loop function — <code>drawVRScene()</code>. The first thing we do inside here is make a call to {{domxref("VRDisplay.requestAnimationFrame()")}} to keep the loop running after it has been called once (this occurred earlier on in our code when we started presenting to the VR display). This call is set as the value of the global <code>vrSceneFrame</code> variable, so we can cancel the loop with a call to {{domxref("VRDisplay.cancelAnimationFrame()")}} once we exit VR presenting.</p> + +<pre class="brush: js notranslate">function drawVRScene() { + // WebVR: Request the next frame of the animation + vrSceneFrame = vrDisplay.requestAnimationFrame(drawVRScene);</pre> + +<p>Next, we call {{domxref("VRDisplay.getFrameData()")}}, passing it the name of the variable that we want to use to contain the frame data. We initialized this earlier on — <code>frameData</code>. After the call completes, this variable will contain the data need to render the next frame to the VR device, packaged up as a {{domxref("VRFrameData")}} object. This contains things like projection and view matrices for rendering the scene correctly for the left and right eye view, and the current {{domxref("VRPose")}} object, which contains data on the VR display such as orientation, position, etc.</p> + +<p>This has to be called on every frame so the rendered view is always up-to-date.</p> + +<pre class="brush: js notranslate"> // Populate frameData with the data of the next frame to display + vrDisplay.getFrameData(frameData);</pre> + +<p>Now we retrieve the current {{domxref("VRPose")}} from the {{domxref("VRFrameData.pose")}} property, store the position and orientation for use later on, and send the current pose to the pose stats box for display, if the <code>poseStatsDisplayed</code> variable is set to true.</p> + +<pre class="brush: js notranslate"> // You can get the position, orientation, etc. of the display from the current frame's pose + + var curFramePose = frameData.pose; + var curPos = curFramePose.position; + var curOrient = curFramePose.orientation; + if(poseStatsDisplayed) { + displayPoseStats(curFramePose); + }</pre> + +<p> We now clear the canvas before we start drawing on it, so that the next frame is clearly seen, and we don't also see previous rendered frames:</p> + +<pre class="brush: js notranslate"> // Clear the canvas before we start drawing on it. + + gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);</pre> + +<p>We now render the view for both the left and right eyes. First of all we need to create projection and view locations for use in the rendering. these are {{domxref("WebGLUniformLocation")}} objects, created using the {{domxref("WebGLRenderingContext.getUniformLocation()")}} method, passing it the shader program's identifier and an identifying name as parameters.</p> + +<pre class="brush: js notranslate"> // WebVR: Create the required projection and view matrix locations needed + // for passing into the uniformMatrix4fv methods below + + var projectionMatrixLocation = gl.getUniformLocation(shaderProgram, "projMatrix"); + var viewMatrixLocation = gl.getUniformLocation(shaderProgram, "viewMatrix");</pre> + +<p>The next rendering step involves:</p> + +<ul> + <li>Specifying the viewport size for the left eye, using {{domxref("WebGLRenderingContext.viewport")}} — this is logically the first half of the canvas width, and the full canvas height.</li> + <li>Specifying the view and projection matrix values to use to render the left eye — this is done using the {{domxref("WebGLRenderingContext.uniformMatrix", "WebGLRenderingContext.uniformMatrix4fv")}} method, which is passed the location values we retrieved above, and the left matrices obtained from the {{domxref("VRFrameData")}} object.</li> + <li>Running the <code>drawGeometry()</code> function, which renders the actual scene — because of what we specified in the previous two steps, we will render it for the left eye only.</li> +</ul> + +<pre class="brush: js notranslate"> // WebVR: Render the left eye’s view to the left half of the canvas + gl.viewport(0, 0, canvas.width * 0.5, canvas.height); + gl.uniformMatrix4fv(projectionMatrixLocation, false, frameData.leftProjectionMatrix); + gl.uniformMatrix4fv(viewMatrixLocation, false, frameData.leftViewMatrix); + drawGeometry();</pre> + +<p>We now do exactly the same thing, but for the right eye:</p> + +<pre class="brush: js notranslate"> // WebVR: Render the right eye’s view to the right half of the canvas + gl.viewport(canvas.width * 0.5, 0, canvas.width * 0.5, canvas.height); + gl.uniformMatrix4fv(projectionMatrixLocation, false, frameData.rightProjectionMatrix); + gl.uniformMatrix4fv(viewMatrixLocation, false, frameData.rightViewMatrix); + drawGeometry();</pre> + +<p>Next we define our <code>drawGeometry()</code> function. Most of this is just general WebGL code required to draw our 3D cube. You'll see some WebVR-specific parts in the <code>mvTranslate()</code> and <code>mvRotate()</code> function calls — these pass matrices into the WebGL program that define the translation and rotation of the cube for the current frame</p> + +<p>You'll see that we are modifying these values by the position (<code>curPos</code>) and orientation (<code>curOrient</code>) of the VR display we got from the {{domxref("VRPose")}} object. The result is that, for example, as you move or rotate your head left, the x position value (<code>curPos[0]</code>) and y rotation value (<code>[curOrient[1]</code>) are added to the x translation value, meaning that the cube will move to the right, as you'd expect when you are looking at something and then move/turn your head left.</p> + +<p>This is a quick and dirty way to use VR pose data, but it illustrates the basic principle.</p> + +<pre class="brush: js notranslate"> function drawGeometry() { + // Establish the perspective with which we want to view the + // scene. Our field of view is 45 degrees, with a width/height + // ratio of 640:480, and we only want to see objects between 0.1 units + // and 100 units away from the camera. + + perspectiveMatrix = makePerspective(45, 640.0/480.0, 0.1, 100.0); + + // Set the drawing position to the "identity" point, which is + // the center of the scene. + + loadIdentity(); + + // Now move the drawing position a bit to where we want to start + // drawing the cube. + + mvTranslate([ + 0.0 - (curPos[0] * 25) + (curOrient[1] * 25), + 5.0 - (curPos[1] * 25) - (curOrient[0] * 25), + -15.0 - (curPos[2] * 25) + ]); + + // Save the current matrix, then rotate before we draw. + + mvPushMatrix(); + mvRotate(cubeRotation, [0.25, 0, 0.25 - curOrient[2] * 0.5]); + + // Draw the cube by binding the array buffer to the cube's vertices + // array, setting attributes, and pushing it to GL. + + gl.bindBuffer(gl.ARRAY_BUFFER, cubeVerticesBuffer); + gl.vertexAttribPointer(vertexPositionAttribute, 3, gl.FLOAT, false, 0, 0); + + // Set the texture coordinates attribute for the vertices. + + gl.bindBuffer(gl.ARRAY_BUFFER, cubeVerticesTextureCoordBuffer); + gl.vertexAttribPointer(textureCoordAttribute, 2, gl.FLOAT, false, 0, 0); + + // Specify the texture to map onto the faces. + + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, cubeTexture); + gl.uniform1i(gl.getUniformLocation(shaderProgram, "uSampler"), 0); + + // Draw the cube. + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVerticesIndexBuffer); + setMatrixUniforms(); + gl.drawElements(gl.TRIANGLES, 36, gl.UNSIGNED_SHORT, 0); + + // Restore the original matrix + + mvPopMatrix(); + } +</pre> + +<p>The next bit of the code has nothing to do with WebVR — it just updates the rotation of the cube on each frame:</p> + +<pre class="brush: js notranslate"> // Update the rotation for the next draw, if it's time to do so. + + var currentTime = (new Date).getTime(); + if (lastCubeUpdateTime) { + var delta = currentTime - lastCubeUpdateTime; + + cubeRotation += (30 * delta) / 1000.0; + } + + lastCubeUpdateTime = currentTime;</pre> + +<p>The last part of the rendering loop involves us calling {{domxref("VRDisplay.submitFrame()")}} — now all the work has been done and we've rendered the display on the {{htmlelement("canvas")}}, this method then submits the frame to the VR display so it is displayed on there as well.</p> + +<pre class="brush: js notranslate"> // WebVR: Indicate that we are ready to present the rendered frame to the VR display + vrDisplay.submitFrame(); +}</pre> + +<h3 id="Displaying_the_pose_position_orientation_etc._data">Displaying the pose (position, orientation, etc.) data</h3> + +<p>In this section we'll discuss the <code>displayPoseStats()</code> function, which displays our updated pose data on each frame. The function is fairly simple.</p> + +<p>First of all, we store the six different property values obtainable from the {{domxref("VRPose")}} object in their own variables — each one is a {{domxref("Float32Array")}}.</p> + +<pre class="brush: js notranslate">function displayPoseStats(pose) { + var pos = pose.position; + var orient = pose.orientation; + var linVel = pose.linearVelocity; + var linAcc = pose.linearAcceleration; + var angVel = pose.angularVelocity; + var angAcc = pose.angularAcceleration;</pre> + +<p>We then write out the data into the information box, updating it on every frame. We've clamped each value to three decimal places using <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed">toFixed()</a></code>, as the values are hard to read otherwise.</p> + +<p>You should note that we've used a conditional expression to detect whether the linear acceleration and angular acceleration arrays are successfully returned before we display the data. These values are not reported by most VR hardware as yet, so the code would throw an error if we did not do this (the arrays return <code>null</code> if they are not successfully reported).</p> + +<pre class="brush: js notranslate"> posStats.textContent = 'Position: x ' + pos[0].toFixed(3) + ', y ' + pos[1].toFixed(3) + ', z ' + pos[2].toFixed(3); + orientStats.textContent = 'Orientation: x ' + orient[0].toFixed(3) + ', y ' + orient[1].toFixed(3) + ', z ' + orient[2].toFixed(3); + linVelStats.textContent = 'Linear velocity: x ' + linVel[0].toFixed(3) + ', y ' + linVel[1].toFixed(3) + ', z ' + linVel[2].toFixed(3); + angVelStats.textContent = 'Angular velocity: x ' + angVel[0].toFixed(3) + ', y ' + angVel[1].toFixed(3) + ', z ' + angVel[2].toFixed(3); + + if(linAcc) { + linAccStats.textContent = 'Linear acceleration: x ' + linAcc[0].toFixed(3) + ', y ' + linAcc[1].toFixed(3) + ', z ' + linAcc[2].toFixed(3); + } else { + linAccStats.textContent = 'Linear acceleration not reported'; + } + + if(angAcc) { + angAccStats.textContent = 'Angular acceleration: x ' + angAcc[0].toFixed(3) + ', y ' + angAcc[1].toFixed(3) + ', z ' + angAcc[2].toFixed(3); + } else { + angAccStats.textContent = 'Angular acceleration not reported'; + } +}</pre> + +<h2 id="WebVR_events">WebVR events</h2> + +<p>The WebVR spec features a number of events that are fired, allowing our app code to react to changes in the state of the VR display (see <a href="/en-US/docs/Web/API/WebVR_API#Window_events">Window events</a>). For example:</p> + +<ul> + <li>{{event("vrdisplaypresentchange")}} — Fires when the presenting state of a VR display changes — i.e. goes from presenting to not presenting, or vice versa.</li> + <li>{{event("vrdisplayconnect")}} — Fires when a compatible VR display has been connected to the computer.</li> + <li>{{event("vrdisplaydisconnect")}} — Fires when a compatible VR display has been disconnected from the computer.</li> +</ul> + +<p>To demonstrate how they work, our simple demo includes the following example:</p> + +<pre class="brush: js notranslate">window.addEventListener('vrdisplaypresentchange', function(e) { + console.log('Display ' + e.display.displayId + ' presentation has changed. Reason given: ' + e.reason + '.'); +});</pre> + +<p>As you can see, the {{domxref("VRDisplayEvent", "event object")}} provides two useful properties — {{domxref("VRDisplayEvent.display")}}, which contains a reference to the {{domxref("VRDisplay")}} the event was fired in response to, and {{domxref("VRDisplayEvent.reason")}}, which contains a human-readable reason why the event was fired.</p> + +<p>This is a very useful event; you could use it to handle cases where the display gets disconnected unexpectedly, stopping errors from being thrown and making sure the user is aware of the situation. In Google's Webvr.info presentation demo, the event is used to run an <a href="https://github.com/toji/webvr.info/blob/master/samples/03-vr-presentation.html#L174"><code>onVRPresentChange()</code> function</a>, which updates the UI controls as appropriate and resizes the canvas.</p> + +<h2 id="Summary">Summary</h2> + +<p>This article has given you the very basics of how to create a simple WebVR 1.1 app, to help you get started.</p> diff --git a/files/es/web/api/webvtt_api/index.html b/files/es/web/api/webvtt_api/index.html new file mode 100644 index 0000000000..b7142d1dce --- /dev/null +++ b/files/es/web/api/webvtt_api/index.html @@ -0,0 +1,903 @@ +--- +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> +<div class="hidden">The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</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/wheelevent/deltay/index.html b/files/es/web/api/wheelevent/deltay/index.html new file mode 100644 index 0000000000..68135cd221 --- /dev/null +++ b/files/es/web/api/wheelevent/deltay/index.html @@ -0,0 +1,95 @@ +--- +title: WheelEvent.deltaY +slug: Web/API/WheelEvent/deltaY +translation_of: Web/API/WheelEvent/deltaY +--- +<p>{{APIRef("DOM Events")}}</p> + +<p>La propiedad de solo lectura <code><strong>WheelEvent.deltaY</strong></code> es un <code>double</code> que representa la cantidad de deslizamiento vertical en la unidad {{domxref("WheelEvent.deltaMode")}} .</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var <code><em>dY</em> = <em>event</em>.deltaY;</code></pre> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush: js">var syntheticEvent = new WheelEvent("syntheticWheel", {"deltaY": 4, "deltaMode": 0}); + +console.log(syntheticEvent.deltaY); +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('DOM3 Events','#widl-WheelEvent-deltaY','WheelEvent.deltaY')}}</td> + <td>{{Spec2('DOM3 Events')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_los_navegadores">Compatibilidad de los navegadores</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 (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>31</td> + <td>{{ CompatGeckoDesktop("17.0") }}</td> + <td>{{ CompatIE("9.0") }} [1]</td> + <td>18</td> + <td>9.0</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 Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatGeckoMobile("17.0") }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatNo() }}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] IE9 soporta un viejo boceto de esta propuedad cuyo valor de retorno era un <code>long</code> en vez de un <code>double</code>.</p> + +<h2 class="note" id="Ver_más">Ver más</h2> + +<ul> + <li>{{ event("wheel") }}</li> + <li>{{domxref("WheelEvent")}}</li> +</ul> diff --git a/files/es/web/api/wheelevent/index.html b/files/es/web/api/wheelevent/index.html new file mode 100644 index 0000000000..c53bbb87cc --- /dev/null +++ b/files/es/web/api/wheelevent/index.html @@ -0,0 +1,174 @@ +--- +title: WheelEvent +slug: Web/API/WheelEvent +tags: + - API + - DOM + - Interface + - Referencia + - WheelEvent + - eventos +translation_of: Web/API/WheelEvent +--- +<p>{{APIRef("DOM Events")}}</p> + +<p>El interface <strong><code>WheelEvent</code></strong> retrata los eventos que ocurren cuando el usuario mueve la rueda del ratón o de un dispositivo similar.</p> + +<div class="note"> +<p><strong>Esta es la forma estándar de usar el evento wheel.</strong></p> + +<p>Antiguas versiones de navegadores implementaron dos formas no-estándar y no-compatibles-entre-navegadores, los interfaces {{ domxref("MouseWheelEvent") }} y {{domxref("MouseScrollEvent")}}. Utilice este interfaz y evite los dos últimos.</p> +</div> + +<p>{{InheritanceDiagram}}</p> + +<h2 id="Constructor">Constructor</h2> + +<dl> + <dt>{{domxref("WheelEvent.WheelEvent", "WheelEvent()")}}</dt> + <dd>Crea el objeto <code>WheelEvent</code>.</dd> +</dl> + +<h2 id="Propiedades">Propiedades</h2> + +<p><em>Este interfaz hereda propiedades de estos padres<em>, {{domxref("MouseEvent")}}, {{domxref("UIEvent")}} y {{domxref("Event")}}.</em></em></p> + +<dl id="raw_prop"> + <dt>{{domxref("WheelEvent.deltaX")}} {{readonlyinline}}</dt> + <dd>Devuelve un doble (número de doble precisión) que representa la cantidad de desplazamiento horizontal.</dd> + <dt>{{domxref("WheelEvent.deltaY")}} {{readonlyinline}}</dt> + <dd>Devuelve un doble que representa la cantidad de desplazamiento vertical.</dd> + <dt>{{domxref("WheelEvent.deltaZ")}} {{readonlyinline}}</dt> + <dd>Devuelve un doble que representa la cantidad de desplazamiento del eje-z.</dd> + <dt>{{domxref("WheelEvent.deltaMode")}} {{readonlyinline}}</dt> + <dd>Devuelve un entero largo sin signo que representa la unidad manejada por los valores de cantidad de desplazamiento delta. Los valores permitidos son: + <table class="standard-table"> + <tbody> + <tr> + <td class="header">Constant</td> + <td class="header">Value</td> + <td class="header">Description</td> + </tr> + <tr> + <td><code>DOM_DELTA_PIXEL</code></td> + <td><code>0x00</code></td> + <td>Los valores delta están especificados en pixeles.</td> + </tr> + <tr> + <td><code>DOM_DELTA_LINE</code></td> + <td><code>0x01</code></td> + <td>Los valores delta están especificados en líneas.</td> + </tr> + <tr> + <td><code>DOM_DELTA_PAGE</code></td> + <td><code>0x02</code></td> + <td>Los valores delta están especificados en páginas.</td> + </tr> + </tbody> + </table> + </dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<p><em>Este interfaz no define ningún método, pero hereda métodos de estos padres, {{domxref("MouseEvent")}}, {{domxref("UIEvent")}} y {{domxref("Event")}}.</em></p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estatus</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('DOM3 Events','#interface-WheelEvent','WheelEvent')}}</td> + <td>{{Spec2('DOM3 Events')}}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_navegadores">Compatibilidad en navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Implementación básica</td> + <td>31</td> + <td>{{ CompatVersionUnknown }}</td> + <td>{{ CompatGeckoDesktop("17.0") }}</td> + <td>{{ CompatIE("9.0") }}</td> + <td>18</td> + <td>7.0</td> + </tr> + <tr> + <td><code>window.WheelEvent</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{ CompatVersionUnknown }}</td> + <td>{{ CompatGeckoDesktop("17.0") }}</td> + <td>{{ CompatIE("9.0") }}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}} [1]</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Implementación básica</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{ CompatGeckoMobile("17.0") }}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>window.WheelEvent</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{ CompatGeckoMobile("17.0") }}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Safari no implementa actualmente <code>WheelEvent</code> actually; sin embargo este devuelve un objeto para <code>window.WheelEvent</code>.</p> + +<h2 class="note" id="Ver_también">Ver también</h2> + +<ul> + <li>{{ event("wheel") }}</li> + <li>Interfaces reemplazados por este: + <ul> + <li>Objeto del evento de la rueda del ratón legado de la plataforma Gecko: {{ domxref("MouseScrollEvent") }}</li> + <li>Navegadores no-gecko, objeto del evento de la rueda del ratón legado: {{ domxref("MouseWheelEvent") }}</li> + </ul> + </li> +</ul> diff --git a/files/es/web/api/window/alert/index.html b/files/es/web/api/window/alert/index.html new file mode 100644 index 0000000000..fd7e9f7d01 --- /dev/null +++ b/files/es/web/api/window/alert/index.html @@ -0,0 +1,69 @@ +--- +title: Window.alert() +slug: Web/API/Window/alert +tags: + - Referencia + - metodo +translation_of: Web/API/Window/alert +--- +<p>{{ APIRef }}</p> + +<p>El método <strong><code>Window.alert()</code></strong> muestra un diálogo de alerta con contenido opcional especificado y un botón OK (Aceptar).</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox">window.alert(<em>message</em>);</pre> + +<ul> + <li><code>message</code> es un valor opcional del texto que se desea mostrar en el diálogo de alerta, o, alternativamente, un objeto que será convertido a texto y mostrado.</li> +</ul> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre class="brush: js">window.alert("Hello world!"); +</pre> + +<p>produce:</p> + +<p><img alt="Image:AlertHelloWorld.png" src="/files/130/AlertHelloWorld.png"></p> + +<h2 id="Notes" name="Notes">Más JS:</h2> + +<pre>alert()</pre> + +<h2 id="Notes" name="Notes">Notas</h2> + +<p>El diálogo alert debe ser usado para mensajes que no requieren respuesta por parte del usuario, otra que la aceptación del mensaje.</p> + +<p>Los cuadros de diálogo son ventanas modales - previenen que el usuario acceda al resto de la interfaz del programa hasta que el diálogo sea cerrado. Por esta razón, no se debe abusar de cualquier función que crea cuadros de diálogo (o ventanas modales).</p> + +<p>Los usuarios de <a href="/en-US/Chrome" title="Chrome">Mozilla Chrome</a> (p.ej. extensiones de Firefox) deben usar preferentemente métodos de {{interface("nsIPromptService")}}.</p> + +<p>A partir de Chrome {{CompatChrome(46.0)}}, este método está bloqueado para los elementos {{htmlelement("iframe")}}, a menos que su atributo <a href="/es/docs/Web/HTML/Elemento/iframe#attr-sandbox">sandbox</a> tenga el valor <code>allow-modal</code>.</p> + +<p>{{gecko_minversion_inline("23.0")}} El argumento es ahora opcional, como establece la especificación.</p> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentarios</th> + </tr> + <tr> + <td>{{SpecName('HTML5 Web application', '#dom-alert', 'alert()')}}</td> + <td>{{Spec2('HTML5 Web application')}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="See_also" name="See_also">Véase también</h2> + +<ul> + <li>{{domxref("window.confirm","confirm")}}</li> + <li>{{domxref("window.prompt","prompt")}}</li> + <li>Para <a href="/en-US/docs/Chrome" title="/en-US/docs/Chrome">Mozilla Chrome</a>, véase {{ifmethod("nsIPromptService","alert")}} y {{ifmethod("nsIPromptService","alertCheck")}}</li> +</ul> diff --git a/files/es/web/api/window/applicationcache/index.html b/files/es/web/api/window/applicationcache/index.html new file mode 100644 index 0000000000..37dac1f769 --- /dev/null +++ b/files/es/web/api/window/applicationcache/index.html @@ -0,0 +1,30 @@ +--- +title: window.applicationCache +slug: Web/API/Window/applicationCache +tags: + - Referencia_DOM_de_Gecko + - páginas_a_traducir +translation_of: Web/API/Window/applicationCache +--- +<p>{{ ApiRef() }} {{ Fx_minversion_header(3) }}</p> + +<h3 id="Resumen" name="Resumen">Resumen</h3> + +<p>Devuelve una referencia al objeto application cache para la ventana.</p> + +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> + +<pre class="eval"><em>cache</em> = window.applicationCache +</pre> + +<h3 id="Par.C3.A1metros" name="Par.C3.A1metros">Parámetros</h3> + +<ul> + <li><code>cache</code> es una referencia a un objeto {{ Interface("nsIDOMOfflineResourceList") }}.</li> +</ul> + +<h3 id="Especificaci.C3.B3n" name="Especificaci.C3.B3n">Especificación</h3> + +<ul> + <li><a class="external" href="http://www.w3.org/TR/2008/WD-html5-20080122/#appcache">HTML 5 working draft</a></li> +</ul> diff --git a/files/es/web/api/window/cancelanimationframe/index.html b/files/es/web/api/window/cancelanimationframe/index.html new file mode 100644 index 0000000000..eae485c315 --- /dev/null +++ b/files/es/web/api/window/cancelanimationframe/index.html @@ -0,0 +1,118 @@ +--- +title: window.cancelAnimationFrame() +slug: Web/API/Window/cancelAnimationFrame +translation_of: Web/API/Window/cancelAnimationFrame +--- +<div>{{APIRef}}{{SeeCompatTable}}</div> + +<h2 id="Summary" name="Summary">Resumen</h2> + +<p>Cancela la petición de animación previamente programada a través de {{domxref("window.requestAnimationFrame()")}}.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox">window.cancelAnimationFrame(<em>requestID</em>); +</pre> + +<div class="note"> +<p><strong>Nota:</strong> Antes de Firefox 23, la función es independiente del proveedor con el prefijo <code>window.mozCancelAnimationFrame()</code>. Consulte la tabla de compatibilidad, a continuación, para otras implementaciones de navegador.</p> +</div> + +<h3 id="Parameters" name="Parameters">Parámetros</h3> + +<dl> + <dt><code>ID de la petición</code></dt> + <dd>El valor del ID regresado por la llamada a {{domxref("window.requestAnimationFrame()")}} que solicitó una llamada de vuelta.</dd> +</dl> + +<h2 id="Examples" name="Examples">Ejemplos</h2> + +<pre class="brush: js">var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || + window.webkitRequestAnimationFrame || window.msRequestAnimationFrame; + +var cancelAnimationFrame = window.cancelAnimationFrame || window.mozCancelAnimationFrame; + +var start = window.mozAnimationStartTime; // Only supported in FF. Other browsers can use something like Date.now(). + +var myReq; + +function step(timestamp) { + var progress = timestamp - start; + d.style.left = Math.min(progress/10, 200) + "px"; + if (progress < 2000) { + myReq = requestAnimationFrame(step); + } +} +myReq = requestAnimationFrame(step); + +window.cancelAnimationFrame(myReq); +</pre> + +<h2 id="Browser_compatibility" name="Browser_compatibility">Compatibilidad de navegadores</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>21.0 {{property_prefix("webkit")}}<br> + 24.0</td> + <td>{{CompatGeckoDesktop("11.0")}} {{property_prefix("moz")}}<br> + 23.0</td> + <td>10</td> + <td>15.0</td> + <td>6.0 {{property_prefix("webkit")}}<br> + 6.1</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</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>Soporte básico</td> + <td>4.4</td> + <td>33</td> + <td>{{CompatGeckoMobile("11.0")}} {{property_prefix("moz")}}<br> + 23.0</td> + <td>10</td> + <td>33</td> + <td>7.1</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<ul> + <li>{{spec("http://www.w3.org/TR/animation-timing/#cancelAnimationFrame", "Timing control for script-based animations: cancelAnimationFrame", "WD")}}</li> +</ul> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("window.mozAnimationStartTime")}}</li> + <li>{{domxref("window.requestAnimationFrame()")}}</li> +</ul> diff --git a/files/es/web/api/window/close/index.html b/files/es/web/api/window/close/index.html new file mode 100644 index 0000000000..e4a3c910ee --- /dev/null +++ b/files/es/web/api/window/close/index.html @@ -0,0 +1,76 @@ +--- +title: Window.close() +slug: Web/API/Window/close +translation_of: Web/API/Window/close +--- +<p>{{ ApiRef() }}</p> + +<h2 id="Summary" name="Summary">Resumen</h2> + +<p>Cierra la ventana actual, o la ventana en la cual fue llamada.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="eval"><em>window</em>.close(); +</pre> + +<h2 id="Description" name="Description">Descripción</h2> + +<p>Cuando este método es llamado, la ventana referenciada es cerrada.</p> + +<p>Este método solo se permite ser llamado por ventanas que fueron abiertas por un script utilizando el método {{domxref("window.open()")}}. Si la ventana no fue abierta por un script, el siguiente error aparece en la consola de JavaScript: S<code>cripts</code><code> may not close windows that were not opened by script.</code></p> + +<h2 id="Examples" name="Examples">Ejemplos</h2> + +<h3 id="Closing_a_window_opened_with_window.open.28.29" name="Closing_a_window_opened_with_window.open.28.29">Cerrar una ventana abierta con window.open()</h3> + +<p>Este es un ejemplo que demuestra como utilizar este método para cerrar una ventana que fue abierta por un script llamando {{domxref("window.open()")}}.</p> + +<pre><script type="text/javascript"> +//Global var to store a reference to the opened window +var openedWindow; + +function openWindow() +{ + openedWindow = window.open('moreinfo.htm'); +} + +function closeOpenedWindow() +{ + openedWindow.close(); +} +</script> +</pre> + +<h3 id="Closing_the_current_window" name="Closing_the_current_window">Cerrando la ventana actual</h3> + +<h3 id="Closing_the_current_window" name="Closing_the_current_window"><span style="font-size: 14px; line-height: 1.5;">Cuando se llama al método del objeto window close() directamente, en vez de llamar a close() en una instancia de la ventana, el navegador cerrará la ventana que está en primer plano, independientemente si el script fue creado en la ventana o no.</span><span style="font-size: 14px; line-height: 1.5;"> (Firefox 35.0.1: los scripts no pueden cerrar ventanas que ellos no han abierto)</span></h3> + +<pre><script type="text/javascript"> +function closeCurrentWindow() +{ + window.close(); +} +</script> +</pre> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', '#dom-window-close', 'window.close()')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Additional_Reference" name="Additional_Reference">Referencia adicional</h2> + +<p>{{Compat("api.Window.close")}}</p> diff --git a/files/es/web/api/window/closed/index.html b/files/es/web/api/window/closed/index.html new file mode 100644 index 0000000000..b5caf862f3 --- /dev/null +++ b/files/es/web/api/window/closed/index.html @@ -0,0 +1,65 @@ +--- +title: Window.closed +slug: Web/API/Window/closed +tags: + - API + - HTML DOM + - Propiedad + - Referencia + - Ventana +translation_of: Web/API/Window/closed +--- +<div>{{APIRef}}</div> + +<h2 id="Resumen">Resumen</h2> + +<p>Esta propiedad de solo lectura indica si la ventana referenciada está cerrada o no.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><var>isClosed</var> = <var>windowRef</var>.closed; +</pre> + +<dl> + <dt><code>isClosed</code></dt> + <dd>Booleano. Valores posibles: + <ul> + <li><code>true</code>: La ventana ha sido cerrada.</li> + <li><code>false</code>: La ventana está abierta.</li> + </ul> + </dd> +</dl> + +<h2 id="Ejemplos">Ejemplos</h2> + +<h3 id="Cambiar_la_URL_de_una_ventana_desde_una_ventana_emergente">Cambiar la URL de una ventana desde una ventana emergente</h3> + +<p>El siguiente ejemplo demuestra cómo una ventana emergente puede cambiar la URL de la ventana que la abrió. Antes de intentar cambiar la URL, verifica que la ventana actual tiene referencia a la ventana que la abrió usando la propiedad <a href="/en-US/docs/DOM/window.opener">window.opener</a> y que esa ventana no está cerrada:</p> + +<pre class="brush:js">// Verifica que <em>opener</em> existe y no esté cerrado +if (window.opener && !window.opener.closed) { + window.opener.location.href = "http://www.mozilla.org"; +}</pre> + +<p>Nótese que las ventanas emergentes solo pueden acceder a la ventana que las abrió.</p> + +<h3 id="Actualizando_una_ventana_emergente_abierta_previamente">Actualizando una ventana emergente abierta previamente</h3> + +<p>En este ejemplo la función <code>refreshPopupWindow()</code> llama al método <code>reload</code> del objeto location de la ventana emergente para actualizar su información. Si la ventana emergente no ha sido abierta o el usuario la cerró una nueva ventana es abierta.</p> + +<pre class="brush:js">var popupWindow = null; + +function refreshPopupWindow() { + if (popupWindow && !popupWindow.closed) { + // popupWindow está abierta, actualízala + popupWindow.location.reload(true); + } else { + // Abre una nueva ventana emergente + popupWindow = window.open("popup.html","dataWindow"); + } +} +</pre> + +<h2 id="Especificación">Especificación</h2> + +<p>HTML5</p> diff --git a/files/es/web/api/window/confirm/index.html b/files/es/web/api/window/confirm/index.html new file mode 100644 index 0000000000..a09a6cdb1d --- /dev/null +++ b/files/es/web/api/window/confirm/index.html @@ -0,0 +1,64 @@ +--- +title: Window.confirm() +slug: Web/API/Window/confirm +translation_of: Web/API/Window/confirm +--- +<div>{{ApiRef("Window")}}</div> + +<p>El método <code><strong>Window.confirm()</strong></code> muestra una ventana de diálogo con un mensaje opcional y dos botones, Aceptar y Cancelar.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre><em>result</em> = window.confirm(<em>message</em>); +</pre> + +<ul> + <li><code>message</code> es la cadena que se muestra opcionalmente en el diálogo.</li> + <li><code>result</code> es un valor booleano indicando si se ha pulsado Aceptar o Cancelar (Aceptar devuelve true).</li> +</ul> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre>if (window.confirm("Do you really want to leave?")) { + window.open("exit.html", "Thanks for Visiting!"); +} +</pre> + +<p>Da como resultado:</p> + +<p><img alt="firefox confirm" src="https://mdn.mozillademos.org/files/7163/firefoxcomfirmdialog_zpsf00ec381.png" style="height: 119px; width: 354px;"><br> + </p> + +<h2 id="Notes" name="Notes">Notas</h2> + +<p><span class="comment">The following text is shared between this article, DOM:window.prompt and DOM:window.alert</span> Las cajas de diálogo son ventanas modales - ello impide al usuario continuar accediendo al resto del interfaz del programa hasta que la ventana modal haya sido cerrada. Por esta razón no se debería usar en exceso funciones que creen cajas de diálogo (o ventanas modales). No obstante, hay muy buenas razones para <a href="http://alistapart.com/article/neveruseawarning">evitar el uso de cajas de diálogo para confirmaciones</a>.</p> + +<p>Los usuarios de <a href="/en-US/Chrome" title="Chrome">Mozilla Chrome</a> users (e.g. Firefox extensions) deberían usar métodos de {{interface("nsIPromptService")}} en vez de cajas de diálogo.</p> + +<p>A partir de la versión {{CompatChrome(46.0)}} de Chrome este método es bloqueado dentro de un {{htmlelement("iframe")}} a no ser que el atributo sandbox tenga el valor <code>allow-modal</code>.</p> + +<p>{{gecko_minversion_inline("23.0")}} El argumento es opcional y no requerido por la especificación.</p> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentarios</th> + </tr> + <tr> + <td>{{SpecName('HTML5 Web application', '#dom-confirm', 'confirm()')}}</td> + <td>{{Spec2('HTML5 Web application')}}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="See_also" name="See_also">Ver también</h2> + +<ul> + <li>{{domxref("window.alert","alert")}}</li> + <li>{{domxref("window.prompt","prompt")}}</li> +</ul> diff --git a/files/es/web/api/window/crypto/index.html b/files/es/web/api/window/crypto/index.html new file mode 100644 index 0000000000..49756dfc08 --- /dev/null +++ b/files/es/web/api/window/crypto/index.html @@ -0,0 +1,88 @@ +--- +title: Window.crypto +slug: Web/API/Window/crypto +translation_of: Web/API/Window/crypto +--- +<p>{{APIRef}}</p> + +<p>La propiedad de sólo lectura {{domxref("Window.crypto")}} devuelve el objeto <a href="/es/docs/Web/API/Crypto">Crypto</a> asociado a un objeto global. Este objeto permite a las páginas web acceder a ciertos servicios relacionados con criptografía.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var <em>cryptoObj</em> = window.crypto || window.msCrypto; // para IE 11 +</pre> + +<h2 id="Specification" name="Specification">Especificaciones</h2> + +<table class="spec-table standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('Web Crypto API')}}</td> + <td>{{Spec2('Web Crypto API')}}</td> + <td>Definición Inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_Navegadores">Compatibilidad de Navegadores</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Sporte Básico</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>11 {{ property_prefix("-ms") }}</td> + <td>15</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th><span style="font-family: open sans light,helvetica,arial,sans-serif; font-size: 16px; line-height: 16px;">Característica</span></th> + <th>Android</th> + <th>Chrome para Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_También">Ver También</h2> + +<ul> + <li>El objeto Global {{domxref("Window")}}</li> +</ul> diff --git a/files/es/web/api/window/devicepixelratio/index.html b/files/es/web/api/window/devicepixelratio/index.html new file mode 100644 index 0000000000..97db13d974 --- /dev/null +++ b/files/es/web/api/window/devicepixelratio/index.html @@ -0,0 +1,91 @@ +--- +title: Window.devicePixelRatio +slug: Web/API/Window/devicePixelRatio +translation_of: Web/API/Window/devicePixelRatio +--- +<p>{{APIRef}}</p> + +<p>La propiedad de sólo-lectura <code>Window.devicePixelRatio</code> retorna la relación de tamaño (vertical) de un pixel físico en el dispositivo de visualización actual respecto del de un dispositivo de tamaño de pixel independiente (dips).</p> + +<p>No hay retrofunciones o eventos a escuchar cuando este valor cambia (por ejemplo, si usted arrastra la ventana entre displays con diferentes densidades de pixels).</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox"><em><var>value</var></em> = window.devicePixelRatio; +</pre> + +<h2 id="Especificación">Especificación</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Observaciones</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("CSSOM View", "#dom-window-devicepixelratio", "Window.devicePixelRatio")}}</td> + <td>{{Spec2("CSSOM View")}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">Compatibilidad con navegadores</h2> + +<p>{{ CompatibilityTable }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Prestación</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Prestación</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/Web/CSS/@media/resolution">consultas de resolución de medio CSS</a></li> + <li>PPK hace alguna <a href="http://www.quirksmode.org/blog/archives/2012/06/devicepixelrati.html">iinvestigación en devicePixelRatio</a></li> +</ul> diff --git a/files/es/web/api/window/dialogarguments/index.html b/files/es/web/api/window/dialogarguments/index.html new file mode 100644 index 0000000000..f3f23cb43e --- /dev/null +++ b/files/es/web/api/window/dialogarguments/index.html @@ -0,0 +1,14 @@ +--- +title: Window.dialogArguments +slug: Web/API/Window/dialogArguments +translation_of: Web/API/Window/dialogArguments +--- +<p>{{APIRef}}</p> + +<h2 id="Summary" name="Summary">Resumen</h2> + +<p>La propiedad <code>dialogArguments</code> retorna los parámetros que fueron pasados al método {{domxref("window.showModalDialog()")}}. Esto permite determinar qué parámetros fueron especificados cuando el diálogo modal fue creado.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox"><var>value</var> = window.dialogArguments;</pre> diff --git a/files/es/web/api/window/document/index.html b/files/es/web/api/window/document/index.html new file mode 100644 index 0000000000..d5acd251de --- /dev/null +++ b/files/es/web/api/window/document/index.html @@ -0,0 +1,46 @@ +--- +title: Window.document +slug: Web/API/Window/document +translation_of: Web/API/Window/document +--- +<div>{{APIRef}}</div> + +<h2 id="Summary" name="Summary">Resumen</h2> + +<p>Retorna una referencia al documento contenido en la ventana.</p> + +<div class="note"><strong>Nota:</strong> {{Fx_minversion_inline(3)}} Firefox 3 altera la seguridad para los documentos entre ventanas, de modo que sólo el dominio desde el cual ha sido cargada una ventana puede acceder al documento. A pesar de que esto rompe el funcionamiento de algunos sitios existentes, es una modificación adoptada por Firefox 3 e Internet Explorer 7, que resulta en una mejora de seguridad.</div> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox"><var>doc</var> = window.document +</pre> + +<h3 id="Parameters" name="Parameters">Parámetros</h3> + +<ul> + <li><code>doc</code> es una referencia al objeto del <a href="/en-US/docs/DOM/document" title="DOM/document">document</a>.</li> +</ul> + +<h2 id="Example" name="Example">Example</h2> + +<pre class="brush:html"><!DOCTYPE html> +<html> +<head> + <title>Hola, Mundo!</title> +</head> +<body> + +<script type="text/javascript"> + var doc = window.document; + console.log(doc.title); // Hola, Mundo! +</script> + +</body> +</html></pre> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<ul> + <li><a href="http://www.whatwg.org/html/#the-window-object" title="http://www.whatwg.org/html/#the-window-object">HTML</a></li> +</ul> diff --git a/files/es/web/api/window/frameelement/index.html b/files/es/web/api/window/frameelement/index.html new file mode 100644 index 0000000000..27f809265c --- /dev/null +++ b/files/es/web/api/window/frameelement/index.html @@ -0,0 +1,106 @@ +--- +title: Window.frameElement +slug: Web/API/Window/frameElement +translation_of: Web/API/Window/frameElement +--- +<div>{{ ApiRef }}</div> + +<p>Retorna el elemento (como es {{HTMLElement("iframe")}} ó {{HTMLElement("object")}}) en el cual la ventana está incrustada o <code>null</code> si el elemento es bien de nivel superior (top-level) o bien está inrustada en un documento con un origen de diferente; esto es, en situaciones de origen cruzado.</p> + +<h2 id="Sintaxes">Sintaxes</h2> + +<pre class="syntaxbox"><var>frameEl</var> = window.frameElement; +</pre> + +<ul> + <li><code>frame El</code> es el elemento dentro del cual está empotrada la ventana. Si la ventana no está incrustada dentro de otro documento, o si el documento en el que está empotrada tiene un origen diferente (como procede de un dominio diferente), este valor será <code>null</code>.</li> +</ul> + +<div class="note"> +<p>A pesar del nombre de esta propiedad, funciona para documentos empotrados en cualquier forma o método de incrustación, incluyendo {{HTMLElement("object")}}, {{HTMLElement("iframe")}}, or {{HTMLElement("embed")}}.</p> +</div> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush:js">var frameEl = window.frameElement; +// Si estamos empotrados, cambia la URL de elemento contenedor to 'http://mozilla.org/' +if (frameEl) { + frameEl.src = 'http://mozilla.org/'; +} +</pre> + +<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">Observaciones</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('HTML WHATWG', '#dom-frameelement', 'Window.frameElement') }}</td> + <td>{{ Spec2('WebRTC 1.0') }}</td> + <td>Especificación inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Prestación</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>4?</td> + <td>{{CompatGeckoDesktop("1")}}</td> + <td>5.5?</td> + <td>12.1?</td> + <td>4?</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Prestación</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("1")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("window.frames")}} retorna un objeto enumerable, listando los sub-frames directos de la ventana actual.</li> + <li>{{domxref("window.parent")}} retorna la ventana padre, la cual es la ventana que contiene el <code>frameElement</code> de la ventana hija.</li> +</ul> diff --git a/files/es/web/api/window/fullscreen/index.html b/files/es/web/api/window/fullscreen/index.html new file mode 100644 index 0000000000..7662bc7888 --- /dev/null +++ b/files/es/web/api/window/fullscreen/index.html @@ -0,0 +1,43 @@ +--- +title: window.fullScreen +slug: Web/API/Window/fullScreen +tags: + - Referencia_DOM_de_Gecko + - páginas_a_traducir +translation_of: Web/API/Window/fullScreen +--- +<div>{{APIRef}}</div> + +<h3 id="Resumen" name="Resumen">Resumen</h3> + +<p>Esta propiedad indica si la ventana se presenta en modo de pantalla comleta o no. Su funcionamiento es sólo fiable a partir de Gecko 1.9 (Firefox 3), ver Notas más abajo.</p> + +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> + +<pre class="eval">var <var>isInFullScreen</var> = <var>windowRef</var>.fullScreen; +</pre> + +<p><br> + Con privilegios chrome, el valor de esta propiedad se puede cambiar, de otra forma, es de sólo lectura. Ten en cuenta que si intentas cambiar el valor de esta propiedad sin tener privilegios chrome, no cambiará nada y la propiedad simplemente fallará. Esto se hace para evitar que los programas diseñados para Internet Explorer fallen.</p> + +<h3 id="Valor_devuelto" name="Valor_devuelto">Valor devuelto</h3> + +<dl> + <dt><code>isInFullScreen</code></dt> + <dd>Un valor<em>binario</em> . Los valores posibles son:</dd> +</dl> + +<ul> + <li><code>true</code>: (Cierto) la ventana esta en modo pantalla completa.</li> + <li><code>false</code>: (Falso)la ventana NO esta en modo pantalla completa.</li> +</ul> + +<h3 id="Ejemplos" name="Ejemplos">Ejemplos</h3> + +<h3 id="Especificaciones" name="Especificaciones">Especificaciones</h3> + +<p>DOM nivel 0. <code>window.fullScreen</code> no forma parte de ninguna especificación W3C.</p> + +<h3 id="Notas" name="Notas">Notas</h3> + +<p>El funcionamiento de esta propiedad es fiable sólo en Mozilla 1.9 (Firefox 3) y posteriores. Mozilla 1.8 y versiones anteriores manejan esta propiedad pero el valor devuelto es siempre <code>false</code>, aún cuando la ventana está en modo pantalla completa ({{ Bug(127013) }}).</p> diff --git a/files/es/web/api/window/getcomputedstyle/index.html b/files/es/web/api/window/getcomputedstyle/index.html new file mode 100644 index 0000000000..3ce1aa1c0b --- /dev/null +++ b/files/es/web/api/window/getcomputedstyle/index.html @@ -0,0 +1,26 @@ +--- +title: Window.getComputedStyle +slug: Web/API/Window/getComputedStyle +translation_of: Web/API/Window/getComputedStyle +--- +<p>{{ ApiRef() }}</p> +<h3 id="Summary" name="Summary">Resumen</h3> +<p>Devuelve el estilo computado del elemento. Los estilos computados representan los valores finales <a class="external" href="http://www.w3.org/TR/1998/REC-CSS2-19980512/cascade.html#computed-value">computed (en)</a> de las propiedades CSS del elemento. </p> +<h3 id="Syntax" name="Syntax">Sintaxis</h3> +<pre class="eval">var <em>style</em> = window.getComputedStyle(<em>element</em>, <em>pseudoElt</em>); +</pre> +<ul> + <li><code>element</code> es un <a href="/es/DOM/element" title="en/DOM/element">element</a>.</li> + <li><code>pseudoElt</code> es una cadena que especifica el pseudo elemento a tratar. Debería ser una cadena vacia para la mayoría de los elementos element.</li> + <li><code>style</code> es un objeto del tipo <a class="external" href="http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSview-getComputedStyle"><code>CSSStyleDeclaration</code></a> .</li> +</ul> +<h3 id="Example" name="Example">Ejemplo</h3> +<pre class="eval">var element = document.getElementById(“elemId”); +var <em>style</em> = document.defaultView.getComputedStyle(<em>element</em>, <em>pseudoElt</em>); +</pre> +<h3 id="Description" name="Description">Descripción</h3> +<p>El objeto devuelto es del mismo tipo que el objeto devuelto por la propiedad <a href="/es/DOM/element.style" title="es/DOM/element.style">style</a> del elemento, sin embargo ambos objetos tienen un propósito distinto. El objeto devuelto por <code>getComputedStyle</code> es de sólo lectura y puede usarse para inspeccionar el estilo del elemento (incluyendo los estilos de una etiqueta <style> o una hoja de estlo). El objeto <code>elt.style</code> debería usarse para establecerel estilo de un elemento específico.</p> +<p>El primer argumento debe ser un Element, no un nodo (como en #texto Node).</p> +<h3 id="Specification" name="Specification">Especificación</h3> +<p><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSview-getComputedStyle">DOM Level 2 Style: getComputedStyle</a></p> +<p>{{ languages( { "ja": "ja/DOM/window.getComputedStyle" } ) }}</p> diff --git a/files/es/web/api/window/getselection/index.html b/files/es/web/api/window/getselection/index.html new file mode 100644 index 0000000000..4e08399ad5 --- /dev/null +++ b/files/es/web/api/window/getselection/index.html @@ -0,0 +1,53 @@ +--- +title: window.getSelection +slug: Web/API/Window/getSelection +tags: + - páginas_a_traducir +translation_of: Web/API/Window/getSelection +--- +<div>{{ ApiRef() }}</div> + +<h3 id="Resumen" name="Resumen">Resumen</h3> + +<p>Devuelve un objeto de selección representando el rango del texto seleccionado por el usuario. <span class="comment">NB. this is nothing to do with the DOM selection list object! What the heck is 'selection list object'? -Nickolay</span></p> + +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> + +<pre class="eval"><em>selection</em> =<em>window</em>.getSelection() ; +</pre> + +<ul> + <li><code>selection</code> es un objeto de <a href="/es/docs/Web/API/Selection">selección</a>.</li> +</ul> + +<h3 id="Ejemplo" name="Ejemplo">Ejemplo</h3> + +<pre class="eval">function foo() { + var selObj = window.getSelection(); + alert(selObj); + var selRange = selObj.getRangeAt(0); + // ... Hacer las cosas con el rango ... +} +</pre> + +<h3 id="Notas" name="Notas">Notas</h3> + +<p>En JavaScript, cuando un objeto de selección es pasado a una función que espera una cadena de caracteres como parámetro (como {{ Domxref("window.alert") }} o {{ Domxref("document.write") }}), una representación de texto, del objeto de selección (e.j. el texto seleccionado) es pasado en vez del objeto en sí. Esto hace al objeto de selección parecer una cadena de caracteres (texto), cuando realmente es un objeto con sus propios métodos y propiedades. Específicamente, el valor de retorno de llamar al método <code><a href="es/DOM/Selection/toString">toString()</a></code> del objeto de selección es lo que realmente se pasa como parámetro a la función.</p> + +<p>En el ejemplo de arriba, <code>selObj</code> es automaticamente "convertido" cuando pasó a <a href="es/DOM/window.alert">window.alert</a>. Sin embargo, para usar una propiedad <a href="es/JS/String">String</a> de JavaScript o un método como <code><a href="es/JS/String.prototype.length">length</a></code> o <code><a href="es/JS/String.prototype.substr">substr</a></code>, debe llamar manualmente al método <code>toString</code>. <span class="comment">I'm treading carefully with the word "convert" here because it could be misinterpreted as a permanent convert - Maian</span></p> + +<h3 id="Especificaci.C3.B3n" name="Especificaci.C3.B3n">Especificación</h3> + +<p>DOM Nivel 0. No es parte de ninguna especificación.</p> + +<h3 id="Ver_tambi.C3.A9n" name="Ver_tambi.C3.A9n">Ver también</h3> + +<p><a href="es/docs/Web/API/Selection">Selection</a>, <a href="es/docs/Web/API/Range">Range</a></p> + + + + + +<div class="noinclude"></div> + +<p>{{ languages( { "en": "en/DOM/window.getSelection", "fr": "fr/DOM/window.getSelection", "it": "it/DOM/window.getSelection", "ja": "ja/DOM/window.getSelection", "pl": "pl/DOM/window.getSelection" } ) }}</p> diff --git a/files/es/web/api/window/hashchange_event/index.html b/files/es/web/api/window/hashchange_event/index.html new file mode 100644 index 0000000000..e0a5be4bbc --- /dev/null +++ b/files/es/web/api/window/hashchange_event/index.html @@ -0,0 +1,194 @@ +--- +title: hashchange +slug: Web/API/Window/hashchange_event +tags: + - Referencia + - URL + - Web +translation_of: Web/API/Window/hashchange_event +--- +<p>El evento <code>hashchange</code> es ejecutado cuando el fragmento identificador de la URL ha cambiado (la parte de la URL que continúa despues del simbolo #, incluyendo el símbolo #).</p> + +<table class="properties"> + <tbody> + <tr> + <td>Burbujas</td> + <td>Si</td> + </tr> + <tr> + <td>Cancelable</td> + <td>No</td> + </tr> + <tr> + <td>Objetivo</td> + <td>{{domxref("Window")}}</td> + </tr> + <tr> + <td>Interface</td> + <td>{{domxref("HashChangeEvent")}}</td> + </tr> + <tr> + <td>Acción predeterminada</td> + <td>Ninguna</td> + </tr> + </tbody> +</table> + +<h2 id="Propiedades">Propiedades</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 browsing context (<code>window</code>).</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> + <tr> + <td><code>oldURL</code> {{readonlyInline}}</td> + <td>{{jsxref("String")}}</td> + <td>The previous URL from which the window was navigated.</td> + </tr> + <tr> + <td>newURL {{readonlyInline}}</td> + <td>{{jsxref("String")}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<p>En <a href="https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills">esta página</a> se enlistan algunos scripts de ejemplo. Básicamente estos scripts revisan el <code>location.hash</code> en un intervalo regular. Aquí se muestra una versión que permite que solo un controlador sea ligado a la propiedad <code>window.onhashchange</code>:</p> + +<pre class="brush:js;">;(function(window) { + + // salir si el navegador implementa el evento + if ("onhashchange" in window) { return; } + + var location = window.location, + oldURL = location.href, + oldHash = location.hash; + + // revisa el hash cada 100ms + setInterval(function() { + var newURL = location.href, + newHash = location.hash; + + // si el hash ha cambiado y un controlador ha sido ligado... + if (newHash != oldHash && typeof window.onhashchange === "function") { + // ejecuta el controlador + window.onhashchange({ + type: "hashchange", + oldURL: oldURL, + newURL: newURL + }); + + oldURL = newURL; + oldHash = newHash; + } + }, 100); + +})(window); +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificacion</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', 'indices.html#event-hashchange', 'hashchange')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>5.0</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("1.9.2")}}<sup>[1]</sup></td> + <td>8.0<sup>[2]</sup></td> + <td>10.6</td> + <td>5.0</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>2.2</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("1.9.2")}}</td> + <td>9.0</td> + <td>11.0</td> + <td>5.0</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Soporte para los atributos <code>oldURL</code>/<code>newURL</code> agregado en Firefox 6.</p> + +<p>[2] Atributos <code>oldURL</code>/<code>newURL</code> no soportados.</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/Mozilla_event_reference/popstate"><code>popstate</code></a></li> + <li><a href="/en-US/docs/Web/API/WindowEventHandlers/onhashchange">WindowEventHandlers.onhashchange</a></li> +</ul> diff --git a/files/es/web/api/window/history/index.html b/files/es/web/api/window/history/index.html new file mode 100644 index 0000000000..02fb7a8cab --- /dev/null +++ b/files/es/web/api/window/history/index.html @@ -0,0 +1,39 @@ +--- +title: Window.history +slug: Web/API/Window/history +translation_of: Web/API/Window/history +--- +<p>{{ APIRef }}</p> + +<p>La propiedad de solo lectura <code><strong>Window.history</strong></code> regresa una referencia al objeto {{domxref("History")}}, quien provee una interfaz para manipular el historial de <em>sesión del navegador</em> (páginas visitadas en el tab o marco de la pagina actual cargada).</p> + +<p>Ver <a href="/es/docs/DOM/Manipulando_el_historial_del_navegador" title="en/DOM/Manipulating the browser history">Manipulando el historial del navegador</a> para ejemplos y detalles. En particular, este articulo explica características seguras de los métodos <code>pushState()</code> y <code>replaceState()</code> que debe tener en cuenta antes de usarlos. </p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox"><em>var historyObj</em> = <em>window</em>.history; +</pre> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre class="brush: js">history.back(); // equivalente a hacer clic en el botón de regresar +history.go(-1); // equivalente a history.back(); +</pre> + +<h2 id="Notes" name="Notes">Notas</h2> + +<p>Para las páginas de nivel superior se puede ver la lista de páginas en el historial de la sesión, accesible a través del objeto de la <code>History</code>, en los desplegables de tu navegador junto a los botones de avance y retroceso.</p> + +<p>Por razones de seguridad el objeto <code>History</code> no permite que el código sin privilegio acceda a las URLs de otras páginas en el historial de la sesión, pero permite navegar por el historial de la sesión.</p> + +<p>No hay manera de limpiar el historial de la sesión o desactivar la parte de atrás/adelante desde la navegación de código sin privilegios. La solución más cercana disponible es el método <code><a href="/es/docs/Web/API/Window/location#replace">location.replace()</a></code>, que sustituye al elemento actual de la historia sesión con la URL proporcionada.</p> + +<p>{{Compat("api.Window.history")}}</p> + +<p> + </p><h2 id="Specification" name="Specification">Especificaciones</h2> +<p></p> + +<ul> + <li><a class="external" href="http://whatwg.org/html#the-history-interface">Historial de interface HTML5</a></li> +</ul> diff --git a/files/es/web/api/window/index.html b/files/es/web/api/window/index.html new file mode 100644 index 0000000000..c0f8e9aa38 --- /dev/null +++ b/files/es/web/api/window/index.html @@ -0,0 +1,412 @@ +--- +title: window +slug: Web/API/Window +tags: + - API + - DOM + - Window + - páginas_a_traducir +translation_of: Web/API/Window +--- +<p>{{APIRef}}</p> + +<p><span class="seoSummary">El objeto <code>window</code> representa la ventana que contiene un documento DOM; la propiedad <code>document</code> apunta al <a href="/es/docs/DOM/document">DOM document</a> cargado en esa ventana.</span> El objeto window al que pertenece un documento puede ser obtenido usando la propiedad {{Domxref("document.defaultView")}}.</p> + +<p>Esta sección proporciona una pequeña referencia a todos los métodos, propiedades y eventos disponibles a través del objeto DOM <code>window</code>. El objeto <code>window</code> implementa la interfaz <code>Window</code> , que a su vez hereda de la interfaz <code><a href="http://www.w3.org/TR/DOM-Level-2-Views/views.html#Views-AbstractView">AbstractView</a></code>. Algunas funciones como globales adicionales, espacios de nombres, interfaces, y constructores no típicamente asociados con el objeto window pero disponibles en éste, están listados en las <a href="/es/docs/Web/JavaScript/Referencia">Referencia de JavaScript</a> y en el <a href="/es/docs/Referencia_DOM_de_Gecko" title="/en-US/docs/DOM/DOM_Reference">Referencia DOM de Gecko</a>.</p> + +<p>En un navegador con pestañas, como Firefox, cada pestaña contine su propio <code>window</code> object (y si está escribiendo una extensión, la ventana del navegador es una ventana separada también - para más información vea <a href="/es/docs/Trabajar_con_ventanas_desde_código_chrome#Content_windows">Trabajar con ventanas desde el código chrome</a>). Esto significa que el objeto <code>window</code> no se comparte entre diferentes pestañas de la misma ventana del navegador. Algunos métodos, como {{Domxref("window.resizeTo")}} y {{Domxref("window.resizeBy")}} se aplican sobre toda la ventana del navegador y no sobre una pestaña específica a la que pertenece el objeto <code>window</code>. Generalmente, cualquier cosa que razonablemente no pueda pertenecer a una pestaña, pertenece a la ventana.</p> + +<h2 id="Constructores">Constructores</h2> + +<p>Ver también <a href="/en-US/docs/DOM/DOM_Reference" title="/en-US/docs/DOM/DOM_Reference">DOM Interfaces</a>.</p> + +<dl> + <dt>{{domxref("Window.DOMParser")}}</dt> + <dd><code>DOMParser</code> puede traducir una fuente XML o HTML almacenada en una cadena en un <a href="/es/docs/Archive/Mozilla/XUL/Tutorial_de_XUL/Modelo_de_objeto_de_documento">Documento</a> DOM. <code>DOMParser</code> se especifica en <a href="https://w3c.github.io/DOM-Parsing/">DOM Parsing and Serialization.</a></dd> + <dt>{{domxref("Image")}}</dt> + <dd>Se usa para crear un {{domxref("HTMLImageElement")}}.</dd> + <dt>{{domxref("Option")}}</dt> + <dd>Se usa para crear un {{domxref("HTMLOptionElement")}}</dd> +</dl> + +<dl> + <dt>{{domxref("StaticRange")}} {{experimental_inline}} {{readonlyinline}}</dt> + <dd>Retorna un constructor {{domxref('StaticRange.StaticRange','StaticRange()')}} que crea un objeto {{domxref('StaticRange')}}.</dd> +</dl> + +<dl> + <dt>{{domxref("Worker")}}</dt> + <dd>Se usa para crear un <a href="/en-US/docs/DOM/Using_web_workers">Web worker.</a></dd> + <dt>{{domxref("Window.XMLSerializer")}}</dt> + <dd>Convierte un árbol DOM en una fuente XML o HTML.</dd> +</dl> + +<h2 id="Propiedades">Propiedades</h2> + +<p><em>Esta interface hereda propiedades de {{domxref("EventTarget")}} interface e implementa propiedades de {{domxref("WindowTimers")}}, {{domxref("WindowBase64")}}, y {{domxref("WindowEventHandlers")}}.</em></p> + +<p>Nota que la propiedades que son objetos (por ejemplo para sobreescribir los prototipos de los elementos built-in) son descritos en una sección separada más abajo.</p> + +<dl> + <dt>{{domxref("Window.applicationCache")}} {{readOnlyInline}} {{gecko_minversion_inline("1.9")}}</dt> + <dd>An {{domxref("OfflineResourceList")}} object providing access to the offline resources for the window.</dd> + <dt>{{domxref("Window.closed")}} {{Non-standard_inline}}{{readOnlyInline}}</dt> + <dd>Esta propiedad indica si la actual ventana esta cerrada o abierta.</dd> + <dt><code><a href="/en-US/docs/Components_object">Window.Components</a></code> {{Non-standard_inline}}</dt> + <dd>El punto de acceso a muchas propiedades <a href="/en-US/docs/XPCOM">XPCOM</a>. Algunas propiedades, ej. <a href="/en-US/docs/Components.classes">classes</a>, son disponibles solamente a codigo suficientemente privilegiado. <strong>El codigo Web no deberia usar esta propiedad.</strong></dd> + <dt>{{domxref("console","Window.console")}} {{Non-standard_inline}} {{ReadOnlyInline}}</dt> + <dd>Retorna una referencia al objeto de la consola proveyendo acceso a la consola debugger del navegador.</dd> + <dt>{{domxref("Window.content")}} and Window._content {{Non-standard_inline}} {{obsolete_inline}}{{ReadOnlyInline}}</dt> + <dd>Returns a reference to the content element in the current window. The obsolete variant with underscore is no longer available from Web content.</dd> + <dt>{{domxref("Window.controllers")}}{{non-standard_inline}}{{ReadOnlyInline}}</dt> + <dd>Returns the XUL controller objects for the current chrome window.</dd> + <dt>{{domxref("Window.crypto")}} {{readOnlyInline}}</dt> + <dd>Returns the browser crypto object.</dd> + <dt>{{domxref("Window.defaultStatus")}} {{Obsolete_inline("gecko23")}}</dt> + <dd>Gets/sets the status bar text for the given window.</dd> + <dt>{{domxref("Window.devicePixelRatio")}} {{non-standard_inline}}{{ReadOnlyInline}}</dt> + <dd>Returns the ratio between physical pixels and device independent pixels in the current display.</dd> + <dt>{{domxref("Window.dialogArguments")}} {{Fx_minversion_inline(3)}} {{ReadOnlyInline}}</dt> + <dd>Gets the arguments passed to the window (if it's a dialog box) at the time {{domxref("window.showModalDialog()")}} was called. This is an {{Interface("nsIArray")}}.</dd> + <dt>{{domxref("Window.directories")}} {{obsolete_inline}}</dt> + <dd>Sinonimo de {{domxref("window.personalbar")}}</dd> + <dt>{{domxref("Window.document")}} {{ReadOnlyInline}}</dt> + <dd>Retorna una referencia al documento que esa ventana contiene.</dd> + <dt>{{domxref("Window.frameElement")}} {{readOnlyInline}}</dt> + <dd>Returns the element in which the window is embedded, or null if the window is not embedded.</dd> + <dt>{{domxref("Window.frames")}} {{readOnlyInline}}</dt> + <dd>Returns an array of the subframes in the current window.</dd> + <dt>{{domxref("Window.fullScreen")}} {{gecko_minversion_inline("1.9")}}</dt> + <dd>Esta propiedad indica si la ventana esta desplegada en pantalla completa o no.</dd> + <dt><code>{{domxref("window.globalStorage")}} </code>{{gecko_minversion_inline("1.8.1")}} {{Non-standard_inline}} {{Obsolete_inline("gecko13")}}</dt> + <dd>Unsupported since Gecko 13 (Firefox 13). Use {{domxref("Window.localStorage")}} instead.<br> + Was: Multiple storage objects that are used for storing data across multiple pages.</dd> + <dt>{{domxref("Window.history")}} {{ReadOnlyInline}}</dt> + <dd>Retorna una referencia a la historia del objeto.</dd> + <dt>{{domxref("Window.innerHeight")}}</dt> + <dd>Obtiene la altura del area de contenido del navegador incluyendo, si es interpretado, la barra de deslizado.</dd> + <dt>{{domxref("window.innerWidth")}}</dt> + <dd>Obtiene el ancho del area de contenido de la ventana del navegador, si es interpretado, la barra de deslizado vertical.</dd> + <dt>{{domxref("Window.length")}} {{readOnlyInline}}</dt> + <dd>Retorna el numero de marcos en la ventana. Ver tambien {{domxref("window.frames")}}.</dd> + <dt>{{domxref("Window.location")}} {{ReadOnlyInline}}</dt> + <dd>Obtiene/fija la location, o URL actual, del objeto de la ventana.</dd> + <dt>{{domxref("Window.locationbar")}} {{ReadOnlyInline}}</dt> + <dd>Retorna el objeto locationbar, cuya visibilidad puede ser fijada en la ventana.</dd> + <dt>{{domxref("Window.localStorage")}} {{readOnlyInline}}{{gecko_minversion_inline("1.9.1")}}</dt> + <dd>Retorna una referencia al objeto almacenamiento local usado para almacenar datos que pueden ser de accedidos por el origen que los creo.</dd> + <dt>{{domxref("Window.menubar")}} {{ReadOnlyInline}}</dt> + <dd>Retorna el objeto barra de menu, cuya visibilidad puede ser fijada en la ventana.</dd> + <dt>{{domxref("Window.messageManager")}} {{gecko_minversion_inline("2.0")}}</dt> + <dd>Retorna el objeto <a href="/en-US/docs/The_message_manager">message manager</a> para esta ventana.</dd> + <dt>{{domxref("Window.mozAnimationStartTime")}} {{ReadOnlyInline}}{{gecko_minversion_inline("2.0")}}</dt> + <dd>The time in milliseconds since epoch at which the current animation cycle began.</dd> + <dt>{{domxref("Window.mozInnerScreenX")}} {{ReadOnlyInline}}{{non-standard_inline}}{{gecko_minversion_inline("1.9.2")}}</dt> + <dd>Returns the horizontal (X) coordinate of the top-left corner of the window's viewport, in screen coordinates. This value is reported in CSS pixels. See <code>mozScreenPixelsPerCSSPixel</code> in {{interface("nsIDOMWindowUtils")}} for a conversion factor to adapt to screen pixels if needed.</dd> + <dt>{{domxref("Window.mozInnerScreenY")}} {{ReadOnlyInline}} {{non-standard_inline}}{{gecko_minversion_inline("1.9.2")}}</dt> + <dd>Returns the vertical (Y) coordinate of the top-left corner of the window's viewport, in screen coordinates. This value is reported in CSS pixels. See <code>mozScreenPixelsPerCSSPixel</code> for a conversion factor to adapt to screen pixels if needed.</dd> + <dt>{{domxref("Window.mozPaintCount")}} {{non-standard_inline}}{{ReadOnlyInline}} {{gecko_minversion_inline("2.0")}}</dt> + <dd>Returns the number of times the current document has been rendered to the screen in this window. This can be used to compute rendering performance.</dd> + <dt>{{domxref("Window.name")}}</dt> + <dd>Gets/sets the name of the window.</dd> + <dt>{{domxref("Window.navigator")}} {{readOnlyInline}}</dt> + <dd>Returns a reference to the navigator object.</dd> + <dt>{{domxref("Window.opener")}}</dt> + <dd>Returns a reference to the window that opened this current window.</dd> + <dt>{{domxref("Window.outerHeight")}} {{readOnlyInline}}</dt> + <dd>Gets the height of the outside of the browser window.</dd> + <dt>{{domxref("Window.outerWidth")}} {{readOnlyInline}}</dt> + <dd>Gets the width of the outside of the browser window.</dd> + <dt>{{domxref("Window.scrollX","Window.pageXOffset")}} {{readOnlyInline}}</dt> + <dd>An alias for {{domxref("window.scrollX")}}.</dd> + <dt>{{domxref("Window.scrollY","Window.pageYOffset")}}{{readOnlyInline}}</dt> + <dd>An alias for {{domxref("window.scrollY")}}</dd> + <dt>{{domxref("Window.sessionStorage")}} {{readOnlyInline}}</dt> + <dd>Returns a reference to the session storage object used to store data that may only be accessed by the origin that created it.</dd> + <dt>{{domxref("SpeechSynthesisGetter.speechSynthesis")}} {{readOnlyInline}}</dt> + <dd></dd> + <dt>{{domxref("Window.parent")}} {{readOnlyInline}}</dt> + <dd>Returns a reference to the parent of the current window or subframe.</dd> + <dt>{{domxref("Window.performance")}} {{readOnlyInline}}</dt> + <dd>Provides a hosting area for <a href="/en-US/docs/Navigation_timing">performance related</a> attributes.</dd> + <dt>{{domxref("Window.personalbar")}} {{readOnlyInline}}</dt> + <dd>Returns the personalbar object, whose visibility can be toggled in the window.</dd> + <dt>{{domxref("Window.pkcs11")}} {{obsolete_inline(29)}}</dt> + <dd>Formerly provided access to install and remove PKCS11 modules.</dd> + <dt>{{domxref("Window.returnValue")}} {{Fx_minversion_inline(3)}}</dt> + <dd>The return value to be returned to the function that called {{domxref("window.showModalDialog()")}} to display the window as a modal dialog.</dd> + <dt>{{domxref("Window.screen")}} {{readOnlyInline}}</dt> + <dd>Returns a reference to the screen object associated with the window.</dd> + <dt>{{domxref("Window.screenX")}} {{readOnlyInline}}</dt> + <dd>Returns the horizontal distance of the left border of the user's browser from the left side of the screen.</dd> + <dt>{{domxref("Window.screenY")}} {{readOnlyInline}}</dt> + <dd>Returns the vertical distance of the top border of the user's browser from the top side of the screen.</dd> + <dt>{{domxref("Window.scrollbars")}} {{readOnlyInline}}</dt> + <dd>Returns the scrollbars object, whose visibility can be toggled in the window.</dd> + <dt>{{domxref("Window.scrollMaxX")}}{{non-standard_inline}}{{ReadOnlyInline}}</dt> + <dd>The maximum offset that the window can be scrolled to horizontally, that is the document width minus the viewport width.</dd> + <dt>{{domxref("Window.scrollMaxY")}}{{non-standard_inline}}{{ReadOnlyInline}}</dt> + <dd>The maximum offset that the window can be scrolled to vertically (i.e., the document height minus the viewport height).</dd> + <dt>{{domxref("Window.scrollX")}} {{readOnlyInline}}</dt> + <dd>Returns the number of pixels that the document has already been scrolled horizontally.</dd> + <dt>{{domxref("Window.scrollY")}} {{readOnlyInline}}</dt> + <dd>Returns the number of pixels that the document has already been scrolled vertically.</dd> + <dt>{{domxref("Window.self")}} {{ReadOnlyInline}}</dt> + <dd>Returns an object reference to the window object itself.</dd> + <dt>{{domxref("Window.sessionStorage")}} {{Fx_minversion_inline("2.0")}}</dt> + <dd>Returns a storage object for storing data within a single page session.</dd> + <dt>{{domxref("Window.sidebar")}} {{non-standard_inline}}{{ReadOnlyInline}}</dt> + <dd>Returns a reference to the window object of the sidebar.</dd> + <dt>{{domxref("Window.status")}}</dt> + <dd>Gets/sets the text in the statusbar at the bottom of the browser.</dd> + <dt>{{domxref("Window.statusbar")}} {{readOnlyInline}}</dt> + <dd>Returns the statusbar object, whose visibility can be toggled in the window.</dd> + <dt>{{domxref("Window.toolbar")}} {{readOnlyInline}}</dt> + <dd>Returns the toolbar object, whose visibility can be toggled in the window.</dd> + <dt>{{domxref("Window.top")}} {{readOnlyInline}}</dt> + <dd>Returns a reference to the topmost window in the window hierarchy. This property is read only.</dd> + <dt>{{domxref("Window.window")}} {{ReadOnlyInline}}</dt> + <dd>Returns a reference to the current window.</dd> + <dt><code>window[0]</code>,<code> window[1]</code>, etc.</dt> + <dd>Returns a reference to the <code>window</code> object in the frames. See {{domxref("Window.frames")}} for more details.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<p><em> Esta interfaz hereda metodos de la interfaz {{domxref("EventTarget")}} e implementa metodos {{domxref("WindowTimers")}}, {{domxref("WindowBase64")}}, y {{domxref("WindowEventHandlers")}}.</em></p> + +<dl> + <dt>{{domxref("EventTarget.addEventListener()")}}</dt> + <dd>Registra un controlador de eventos a un tipo de evento especifico en la ventana.</dd> + <dt>{{domxref("Window.alert()")}}</dt> + <dd>Muestra una pequeña ventana de alerta.</dd> + <dd>El estilo y posición de la ventana puede variar dependiendo de que navegador este usando.</dd> + <dt>{{domxref("WindowBase64.atob()")}}</dt> + <dd>Decodes a string of data which has been encoded using base-64 encoding.</dd> + <dt>{{domxref("Window.back()")}} {{Non-standard_inline}} {{obsolete_inline}}</dt> + <dd>Regresa en la ventana de historial.</dd> + <dt>{{domxref("Window.blur()")}}</dt> + <dd>Sets focus away from the window.</dd> + <dt>{{domxref("WindowBase64.btoa()")}}</dt> + <dd>Creates a base-64 encoded ASCII string from a string of binary data.</dd> + <dt>{{domxref("Window.captureEvents()")}} {{Deprecated_inline}}</dt> + <dd>Registers the window to capture all events of the specified type.</dd> + <dt>{{domxref("Window.clearImmediate()")}}</dt> + <dd>Cancels the repeated execution set using <code>setImmediate</code>.</dd> + <dt>{{domxref("WindowTimers.clearInterval()")}}</dt> + <dd>Cancels the repeated execution set using {{domxref("WindowTimers.setInterval()")}}.</dd> + <dt>{{domxref("WindowTimers.clearTimeout()")}}</dt> + <dd>Cancels the repeated execution set using {{domxref("WindowTimers.setTimeout()")}}.</dd> + <dt>{{domxref("Window.close()")}}</dt> + <dd>Cierra la ventana actual.</dd> + <dt>{{domxref("Window.confirm()")}}</dt> + <dd>Muestra una ventana de comfirmación con dos únicas y posibles respuestas. <strong>Confirmar </strong>y<strong> Cancelar</strong>.</dd> + <dt>{{domxref("Window.disableExternalCapture()")}} {{obsolete_inline(24)}}</dt> + <dd>{{todo("NeedsContents")}}</dd> + <dt>{{domxref("Window.dispatchEvent()")}}</dt> + <dd>Usado para activar un evento.</dd> + <dt>{{domxref("Window.dump()")}}</dt> + <dd>Escribe un mensaje a la consola.</dd> + <dt>{{domxref("Window.enableExternalCapture()")}} {{obsolete_inline(24)}}</dt> + <dd>{{todo("NeedsContents")}}</dd> + <dt>{{domxref("Window.find()")}}</dt> + <dd>Busca un string dado en una ventana.</dd> + <dt>{{domxref("Window.focus()")}}</dt> + <dd>Fija el enfoque en la ventana actual.</dd> + <dt>{{domxref("Window.forward()")}} {{Non-standard_inline}} {{obsolete_inline}}</dt> + <dd>Moves the window one document forward in the history.</dd> + <dt>{{domxref("Window.getAttention()")}}</dt> + <dd>Flashes the application icon.</dd> + <dt>{{domxref("Window.getAttentionWithCycleCount()")}}</dt> + <dd>{{todo("NeedsContents")}}</dd> + <dt>{{domxref("Window.getComputedStyle()")}}</dt> + <dd>Gets computed style for the specified element. Computed style indicates the computed values of all CSS properties of the element.</dd> + <dt>{{domxref("Window.getDefaulComputedStyle()")}}</dt> + <dd>Gets default computed style for the specified element, ignoring author stylesheets.</dd> + <dt>{{domxref("Window.getSelection()")}}</dt> + <dd>Returns the selection object representing the selected item(s).</dd> + <dt>{{domxref("Window.home()")}} {{Non-standard_inline}} {{obsolete_inline}}</dt> + <dd>Regresa el navegador a la pagina de inicio.</dd> + <dt>{{domxref("Window.matchMedia()")}} {{gecko_minversion_inline("6.0")}}</dt> + <dd>Returns a {{domxref("MediaQueryList")}} object representing the specified media query string.</dd> + <dt>{{domxref("Window.maximize()")}}</dt> + <dd>{{todo("NeedsContents")}}</dd> + <dt>{{domxref("Window.minimize()")}} (top-level XUL windows only)</dt> + <dd>Minimiza la ventana.</dd> + <dt>{{domxref("Window.moveBy()")}}</dt> + <dd>Mueve la ventana actual por una cantidad especificada.</dd> + <dt>{{domxref("Window.moveTo()")}}</dt> + <dd>Mueve la ventana a una coordenada especificada.</dd> + <dt>{{domxref("Window.mozRequestAnimationFrame()")}} {{gecko_minversion_inline("2.0")}}</dt> + <dd>Tells the browser that an animation is in progress, requesting that the browser schedule a repaint of the window for the next animation frame. This will cause a <code>MozBeforePaint</code> event to fire before that repaint occurs.</dd> + <dt>{{domxref("Window.open()")}}</dt> + <dd>Abre una nueva ventana.</dd> + <dt>{{domxref("Window.openDialog()")}}</dt> + <dd>Abre una nueva ventana de dialogo.</dd> + <dt>{{domxref("Window.postMessage()")}} {{Fx_minversion_inline(3)}}</dt> + <dd>Provides a secure means for one window to send a string of data to another window, which need not be within the same domain as the first.</dd> + <dt>{{domxref("Window.print()")}}</dt> + <dd>Opens the Print Dialog to print the current document.</dd> + <dt>{{domxref("Window.prompt()")}}</dt> + <dd>Returns the text entered by the user in a prompt dialog.</dd> + <dt>{{domxref("Window.releaseEvents()")}} {{Deprecated_inline}}</dt> + <dd>Releases the window from trapping events of a specific type.</dd> + <dt>{{domxref("element.removeEventListener","Window.removeEventListener()")}}</dt> + <dd>Removes an event listener from the window.</dd> + <dt>{{domxref("Window.resizeBy()")}}</dt> + <dd>Resizes the current window by a certain amount.</dd> + <dt>{{domxref("Window.resizeTo()")}}</dt> + <dd>Dynamically resizes window.</dd> + <dt>{{domxref("Window.restore()")}}</dt> + <dd>{{todo("NeedsContents")}}</dd> + <dt>{{domxref("Window.routeEvent()")}} {{obsolete_inline(24)}}</dt> + <dd>{{todo("NeedsContents")}}</dd> + <dt>{{domxref("Window.scroll()")}}</dt> + <dd>Scrolls the window to a particular place in the document.</dd> + <dt>{{domxref("Window.scrollBy()")}}</dt> + <dd>Scrolls the document in the window by the given amount.</dd> + <dt>{{domxref("Window.scrollByLines()")}}</dt> + <dd>Scrolls the document by the given number of lines.</dd> + <dt>{{domxref("Window.scrollByPages()")}}</dt> + <dd>Scrolls the current document by the specified number of pages.</dd> + <dt>{{domxref("Window.scrollTo()")}}</dt> + <dd>Scrolls to a particular set of coordinates in the document.</dd> + <dt>{{domxref("Window.setCursor()")}}</dt> + <dd>Changes the cursor for the current window</dd> + <dt>{{domxref("Window.setImmediate()")}}</dt> + <dd>Executes a function after the browser has finished other heavy tasks</dd> + <dt>{{domxref("WindowTimers.setInterval()")}}</dt> + <dd>Schedules the execution of a function each X milliseconds.</dd> + <dt>{{domxref("Window.setResizable")}}</dt> + <dd>{{todo("NeedsContents")}}</dd> + <dt>{{domxref("WindowTimers.setTimeout()")}}</dt> + <dd>Sets a delay for executing a function.</dd> + <dt>{{domxref("Window.showModalDialog()")}} {{Fx_minversion_inline(3)}}</dt> + <dd>Displays a modal dialog.</dd> + <dt>{{domxref("Window.sizeToContent()")}}</dt> + <dd>Sizes the window according to its content.</dd> + <dt>{{domxref("Window.stop()")}}</dt> + <dd>This method stops window loading.</dd> + <dt>{{domxref("Window.updateCommands()")}}</dt> + <dd>Updates the state of commands of the current chrome window (UI).</dd> +</dl> + +<h2 id="Controlador_de_Eventos">Controlador de Eventos</h2> + +<p>Estas son propiedades del objeto ventana que pueden ser fijadas para establecer controladores de eventos para las diversar cosas que pueden pasar en la ventana que podria ser de interes.</p> + +<p><em>Esta interfaz hereda controladores de eventos de la interfaz {{domxref("EventTarget")}} e implementa controladores de eventos desde {{domxref("WindowTimers")}}, {{domxref("WindowBase64")}}, y {{domxref("WindowEventHandlers")}}.</em></p> + +<div class="note"> +<p><strong>Nota:</strong> Empezando en {{Gecko("9.0")}}, se puede usar el sintaxis <code>if ("onabort" in window)</code> para determinar si existe una propiedad dada de controlador de eventos o no. Esto es porque interfazes de controlador de eventos han sido actualizadas al respectivo web IDL interfaz. Ver <a href="/en-US/docs/DOM/DOM_event_handlers">DOM event handlers</a> para mas detalles.</p> +</div> + +<dl> + <dt>{{domxref("GlobalEventHandlers.onabort")}}</dt> + <dd>An event handler property for abort events on the window.</dd> + <dt>{{domxref("WindowEventHandlers.onbeforeunload")}}</dt> + <dd>An event handler property for before-unload events on the window.</dd> + <dt>{{domxref("GlobalEventHandlers.onblur")}}</dt> + <dd>An event handler property for blur events on the window.</dd> + <dt>{{domxref("GlobalEventHandlers.onchange")}}</dt> + <dd>An event handler property for change events on the window.</dd> + <dt>{{domxref("GlobalEventHandlers.onclick")}}</dt> + <dd>An event handler property for click events on the window.</dd> + <dt>{{domxref("GlobalEventHandlers.onclose")}}</dt> + <dd>An event handler property for handling the window close event.</dd> + <dt>{{domxref("GlobalEventHandlers.oncontextmenu")}}</dt> + <dd>An event handler property for right-click events on the window.</dd> + <dt>{{domxref("Window.ondevicelight")}}</dt> + <dd>An event handler property for any ambient light levels changes</dd> + <dt>{{domxref("Window.ondevicemotion")}} {{gecko_minversion_inline("6.0")}}</dt> + <dd>{{todo("NeedsContents")}}</dd> + <dt>{{domxref("Window.ondeviceorientation")}} {{gecko_minversion_inline("6.0")}}</dt> + <dd>An event handler property for any device orientation changes</dd> + <dt>{{domxref("Window.ondeviceproximity")}}</dt> + <dd>An event handler property for device proximity event</dd> + <dt>{{domxref("GlobalEventHandlers.onerror")}}</dt> + <dd>An event handler property for {{event("error")}} events raised on the window.</dd> + <dt>{{domxref("GlobalEventHandlers.onfocus")}}</dt> + <dd>An event handler property for {{event("focus")}} events on the window.</dd> + <dt>{{domxref("WindowEventHandlers.onhashchange")}} {{gecko_minversion_inline("1.9.2")}}</dt> + <dd>An event handler property for hash change events on the window; called when the part of the URL after the hash mark ("#") changes.</dd> + <dt>{{domxref("GlobalEventHandlers.onkeydown")}}</dt> + <dd>An event handler property for {{event("keydown")}} events on the window.</dd> + <dt>{{domxref("GlobalEventHandlers.onkeypress")}}</dt> + <dd>An event handler property for {{event("keypress")}} events on the window.</dd> + <dt>{{domxref("GlobalEventHandlers.onkeyup")}}</dt> + <dd>An event handler property for {{event("keyup")}} events on the window.</dd> + <dt>{{domxref("WindowEventHandlers.onlanguagechange")}}</dt> + <dd>An event handler property for {{event("languagechange")}} events on the window.</dd> + <dt>{{domxref("GlobalEventHandlers.onload")}}</dt> + <dd>An event handler property for window loading.</dd> + <dt>{{domxref("GlobalEventHandlers.onmousedown")}}</dt> + <dd>An event handler property for mousedown events on the window.</dd> + <dt>{{domxref("GlobalEventHandlers.onmousemove")}}</dt> + <dd>An event handler property for mousemove events on the window.</dd> + <dt>{{domxref("GlobalEventHandlers.onmouseout")}}</dt> + <dd>An event handler property for mouseout events on the window.</dd> + <dt>{{domxref("GlobalEventHandlers.onmouseover")}}</dt> + <dd>An event handler property for mouseover events on the window.</dd> + <dt>{{domxref("GlobalEventHandlers.onmouseup")}}</dt> + <dd>An event handler property for mouseup events on the window.</dd> + <dt>{{domxref("Window.onmozbeforepaint")}} {{gecko_minversion_inline("2.0")}}</dt> + <dd>An event handler property for the <code>MozBeforePaint</code> event, which is sent before repainting the window if the event has been requested by a call to the {{domxref("Window.mozRequestAnimationFrame()")}} method.</dd> + <dt>{{domxref("WindowEventHandlers.onpageshow")}}</dt> + <dd>An event handler property for pageshow events on the window.</dd> + <dt>{{domxref("WindowEventHandlers.onpagehide")}}</dt> + <dd>An event handler property for pagehide events on the window.</dd> + <dt>{{domxref("Window.onpaint")}}</dt> + <dd>An event handler property for paint events on the window.</dd> + <dt>{{domxref("WindowEventHandlers.onpopstate")}} {{gecko_minversion_inline("2.0")}}</dt> + <dd>An event handler property for popstate events, which are fired when navigating to a session history entry representing a state object.</dd> + <dt>{{domxref("GlobalEventHandlers.onreset")}}</dt> + <dd>An event handler property for reset events on the window.</dd> + <dt>{{domxref("GlobalEventHandlers.onresize")}}</dt> + <dd>An event handler property for window resizing.</dd> + <dt>{{domxref("GlobalEventHandlers.onscroll")}}</dt> + <dd>An event handler property for window scrolling.</dd> + <dt>{{domxref("GlobalEventHandlers.onselect")}}</dt> + <dd>An event handler property for window selection.</dd> + <dt>{{domxref("GlobalEventHandlers.onsubmit")}}</dt> + <dd>An event handler property for submits on window forms.</dd> + <dt>{{domxref("Window.onunload")}}</dt> + <dd>An event handler property for unload events on the window.</dd> + <dt>{{domxref("Window.onuserproximity")}}</dt> + <dd>An event handler property for user proximity events</dd> +</dl> + +<h2 id="Constructores_2">Constructores</h2> + +<p>See also the <a href="/en-US/docs/DOM/DOM_Reference" title="/en-US/docs/DOM/DOM_Reference">DOM Interfaces</a>.</p> + +<dl> + <dt>{{domxref("Window.DOMParser")}}</dt> + <dd>{{todo("NeedsContents")}}</dd> + <dt>{{domxref("Window.GeckoActiveXObject")}}</dt> + <dd>{{todo("NeedsContents")}}</dd> + <dt>{{domxref("Image")}}</dt> + <dd>Used for creating an {{domxref("HTMLImageElement")}}.</dd> + <dt>{{domxref("Option")}}</dt> + <dd>Used for creating an {{domxref("HTMLOptionElement")}}</dd> + <dt>{{domxref("Window.QueryInterface")}}</dt> + <dd>{{todo("NeedsContents")}}</dd> + <dt>{{domxref("Window.XMLSerializer")}}</dt> + <dd>{{todo("NeedsContents")}}</dd> + <dt>{{domxref("Worker")}}</dt> + <dd>Used for creating a <a href="/en-US/docs/DOM/Using_web_workers">Web worker</a></dd> + <dt>{{domxref("Window.XPCNativeWrapper")}}</dt> + <dd>{{todo("NeedsContents")}}</dd> + <dt>{{domxref("Window.XPCSafeJSObjectWrapper")}}</dt> + <dd>{{todo("NeedsContents")}}</dd> +</dl> + +<h2 id="Interfaces">Interfaces</h2> + +<p>Ver <a href="/en-US/docs/DOM/DOM_Reference" title="/en-US/docs/DOM/DOM_Reference">DOM Reference</a></p> + +<h2 id="Ver_Tambien">Ver Tambien</h2> + +<ul> + <li><a href="/en-US/docs/Working_with_windows_in_chrome_code">Trabajar con ventanas en codigo chrome</a></li> +</ul> diff --git a/files/es/web/api/window/innerheight/index.html b/files/es/web/api/window/innerheight/index.html new file mode 100644 index 0000000000..ef563d9e97 --- /dev/null +++ b/files/es/web/api/window/innerheight/index.html @@ -0,0 +1,79 @@ +--- +title: window.innerHeight +slug: Web/API/Window/innerHeight +tags: + - API + - Propiedades + - Referências + - Window +translation_of: Web/API/Window/innerHeight +--- +<div><strong><em>//Propiedad solo lectura del objeto window.</em></strong></div> + +<p> Representa la altura (en pixeles) del viewport</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox notranslate">var <em>alturaDelViewport</em> = window.innerHeight;</pre> + +<h3 id="Valor">Valor</h3> + +<p>Como retorno, la propiedad innerHeight del objeto window nos retornara un valor de tipo entero, que representara (en pixeles) la altura del viewport.</p> + +<p>La propiedad <code>window.innerHeight</code> es solo de lectura; Y no tiene un valor por defecto.</p> + +<h2 id="Notas_."><span style="">Notas . </span></h2> + +<p><span style="">La propiedad innerHeight es soportada por cualquier objeto de ventana. Pudiendo ejectutarse en un conjunto de marcos (<frameset> </frameset>). O en una ventana secundaria.</span></p> + +<p>Es un algoritmo para obtener la altura del viewport, excluyendo si se representa la barra de desplazamiento horizontal</p> + +<h3 id="Ejemplo"><font color="#333333"><span style="background-color: #ffffff; font-size: 37.3333px;"><strong>Ejemplo</strong></span></font></h3> + +<h3 id="Asumiendo_un_frameset">Asumiendo un frameset</h3> + +<pre class="brush:js notranslate">var alturaViewport = window.innerHeight; + +var alturaViewport = self.innerHeight; +// self es window + + +</pre> + +<p> <span class="seoSummary"> <strong>//otra forma de obtener la altura (aúnque, no del viewport, síno de la ventana), es usando la propiedad outerHeight, del objeto window.</strong></span></p> + +<h3 id="Ejemplo_Grafica"><span style="">Ejemplo (Grafica)</span></h3> + +<p><img alt="innerHeight vs outerHeight illustration" src="/@api/deki/files/213/=FirefoxInnerVsOuterHeight2.png"></p> + +<h2 id="Especificacion">Especificacion</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('CSSOM View', '#dom-window-innerheight', 'window.innerHeight')}}</td> + <td>{{Spec2('CSSOM View')}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<p><br> + <font face="x-locale-heading-primary, zillaslab, Palatino, Palatino Linotype, x-locale-heading-secondary, serif"><span style="font-size: 37.3333px;"><strong>Compatibilidad del navegador</strong></span></font></p> + +<p class="hidden"><span class="seoSummary">La compatibilidad de la tabla en esta pagina es generada por la estructura de datos. Si tú gustas contribuir, por favor dirigete a <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> y envia un pull Request</span></p> + +<h2 id="Tambien_me_intersa">Tambien me intersa</h2> + +<ul> + <li>{{domxref("window.innerWidth")}}</li> + <li>{{domxref("window.outerHeight")}}</li> + <li>{{domxref("window.outerWidth")}}</li> +</ul> diff --git a/files/es/web/api/window/localstorage/index.html b/files/es/web/api/window/localstorage/index.html new file mode 100644 index 0000000000..c93ae93d98 --- /dev/null +++ b/files/es/web/api/window/localstorage/index.html @@ -0,0 +1,148 @@ +--- +title: Window.localStorage +slug: Web/API/Window/localStorage +tags: + - API + - Propiedad + - Referencia + - Web Storage + - WindowLocalStorage + - localStorage +translation_of: Web/API/Window/localStorage +--- +<p>{{APIRef()}}</p> + +<p>La propiedad de sólo lectura <strong><code>localStorage</code></strong> te permite acceder al objeto local {{DOMxRef("Storage")}}; los datos persisten almacenados entre de las diferentes sesiones de navegación. localStorage es similar a <code><a href="/es/docs/Web/API/Window.sessionStorage">sessionStorage</a></code>. La única diferencia es que, mientras los datos almacenados en localStorage no tienen fecha de expiración, los datos almacenados en sessionStorage son eliminados cuando finaliza la sesion de navegación - lo cual ocurre cuando se cierra la página.</p> + +<p>Con <code><a href="/es/docs/Web/API/Window.sessionStorage">sessionStorage</a></code> los datos persisten sólo en la ventana/tab que los creó, mientras que con <code>localStorage</code> los datos persisten entre ventanas/tabs con el mismo origen.</p> + +<p>Debe tenerse en cuenta que los datos almacenados tanto en <code>localStorage</code> como en <code>sessionStorage</code> <strong>son específicos del protocolo de la página</strong>.</p> + +<p>Las claves y los valores son <strong>siempre cadenas de texto</strong> (ten en cuenta que, al igual que con los objetos, las claves de enteros se convertirán automáticamente en cadenas de texto).</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="brush: js">miStorage = window.localStorage;</pre> + +<h3 id="Valor">Valor</h3> + +<p>Un objeto {{DOMxRef("Storage")}} que se puede utilizar para acceder al espacio de almacenamiento local del origen actual.</p> + +<h3 id="Excepciones">Excepciones</h3> + +<dl> + <dt><code>SecurityError</code></dt> + <dd>La solicitud viola una decisión de política, o el origen no es <a href="https://developer.mozilla.org/es/docs/Web/Security/Same-origin_politica">una tupla válida de protocolo/host/puerto</a> (esto puede suceder si el origen usa el protocolo <code>file:</code> o <code>data:</code>, por ejemplo). Por ejemplo, el usuario puede tener su navegador configurado a fin de denegar el permiso para conservar datos al origen especificado.</dd> +</dl> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>El siguiente código accede al objeto local {{DOMxRef("Storage")}} actual y agrega un ítem al mismo usando {{DOMxRef("Storage.setItem()")}}.</p> + +<pre class="brush: js">localStorage.setItem('miGato', 'Juan');</pre> + +<div class="note"> +<p><strong>Nota</strong>: Por favor ver el articulo <a href="/es/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API">Usando la Web Storage API</a> para un ejemplo completo.</p> +</div> + +<p>La sintaxis para leer el ítem almacenado en <code>localStorage</code> es la siguiente:</p> + +<pre class="brush: js">var cat = localStorage.getItem('miGato');</pre> + +<p>La sintaxis para eliminar el ítem almacenado en <code>localStorage</code> es la siguiente:</p> + +<pre class="brush: js">localStorage.removeItem('miGato');</pre> + +<p>La sintaxis para eliminar todos los ítems almacenados en <code>localStorage</code> es la siguiente:</p> + +<pre class="brush: js">// Elimina todos los elementos +localStorage.clear(); +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación </th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('Web Storage', '#dom-localstorage', 'localStorage')}}</td> + <td>{{Spec2('Web Storage')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibiliad_de_Navegadores">Compatibiliad de Navegadores</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidad</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>localStorage</td> + <td>4</td> + <td>3.5</td> + <td>8</td> + <td>10.50</td> + <td>4</td> + </tr> + <tr> + <td>sessionStorage</td> + <td>5</td> + <td>2</td> + <td>8</td> + <td>10.50</td> + <td>4</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th><span style="font-family: open sans light,helvetica,arial,sans-serif; font-size: 16px; line-height: 16px;">Funcionalidad</span></th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>2.1</td> + <td>{{ CompatUnknown }}</td> + <td>8</td> + <td>11</td> + <td>iOS 3.2</td> + </tr> + </tbody> +</table> + +<p>Todos los navegadores tienen variaciones en los niveles de capacidad de almacenamiento tanto para localStorage como para sessionStorage. He aquí un <a class="external" href="http://dev-test.nemikor.com/web-storage/support-test/" title="http://dev-test.nemikor.com/web-storage/support-test/">detalle sobre las distintas capacidades en los diferentes navegadores.</a></p> +</div> + +<div class="note"> +<p><strong>Nota: </strong>a partir de iOS 5.1, Safari Mobile almacena la data del localStorage en el directorio de cache, lo cual esta sujeto al borrado y perdida ocacional de los datos ante la petición del sistema operativo, tipicamente requerido cuando el dispositivo sufre de falta de espacio de almacenamiento.</p> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="/es/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API">Usando la Web Storage API</a></li> + <li><a href="/es/docs/Web/API/Window.sessionStorage">Window.sessionStorage</a></li> +</ul> diff --git a/files/es/web/api/window/location/index.html b/files/es/web/api/window/location/index.html new file mode 100644 index 0000000000..d1d44a2b84 --- /dev/null +++ b/files/es/web/api/window/location/index.html @@ -0,0 +1,274 @@ +--- +title: Window.location +slug: Web/API/Window/location +tags: + - Location + - contexto + - navegación +translation_of: Web/API/Window/location +--- +<p>{{APIRef}}</p> + +<p>La propiedad de sólo lectura <code><strong>Window.location</strong> </code>retorna un objeto {{domxref("Location")}} con información acerca de la ubicación actual del documento.</p> + +<p><code>Window.location</code> no sólo es una propiedad de sólo lectura, también se le puede asignar un {{domxref("DOMString")}}. Esto significa que puedes trabajar con <code>location </code>como si fuera una cadena de caracteres en la mayoría de los casos: <code>location = 'http://www.example.com'</code> es un sinónimo de <code>location.href = 'http://www.example.com'</code>.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox">var <em>oldLocation</em> = location; +location = <em>newLocation</em>; +</pre> + +<h2 id="Example" name="Example">Ejemplos</h2> + +<h3 id="Ejemplo_básico">Ejemplo básico</h3> + +<pre class="brush: js">alert(location); // alerts "https://developer.mozilla.org/en-US/docs/Web/API/Window.location"</pre> + +<h3 id="Ejemplo_1_Navegar_a_una_nueva_página">Ejemplo #1: Navegar a una nueva página</h3> + +<p>Cuando un nuevo valor es asignado a un objeto location, un documento será cargado usando la URL como si location.assing() fuera llamada con la URL modificada. Note que configuraciones de seguridad como CORS, esto puede ser prevenido cuando pase.</p> + +<pre class="brush: js">location.assign("http://www.mozilla.org"); // o +location = "http://www.mozilla.org"; +</pre> + +<h3 id="Ejemplo_2_Forzar_la_recarga_de_una_página_desde_el_servidor">Ejemplo #2: Forzar la recarga de una página desde el servidor</h3> + +<pre class="brush: js">location.reload(true);</pre> + +<h3 id="Ejemplo_3">Ejemplo #3</h3> + +<p>Considerando el siguiente ejemplo, el cual recargará la página usando el método <a href="/en-US/docs/Web/API/Location.replace"><code>replace()</code></a> para insertar un valor de location.pathname dentro del hash:</p> + +<pre class="brush: js">function reloadPageWithHash() { + var initialPage = location.pathname; + location.replace('http://example.com/#' + initialPage); +} +</pre> + +<div class="note"><strong>Nota:</strong> El ejemplo anterior funciona en situaciones cuando location.hash no necesita ser retenido. Sin embargo, en navegadores basados en Gecko, configurar <code>location.pathname</code> en esta manera eliminará cualquier información en location.hash, mientras que en WebKit (y posiblemente en otros navegadores), configurar el pathname no afectará el hash. Si necesitas cambiar el pathname pero mantener el hash como está, usa el método <code>replace()</code>, el cual funcionará consistentemente a través de los navegadores..</div> + +<h3 id="Ejemplo_4_Muestra_las_propiedades_de_la_URL_actual_en_una_ventana_emergente">Ejemplo #4: Muestra las propiedades de la URL actual en una ventana emergente:</h3> + +<pre class="brush: js">function showLoc() { + var oLocation = location, aLog = ["Property (Typeof): Value", "location (" + (typeof oLocation) + "): " + oLocation ]; + for (var sProp in oLocation){ + aLog.push(sProp + " (" + (typeof oLocation[sProp]) + "): " + (oLocation[sProp] || "n/a")); + } + alert(aLog.join("\n")); +} + +// in html: <button onclick="showLoc();">Show location properties</button> +</pre> + +<h3 id="Ejemplo_5_Enviar_una_cadena_de_caracteres_de_datos_al_servidor_por_modificar_la_propiedad_search">Ejemplo #5: Enviar una cadena de caracteres de datos al servidor por modificar la propiedad <code>search</code>:</h3> + +<pre class="brush: js">function sendData (sData) { + location.search = sData; +} + +// in html: <button onclick="sendData('Some data');">Send data</button> +</pre> + +<p>La siguiente URL con "?Some%20data" anexa es enviada al servidor (Si no hay ninguna acción tomada por el servidor, el documento actual es recargado con la cadena de caracteres modificada).</p> + +<h3 id="Ejemplo_6_Usando_marcadores_sin_cambiar_la_propiedad_hash">Ejemplo #6: Usando marcadores sin cambiar la propiedad hash:</h3> + +<pre class="brush: html"><!doctype html> +<html> +<head> +<meta charset="UTF-8"/> +<title>MDN Example</title> +<script> +function showNode (oNode) { + var nLeft = 0, nTop = 0; + for (var oItNode = oNode; oItNode; nLeft += oItNode.offsetLeft, nTop += oItNode.offsetTop, oItNode = oItNode.offsetParent); + document.documentElement.scrollTop = nTop; + document.documentElement.scrollLeft = nLeft; +} + +function showBookmark (sBookmark, bUseHash) { + if (arguments.length === 1 || bUseHash) { location.hash = sBookmark; return; } + var oBookmark = document.querySelector(sBookmark); + if (oBookmark) { showNode(oBookmark); } +} +</script> +<style> +span.intLink { + cursor: pointer; + color: #0000ff; + text-decoration: underline; +} +</style> +</head> + +<body> +<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam ultrices dolor ac dolor imperdiet ullamcorper. Suspendisse quam libero, luctus auctor mollis sed, malesuada condimentum magna. Quisque in ante tellus, in placerat est. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec a mi magna, quis mattis dolor. Etiam sit amet ligula quis urna auctor imperdiet nec faucibus ante. Mauris vel consectetur dolor. Nunc eget elit eget velit pulvinar fringilla consectetur aliquam purus. Curabitur convallis, justo posuere porta egestas, velit erat ornare tortor, non viverra justo diam eget arcu. Phasellus adipiscing fermentum nibh ac commodo. Nam turpis nunc, suscipit a hendrerit vitae, volutpat non ipsum.</p> +<p>Duis lobortis sapien quis nisl luctus porttitor. In tempor semper libero, eu tincidunt dolor eleifend sit amet. Ut nec velit in dolor tincidunt rhoncus non non diam. Morbi auctor ornare orci, non euismod felis gravida nec. Curabitur elementum nisi a eros rutrum nec blandit diam placerat. Aenean tincidunt risus ut nisi consectetur cursus. Ut vitae quam elit. Donec dignissim est in quam tempor consequat. Aliquam aliquam diam non felis convallis suscipit. Nulla facilisi. Donec lacus risus, dignissim et fringilla et, egestas vel eros. Duis malesuada accumsan dui, at fringilla mauris bibendum quis. Cras adipiscing ultricies fermentum. Praesent bibendum condimentum feugiat.</p> +<p id="myBookmark1">[&nbsp;<span class="intLink" onclick="showBookmark('#myBookmark2');">Go to bookmark #2</span>&nbsp;]</p> +<p>Vivamus blandit massa ut metus mattis in fringilla lectus imperdiet. Proin ac ante a felis ornare vehicula. Fusce pellentesque lacus vitae eros convallis ut mollis magna pellentesque. Pellentesque placerat enim at lacus ultricies vitae facilisis nisi fringilla. In tincidunt tincidunt tincidunt. Nulla vitae tempor nisl. Etiam congue, elit vitae egestas mollis, ipsum nisi malesuada turpis, a volutpat arcu arcu id risus.</p> +<p>Nam faucibus, ligula eu fringilla pulvinar, lectus tellus iaculis nunc, vitae scelerisque metus leo non metus. Proin mattis lobortis lobortis. Quisque accumsan faucibus erat, vel varius tortor ultricies ac. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nec libero nunc. Nullam tortor nunc, elementum a consectetur et, ultrices eu orci. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque a nisl eu sem vehicula egestas.</p> +<p>Aenean viverra varius mauris, sed elementum lacus interdum non. Phasellus sit amet lectus vitae eros egestas pellentesque fermentum eget magna. Quisque mauris nisl, gravida vitae placerat et, condimentum id metus. Nulla eu est dictum dolor pulvinar volutpat. Pellentesque vitae sollicitudin nunc. Donec neque magna, lobortis id egestas nec, sodales quis lectus. Fusce cursus sollicitudin porta. Suspendisse ut tortor in mauris tincidunt rhoncus. Maecenas tincidunt fermentum facilisis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p> +<p>Suspendisse turpis nisl, consectetur in lacinia ut, ornare vel mi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin non lectus eu turpis vulputate cursus. Mauris interdum tincidunt erat id pharetra. Nullam in libero elit, sed consequat lectus. Morbi odio nisi, porta vitae molestie ut, gravida ut nunc. Ut non est dui, id ullamcorper orci. Praesent vel elementum felis. Maecenas ornare, dui quis auctor hendrerit, turpis sem ullamcorper odio, in auctor magna metus quis leo. Morbi at odio ante.</p> +<p>Curabitur est ipsum, porta ac viverra faucibus, eleifend sed eros. In sit amet vehicula tortor. Vestibulum viverra pellentesque erat a elementum. Integer commodo ultricies lorem, eget tincidunt risus viverra et. In enim turpis, porttitor ac ornare et, suscipit sit amet nisl. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Pellentesque vel ultrices nibh. Sed commodo aliquam aliquam. Nulla euismod, odio ut eleifend mollis, nisi dui gravida nibh, vitae laoreet turpis purus id ipsum. Donec convallis, velit non scelerisque bibendum, diam nulla auctor nunc, vel dictum risus ipsum sit amet est. Praesent ut nibh sit amet nibh congue pulvinar. Suspendisse dictum porttitor tempor.</p> +<p>Vestibulum dignissim erat vitae lectus auctor ac bibendum eros semper. Integer aliquet, leo non ornare faucibus, risus arcu tristique dolor, a aliquet massa mauris quis arcu. In porttitor, lectus ac semper egestas, ligula magna laoreet libero, eu commodo mauris odio id ante. In hac habitasse platea dictumst. In pretium erat diam, nec consequat eros. Praesent augue mi, consequat sed porttitor at, volutpat vitae eros. Sed pretium pharetra dapibus. Donec auctor interdum erat, lacinia molestie nibh commodo ut. Maecenas vestibulum vulputate felis, ut ullamcorper arcu faucibus in. Curabitur id arcu est. In semper mollis lorem at pellentesque. Sed lectus nisl, vestibulum id scelerisque eu, feugiat et tortor. Pellentesque porttitor facilisis ultricies.</p> +<p id="myBookmark2">[&nbsp;<span class="intLink" onclick="showBookmark('#myBookmark1');">Go to bookmark #1</span> | <span class="intLink" onclick="showBookmark('#myBookmark1', false);">Go to bookmark #1 without using location.hash</span> | <span class="intLink" onclick="showBookmark('#myBookmark3');">Go to bookmark #3</span>&nbsp;]</p> +<p>Phasellus tempus fringilla nunc, eget sagittis orci molestie vel. Nulla sollicitudin diam non quam iaculis ac porta justo venenatis. Quisque tellus urna, molestie vitae egestas sit amet, suscipit sed sem. Quisque nec lorem eu velit faucibus tristique ut ut dolor. Cras eu tortor ut libero placerat venenatis ut ut massa. Sed quis libero augue, et consequat libero. Morbi rutrum augue sed turpis elementum sed luctus nisl molestie. Aenean vitae purus risus, a semper nisl. Pellentesque malesuada, est id sagittis consequat, libero mauris tincidunt tellus, eu sagittis arcu purus rutrum eros. Quisque eget eleifend mi. Duis pharetra mi ac eros mattis lacinia rutrum ipsum varius.</p> +<p>Fusce cursus pulvinar aliquam. Duis justo enim, ornare vitae elementum sed, porta a quam. Aliquam eu enim eu libero mollis tempus. Morbi ornare aliquam posuere. Proin faucibus luctus libero, sed ultrices lorem sagittis et. Vestibulum malesuada, ante nec molestie vehicula, quam diam mollis ipsum, rhoncus posuere mauris lectus in eros. Nullam feugiat ultrices augue, ac sodales sem mollis in.</p> +<p id="myBookmark3"><em>Here is the bookmark #3</em></p> +<p>Proin vitae sem non lorem pellentesque molestie. Nam tempus massa et turpis placerat sit amet sollicitudin orci sodales. Pellentesque enim enim, sagittis a lobortis ut, tempus sed arcu. Aliquam augue turpis, varius vel bibendum ut, aliquam at diam. Nam lobortis, dui eu hendrerit pellentesque, sem neque porttitor erat, non dapibus velit lectus in metus. Vestibulum sit amet felis enim. In quis est vitae nunc malesuada consequat nec nec sapien. Suspendisse aliquam massa placerat dui lacinia luctus sed vitae risus. Fusce tempus, neque id ultrices volutpat, mi urna auctor arcu, viverra semper libero sem vel enim. Mauris dictum, elit non placerat malesuada, libero elit euismod nibh, nec posuere massa arcu eu risus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer urna velit, dapibus eget varius feugiat, pellentesque sit amet ligula. Maecenas nulla nisl, facilisis eu egestas scelerisque, mollis eget metus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Morbi sed congue mi.</p> +<p>Fusce metus velit, pharetra at vestibulum nec, facilisis porttitor mi. Curabitur ligula sapien, fermentum vel porttitor id, rutrum sit amet magna. Sed sit amet sollicitudin turpis. Aenean luctus rhoncus dolor, et pulvinar ante egestas et. Donec ac massa orci, quis dapibus augue. Vivamus consectetur auctor pellentesque. Praesent vestibulum tincidunt ante sed consectetur. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Fusce purus metus, imperdiet vitae iaculis convallis, bibendum vitae turpis.</p> +<p>Fusce aliquet molestie dolor, in ornare dui sodales nec. In molestie sollicitudin felis a porta. Mauris nec orci sit amet orci blandit tristique congue nec nunc. Praesent et tellus sollicitudin mauris accumsan fringilla. Morbi sodales, justo eu sollicitudin lacinia, lectus sapien ullamcorper eros, quis molestie urna elit bibendum risus. Proin eget tincidunt quam. Nam luctus commodo mauris, eu posuere nunc luctus non. Nulla facilisi. Vivamus eget leo rhoncus quam accumsan fringilla. Aliquam sit amet lorem est. Nullam vel tellus nibh, id imperdiet orci. Integer egestas leo eu turpis blandit scelerisque.</p> +<p>Etiam in blandit tellus. Integer sed varius quam. Vestibulum dapibus mi gravida arcu viverra blandit. Praesent tristique augue id sem adipiscing pellentesque. Sed sollicitudin, leo sed interdum elementum, nisi ante condimentum leo, eget ornare libero diam semper quam. Vivamus augue urna, porta eget ultrices et, dapibus ut ligula. Ut laoreet consequat faucibus. Praesent at lectus ut lectus malesuada mollis. Nam interdum adipiscing eros, nec sodales mi porta nec. Proin et quam vitae sem interdum aliquet. Proin vel odio at lacus vehicula aliquet.</p> +<p>Etiam placerat dui ut sem ornare vel vestibulum augue mattis. Sed semper malesuada mi, eu bibendum lacus lobortis nec. Etiam fringilla elementum risus, eget consequat urna laoreet nec. Etiam mollis quam non sem convallis vel consectetur lectus ullamcorper. Aenean mattis lacus quis ligula mattis eget vestibulum diam hendrerit. In non placerat mauris. Praesent faucibus nunc quis eros sagittis viverra. In hac habitasse platea dictumst. Suspendisse eget nisl erat, ac molestie massa. Praesent mollis vestibulum tincidunt. Fusce suscipit laoreet malesuada. Aliquam erat volutpat. Aliquam dictum elementum rhoncus. Praesent in est massa, pulvinar sodales nunc. Pellentesque gravida euismod mi ac convallis.</p> +<p>Mauris vel odio vel nulla facilisis lacinia. Aliquam ultrices est at leo blandit tincidunt. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Suspendisse porttitor adipiscing facilisis. Duis cursus quam iaculis augue interdum porttitor. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Duis vulputate magna ac metus pretium condimentum. In tempus, est eget vestibulum blandit, velit massa dignissim nisl, ut scelerisque lorem neque vel velit. Maecenas fermentum commodo viverra. Curabitur a nibh non velit aliquam cursus. Integer semper condimentum tortor a pellentesque. Pellentesque semper, nisl id porttitor vehicula, sem dui feugiat lacus, vitae consequat augue urna vel odio.</p> +<p>Vestibulum id neque nec turpis iaculis pulvinar et a massa. Vestibulum sed nibh vitae arcu eleifend egestas. Mauris fermentum ultrices blandit. Suspendisse vitae lorem libero. Aenean et pellentesque tellus. Morbi quis neque orci, eu dignissim dui. Fusce sollicitudin mauris ac arcu vestibulum imperdiet. Proin ultricies nisl sit amet enim imperdiet eu ornare dui tempus. Maecenas lobortis nisi a tortor vestibulum vel eleifend tellus vestibulum. Donec metus sapien, hendrerit a fermentum id, dictum quis libero.</p> +<p>Pellentesque a lorem nulla, in tempor justo. Duis odio nisl, dignissim sed consequat sit amet, hendrerit ac neque. Nunc ac augue nec massa tempor rhoncus. Nam feugiat, tellus a varius euismod, justo nisl faucibus velit, ut vulputate justo massa eu nibh. Sed bibendum urna quis magna facilisis in accumsan dolor malesuada. Morbi sit amet nunc risus, in faucibus sem. Nullam sollicitudin magna sed sem mollis id commodo libero condimentum. Duis eu massa et lacus semper molestie ut adipiscing sem.</p> +<p>Sed id nulla mi, eget suscipit eros. Aliquam tempus molestie rutrum. In quis varius elit. Nullam dignissim neque nec velit vulputate porttitor. Mauris ac ligula sit amet elit fermentum rhoncus. In tellus urna, pulvinar quis condimentum ut, porta nec justo. In hac habitasse platea dictumst. Proin volutpat elit id quam molestie ac commodo lacus sagittis. Quisque placerat, augue tempor placerat pulvinar, nisi nisi venenatis urna, eget convallis eros velit quis magna. Suspendisse volutpat iaculis quam, ut tristique lacus luctus quis.</p> +<p>Nullam commodo suscipit lacus non aliquet. Phasellus ac nisl lorem, sed facilisis ligula. Nam cursus lobortis placerat. Sed dui nisi, elementum eu sodales ac, placerat sit amet mauris. Pellentesque dapibus tellus ut ipsum aliquam eu auctor dui vehicula. Quisque ultrices laoreet erat, at ultrices tortor sodales non. Sed venenatis luctus magna, ultricies ultricies nunc fringilla eget. Praesent scelerisque urna vitae nibh tristique varius consequat neque luctus. Integer ornare, erat a porta tempus, velit justo fermentum elit, a fermentum metus nisi eu ipsum. Vivamus eget augue vel dui viverra adipiscing congue ut massa. Praesent vitae eros erat, pulvinar laoreet magna. Maecenas vestibulum mollis nunc in posuere. Pellentesque sit amet metus a turpis lobortis tempor eu vel tortor. Cras sodales eleifend interdum.</p> +</body> +</html> +</pre> + +<div class="note"><strong>Nota:</strong> La función showNode es también un ejemplo del uso del ciclo <code><a href="/en/JavaScript/Reference/Statements/for" title="en/JavaScript/Reference/Statements/for">for</a></code> sin una sección de <code>statement</code>. En este caso <strong>un punto y coma es siempre puesto inmediatamente después de la declaración de el ciclo.</strong></div> + +<p>…De igual manera pero con un scroll animado:</p> + +<pre class="brush: js">var showBookmark = (function () { + var _useHash, _scrollX, _scrollY, _nodeX, _nodeY, _itFrame, _scrollId = -1, _bookMark, + /* + * nDuration: the duration in milliseconds of each frame + * nFrames: number of frames for each scroll + */ + nDuration = 200, nFrames = 10; + + function _next () { + if (_itFrame > nFrames) { clearInterval(_scrollId); _scrollId = -1; return; } + _isBot = true; + document.documentElement.scrollTop = Math.round(_scrollY + (_nodeY - _scrollY) * _itFrame / nFrames); + document.documentElement.scrollLeft = Math.round(_scrollX + (_nodeX - _scrollX) * _itFrame / nFrames); + if (_useHash && _itFrame === nFrames) { location.hash = _bookMark; } + _itFrame++; + } + + function _chkOwner () { + if (_isBot) { _isBot = false; return; } + if (_scrollId > -1) { clearInterval(_scrollId); _scrollId = -1; } + } + + if (window.addEventListener) { window.addEventListener("scroll", _chkOwner, false); } + else if (window.attachEvent) { window.attachEvent("onscroll", _chkOwner); } + + return function (sBookmark, bUseHash) { + _scrollY = document.documentElement.scrollTop; + _scrollX = document.documentElement.scrollLeft; + _bookMark = sBookmark; + _useHash = arguments.length === 1 || bUseHash; + for ( + var nLeft = 0, nTop = 0, oNode = document.querySelector(sBookmark); + oNode; + nLeft += oNode.offsetLeft, nTop += oNode.offsetTop, oNode = oNode.offsetParent + ); + _nodeX = nLeft, _nodeY = nTop, _itFrame = 1; + if (_scrollId === -1) { _scrollId = setInterval(_next, Math.round(nDuration / nFrames)); } + }; +})(); +</pre> + +<h2 id="Especificaciones">Especificaciones</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', "history.html#the-location-interface", "Window.location")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>No change from {{SpecName("HTML5 W3C")}}.</td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', "browsers.html#the-location-interface", "Window.location")}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_entre_navegadores">Compatibilidad entre navegadores</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 (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>window.location.origin</code></td> + <td>30.0.1599.101 (possibly earlier)</td> + <td>{{CompatGeckoDesktop("21.0")}}</td> + <td>11</td> + <td>{{CompatUnknown}}</td> + <td>7 (possibly earlier, see webkit bug 46558)</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 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>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>window.location.origin</code></td> + <td>30.0.1599.101 (possibly earlier)</td> + <td>{{CompatGeckoMobile("21.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td><span style="font-size: 12px; line-height: 18px;">7 (possibly earlier, see webkit bug </span><span style="font-size: 12px; line-height: 18px;">46558)</span></td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>La interfaz de retorno de un valor, {{domxref("Location")}}.</li> + <li>Información similar, pero agregando contexto del navegador, {{domxref("Document.location")}}</li> + <li><a href="/en-US/docs/DOM/Mozilla_event_reference/hashchange" title="/en-US/docs/DOM/Mozilla_event_reference/hashchange">Manipulando el historial del navegador</a></li> + <li><a href="/en-US/docs/DOM/Mozilla_event_reference/hashchange" title="/en-US/docs/DOM/Mozilla_event_reference/hashchange">hashchange</a></li> +</ul> diff --git a/files/es/web/api/window/locationbar/index.html b/files/es/web/api/window/locationbar/index.html new file mode 100644 index 0000000000..8cff663446 --- /dev/null +++ b/files/es/web/api/window/locationbar/index.html @@ -0,0 +1,66 @@ +--- +title: Window.locationbar +slug: Web/API/Window/locationbar +translation_of: Web/API/Window/locationbar +--- +<div>{{APIRef}}</div> + +<div class="hidden"> +<h2 id="Resumen">Resumen</h2> +</div> + +<p>Devuelve el objeto <code>locationbar</code>, del cual se puede comprobar su visibilidad.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><var>objRef</var> = window.locationbar +</pre> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>El siguiente ejemplo completo en HTML, muestra la forma en la que se utiliza la propiedad <code>visible </code>del objeto <code>locationbar.</code></p> + +<pre class="brush:html"><!DOCTYPE html> +<html lang="en"> +<head> +<meta charset="UTF-8" /> +<title>Various DOM Tests</title> + +<script> +var visible = window.locationbar.visible; +</script> + +</head> +<body> + <p>Various DOM Tests</p> +</body> +</html> +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', 'browsers.html#dom-window-locationbar', 'Window.locationbar')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', 'browsers.html#dom-window-locationbar', 'Window.locationbar')}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("window.locationbar")}}, {{domxref("window.menubar")}}, {{domxref("window.personalbar")}}, {{domxref("window.scrollbars")}}, {{domxref("window.statusbar")}}, {{domxref("window.toolbar")}}</li> +</ul> diff --git a/files/es/web/api/window/matchmedia/index.html b/files/es/web/api/window/matchmedia/index.html new file mode 100644 index 0000000000..eaa7be6dc3 --- /dev/null +++ b/files/es/web/api/window/matchmedia/index.html @@ -0,0 +1,67 @@ +--- +title: Window.matchMedia() +slug: Web/API/Window/matchMedia +tags: + - API + - CSSOM View + - JavaScript + - Media Queries + - Referencia + - Window + - metodo +translation_of: Web/API/Window/matchMedia +--- +<div>{{APIRef}}</div> + +<p>El método <code><strong>Window.matchMedia()</strong></code> devuelve un nuevo objeto {{domxref("MediaQueryList")}} que representa los analizados de la <a href="/es/docs/CSS/Media_queries" title="CSS/Media queries">media query</a> indicada.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><em>mql</em> = window.matchMedia(<em>mediaQueryString</em>)</pre> + +<p>Donde <code>mediaQueryString</code> es una cadena de texto que representa la media query de la que devolver un nuevo objeto {{domxref("MediaQueryList")}}.</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>Este código le permite manejar las cosas de forma diferente cuando la ventana es muy estrecha.</p> + +<pre class="brush: js">if (window.matchMedia("(min-width: 400px)").matches) { + /* La pantalla tiene al menos 400 píxeles de ancho */ +} else { + /* La pantalla tiene menos de 400 píxeles de ancho */ +}</pre> + +<p>Consulte <a href="/en-US/docs/DOM/Using_media_queries_from_code" title="CSS/Using media queries from code">Probando media queries</a> para ver ejemplos adicionales.</p> + +<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("CSSOM View", "#dom-window-matchmedia", "Window.matchMedia()")}}</td> + <td>{{Spec2("CSSOM View")}}</td> + <td>Definición initial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_navegadores">Compatibilidad en navegadores</h2> + +<p>{{Compat("api.Window.matchMedia")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="/es/docs/CSS/Media_queries" title="CSS/Media queries">Media queries</a></li> + <li><a href="/es/docs/Web/Guide/CSS/probando_media_queries" title="CSS/Probando media queries +">Probando media queries </a></li> + <li>{{domxref("MediaQueryList")}}</li> + <li>{{domxref("MediaQueryListListener")}}</li> +</ul> diff --git a/files/es/web/api/window/menubar/index.html b/files/es/web/api/window/menubar/index.html new file mode 100644 index 0000000000..a81e1e45ef --- /dev/null +++ b/files/es/web/api/window/menubar/index.html @@ -0,0 +1,42 @@ +--- +title: Window.menubar +slug: Web/API/Window/menubar +translation_of: Web/API/Window/menubar +--- +<p>{{ APIRef() }}</p> + +<h3 id="Summary" name="Summary">Resumen</h3> + +<p>Retorna el objeto <strong>menubar</strong>, cuya visibilidad puede ser examinada.</p> + +<h3 id="Syntax" name="Syntax">Sintaxis</h3> + +<pre class="eval"><em>objRef</em> = window.menubar +</pre> + +<h3 id="Example" name="Example">Ejemplo</h3> + +<p>El siguiente ejemplo HTML completo muestra la forma en que es utilizada la propiedad visible del objeto menubar.</p> + +<pre><html> +<head> + <title>Various DOM Tests</title> + <script> + var visible = window.menubar.visible; + </script> +</head> +<body> + <p>Various DOM Tests</p> +</body> +</html> +</pre> + +<h3 id="Ver_también">Ver también:</h3> + +<p><a href="/en/DOM/window.locationbar" title="en/DOM/window.locationbar">window.locationbar</a>,<a href="/en/DOM/window.personalbar" title="en/DOM/window.personalbar"> window.personalbar</a>,<a href="/en/DOM/window.scrollbars" title="en/DOM/window.scrollbars"> window.scrollbars</a>, <a href="/en/DOM/window.statusbar" title="en/DOM/window.statusbar">window.statusbar</a>,<a href="/en/DOM/window.toolbar" title="en/DOM/window.toolbar"> window.toolbar</a></p> + +<p> </p> + +<h3 id="Specification" name="Specification">Especificación</h3> + +<p>HTML5</p> diff --git a/files/es/web/api/window/moveby/index.html b/files/es/web/api/window/moveby/index.html new file mode 100644 index 0000000000..cd8cd4ba9d --- /dev/null +++ b/files/es/web/api/window/moveby/index.html @@ -0,0 +1,70 @@ +--- +title: Window.moveBy() +slug: Web/API/Window/moveBy +translation_of: Web/API/Window/moveBy +--- +<div>{{APIRef}}</div> + +<h2 id="Resumen">Resumen</h2> + +<p>Mueve la actual ventana a consecuencia de una cantidad especificada.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">window.moveBy(<em>deltaX</em>, <em>deltaY</em>) +</pre> + +<h3 id="Parametros">Parametros</h3> + +<ul> + <li><code>deltaX</code> es la cantidad de pixeles a mover la ventana horizontalmente.</li> + <li><code>deltaY</code> es la cantidad de pixeles a mover la ventana verticalmente.</li> +</ul> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush:js">function budge() { + moveBy(10, -10); +}</pre> + +<h2 id="Notes">Notes</h2> + +<p>Puedes usar numeros negativos como parametros para esta función. Esta función realiza un movimiento relativo mientras que {{domxref("window.moveTo")}} hace un movimiento absoluto.</p> + +<p>Desde Firefox 7, no es posible para un sitio web mover una ventana en el navegador, deacuerdo con las <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=565541#c24">siguientes reglas</a>:</p> + +<ol> + <li>No puedes mover una ventana o pestaña que no haya sido creada por window.open.</li> + <li>No puedes mover una ventana o pestaña cuando esta en una ventana con más de una sola pestaña.</li> +</ol> + +<h2 id="Especificación">Especificación</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('CSSOM View', '#dom-window-moveby', 'window.moveBy()') }}</td> + <td>{{ Spec2('CSSOM View') }}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatilidad_de_Navegador">Compatilidad de Navegador</h2> + + + +<p>{{Compat("api.Window.moveBy")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("window.moveTo")}}</li> +</ul> diff --git a/files/es/web/api/window/navigator/index.html b/files/es/web/api/window/navigator/index.html new file mode 100644 index 0000000000..4766713060 --- /dev/null +++ b/files/es/web/api/window/navigator/index.html @@ -0,0 +1,60 @@ +--- +title: Window.navigator +slug: Web/API/Window/navigator +tags: + - API + - DOM + - DOM Reference + - HTML-DOM + - Property + - Reference + - WebAPI + - Window + - Window.navigator +translation_of: Web/API/Window/navigator +--- +<div> + {{ApiRef}}</div> +<div> + <span style="line-height: 1.5;">La propiedad de solo lectura </span><code style="font-size: 14px;">Window.navigator </code><span style="line-height: 1.5;">es una referencia al objeto {{domxref("Navigator")}}, el cual puede ser utilizado para obtener información sobre la aplicación que está ejecutando el script.</span></div> +<h2 id="Example" name="Example"> </h2> +<h2 id="Example" name="Example">Sintaxis</h2> +<pre class="syntaxbox"><em>navigatorObject<code> = window.navigator</code></em></pre> +<h2 id="Specification" name="Specification"> </h2> +<h2 id="Specification" name="Specification">Ejemplos</h2> +<h3 id="Ejemplo_1_Detectar_un_navegador_y_retornar_un_string">Ejemplo #1: Detectar un navegador y retornar un string</h3> +<pre class="brush: js">var sBrowser, sUsrAg = navigator.userAgent; + +if(sUsrAg.indexOf("Chrome") > -1) { + sBrowser = "Google Chrome"; +} else if (sUsrAg.indexOf("Safari") > -1) { + sBrowser = "Apple Safari"; +} else if (sUsrAg.indexOf("Opera") > -1) { + sBrowser = "Opera"; +} else if (sUsrAg.indexOf("Firefox") > -1) { + sBrowser = "Mozilla Firefox"; +} else if (sUsrAg.indexOf("MSIE") > -1) { + sBrowser = "Microsoft Internet Explorer"; +} + +alert("Usted está utilizando: " + sBrowser);</pre> +<h3 id="Ejemplo_2_Detectar_un_navegador_y_retornar_un_índice">Ejemplo #2: Detectar un navegador y retornar un índice</h3> +<pre class="brush: js">function obtenerIdNavegador() { + var + aKeys = ["MSIE", "Firefox", "Safari", "Chrome", "Opera"], + sUsrAg = navigator.userAgent, nIdx = aKeys.length - 1; + + for (nIdx; nIdx > -1 && sUsrAg.indexOf(aKeys[nIdx]) === -1; nIdx--); + + return nIdx +} + +console.log(<span style="line-height: normal;">obtenerIdNavegador</span><span style="line-height: normal;">());</span> +</pre> +<h2 id="Specification" name="Specification">Especificación</h2> +<ul> + <li>{{SpecName("HTML5 W3C", "webappapis.html#the-navigator-object","window.navigator")}}</li> + <li>{{SpecName("HTML5.1", "webappapis.html#the-navigator-object", "window.navigator")}}</li> + <li>{{SpecName("HTML WHATWG", "timers.html#the-navigator-object", "window.navigator")}}</li> +</ul> +<h2 id="See_also" name="See_also">Vea además</h2> diff --git a/files/es/web/api/window/offline_event/index.html b/files/es/web/api/window/offline_event/index.html new file mode 100644 index 0000000000..7c503b836a --- /dev/null +++ b/files/es/web/api/window/offline_event/index.html @@ -0,0 +1,70 @@ +--- +title: Offline +slug: Web/API/Window/offline_event +tags: + - Event + - Evento + - Reference + - Referencia +translation_of: Web/API/Window/offline_event +--- +<div>{{APIRef}}</div> + +<p>El evento <strong><code>offline</code></strong> se activa cuando el navegador ha pierdido acceso a la red y el valor de <code>navigator.onLine</code> cambia a <code>false</code>.</p> + +<h2 id="Información_General">Información General</h2> + +<dl> + <dt style="float: left; text-align: right; width: 120px;">Especificación</dt> + <dd style="margin: 0 0 0 120px;"><a class="external" href="http://www.whatwg.org/specs/web-apps/current-work/multipage/offline.html#event-offline">HTML5 Offline</a></dd> + <dt style="float: left; text-align: right; width: 120px;">Interfaz</dt> + <dd style="margin: 0 0 0 120px;">Evento</dd> + <dt style="float: left; text-align: right; width: 120px;">Burbujas</dt> + <dd style="margin: 0 0 0 120px;">No</dd> + <dt style="float: left; text-align: right; width: 120px;">Cancelable</dt> + <dd style="margin: 0 0 0 120px;">No</dd> + <dt style="float: left; text-align: right; width: 120px;">Target</dt> + <dd style="margin: 0 0 0 120px;">DefaultView (<code><window></code>)</dd> + <dt style="float: left; text-align: right; width: 120px;">Acción por Defecto</dt> + <dd style="margin: 0 0 0 120px;">Ninguna</dd> +</dl> + +<h2 id="Propiedades">Propiedades</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Propiedad</th> + <th scope="col">Tipo</th> + <th scope="col">Descripción</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>target</code> {{readonlyInline}}</td> + <td>{{domxref("EventTarget")}}</td> + <td>Evento target (el objetivo más alto en el árbol DOM).</td> + </tr> + <tr> + <td><code>type</code> {{readonlyInline}}</td> + <td>{{domxref("DOMString")}}</td> + <td>Tipo de evento.</td> + </tr> + <tr> + <td><code>bubbles</code> {{readonlyInline}}</td> + <td>{{jsxref("Boolean")}}</td> + <td>Si el evento normalmente burbujea o no.</td> + </tr> + <tr> + <td><code>cancelable</code> {{readonlyInline}}</td> + <td>{{jsxref("Boolean")}}</td> + <td>Si el evento normalmente es cancelable o no.</td> + </tr> + </tbody> +</table> + +<h2 id="Eventos_Relacionados">Eventos Relacionados</h2> + +<ul> + <li><a href="/en-US/docs/Mozilla_event_reference/online"><code>online</code></a></li> +</ul> diff --git a/files/es/web/api/window/open/index.html b/files/es/web/api/window/open/index.html new file mode 100644 index 0000000000..8e0376ee75 --- /dev/null +++ b/files/es/web/api/window/open/index.html @@ -0,0 +1,663 @@ +--- +title: Window.open() +slug: Web/API/Window/open +translation_of: Web/API/Window/open +--- +<p>{{APIRef}}</p> + +<p>Carga un recurso en el contexto de un nuevo navegador (como una ventana) o uno que ya existe, dependiendo de los parametros.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox"><code>var <em>referencia_objeto_window</em> = window.open(<var>[url],</var>[<var>nombre_de_la_ventana],</var>[<var>configuracion_ventana</var>]);</code></pre> + +<h2 id="Return_value_and_parameters" name="Return_value_and_parameters">Parámetros</h2> + +<dl> + <dt><code><em>referencia_objeto_window</em></code></dt> + <dd><code><em>Una referencia de la ventana creada. La referencia puede ser usada para acceder a propiedades y métodos de la nueva ventana.</em></code></dd> + <dt><code><var>url (opcional)</var></code></dt> + <dd><code>La <strong>URL </strong>especifica que página se va cargar en la ventana creada. La URL puede ser una página web <strong>(http://www.ejemplo.com.co)</strong> o un documento que se encuentre en algun directorio de su PC <strong>(html, imagenes y demás). </strong>Si no se expecifica una <strong>URL</strong>, por defecto abrira la ventana en blanco</code></dd> + <dt><code><var>nombre_de_la_ventana (opcional)</var></code></dt> + <dd>Un nombre para la nueva ventana. El nombre puede ser usado como el destino de enlaces y formularios usando el atributo de un elemento {{HTMLElement("a")}} ó {{HTMLElement("form")}}. El nombre no debe contener ningun caracter de espacio en blanco. Notese que <code>nombre_de_la_ventana</code> <strong>no</strong> especifica el titulo de la nueva ventana.</dd> + <dt><code>strWindowFeatures</code></dt> + <dd>An optional parameter listing the features (size, position, scrollbars, etc.) of the new window as a string. The string must not contain any whitespace, and each feature name and its value must be separated by a comma. See {{anch("Position and size features")}} below for details.</dd> +</dl> + +<h2 id="Description" name="Description">Descripción</h2> + +<p class="brush: js">El metodo <code>open()</code> crea una nueva ventana secundaria del navegador, similar a seleccionar Nueva ventana desde el menú archivo. El parámetro <code>url</code> especifica la URL a ser solicitada y cargada en la nueva ventana. Si <code>url</code> es una cadena de caracteres vacia, entonces se creará una nueva ventana en blanco (URL <code>about:blank</code>) con las barras de herramientas por defecto de la ventana principal.</p> + +<p>Observe que las URLs no cargarán inmediatamente. Cuando <code>window.open()</code> retorna, la ventana siempre contiene <code>about:blank</code>. La solicitud de la URL es diferida y comienza luego de que el bloque actual se termine de ejecutar. La creación de la ventana y la carga de los recursos referenciados suceden de forma asíncrona.</p> + +<h2 id="Examples" name="Examples">Ejemplo</h2> + +<pre class="brush: js">var objeto_window_referencia; +var configuracion_ventana = "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes"; + +function abrir_Popup() { + objeto_window_referencia = window.open("http://www.cnn.com/", "Pagina_CNN", configuracion_ventana); +} + +// Llamamos a la función + +abrir_Popup();</pre> + + + + + +<pre class="brush:js">var windowObjectReference; + +function openRequestedPopup() { + windowObjectReference = window.open( + "http://www.domainname.ext/path/ImageFile.png", + "DescriptiveWindowName", + "resizable,scrollbars,status" + ); +}</pre> + +<p>If a window with the name <code>strWindowName</code> already exists, then <code>strUrl</code> is loaded into the <em>existing</em> window. In this case the return value of the method is the existing window and <code>strWindowFeatures</code> is ignored. Providing an empty string for <code>strUrl</code> is a way to get a reference to an open window by its name without changing the window's location. To open a <em>new</em> window on every call of <code>window.open()</code>, use the special value <code>_blank</code> for <code>strWindowName</code>.</p> + +<p><code>strWindowFeatures</code> is an optional string containing a comma-separated list of requested features of the new window. After a window is opened, JavaScript can't be used to change the features. If <code>strWindowName</code> does not specify an existing window and the <code>strWindowFeatures</code> parameter is not provided (or if the <code>strWindowFeatures</code> parameter is an empty string), then the new secondary window will render the default toolbars of the main window.</p> + +<p>If the <code>strWindowFeatures</code> parameter is used and no size features are defined, then the new window dimensions will be the same as the dimensions of the most recently rendered window.</p> + +<p>If the <code>strWindowFeatures</code> parameter is used and if no position features are defined, then the left and top coordinates of the new window dimension will be 22 pixels from where the most recently rendered window was. An offset is universally implemented by browser manufacturers (it is 29 pixels in MSIE 6 SP2 with the default theme) and its purpose is to help users to notice new windows opening. If the most recently used window was maximized, then there is no offset: the new window will be maximized as well.</p> + +<p><strong>If the <code>strWindowFeatures</code> parameter is used, the features that are not listed will be disabled or removed</strong> (except <code>titlebar</code> and <code>close</code> which are by default <code>yes</code>).</p> + +<div class="note"> +<p><strong>Tip</strong>: If using the <code>strWindowFeatures</code> parameter, only list the features to be enabled or rendered; the others (except <code>titlebar</code> and <code>close</code>) will be disabled or removed.</p> + +<p>Note that in some browsers, users can override the <code>strWindowFeatures</code> settings and enable (or prevent the disabling of) features.</p> +</div> + +<p><img alt="Firefox Chrome Toolbars Illustration" src="/@api/deki/files/210/=FirefoxChromeToolbarsDescription7a.gif" style="border: 1px dotted green;"></p> + +<h3 id="Position_and_size_features" name="Position_and_size_features">Características de posición y tamaño</h3> + +<div>{{gecko_minversion_note("1.9.2", "Starting in Gecko 1.9.2 (Firefox 3.6), overriding the position of a window using window features will not change the persisted values saved by the session store feature. That means the next time the window is opened, it will still open in the saved location.")}}</div> + +<p><a href="#Note_on_position_and_dimension_error_correction">Note on position and dimension error correction</a></p> + +<div class="bug">{{bug(176320)}}</div> + +<p><a href="#Note_on_precedence">Note on precedence</a></p> + +<dl> + <dt id="left">left</dt> + <dd>Specifies the distance the new window is placed from the left side of the work area for applications of the user's operating system to the leftmost border (resizing handle) of the browser window. The new window can not be initially positioned offscreen.</dd> + <dd>Supported in: <img alt="Internet Explorer 5+" src="/@api/deki/files/260/=MSIE_ico.png">, <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png">, <img alt="Opera 6+" src="/@api/deki/files/288/=Opera6.gif"></dd> + <dt id="top">top</dt> + <dd>Specifies the distance the new window is placed from the top side of the work area for applications of the user's operating system to the topmost border (resizing handle) of the browser window. The new window can not be initially positioned offscreen.</dd> + <dd>Supported in: <img alt="Internet Explorer 5+" src="/@api/deki/files/260/=MSIE_ico.png">, <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png">, <img alt="Opera 6+" src="/@api/deki/files/288/=Opera6.gif"></dd> + <dt id="height">height</dt> + <dd>Specifies the height of the content area, viewing area of the new secondary window in pixels. The height value includes the height of the horizontal scrollbar if present. The minimum required value is 100.</dd> + <dd><a href="#Note_on_outerHeight_versus_height">Note on outerHeight versus height (or innerHeight)</a></dd> + <dd>Supported in: <img alt="Internet Explorer 5+" src="/@api/deki/files/260/=MSIE_ico.png">, <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png">, <img alt="Opera 6+" src="/@api/deki/files/288/=Opera6.gif"></dd> + <dt id="width">width</dt> + <dd>Specifies the width of the content area, viewing area of the new secondary window in pixels. The width value includes the width of the vertical scrollbar if present. The width value does not include the sidebar if it is expanded. The minimum required value is 100.</dd> + <dd>Supported in: <img alt="Internet Explorer 5+" src="/@api/deki/files/260/=MSIE_ico.png">, <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png">, <img alt="Opera 6+" src="/@api/deki/files/288/=Opera6.gif"></dd> + <dt>screenX</dt> + <dd>Deprecated. Same as <a href="#left">left</a> but only supported by Netscape and Mozilla-based browsers.</dd> + <dd>Supported in: <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png"></dd> + <dt>screenY</dt> + <dd>Deprecated. Same as <a href="#topS">top</a> but only supported by Netscape and Mozilla-based browsers.</dd> + <dd>Supported in: <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png"></dd> + <dt>centerscreen</dt> + <dd>Centers the window in relation to its parent's size and position. Requires chrome=yes.</dd> + <dt>outerHeight</dt> + <dd>Specifies the height of the whole browser window in pixels. This outerHeight value includes any/all present toolbar, window horizontal scrollbar (if present) and top and bottom window resizing borders. Minimal required value is 100.</dd> + <dd><strong>Note</strong>: since titlebar is always rendered, then requesting outerHeight=100 will make the innerHeight of the browser window under the minimal 100 pixels.</dd> + <dd><a href="#Note_on_outerHeight_versus_height">Note on outerHeight versus height (or innerHeight)</a></dd> + <dd>Supported in: <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png"></dd> + <dt>outerWidth</dt> + <dd>Specifies the width of the whole browser window in pixels. This outerWidth value includes the window vertical scrollbar (if present) and left and right window resizing borders.</dd> + <dd>Supported in: <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png"></dd> + <dt>innerHeight</dt> + <dd>Same as <a href="#height">height</a> but only supported by Netscape and Mozilla-based browsers. Specifies the height of the content area, viewing area of the new secondary window in pixels. The <var>innerHeight</var> value includes the height of the horizontal scrollbar if present. Minimal required value is 100.</dd> + <dd><a href="#Note_on_outerHeight_versus_height">Note on outerHeight versus height (or innerHeight)</a></dd> + <dd>Supported in: <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png"></dd> + <dt>innerWidth</dt> + <dd>Same as <a href="#width">width</a> but only supported by Netscape and Mozilla-based browsers. Specifies the width of the content area, viewing area of the new secondary window in pixels. The innerWidth value includes the width of the vertical scrollbar if present. The innerWidth value does not include the sidebar if it is expanded. Minimal required value is 100.</dd> + <dd>Supported in: <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png"></dd> +</dl> + +<h3 id="Toolbar_and_chrome_features" name="Toolbar_and_chrome_features">Barra de herramienta y características de chrome</h3> + +<dl> + <dt>NOTE: All features can be set to yes, 1 or just be present to be "on", set to <em>no</em> or<em> 0 </em>or in most cases just not present to be "off"</dt> + <dd>example "status=yes", "status=1" and "status" have identical results</dd> + <dt></dt> + <dt>menubar</dt> + <dd>If this feature is on, then the new secondary window renders the menubar.</dd> + <dd>Mozilla and Firefox users can force new windows to always render the menubar by setting <code>dom.disable_window_open_feature.menubar</code> to <var>true</var> in <a href="http://support.mozilla.com/en-US/kb/Editing+configuration+files#about_config">about:config</a> or in their <a href="http://support.mozilla.com/en-US/kb/Editing+configuration+files#user_js">user.js file</a>.</dd> + <dd>Supported in: <img alt="Internet Explorer 5+" src="/@api/deki/files/260/=MSIE_ico.png">, <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png"></dd> + <dt>toolbar</dt> + <dd>If this feature is on, then the new secondary window renders the Navigation Toolbar (Back, Forward, Reload, Stop buttons). In addition to the Navigation Toolbar, Mozilla-based browsers will render the Tab Bar if it is visible, present in the parent window. (If this feature is set to <var>no</var> all toolbars in the window will be invisible, for example extension toolbars).</dd> + <dd>Mozilla and Firefox users can force new windows to always render the Navigation Toolbar by setting <code>dom.disable_window_open_feature.toolbar</code> to <var>true</var> in <a href="http://support.mozilla.com/en-US/kb/Editing+configuration+files#about_config">about:config</a> or in their <a href="http://support.mozilla.com/en-US/kb/Editing+configuration+files#user_js">user.js file</a>.</dd> + <dd>Supported in: <img alt="Internet Explorer 5+" src="/@api/deki/files/260/=MSIE_ico.png">, <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png"></dd> + <dt>location</dt> + <dd>If this feature is on, then the new secondary window renders the Location bar in Mozilla-based browsers. MSIE 5+ and Opera 7.x renders the Address Bar.</dd> + <dd>Mozilla and Firefox users can force new windows to always render the location bar by setting <code>dom.disable_window_open_feature.location</code> to <var>true</var> in <a href="http://support.mozilla.com/en-US/kb/Editing+configuration+files#about_config">about:config</a> or in their <a href="http://support.mozilla.com/en-US/kb/Editing+configuration+files#user_js">user.js file</a>. {{Fx_minversion_note(3, "In Firefox 3, <code>dom.disable_window_open_feature.location</code> now defaults to <var>true</var>, forcing the presence of the Location Bar much like in IE7. See bug 337344 for more information.")}}</dd> + <dd>Supported in: <img alt="Internet Explorer 5+" src="/@api/deki/files/260/=MSIE_ico.png">, <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png">, <img alt="Opera 6+" src="/@api/deki/files/288/=Opera6.gif"></dd> + <dt>personalbar</dt> + <dd>If this feature is on, then the new secondary window renders the Personal Toolbar in Netscape 6.x, Netscape 7.x and Mozilla browser. It renders the Bookmarks Toolbar in Firefox. In addition to the Personal Toolbar, Mozilla browser will render the Site Navigation Bar if such toolbar is visible, present in the parent window.</dd> + <dd>Mozilla and Firefox users can force new windows to always render the Personal Toolbar/Bookmarks toolbar by setting <code>dom.disable_window_open_feature.personalbar</code> to <var>true</var> in <a href="http://support.mozilla.com/en-US/kb/Editing+configuration+files#about_config">about:config</a> or in their <a href="http://support.mozilla.com/en-US/kb/Editing+configuration+files#user_js">user.js file</a>.</dd> + <dd>Supported in: <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png"></dd> + <dt>directories {{obsolete_inline("2")}}</dt> + <dd>Obsolete synonym of personalbar. In IE, it rendered the Links bar. Supported in Gecko up to 1.9.2 and in IE up to 6.</dd> + <dt>status</dt> + <dd>If this feature is on, then the new secondary window has a status bar. Users can force the rendering of status bar in all Mozilla-based browsers, in MSIE 6 SP2 (<a href="#Note_on_security_issues_of_the_status_bar_presence">Note on status bar in XP SP2</a>) and in Opera 6+. The default preference setting in recent Mozilla-based browser releases and in Firefox 1.0 is to force the presence of the status bar.</dd> + <dd><a href="#Note_on_status_bar">Note on status bar</a></dd> + <dd>Supported in: <img alt="Internet Explorer 5+" src="/@api/deki/files/260/=MSIE_ico.png">, <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png"></dd> +</dl> + + + +<h3 id="Window_functionality_features" name="Window_functionality_features">Características de funcionalidad de window</h3> + +<dl> + <dt></dt> + <dt>attention {{NonStandardBadge}}</dt> + <dd>If this feature is specified, the window is able to open even if another application is already in the foreground. This feature is for Firefox OS applications only, and is currently restricted to certified applications. See {{SectionOnPage("/en-US/docs/Archive/B2G_OS/Firefox_OS_apps/App_permissions", "Internal (Certified) app permissions")}} for more information.</dd> + <dd>Supported in: <img alt="" src="https://mdn.mozillademos.org/files/8003/firefox_os_logo_wordmark-75px.png" style="height: 25px; width: 83px;"></dd> + <dt>dependent</dt> + <dd>If on, the new window is said to be dependent of its parent window. A dependent window closes when its parent window closes. A dependent window is minimized on the Windows task bar only when its parent window is minimized. On Windows platforms, a dependent window does not show on the task bar. A dependent window also stays in front of the parent window.</dd> + <dd>Dependent windows are not implemented on MacOS X, this option will be ignored.</dd> + <dd>The dependent feature is currently under revision to be removed ({{Bug(214867)}})</dd> + <dd>In MSIE 6, the nearest equivalent to this feature is the <code>showModelessDialog()</code> method.</dd> + <dd>Supported in: <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png"></dd> + <dt>minimizable</dt> + <dd>This setting can only apply to dialog windows; "minimizable" requires <code>dialog=yes</code>. If <code>minimizable</code> is on, the new dialog window will have a minimize system command icon in the titlebar and it will be minimizable. Any non-dialog window is always minimizable and <code>minimizable=no</code> will be ignored.</dd> + <dd>Supported in: <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png"></dd> + <dt>fullscreen</dt> + <dd>Do not use. Not implemented in Mozilla. There are no plans to implement this feature in Mozilla.</dd> + <dd>This feature no longer works in MSIE 6 SP2 the way it worked in MSIE 5.x. The Windows taskbar, as well as the titlebar and the status bar of the window are not visible, nor accessible when fullscreen is enabled in MSIE 5.x.</dd> + <dd><code>fullscreen</code> always upsets users with large monitor screen or with dual monitor screen. Forcing <code>fullscreen</code> onto other users is also extremely unpopular and is considered an outright rude attempt to impose web author's viewing preferences onto users.</dd> + <dd><a href="#Note_on_fullscreen">Note on fullscreen</a></dd> + <dd>Supported in: <img alt="Internet Explorer 5+" src="/@api/deki/files/260/=MSIE_ico.png"></dd> + <dd><code>fullscreen</code> does not really work in MSIE 6 SP2.</dd> + <dt>resizable</dt> + <dd>If this feature is on, the new secondary window will be resizable.</dd> + <dd><strong>Note</strong>: Starting with version 1.4, Mozilla-based browsers have a window resizing grippy at the right end of the status bar, this ensures that users can resize the browser window even if the web author requested this secondary window to be non-resizable. In such case, the maximize/restore icon in the window's titlebar will be disabled and the window's borders won't allow resizing but the window will still be resizable via that grippy in the status bar. + <p>Starting with Firefox 3, secondary windows are always resizable ({{Bug(177838)}})</p> + + <div class="note"> + <p><strong>Tip</strong>: For accessibility reasons, it is strongly recommended to set this feature always on</p> + </div> + </dd> + <dd>Mozilla and Firefox users can force new windows to be easily resizable by setting<br> + <code>dom.disable_window_open_feature.resizable</code><br> + to <var>true</var> in <a href="http://support.mozilla.com/en-US/kb/Editing+configuration+files#about_config">about:config</a> or in their <a href="http://support.mozilla.com/en-US/kb/Editing+configuration+files#user_js">user.js file</a>.</dd> + <dd>Supported in: <img alt="Internet Explorer 5+" src="/@api/deki/files/260/=MSIE_ico.png">, <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png"></dd> + <dt>scrollbars</dt> + <dd>If this feature is on, the new secondary window will show horizontal and/or vertical scrollbar(s) if the document doesn't fit into the window's viewport. + <div class="note"> + <p><strong>Tip</strong>: For accessibility reasons, it is strongly encouraged to set this feature always on.</p> + </div> + </dd> + <dd>Mozilla and Firefox users can force this option to be always enabled for new windows by setting<br> + <code>dom.disable_window_open_feature.scrollbars</code><br> + to <var>true</var> in <a href="http://support.mozilla.com/en-US/kb/Editing+configuration+files#about_config">about:config</a> or in their <a href="http://support.mozilla.com/en-US/kb/Editing+configuration+files#user_js">user.js file</a>.</dd> + <dd><a href="#Note_on_scrollbars">Note on scrollbars</a></dd> + <dd>Supported in: <img alt="Internet Explorer 5+" src="/@api/deki/files/260/=MSIE_ico.png">, <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png"></dd> +</dl> + +<h3 id="Features_requiring_privileges" name="Features_requiring_privileges">Características que requieren privilegios</h3> + +<p>The following features require the <code>UniversalBrowserWrite</code> privilege, otherwise they will be ignored. Chrome scripts have this privilege automatically, others have to request it from the PrivilegeManager.</p> + +<dl> + <dt>chrome</dt> + <dd><strong>Note</strong>: Starting with Mozilla 1.7/Firefox 0.9, this feature requires the <code>UniversalBrowserWrite</code> privilege ({{Bug(244965)}}). Without this privilege, it is ignored.</dd> + <dd>If on, the page is loaded as window's only content, without any of the browser's interface elements. There will be no context menu defined by default and none of the standard keyboard shortcuts will work. The page is supposed to provide a user interface of its own, usually this feature is used to open XUL documents (standard dialogs like the JavaScript Console are opened this way).</dd> + <dd>Supported in: <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png"></dd> + <dt>dialog</dt> + <dd><strong>Note</strong>: Starting with Firefox 44, this feature can only be used with chrome privileges. If content attempts to toggle this feature, it will be ignored.</dd> + <dd><span class="float-right"><a href="/@api/deki/files/268/=MenuSystemCommands.png" title="MenuSystemCommands.png"><img alt="MenuSystemCommands.png" class="internal lwrap" src="/@api/deki/files/268/=MenuSystemCommands.png?size=webview" style="float: left; height: 170px; width: 170px;"></a></span>The <code>dialog</code> feature removes all icons (restore, minimize, maximize) from the window's titlebar, leaving only the close button. Mozilla 1.2+ and Netscape 7.1 will render the other menu system commands (in FF 1.0 and in NS 7.0x, the command system menu is not identified with the Firefox/NS 7.0x icon on the left end of the titlebar: that's probably a bug. You can access the command system menu with a right-click on the titlebar). Dialog windows are windows which have no minimize system command icon and no maximize/restore down system command icon on the titlebar nor in correspondent menu item in the command system menu. They are said to be dialog because their normal, usual purpose is to only notify info and to be dismissed, closed. On Mac systems, dialog windows have a different window border and they may get turned into a sheet.</dd> + <dd>Supported in: <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png"></dd> + <dt>modal</dt> + <dd><strong>Note</strong>: Starting with Mozilla 1.2.1, this feature requires the <code>UniversalBrowserWrite</code> privilege ({{Bug(180048)}}). Without this privilege, it is ignored.</dd> + <dd>If on, the new window is said to be modal. The user cannot return to the main window until the modal window is closed. A typical modal window is created by the <a href="/en-US/docs/DOM/window.alert" title="DOM/window.alert">alert() function</a>.</dd> + <dd>The exact behavior of modal windows depends on the platform and on the Mozilla release version. + <div class="note"> + <p><strong>Note:</strong> As of {{Gecko("1.9")}}, the Internet Explorer equivalent to this feature is the {{domxref("window.showModalDialog()")}} method. For compatibility reasons, it's now supported in Firefox. Note also that starting in {{Gecko("2.0")}}, you can use {{domxref("window.showModalDialog()")}} without UniversalBrowserWrite privileges.</p> + </div> + </dd> + <dd>Supported in: <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png"></dd> + <dt>titlebar</dt> + <dd>By default, all new secondary windows have a titlebar. If set to <var>no or 0</var>, this feature removes the titlebar from the new secondary window.</dd> + <dd>Mozilla and Firefox users can force new windows to always render the titlebar by setting<br> + <code>dom.disable_window_open_feature.titlebar</code><br> + to <var>true</var> in <a href="http://support.mozilla.com/en-US/kb/Editing+configuration+files#about_config">about:config</a> or in their <a href="http://support.mozilla.com/en-US/kb/Editing+configuration+files#user_js">user.js file</a>.</dd> + <dd>Supported in: <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png"></dd> + <dt>alwaysRaised</dt> + <dd>If on, the new window will always be displayed on top of other browser windows, regardless of whether it is active or not.</dd> + <dd>Supported in: <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png"></dd> + <dt>alwaysLowered</dt> + <dd>If on, the new created window floats below, under its own parent when the parent window is not minimized. alwaysLowered windows are often referred as pop-under windows. The alwaysLowered window can not be on top of the parent but the parent window can be minimized. In NS 6.x, the alwaysLowered window has no minimize system command icon and no restore/maximize system command.</dd> + <dd>Supported in: <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png"></dd> + <dt>z-lock</dt> + <dd>Same as <code>alwaysLowered</code>.</dd> + <dt>close</dt> + <dd>When set to <var>no or 0</var>, this feature removes the system close command icon and system close menu item. It will only work for dialog windows (<code>dialog</code> feature set). <code>close=no</code> will override <code>minimizable=yes</code>.</dd> + <dd>Mozilla and Firefox users can force new windows to always have a close button by setting<br> + <code>dom.disable_window_open_feature.close</code><br> + to <var>true</var> in <a href="http://support.mozilla.com/en-US/kb/Editing+configuration+files#about_config">about:config</a> or in their <a href="http://support.mozilla.com/en-US/kb/Editing+configuration+files#user_js">user.js file</a>.</dd> + <dd>Supported in: <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png"></dd> +</dl> + +<p>The position and size feature elements require a number to be set. The toolbars and window functionalities can be set with a <var>yes</var> or <var>no</var>; you can use <var>1</var> instead of <var>yes</var> and <var>0</var> instead of <var>no</var>. The toolbar and functionality feature elements also accept the shorthand form: you can turn a feature on by simply listing the feature name in the <var>features</var> string. If you supply the <var>features</var> parameter, then the <code>titlebar</code> and <code>close</code> are still <var>yes</var> by default, but the other features which have a <var>yes</var>/<var>no</var> choice will be <var>no</var> by default and will be turned off.</p> + +<p>Example:</p> + +<pre class="brush:js">var windowObjectReference; // global variable + +function openRequestedPopup() { + windowObjectReference = window.open( + "http://www.domainname.ext/path/ImgFile.png", + "DescriptiveWindowName", + "width=420,height=230,resizable,scrollbars=yes,status=1" + ); +}</pre> + +<p>In this example, the window will be resizable, it will render scrollbar(s) if needed, if the content overflows requested window dimensions and it will render the status bar. It will not render the menubar nor the location bar. Since the author knew about the size of the image (400 pixels wide and 200 pixels high), he added the margins applied to the root element in MSIE 6 which is 15 pixels for top margin, 15 pixels for the bottom margin, 10 pixels for the left margin and 10 pixels for the right margin.</p> + +<h2 id="Best_practices" name="Best_practices">Buenas prácticas</h2> + +<pre class="brush:js"><script type="text/javascript"> +var windowObjectReference = null; // global variable + +function openFFPromotionPopup() { + if(windowObjectReference == null || windowObjectReference.closed) + /* if the pointer to the window object in memory does not exist + or if such pointer exists but the window was closed */ + + { + windowObjectReference = window.open("http://www.spreadfirefox.com/", + "PromoteFirefoxWindowName", "resizable,scrollbars,status"); + /* then create it. The new window will be created and + will be brought on top of any other window. */ + } + else + { + windowObjectReference.focus(); + /* else the window reference must exist and the window + is not closed; therefore, we can bring it back on top of any other + window with the focus() method. There would be no need to re-create + the window or to reload the referenced resource. */ + }; +} +</script> + +(...) + +<p><a + href="http://www.spreadfirefox.com/" + target="PromoteFirefoxWindowName" + onclick="openFFPromotionPopup(); return false;" + title="This link will create a new window or will re-use an already opened one" +>Promote Firefox adoption</a></p> +</pre> + +<p>The above code solves a few usability problems related to links opening secondary window. The purpose of the <code>return false</code> in the code is to cancel default action of the link: if the onclick event handler is executed, then there is no need to execute the default action of the link. But if javascript support is disabled or non-existent on the user's browser, then the onclick event handler is ignored and the browser loads the referenced resource in the target frame or window that has the name "PromoteFirefoxWindowName". If no frame nor window has the name "PromoteFirefoxWindowName", then the browser will create a new window and will name it "PromoteFirefoxWindowName".</p> + +<p>More reading on the use of the target attribute:</p> + +<p><a href="http://www.w3.org/TR/html401/present/frames.html#h-16.3.2">HTML 4.01 Target attribute specifications</a></p> + +<p><a href="http://www.htmlhelp.com/faq/html/links.html#new-window">How do I create a link that opens a new window?</a></p> + +<p>You can also parameterize the function to make it versatile, functional in more situations, therefore re-usable in scripts and webpages:</p> + +<pre class="brush:js"><script type="text/javascript"> +var windowObjectReference = null; // global variable + +function openRequestedPopup(strUrl, strWindowName) { + if(windowObjectReference == null || windowObjectReference.closed) { + windowObjectReference = window.open(strUrl, strWindowName, + "resizable,scrollbars,status"); + } else { + windowObjectReference.focus(); + }; +} +</script> + +(...) + +<p><a + href="http://www.spreadfirefox.com/" + target="PromoteFirefoxWindow" + onclick="openRequestedPopup(this.href, this.target); return false;" + title="This link will create a new window or will re-use an already opened one" +>Promote Firefox adoption</a></p> +</pre> + +<p>You can also make such function able to open only 1 secondary window and to reuse such single secondary window for other links in this manner:</p> + +<pre class="brush:js"><script type="text/javascript"> +var windowObjectReference = null; // global variable +var PreviousUrl; /* global variable which will store the + url currently in the secondary window */ + +function openRequestedSinglePopup(strUrl) { + if(windowObjectReference == null || windowObjectReference.closed) { + windowObjectReference = window.open(strUrl, "SingleSecondaryWindowName", + "resizable,scrollbars,status"); + } else if(PreviousUrl != strUrl) { + windowObjectReference = window.open(strUrl, "SingleSecondaryWindowName", + "resizable=yes,scrollbars=yes,status=yes"); + /* if the resource to load is different, + then we load it in the already opened secondary window and then + we bring such window back on top/in front of its parent window. */ + windowObjectReference.focus(); + } else { + windowObjectReference.focus(); + }; + + PreviousUrl = strUrl; + /* explanation: we store the current url in order to compare url + in the event of another call of this function. */ +} +</script> + +(...) + +<p><a + href="http://www.spreadfirefox.com/" + target="SingleSecondaryWindowName" + onclick="openRequestedSinglePopup(this.href); return false;" + title="This link will create a new window or will re-use an already opened one" +>Promote Firefox adoption</a></p> + +<p><a + href="http://www.mozilla.org/support/firefox/faq" + target="SingleSecondaryWindowName" + onclick="openRequestedSinglePopup(this.href); return false;" + title="This link will create a new window or will re-use an already opened one" +>Firefox FAQ</a></p> +</pre> + +<h2 id="FAQ" name="FAQ">FAQ</h2> + +<dl> + <dt>How can I prevent the confirmation message asking the user whether he wants to close the window?</dt> + <dd>You can not. <strong>New windows not opened by javascript can not as a rule be closed by JavaScript.</strong> The JavaScript Console in Mozilla-based browsers will report the warning message: <code>"Scripts may not close windows that were not opened by script."</code> Otherwise the history of URLs visited during the browser session would be lost.</dd> + <dd><a href="/en-US/docs/DOM/window.close" title="DOM/window.close">More on the window.close()</a> method</dd> + <dt>How can I bring back the window if it is minimized or behind another window?</dt> + <dd>First check for the existence of the window object reference of such window and if it exists and if it has not been closed, then use the <a href="/en-US/docs/DOM/window.focus" title="DOM/window.focus">focus()</a> method. There is no other reliable way. You can examine an <a href="#Best_practices">example explaining how to use the focus() method</a>.</dd> + <dt>How do I force a maximized window?</dt> + <dd>You cannot. All browser manufacturers try to make the opening of new secondary windows noticed by users and noticeable by users to avoid confusion, to avoid disorienting users.</dd> + <dt>How do I turn off window resizability or remove toolbars?</dt> + <dd>You cannot force this. Users with Mozilla-based browsers have absolute control over window functionalities like resizability, scrollability and toolbars presence via user preferences in <code>about:config</code>. Since your users are the ones who are supposed to use such windows (and not you, being the web author), the best is to avoid interfering with their habits and preferences. We recommend to always set the resizability and scrollbars presence (if needed) to yes to insure accessibility to content and usability of windows. This is in the best interests of both the web author and the users.</dd> + <dt>How do I resize a window to fit its content?</dt> + <dd>You can not reliably because the users can prevent the window from being resized by unchecking the <code>Edit/Preferences/Advanced/Scripts & Plug-ins/Allow Scripts to/ Move or resize existing windows</code> checkbox in Mozilla or <code>Tools/Options.../Content tab/Enable Javascript/Advanced button/Move or resize existing windows</code> checkbox in Firefox or by setting <code>dom.disable_window_move_resize</code> to <var>true</var> in <code>about:config</code> or by editing accordingly their <a href="http://www.mozilla.org/support/firefox/edit#user">user.js file</a>.</dd> + <dd>In general, users usually disable moving and resizing of existing windows because allowing authors' scripts to do so has been abused overwhelmingly in the past and the rare scripts that do not abuse such feature are often wrong, inaccurate when resizing the window. 99% of all those scripts disable window resizability and disable scrollbars when in fact they should enable both of these features to allow a cautious and sane fallback mechanism if their calculations are wrong.</dd> + <dd>The window method <a href="/en-US/docs/DOM/window.sizeToContent" title="DOM/window.sizeToContent">sizeToContent()</a> is also disabled if the user unchecks the preference <code>Move or resize existing windows</code> checkbox. Moving and resizing a window remotely on the user's screen via script will very often annoy the users, will disorient the user, and will be wrong at best. The web author expects to have full control of (and can decide about) every position and size aspects of the users' browser window ... which is simply not true.</dd> + <dt>How do I open a referenced resource of a link in a new tab? or in a specific tab?</dt> + <dd>To open a resource in a new tab see <a href="https://developer.mozilla.org/en-US/docs/XUL/tabbrowser">Tabbed browser</a>. Some <a href="https://developer.mozilla.org/en-US/Add-ons/Code_snippets/Tabbed_browser?redirectlocale=en-US&redirectslug=Code_snippets%2FTabbed_browser">Code snippets</a> are available. If you are using the SDK, tabs are <a href="https://developer.mozilla.org/en-US/Add-ons/SDK/High-Level_APIs/tabs">handled a bit differently</a></dd> + <dd><a href="http://kmeleon.sourceforge.net/">K-meleon 1.1</a>, a Mozilla-based browser, gives complete control and power to the user regarding how links are opened. Only the user can set his advanced preferences to do that. Some advanced extensions also give Mozilla and Firefox a lot of power over how referenced resources are loaded.</dd> + <dd>In a few years, the <a href="http://www.w3.org/TR/2004/WD-css3-hyperlinks-20040224/#target0">target property of the CSS3 hyperlink module</a> may be implemented (if CSS3 Hyperlink module as it is right now is approved). And even if and when this happens, you can expect developers of browsers with tab-browsing to give the user entire veto power and full control over how links can open web pages. How to open a link should always be entirely under the control of the user.</dd> + <dt>How do I know whether a window I opened is still open?</dt> + <dd>You can test for the existence of the window object reference which is the returned value in case of success of the window.open() call and then verify that <em>w</em><var>indowObjectReference</var>.closed return value is <var>false</var>.</dd> + <dt>How can I tell when my window was blocked by a popup blocker?</dt> + <dd>With the built-in popup blockers of Mozilla/Firefox and Internet Explorer 6 SP2, you have to check the return value of <code>window.open()</code>: it will be <var>null</var> if the window wasn't allowed to open. However, for most other popup blockers, there is no reliable way.</dd> + <dt>What is the JavaScript relationship between the main window and the secondary window?</dt> + <dd>The <code>window.open()</code> method gives a main window a reference to a secondary window; the <a href="/en-US/docs/DOM/window.opener" title="DOM/window.opener">opener</a> property gives a secondary window a reference to its main window.</dd> + <dt>I can not access the properties of the new secondary window. I always get an error in the javascript console saying "Error<span class="nowiki">:</span> uncaught exception<span class="nowiki">:</span> Permission denied to get property <property_name or method_name>. Why is that?</dt> + <dd>It is because of the cross-domain script security restriction (also referred as the "Same Origin Policy"). A script loaded in a window (or frame) from a distinct origin (domain name) <strong>cannot get nor set</strong> properties of another window (or frame) or the properties of any of its HTML objects coming from another distinct origin (domain name). Therefore, before executing a script targeting a secondary window, the browser in the main window will verify that the secondary window has the same domain name.</dd> + <dd>More reading on the cross-domain script security restriction: <a href="http://www.mozilla.org/projects/security/components/same-origin.html" rel="freelink">http://www.mozilla.org/projects/secu...me-origin.html</a></dd> +</dl> + +<h2 id="Usability_issues" name="Usability_issues">Problemas de usos</h2> + +<h3 id="Avoid_resorting_to_window.open.28.29" name="Avoid_resorting_to_window.open.28.29">Avoid resorting to <code>window.open()</code></h3> + +<p>Generally speaking, it is preferable to avoid resorting to window.open() for several reasons:</p> + +<ul> + <li>All Mozilla-based browsers offer <a href="https://developer.mozilla.org/en-US/docs/XUL/tabbrowser">tab-browsing</a> and this is the preferred mode of <a href="https://developer.mozilla.org/en-US/Add-ons/Code_snippets/Tabbed_browser?redirectlocale=en-US&redirectslug=Code_snippets%2FTabbed_browser">opening referenced resources</a> (<a href="https://developer.mozilla.org/en-US/Add-ons/SDK/High-Level_APIs/tabs">SDK</a>)... not just in Mozilla-based browsers but in all other browsers offering tab-browsing. In other words, tab-capable browser users overall prefer opening new tabs than opening new windows in a majority of webpage situations. Tab-capable browsers have rapidly gained support and enthusiasm on internet in the last 3 years; this trend will not revert back. MSIE 7, released in October 2006, has full support for tab browsing.</li> + <li>There are now <a href="https://addons.mozilla.org/seamonkey/browse/type:1/cat:48/sort:updated">several Mozilla extensions</a> (like Multizilla) and <a href="https://addons.update.mozilla.org/firefox/browse/type:1/cat:14/sort:updated">Firefox extensions</a> (like <a href="https://addons.mozilla.org/firefox/addon/158">Tabbrowser preferences</a>), features, settings and advanced preferences based on tab-browsing and based on converting window.open() calls into opening tabs, based on neutralizing window.open() calls, in particular in neutralizing unrequested openings of new windows (often referred as blocking unrequested popups or as blocking script-initiated windows opening automatically). Such features found in extensions include opening a link in a new window or not, in the same window, in a new tab or not, in "background" or not. Coding carelessly to open new windows can no longer be assured of success, can not succeed by force and, if it does, it will annoy a majority of users.</li> + <li>New windows can have menubar missing, scrollbars missing, status bar missing, window resizability disabled, etc.; new tabs can not be missing those functionalities or toolbars (or at least, the toolbars which are present by default). Therefore, tab-browsing is preferred by a lot of users because the normal user-interface of the browser window they prefer is kept intact, remains stable.</li> + <li>Opening new windows, even with reduced features, uses considerably a lot of the user's system resources (cpu, RAM) and involves considerably a lot of coding in the source code (security management, memory management, various code branchings sometimes quite complex, window frame/chrome/toolbars building, window positioning and sizing, etc.). Opening new tabs is less demanding on the user's system resources (and faster to achieve) than opening new windows.</li> +</ul> + +<h3 id="Offer_to_open_a_link_in_a_new_window.2C_using_these_guidelines" name="Offer_to_open_a_link_in_a_new_window.2C_using_these_guidelines">Offer to open a link in a new window, using these guidelines</h3> + +<p>If you want to offer to open a link in a new window, then follow tested and recommendable usability and accessibility guidelines:</p> + +<h4 id="Never_use_this_form_of_code_for_links.3Ca_href.3D.22javascriptwindow.open.28....29.22_....3E" name="Never_use_this_form_of_code_for_links:.3Ca_href.3D.22javascript:window.open.28....29.22_....3E"><em>Never</em> use this form of code for links: <code><a href="javascript:window.open(...)" ...></code></h4> + +<p>"javascript:" links break accessibility and usability of webpages in every browser.</p> + +<ul> + <li>"javascript:" pseudo-links become dysfunctional when javascript support is disabled or inexistent. Several corporations allow their employees to surf on the web but under strict security policies: no javascript enabled, no java, no activeX, no Flash. For various reasons (security, public access, text browsers, etc..), about 5% to 10% of users on the web surf with javascript disabled.</li> + <li>"javascript:" links will interfere with advanced features in tab-capable browsers: eg. middle-click on links, Ctrl+click on links, tab-browsing features in extensions, etc.</li> + <li>"javascript:" links will interfere with the process of indexing webpages by search engines.</li> + <li>"javascript:" links interfere with assistive technologies (e.g. voice browsers) and several web-aware applications (e.g. <abbr title="Personal Digital Assistant">PDAs</abbr> and mobile browsers).</li> + <li>"javascript:" links also interfere with "mouse gestures" features implemented in browsers.</li> + <li>Protocol scheme "javascript:" will be reported as an error by link validators and link checkers.</li> +</ul> + +<p><strong>Further reading:</strong></p> + +<ul> + <li><a href="http://www.useit.com/alertbox/20021223.html">Top Ten Web-Design Mistakes of 2002</a>, 6. JavaScript in Links, Jakob Nielsen, December 2002</li> + <li><a href="http://www.evolt.org/article/Links_and_JavaScript_Living_Together_in_Harmony/17/20938/">Links & JavaScript Living Together in Harmony</a>, Jeff Howden, February 2002</li> + <li><a href="http://jibbering.com/faq/#FAQ4_24">comp.lang.javascript newsgroup discussion FAQ on "javascript:" links</a></li> +</ul> + +<h4 id="Never_use_.3Ca_href.3D.22.23.22_onclick.3D.22window.open.28....29.3B.22.3E" name="Never_use_.3Ca_href.3D.22.23.22_onclick.3D.22window.open.28....29.3B.22.3E">Never use <code><a href="#" onclick="window.open(...);"></code></h4> + +<p>Such pseudo-link also breaks accessibility of links. <strong>Always use a real URL for the href attribute value</strong> so that if javascript support is disabled or inexistent or if the user agent does not support opening of secondary window (like MS-Web TV, text browsers, etc), then such user agents will still be able to load the referenced resource according to its default mode of opening/handling a referenced resource. This form of code also interferes with advanced features in tab-capable browsers: eg. middle-click on links, Ctrl+click on links, Ctrl+Enter on links, "mouse gestures" features.</p> + +<h4 id="Always_identify_links_which_will_create_.28or_will_re-use.29_a_new.2C_secondary_window" name="Always_identify_links_which_will_create_.28or_will_re-use.29_a_new.2C_secondary_window">Always identify links which will create (or will re-use) a new, secondary window</h4> + +<p>Identify links that will open new windows in a way that helps navigation for users by coding the title attribute of the link, by adding an icon at the end of the link or by coding the cursor accordingly.</p> + +<p>The purpose is to warn users in advance of context changes to minimize confusion on the user's part: changing the current window or popping up new windows can be very disorienting to users (Back toolbar button is disabled).</p> + +<blockquote> +<p>"Users often don't notice that a new window has opened, especially if they are using a small monitor where the windows are maximized to fill up the screen. So a user who tries to return to the origin will be confused by a grayed out <em>Back</em> button."<br> + quote from <a href="http://www.useit.com/alertbox/990530.html">The Top Ten <em>New</em> Mistakes of Web Design</a>: 2. Opening New Browser Windows, Jakob Nielsen, May 1999</p> +</blockquote> + +<p>When extreme changes in context are explicitly identified before they occur, then the users can determine if they wish to proceed or so they can be prepared for the change: not only they will not be confused or feel disoriented, but more experienced users can better decide how to open such links (in a new window or not, in the same window, in a new tab or not, in "background" or not).</p> + +<p><strong>References</strong></p> + +<ul> + <li>"If your link spawns a new window, or causes another windows to 'pop up' on your display, or move the focus of the system to a new FRAME or Window, then the nice thing to do is to tell the user that something like that will happen." <a href="http://www.w3.org/WAI/wcag-curric/sam77-0.htm">World Wide Web Consortium Accessibility Initiative regarding popups</a></li> + <li>"Use link titles to provide users with a preview of where each link will take them, before they have clicked on it." <a href="http://www.useit.com/alertbox/991003.html">Ten Good Deeds in Web Design</a>, Jakob Nielsen, October 1999</li> + <li><a href="http://www.useit.com/alertbox/980111.html">Using Link Titles to Help Users Predict Where They Are Going</a>, Jakob Nielsen, January 1998</li> +</ul> + +<table class="standard-table"> + <tbody> + <tr> + <td class="header" colspan="4">Example "New Window" Icons & Cursors</td> + </tr> + <tr> + <td style="width: 25%;"><img alt="New window icon from yahoo.com" src="/@api/deki/files/782/=NewwindowYahoo.png"></td> + <td style="width: 25%;"><img alt="New window icon from microsoft.com" src="/@api/deki/files/780/=NewwinMSIE.gif"></td> + <td style="width: 25%;"><img alt="New window icon from webaim.org" src="/@api/deki/files/296/=Popup_requested_new_window.gif"></td> + <td style="width: 25%;"><img alt="New window icon from sun.com" src="/@api/deki/files/811/=PopupImageSun.gif"></td> + </tr> + <tr> + <td><img alt="New window icon from bbc.co.uk" src="/@api/deki/files/795/=Opennews_rb.gif"></td> + <td><img alt="New window icon from Accessible Internet Solutions" src="/@api/deki/files/15/=AIS_NewWindowIcon.png"></td> + <td><img alt="New window icon from accessify.com" src="/@api/deki/files/809/=Pop-up-launcher.gif"></td> + <td><img alt="New window icon from webstyleguide.com" src="/@api/deki/files/417/=Webstyleguide_com_newwind.gif"></td> + </tr> + <tr> + <td><img alt="New window icon from an unknown source" src="/@api/deki/files/810/=Popicon_1.gif"></td> + <td><img alt="New window icon from an unknown source" src="/@api/deki/files/779/=New.gif"></td> + <td><img alt="New window icon from an unknown source" src="/@api/deki/files/419/=WillCreateOrRecycleNewWindow.gif"></td> + <td><img alt="New window icon from gtalbot.org" src="/@api/deki/files/287/=OpenRequestedPopup.png"></td> + </tr> + <tr> + <td colspan="2"><img alt="New window cursor from draig.de" src="/@api/deki/files/169/=Cursor_LinkNewWindowTargetBlank.png"></td> + <td colspan="2"><img alt="New window cursor from mithgol.ru" src="/@api/deki/files/170/=Cursor_newwindowSergeySokoloff.png"></td> + </tr> + </tbody> +</table> + +<h4 id="Always_use_the_target_attribute" name="Always_use_the_target_attribute">Always use the target attribute</h4> + +<p>If javascript support is disabled or non-existent, then the user agent will create a secondary window accordingly or will render the referenced resource according to its handling of the target attribute: e.g. some user agents which can not create new windows, like MS Web TV, will fetch the referenced resource and append it at the end of the current document. The goal and the idea is to try to provide - <strong>not impose</strong> - to the user a way to open the referenced resource, a mode of opening the link. Your code should not interfere with the features of the browser at the disposal of the user and your code should not interfere with the final decision resting with the user.</p> + +<h4 id="Do_not_use_target.3D.22_blank.22" name="Do_not_use_target.3D.22_blank.22">Do not use <code>target="_blank"</code></h4> + +<p>Always provide a meaningful name to your target attribute and try to reuse such target attribute in your page so that a click on another link may load the referenced resource in an already created and rendered window (therefore speeding up the process for the user) and therefore justifying the reason (and user system resources, time spent) for creating a secondary window in the first place. Using a single target attribute value and reusing it in links is much more user resources friendly as it only creates one single secondary window which is recycled. On the other hand, using "_blank" as the target attribute value will create several new and unnamed windows on the user's desktop which can not be recycled, reused. In any case, if your code is well done, it should not interfere with the user's final choice but rather merely offer him more choices, more ways to open links and more power to the tool he's using (a browser).</p> + +<h2 id="Glossary" name="Glossary">Glosario</h2> + +<dl> + <dt>Opener window, parent window, main window, first window</dt> + <dd>Terms often used to describe or to identify the same window. It is the window from which a new window will be created. It is the window on which the user clicked a link which lead to the creation of another, new window.</dd> + <dt>Sub-window, child window, secondary window, second window</dt> + <dd>Terms often used to describe or to identify the same window. It is the new window which was created.</dd> + <dt>Unrequested popup windows</dt> + <dd>Script-initiated windows opening automatically without the user's consent.</dd> +</dl> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('HTML WHATWG', 'browsers.html#dom-open', 'Window.open()')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td></td> + </tr> + <tr> + <td>{{ SpecName('CSSOM View', '#the-features-argument-to-the-open()-method', 'The features argument to the open() method') }}</td> + <td>{{ Spec2('CSSOM View') }}</td> + <td>Defines the effect of the <code>features</code> argument</td> + </tr> + </tbody> +</table> + +<h2 id="Notes" name="Notes">Notas</h2> + +<h3 id="Note_on_precedence" name="Note_on_precedence">Nota sobre la precedencia</h3> + +<p>In cases where <code>left</code> and <code>screenX</code> (and/or <code>top</code> and <code>screenY</code>) have conflicting values, then <code>left</code> and <code>top</code> have precedence over <code>screenX</code> and <code>screenY</code> respectively. If <code>left</code> and <code>screenX</code> (and/or <code>top</code> and <code>screenY</code>) are defined in the <var>features</var> list, then <code>left</code> (and/or <code>top</code>) will be honored and rendered. In the following example the new window will be positioned at 100 pixels from the left side of the work area for applications of the user's operating system, not at 200 pixels.</p> + +<pre class="brush:js">windowObjectReference = window.open( + "http://news.bbc.co.uk/", + "BBCWorldNewsWindowName", + "left=100,screenX=200,resizable,scrollbars,status" +);</pre> + +<p>If left is set but top has no value and screenY has a value, then left and screenY will be the coordinate positioning values of the secondary window.</p> + +<p>outerWidth has precedence over width and width has precedence over innerWidth. outerHeight has precedence over height and height has precedence over innerHeight. In the following example, Mozilla-browsers will create a new window with an outerWidth of 600 pixels wide and will ignore the request of a width of 500 pixels and will also ignore the request of an innerWidth of 400 pixels.</p> + +<pre class="brush:js">windowObjectReference = window.open( + "http://www.wwf.org/", + "WWildlifeOrgWindowName", + "outerWidth=600,width=500,innerWidth=400,resizable,scrollbars,status" +);</pre> + +<h3 id="Note_on_position_and_dimension_error_correction" name="Note_on_position_and_dimension_error_correction">Note on position and dimension error correction</h3> + +<p>Requested position and requested dimension values in the <var>features</var> list will not be honored and <strong>will be corrected</strong> if any of such requested value does not allow the entire browser window to be rendered within the work area for applications of the user's operating system. <strong>No part of the new window can be initially positioned offscreen. This is by default in all Mozilla-based browser releases.</strong></p> + +<p><a href="http://msdn2.microsoft.com/en-us/library/ms997645.aspx#xpsp_topic5">MSIE 6 SP2 has a similar error correction mechanism</a> but it is not activated by default in all security levels: a security setting can disable such error correction mechanism.</p> + +<h3 id="Note_on_scrollbars" name="Note_on_scrollbars">Note on scrollbars</h3> + +<p>When content overflows window viewport dimensions, then scrollbar(s) (or some scrolling mechanism) are necessary to ensure that content can be accessed by users. Content can overflow window dimensions for several reasons which are outside the control of web authors:</p> + +<ul> + <li>user resizes the window</li> + <li>user increases the text size of fonts via View/Text Zoom (%) menuitem in Mozilla or View/Text Size/Increase or Decrease in Firefox</li> + <li>user sets a minimum font size for pages which is bigger than the font-size the web author requested. People over 40 years old or with particular viewing habit or reading preference often set a minimal font size in Mozilla-based browsers.</li> + <li>web author is not aware of default margin (and/or border and/or padding) values applying to root element or body node in various browsers and various browser versions</li> + <li>user uses an user stylesheet (<a href="http://www.mozilla.org/support/firefox/edit#content">userContent.css in Mozilla-based browsers</a>) for his viewing habits which increases document box dimensions (margin, padding, default font size)</li> + <li>user can customize individually the size (height or width) of most toolbars via operating system settings. E.g. window resizing borders, height of browser titlebar, menubar, scrollbars, font size are entirely customizable by the user in Windows XP operating system. These toolbars dimensions can also be set via browser themes and skins or by operating system themes</li> + <li>web author is unaware that the user default browser window has custom toolbar(s) for specific purpose(s); e.g.: prefs bar, web developer bar, accessibility toolbar, popup blocking and search toolbar, multi-feature toolbar, etc.</li> + <li>user uses assistive technologies or add-on features which modify the operating system's work area for applications: e.g. MS-Magnifier</li> + <li>user repositions and/or resizes directly or indirectly the operating system's work area for applications: e.g. user resizes the Windows taskbar, user positions the Windows taskbar on the left side (arabic language based) or right side (Hebrew language), user has a permanent MS-Office quick launch toolbar, etc.</li> + <li>some operating system (Mac OS X) forces presence of toolbars which can then fool the web author's anticipations, calculations of the effective dimensions of the browser window</li> +</ul> + +<h3 id="Note_on_status_bar" name="Note_on_status_bar">Note on status bar</h3> + +<p>You should assume that a large majority of users' browsers will have the status bar or that a large majority of users will want to force the status bar presence: best is to always set this feature to yes. Also, if you specifically request to remove the status bar, then Firefox users will not be able to view the Site Navigation toolbar if it is installed. In Mozilla and in Firefox, all windows with a status bar have a window resizing grippy at its right-most side. The status bar also provides info on http connection, hypertext resource location, download progress bar, encryption/secure connection info with <abbr title="Secure Socket Layer">SSL</abbr> connection (displaying a yellow padlock icon), internet/security zone icons, privacy policy/cookie icon, etc. <strong>Removing the status bar usually removes a lot of functionality, features and information considered useful (and sometimes vital) by the users.</strong></p> + +<h3 id="Note_on_security_issues_of_the_status_bar_presence" name="Note_on_security_issues_of_the_status_bar_presence">Note on security issues of the status bar presence</h3> + +<p>In MSIE 6 for XP SP2: For windows opened using <code>window.open()</code>:</p> + +<blockquote> +<p>"For windows opened using window.open():<br> + Expect the status bar to be present, and code for it. <strong>The status bar will be on by default</strong> and is 20-25 pixels in height. (...)"<br> + quote from <a href="http://msdn2.microsoft.com/en-us/library/ms997645.aspx#xpsp_topic5">Fine-Tune Your Web Site for Windows XP Service Pack 2, Browser Window Restrictions in XP SP2</a></p> +</blockquote> + +<blockquote> +<p>"(...) windows that are created using the window.open() method can be called by scripts and used to spoof a user interface or desktop or to hide malicious information or activity by sizing the window so that the status bar is not visible.<br> + Internet Explorer windows provide visible security information to the user to help them ascertain the source of the Web page and the security of the communication with that page. When these elements are not in view, the user might think they are on a more trusted page or interacting with a system process when they are actually interacting with a malicious host. (...)<br> + <strong>Script-initiated windows will be displayed fully, with the Internet Explorer title bar and status bar.</strong> (...)<br> + Script management of Internet Explorer status bar<br> + Detailed description<br> + <strong>Internet Explorer has been modified to not turn off the status bar for any windows. The status bar is always visible for all Internet Explorer windows.</strong> (...) Without this change, windows that are created using the window.open() method can be called by scripts and spoof a user interface or desktop or hide malicious information or activity by hiding important elements of the user interface from the user.<br> + The status bar is a security feature of Internet Explorer windows that provides Internet Explorer security zone information to the user. This zone cannot be spoofed (...)"<br> + quote from <a href="http://technet.microsoft.com/en-us/library/bb457150.aspx#ECAA">Changes to Functionality in Microsoft Windows XP Service Pack 2, Internet Explorer Window Restrictions</a></p> +</blockquote> + +<h3 id="Note_on_fullscreen" name="Note_on_fullscreen">Note on fullscreen</h3> + +<p>In MSIE 6 for XP SP2:</p> + +<ul> + <li>"window.open() with fullscreen=yes will now result in a maximized window, not a kiosk mode window."</li> + <li>"The definition of the fullscreen=yes specification is changed to mean 'show the window as maximized,' which will keep the title bar, address bar, and status bar visible."</li> +</ul> + +<p><em>References:</em></p> + +<ul> + <li><a href="http://msdn2.microsoft.com/en-us/library/ms997645.aspx#xpsp_topic5">Fine-Tune Your Web Site for Windows XP Service Pack 2</a></li> + <li><a href="http://technet.microsoft.com/en-us/library/bb457150.aspx#ECAA">Changes to Functionality in Microsoft Windows XP Service Pack 2, Script sizing of Internet Explorer windows</a></li> +</ul> + +<h3 id="Note_on_outerHeight_versus_height" name="Note_on_outerHeight_versus_height">Note on outerHeight versus height</h3> + +<p><img alt="innerHeight vs outerHeight illustration" src="/@api/deki/files/212/=FirefoxInnerVsOuterHeight.png"></p> + +<h3 id="Note_on_refreshing_vs._opening_a_new_windowtab">Note on refreshing vs. opening a new window/tab</h3> + +<p>If the <code>strWindowName</code> parameter is omitted, a new window or tab is opened. If a window with the same name already exists, the existing window is refreshed.</p> + +<pre class="script-jem;brush:js">//Always opens a new window/tab +window.open("map.php"); + +//Refreshes an existing window/tab that was opened with the same name, if one exists +window.open("map.php", "BiggerMap");</pre> + +<h2 id="Tutorials" name="Tutorials">Tutoriales</h2> + +<ul> + <li><a href="http://www.infimum.dk/HTML/JSwindows.html">JavaScript windows (tutorial)</a> by Lasse Reichstein Nielsen</li> + <li><a href="http://accessify.com/features/tutorials/the-perfect-popup/" title="http://accessify.com/features/tutorials/the-perfect-popup/">The perfect pop-up (tutorial)</a> by Ian Lloyd</li> + <li><a href="http://www.gtalbot.org/FirefoxSection/Popup/PopupAndFirefox.html">Popup windows and Firefox (interactive demos)</a> by Gérard Talbot</li> +</ul> + +<h2 id="References" name="References">Referencias</h2> + +<ul> + <li><a href="http://www.cs.tut.fi/~jkorpela/www/links.html">Links Want To Be Links</a> by Jukka K. Korpela</li> + <li><a href="http://www.evolt.org/article/Links_and_JavaScript_Living_Together_in_Harmony/17/20938/">Links & JavaScript Living Together in Harmony</a> by Jeff Howden</li> +</ul> diff --git a/files/es/web/api/window/opener/index.html b/files/es/web/api/window/opener/index.html new file mode 100644 index 0000000000..531eb6d2e4 --- /dev/null +++ b/files/es/web/api/window/opener/index.html @@ -0,0 +1,28 @@ +--- +title: Window.opener +slug: Web/API/Window/opener +translation_of: Web/API/Window/opener +--- +<div>{{APIRef}}</div> + +<h2 id="Summary" name="Summary">Resumen</h2> + +<p>Devuelve una referencia de, la ventana que abrió la ventana actuál.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox"><var>objRef</var> = window.opener; +</pre> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre class="brush:js">if (window.opener != indexWin) { + referToTop(window.opener); +} +</pre> + +<h2 id="Notes" name="Notes">Notas</h2> + +<p>Cuando una ventana es abierta desde otra utilizando "Window.open()", esta, mantiene una referencia a la primera mediante "window.opener". Si la ventana actuál no fué abierta, el metodo retorna NULL.</p> + +<p>El navegador de Windows Phone no soporta window.opener. Tampoco es soportado en Internet Explorer si la ventana nueva se encuentra en una zona de seguridad distinta.</p> diff --git a/files/es/web/api/window/outerheight/index.html b/files/es/web/api/window/outerheight/index.html new file mode 100644 index 0000000000..cb77c574f4 --- /dev/null +++ b/files/es/web/api/window/outerheight/index.html @@ -0,0 +1,114 @@ +--- +title: Window.outerHeight +slug: Web/API/Window/outerHeight +tags: + - API + - Propiedad + - Referencia +translation_of: Web/API/Window/outerHeight +--- +<div>{{APIRef}}</div> + +<h2 id="Summary" name="Summary">Sumario</h2> + +<p><code>Window.outerHeight </code>obtiene la altura en pixeles de toda la ventana del navegador. Representa el alto de toda la ventana, incluyendo la barra de notificaciones (si se encuentra) y los bordes.</p> + +<p>Esta propiedad es de sólo lectura, no tiene valor por defecto</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox"><var>outWindowHeight</var> = window.outerHeight; +</pre> + +<p>Al obtener, <code>outWindowHeight</code> contiene el alto de la ventana.</p> + +<h2 id="Notes" name="Notes">Notas</h2> + +<p>Para cambiar el tamaño de una ventana, ver {{domxref("window.resizeBy()")}} y {{domxref("window.resizeTo()")}}.</p> + +<p>Para obtener la altura interna de una ventana, por ejemplo, el alto de una página siendo desplegada, ver {{domxref("window.innerHeight")}}.</p> + +<h3 id="Graphical_example" name="Graphical_example">Ejemplo gráfico</h3> + +<p>La siguiente figura muestra la diferencia entre <code>innerHeight </code>y <code>outerHeight</code>.</p> + +<p><img alt="innerHeight vs outerHeight illustration" src="/@api/deki/files/213/=FirefoxInnerVsOuterHeight2.png"></p> + +<h2 id="Browser_compatibility" name="Browser_compatibility">Compatibilidad del navegador</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</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</td> + <td>{{CompatGeckoDesktop(1.0)}}</td> + <td>9</td> + <td>9</td> + <td>3</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</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>1</td> + <td>{{CompatGeckoMobile(1.0)}}</td> + <td>9</td> + <td>9</td> + <td>3</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Specification" name="Specification">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('CSSOM View', '#dom-window-outerheight', 'Window.outerHeight') }}</td> + <td>{{ Spec2('CSSOM View') }}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("window.innerHeight")}}</li> + <li>{{domxref("window.innerWidth")}}</li> + <li>{{domxref("window.outerWidth")}}</li> + <li>{{domxref("window.resizeBy()")}}</li> + <li>{{domxref("window.resizeTo()")}}</li> +</ul> diff --git a/files/es/web/api/window/outerwidth/index.html b/files/es/web/api/window/outerwidth/index.html new file mode 100644 index 0000000000..b0b91a9beb --- /dev/null +++ b/files/es/web/api/window/outerwidth/index.html @@ -0,0 +1,105 @@ +--- +title: Window.outerWidth +slug: Web/API/Window/outerWidth +translation_of: Web/API/Window/outerWidth +--- +<div>{{APIRef}}</div> + +<h2 id="Summary" name="Summary">Sumario</h2> + +<p><code>Window.outerWidth</code> obtiene el ancho exterior del navegador. Representa el ancho total de la ventana incluyendo las barras laterales (si es expandida), interfaz grafíca y los de elementos para redimencionado de bordes.</p> + +<p>Esta propiedad es de sólo lectura; no tiene valores por default.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox"><var>outWindowWidth</var> = window.outerWidth; +</pre> + +<p>Lo que retorna <code>outWindowWidth</code> es el ancho exterior del navegador.</p> + +<h2 id="Notes" name="Notes">Notas</h2> + +<p>Para cambiar el tamaño de la ventana, ver {{domxref("window.resizeBy()")}} y {{domxref("window.resizeTo()")}}.</p> + +<p>Para obtener el ancho exterior de la ventana, i.e. el ancho de la pagina desplegada, ver {{domxref("window.innerWidth")}}.</p> + +<h2 id="Compatibilidad_del_navegador">Compatibilidad del navegador</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>1</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(1.0)}}</td> + <td>9</td> + <td>9</td> + <td>3</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Edge</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>1</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile(1.0)}}</td> + <td>9</td> + <td>9</td> + <td>3</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Specification" name="Specification">Specificaciones</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('CSSOM View', '#dom-window-outerwidth', 'Window.outerWidth') }}</td> + <td>{{ Spec2('CSSOM View') }}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("window.outerHeight")}}, {{domxref("window.innerHeight")}}, {{domxref("window.innerWidth")}}</li> + <li>{{domxref("window.resizeBy()")}}, {{domxref("window.resizeTo()")}}</li> +</ul> diff --git a/files/es/web/api/window/print/index.html b/files/es/web/api/window/print/index.html new file mode 100644 index 0000000000..7ab8bdb63f --- /dev/null +++ b/files/es/web/api/window/print/index.html @@ -0,0 +1,58 @@ +--- +title: Window.print() +slug: Web/API/Window/print +tags: + - API + - Compatibilidad + - Compatibilidad en móviles + - DOM + - Referencia + - Window + - metodo +translation_of: Web/API/Window/print +--- +<p>{{ ApiRef() }}</p> + +<p>Abre el diálogo para imprimir el documento actual.</p> + +<p>En la mayoría de navegadores, este método bloquea mientras el díalogo de impresión esté abierto, sin embargo, en algunas versiones recientes de Safari podría retornar de inmediato.</p> + +<h2 id="Summary" name="Summary">Resumen</h2> + +<p>Abre el <em>Diálogo de Impresión</em> para imprimir el documento actual.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="eval">window.print() +</pre> + +<h2 id="Specification" name="Specification">Notas</h2> + +<p>Empezando con Chrome {{CompatChrome(46.0)}} este método esta bloqueado dentro de un {{htmlelement("iframe")}} a menos que el atributo del contenedor tenga el valor <code>allow-modal</code>.</p> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estatus</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('HTML5 Web application', '#dom-print', 'print()')}}</td> + <td>{{Spec2('HTML5 Web application')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="/en/Printing" title="en/Printing">Impresión</a></li> + <li>{{ domxref("window.onbeforeprint") }}</li> + <li>{{ domxref("window.onafterprint") }}</li> +</ul> + +<p>{{ languages( { "ja": "ja/DOM/window.print", "it": "it/DOM/window.print" , "zh-cn": "zh-cn/DOM/window.print" } ) }}</p> diff --git a/files/es/web/api/window/prompt/index.html b/files/es/web/api/window/prompt/index.html new file mode 100644 index 0000000000..f05be58868 --- /dev/null +++ b/files/es/web/api/window/prompt/index.html @@ -0,0 +1,82 @@ +--- +title: Window.prompt() +slug: Web/API/Window/prompt +tags: + - Referencia + - metodo +translation_of: Web/API/Window/prompt +--- +<div>{{ApiRef("Window")}}</div> + +<p>El método <code>Window.prompt()</code> muestra un diálogo con mensaje opcional, que solicita al usuario que introduzca un texto.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox"><em>result</em> = window.prompt(<em>message</em>, <em>default</em>); +</pre> + +<ul> + <li><code>result</code> es una cadena de texto que contiene el valor introducido por el usuario, o <code>null</code>.</li> + <li><code>message</code> es una cadena de texto que se mostrará al usuario. Este parámetro es opcional y puede ser omitido si no se necesita mostrar nada en la ventana.</li> + <li><code>default</code> es una cadena de texto que contiene el valor predeterminado para el texto de entrada. Es un parámetro opcional. Nótese que en Internet Explorer 7 y 8, si no se provee un valor para este parámetro, el valor predeterminado es <code>"undefined"</code>.</li> +</ul> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre class="brush: js">var sign = prompt("What's your sign?"); + +if (sign.toLowerCase() == "scorpio") { + alert("Wow! I'm a Scorpio too!"); +} + +// there are many ways to use the prompt feature +var sign = window.prompt(); // open the blank prompt window +var sign = prompt(); // open the blank prompt window +var sign = window.prompt('Are you feeling lucky'); // open the window with Text "Are you feeling lucky" +var sign = window.prompt('Are you feeling lucky', 'sure'); // open the window with Text "Are you feeling lucky" and default value "sure"</pre> + +<p>Cuando el usuario hace clic en el botón OK, el valor introducido en el campo de texto es devuelto por el método. Si el usuario da clic al botón OK sin introducir algun texto, se devuelve una cadena vacía. Si el usuario presiona el botón Cancel, la función devuelve <code>null</code>.</p> + +<p>El ejemplo anterior muestra el siguiente cuadro de diálogo (en Chrome en OS X):</p> + +<p><a href="https://mdn.mozillademos.org/files/11303/prompt.png"><img alt="prompt() dialog in Chrome on OS X" src="https://mdn.mozillademos.org/files/11303/prompt.png" style="height: 298px; width: 535px;"></a></p> + +<h2 id="Notes" name="Notes">Notas</h2> + +<p>Un diálogo prompt contiene un cuadro de texto de una línea, un botón Cancel (Cancelar) un botón OK (Aceptar), y devuelve el texto (posiblemente vacío) que el usuario introdujo en el cuadro de texto.</p> + +<p><span class="comment">The following text is shared between this article, DOM:window.confirm and DOM:window.alert</span>Los cuadros de diálogo son ventanas modales; previenen que el usuario acceda al resto de la interfaz del programa hasta que el cuadro de diálogo es cerrado. Por esta razón, no se debe abusar de cualquier función que crea un cuadro de diálogo (o ventana modal).</p> + +<p>Nótese que el resultado es una cadena de texto. Esto significa que a veces se deberá hacer una conversión al valor introducido por el usuario. Por ejemplo, si la respuesta debe ser un valor numérico, se debe hacer la conversión del valor a tipo Number. <span style="background-color: #f6f6f2; font-family: courier new,andale mono,monospace; font-size: 12px; line-height: normal;">var aNumber = Number(window.prompt("Type a number", "")); </span></p> + +<p>Usuarios de <a href="/en-US/Chrome" title="Chrome">Mozilla Chrome</a> (p.ej. extensiones de Firefox) deben usar preferentemente métodos de {{interface("nsIPromptService")}}.</p> + +<p>A partir de Chrome {{CompatChrome(46.0)}} este método está bloqueado para los elementos {{htmlelement("iframe")}}, , a menos que su atributo <a href="https://developer.mozilla.org/es/docs/Web/HTML/Elemento/iframe#attr-sandbox">sandbox</a> tenga el valor <code>allow-modal</code>.</p> + +<p>En Safari, si el usuario presiona el botón Cancel, la función devuelve una cadena vacía. Por lo tanto, no se puede diferenciar si canceló o si mandó una cadena de texto vacía como valor del cuadro de texto.</p> + +<p>Esta función no tiene efecto en la versión Modern UI/Metro de Internet Explorer para Windows 8. No se muestra un diálogo al usuario, y siempre devuelve <code>undefined</code>. No está claro si esto es un bug o un comportamiento previsto. Las versiones de escritorio de IE sí implementan esta función</p> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentarios</th> + </tr> + <tr> + <td>{{SpecName('HTML5 Web application', '#dom-prompt', 'prompt()')}}</td> + <td>{{Spec2('HTML5 Web application')}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="See_also" name="See_also">Véase también</h2> + +<ul> + <li>{{domxref("window.alert", "alert")}}</li> + <li>{{domxref("window.confirm", "confirm")}}</li> +</ul> diff --git a/files/es/web/api/window/requestanimationframe/index.html b/files/es/web/api/window/requestanimationframe/index.html new file mode 100644 index 0000000000..2f3ae5342b --- /dev/null +++ b/files/es/web/api/window/requestanimationframe/index.html @@ -0,0 +1,153 @@ +--- +title: Window.requestAnimationFrame() +slug: Web/API/Window/requestAnimationFrame +translation_of: Web/API/window/requestAnimationFrame +--- +<div>{{APIRef}}</div> + +<div>El método <strong><code>window.requestAnimationFrame</code></strong> informa al navegador que quieres realizar una animación y solicita que el navegador programe el repintado de la ventana para el próximo ciclo de animación. El método acepta como argumento una función a la que llamar antes de efectuar el repintado.</div> + +<div></div> + +<div class="note"><strong>Nota:</strong> Si no quieres que tu animación se detenga, debes asegurarte de llamar a su vez a <code>requestAnimationFrame() </code>desde tu callback.</div> + +<p>Debes llamar a este método cuando estés preparado para actualizar tu animación en la pantalla para pedir que se programe el repintado. Ésto puede suceder hasta 60 veces por segundo en pestañas en primer plano, pero se puede ver reducido a velocidades inferiores en pestañas en segundo plano.</p> + +<p>El método indicado como callback recibe un único argumento que indica el tiempo en el que está programado que se ejecute el ciclo de animación.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox notranslate"><em>requestID</em> = window.mozRequestAnimationFrame(<em>callback</em>); // Firefox +window.msRequestAnimationFrame(<em><code>callback</code></em>); // IE 10 PP2+ +window.webkitRequestAnimationFrame(callback<em>[, element]</em>); // Chrome/Webkit +</pre> + +<h3 id="Parameters" name="Parameters">Parámetros</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>Parámetro que especifica la función a la cual llamar llegado el momento de actualizar tu animación para el próximo repintado.</dd> +</dl> + +<h3 id="Valor_devuelto">Valor devuelto</h3> + +<p>Un valor entero <code>long</code>, es un entero de tipo long que identifica de manera exclusiva la entrada en la lista de callbacks. Es siempre un distinto de cero, pero no debes realizar ninguna otra suposición acerca de su valor. Puedes pasar este valor a {{ domxref("window.cancelAnimationFrame()") }} para cancelar la petición de actualización del callback.</p> + +<h2 id="Notes" name="Notes">Ejemplo</h2> + +<pre class="brush: js notranslate">(function() { + var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || + window.webkitRequestAnimationFrame || window.msRequestAnimationFrame; + window.requestAnimationFrame = requestAnimationFrame; +})(); + +<code>var start = null; +var element = document.getElementById('SomeElementYouWantToAnimate'); + +function step(timestamp) { + if (!start) start = timestamp; + var progress = timestamp - start; + element.style.transform = 'translateX(' + Math.min(progress / 10, 200) + 'px)'; + if (progress < 2000) { + window.requestAnimationFrame(step); + } +} + +window.requestAnimationFrame(step);</code></pre> + +<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>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>21.0 {{ property_prefix("webkit") }}</td> + <td>14.0 {{ property_prefix("moz") }}</td> + <td>10.0</td> + <td>{{ CompatNo() }}</td> + <td>6.0 {{ property_prefix("webkit") }}</td> + </tr> + <tr> + <td><code>requestID</code> return value</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatGeckoDesktop("11.0") }} {{ property_prefix("moz") }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>BlackBerry Browser</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>10.0 {{ property_prefix("webkit") }}</td> + <td> + <p>0.16 {{ property_prefix("webkit") }}</p> + </td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatNo() }}</td> + <td>6.0 {{ property_prefix("webkit") }}</td> + </tr> + <tr> + <td><code>requestID</code> return value</td> + <td>{{ CompatUnknown() }}</td> + <td></td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatGeckoMobile("11.0") }} {{ property_prefix("moz") }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<h3 id="Specification" name="Specification">Notas para Gecko</h3> + +<p>Antes que Gecko 11.0 {{ geckoRelease("11.0") }}, <code>mozRequestAnimationFrame()</code> se podía llamar sin parámetros. Esta opción ya no está soportada ya que no es probable que se convierta en parte del estándar.</p> + +<h3 id="Notas_para_Chrome">Notas para Chrome</h3> + +<p>En estos momentos, la llamada correcta en Chrome para cancelar la petición es <code>window.webkitCancelAnimationFrame()</code>. La antigua versión, <code>window.webkitCancelRequestAnimationFrame()</code>, está obsoleta se sigue soportando por ahora.</p> + +<h2 id="Specification" name="Specification">Especificaciones</h2> + +<p>{{ spec("http://www.w3.org/TR/animation-timing/#requestAnimationFrame", "Timing control for script-based animations: requestAnimationFrame", "WD") }}</p> + +<h2 id="Véase_también">Véase también</h2> + +<ul> + <li>{{ domxref("window.mozAnimationStartTime") }}</li> + <li>{{ domxref("window.cancelAnimationFrame()") }}</li> + <li><a class="external" href="http://weblogs.mozillazine.org/roc/archives/2010/08/mozrequestanima.html">mozRequestAnimationFrame</a> - Blog post</li> + <li><a class="external" href="http://paulirish.com/2011/requestanimationframe-for-smart-animating/">requestAnimationFrame for smart animating</a> - Blog post</li> + <li><a class="external" href="http://hacks.mozilla.org/2011/08/animating-with-javascript-from-setinterval-to-requestanimationframe/">Animating with javascript: from setInterval to requestAnimationFrame</a> - Blog post</li> + <li><a class="external" href="http://blogs.msdn.com/b/ie/archive/2011/07/05/using-pc-hardware-more-efficiently-in-html5-new-web-performance-apis-part-1.aspx">Using PC Hardware more efficiently in HTML5: New Web Performance APIs, Part 1</a> - Blog post</li> +</ul> diff --git a/files/es/web/api/window/requestidlecallback/index.html b/files/es/web/api/window/requestidlecallback/index.html new file mode 100644 index 0000000000..ba4351f818 --- /dev/null +++ b/files/es/web/api/window/requestidlecallback/index.html @@ -0,0 +1,126 @@ +--- +title: requestIdleCallback +slug: Web/API/Window/requestIdleCallback +translation_of: Web/API/Window/requestIdleCallback +--- +<div>{{APIRef("HTML DOM")}}{{SeeCompatTable}}</div> + +<p>El método <code><strong>w</strong></code><strong><code>indow.requestIdleCallback()</code></strong> encola la función que será ejecutada en periodos de inactividad del navegador permitiendo a los desarrolladores ejecutar en segundo plano tareas de baja prioridad del bucle de eventos, sin perjudicar la latencia de eventos principales como animaciones o respuestas a entradas. La funciones son ejecutadas normalmente en orden FIFO (primero en entrar primero en salir) salvo que se alcance el timeout definido de la función antes de que el navegador la ejecute.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox notranslate"><code>var handle = window.requestIdleCallback(callback[, options])</code></pre> + +<h3 id="Valor_devuelto">Valor devuelto</h3> + +<p>Un entero largo sin signo (unsigned long integer) que puede utilizarse para cancelar el callback a través del método {{domxref("Window.cancelIdleCallback()")}}.</p> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>La referencia a la función que debe ser ejecutada en un futuro inmediato. La función callback toma un argumento con las siguientes propiedades: + <ul> + <li><code>timeRemaining</code>: Referencia a un metodo que devuelve un {{domxref("DOMHighResTimeStamp")}}.</li> + <li><code>didTimeout</code>: Booleano que se devuelve a false si el callback fue invocado por el navegador durante su inactividad, y true en otro caso (por ejemplo, si se definió timeout y expiró antes de que hubiera suficiente tiempo de inactividad).</li> + </ul> + </dd> + <dt><code>options</code> {{optional_inline}}</dt> +</dl> + +<p>Contiene parametros opcionales de configuración. Contiene la siguiente propiedad:</p> + +<ul> + <li><code>timeout</code>: Plazo para que el navegador ejecute la función callback. Valor en milisegundos.</li> +</ul> + + + +<h2 id="Example" name="Example">Ejemplos</h2> + +<p>Ver <a href="https://wiki.developer.mozilla.org/en-US/docs/Web/API/Background_Tasks_API#Example">ejemplo</a> en el artículo <a href="https://wiki.developer.mozilla.org/en-US/docs/Web/API/Background_Tasks_API">Planificación Cooperativa de la API de Tareas en segundo plano</a>.</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col"> + <p>Especificación</p> + </th> + <th scope="col">Estado</th> + <th scope="col">Comentarios</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('Background Tasks')}}</td> + <td>{{Spec2('Background Tasks')}}</td> + <td>Definición Inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_Navegadores">Compatibilidad en Navegadores</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>{{CompatChrome(47)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Webview Android</th> + <th>Firefox para Móvil (Gecko)</th> + <th>Firefox OS</th> + <th>IE para Móvil</th> + <th>Opera para Móvil</th> + <th>Safari para Móvil</th> + <th>Chrome para Android</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(47)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatChrome(47)}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Vease_también">Vease también</h2> + +<ul> + <li>{{domxref("window.cancelIdleCallback()")}}</li> + <li>{{domxref("IdleDeadline")}}</li> + <li>{{domxref("window.setTimeout()")}}</li> + <li>{{domxref("window.setInterval()")}}</li> + <li>{{domxref("window.requestAnimationFrame")}}</li> +</ul> diff --git a/files/es/web/api/window/scroll/index.html b/files/es/web/api/window/scroll/index.html new file mode 100644 index 0000000000..ec2c61ab41 --- /dev/null +++ b/files/es/web/api/window/scroll/index.html @@ -0,0 +1,84 @@ +--- +title: Window.scroll() +slug: Web/API/Window/scroll +tags: + - API + - CSSOM View + - Referencia + - metodo +translation_of: Web/API/Window/scroll +--- +<div>{{APIRef}}</div> + +<p>El método <code><strong>Window.scroll()</strong></code> desplaza la ventana a un lugar particular en el documento.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">window.scroll(<em>x-coord</em>, <em>y-coord</em>) +window.scroll(<em>options</em>) +</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<ul> + <li><code>x-coord</code> es la coordenada sobre el eje horizontal del documento del pixel que querés que se muestre en la parte superior izquierda.</li> + <li><code>y-coord</code> es la coordenada sobre el eje vertical del documento del pixel que querés que se muestre en la parte superior izquierda.</li> +</ul> + +<p>- o -</p> + +<ul> + <li><code>options</code> es un diccionario {{domxref("ScrollToOptions")}}.</li> +</ul> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush:html;htmlScript:true;"><!-- poner el pixel 100º verticalmente en el tope superior de la ventana --> + +<button onClick="scroll(0, 100);">Clic para desplazarse hacia abajo 100 pixeles</button> +</pre> + +<p>Utilizando <code>options</code>:</p> + +<pre class="brush: js">window.scroll({ + top: 100, + left: 100, + behavior: 'smooth' +});</pre> + +<h2 id="Notas">Notas</h2> + +<p>{{domxref("Window.scrollTo()")}} es efectivamente idéntico a este método. Para desplazamiento relativo, mira {{domxref("Window.scrollBy()")}}, {{domxref("Window.scrollByLines()")}} y {{domxref("Window.scrollByPages()")}}.</p> + +<p>Para desplazarse sobre elementos, mira {{domxref("Element.scrollTop")}} y {{domxref("Element.scrollLeft")}}.</p> + +<h2 id="Especificación">Especificación</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('CSSOM View', '#dom-window-scroll', 'window.scroll()') }}</td> + <td>{{ Spec2('CSSOM View') }}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_navegadores">Compatibilidad en navegadores</h2> + +<p>{{Compat("api.Window.scroll")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("Window.scrollByLines()")}}</li> + <li>{{domxref("Window.scrollByPages()")}}</li> + <li>{{domxref("Element.scrollIntoView()")}}</li> +</ul> diff --git a/files/es/web/api/window/scrollby/index.html b/files/es/web/api/window/scrollby/index.html new file mode 100644 index 0000000000..e07da04b65 --- /dev/null +++ b/files/es/web/api/window/scrollby/index.html @@ -0,0 +1,85 @@ +--- +title: Window.scrollBy() +slug: Web/API/Window/scrollBy +tags: + - API + - CSSOM View + - Método(2) + - NeedsCompatTable + - NeedsSpecTable + - Referencia +translation_of: Web/API/Window/scrollBy +--- +<p>{{ APIRef() }}</p> + +<h2 id="Summary" name="Summary">Resumen</h2> + +<p>Desplaza el documento el número de pixels proporcionados.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre>window.scrollBy(<em>X</em>, <em>Y</em>); +window.scrollBy(opciones)</pre> + +<h3 id="Parameters" name="Parameters">Parámetros</h3> + +<ul> + <li><code>X</code> es el número de pixels a desplazar horizontalmente.</li> + <li><code>Y</code> es el número de pixels a desplazar verticalmente.</li> +</ul> + +<p>Si X o Y son positivos, desplazarán la página hacia la derecha o hacia abajo respectivamente. Si son negativos, la desplazarán hacia la izquierda o hacia arriba respectivamente.</p> + +<p>- or -</p> + +<ul> + <li><font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">opciones</span></font> es un objeto con tres posibles propiedades: + + <ul> + <li><font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">top</span></font>, que es lo mismo que <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">Y</span></font></li> + <li><font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">left</span></font>, que es lo mismo que X</li> + <li><font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">behavior</span></font>, que es un string cuyo valor puede ser <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">smooth</span></font>, <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">instant</span></font>, or <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">auto</span></font>. Por defecto el valor es <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">auto</span></font></li> + </ul> + </li> +</ul> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre class="eval">// Desplazarse la longitud de una página +window.scrollBy(0, window.innerHeight); +</pre> + +<p>Para hacer scroll hacia arriba:</p> + +<pre>window.scrollBy(0, -window.innerHeight);</pre> + +<p>Utilizando <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">opciones</span></font>:</p> + +<pre>window.scrollBy({ + top: 100, + left: 100, + behaviour: 'smooth' +})</pre> + +<h2 id="Notes" name="Notes">Notas</h2> + +<p><a href="/en-US/docs/DOM/Window.scrollBy">window.scrollBy</a> desplaza el documento una cantidad determinada, mientras que <a href="/en-US/docs/DOM/Window.scroll">window.scroll</a> lo hace hacia una posición absoluta en el documento. Vea también <a href="/en-US/docs/DOM/Window.scrollByLines">window.scrollByLines</a>, <a href="/en-US/docs/DOM/Window.scrollByPages">window.scrollByPages</a></p> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentarios</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('CSSOM View', '#dom-window-scrollby', 'window.scrollBy()') }}</td> + <td>{{ Spec2('CSSOM View') }}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> diff --git a/files/es/web/api/window/scrollto/index.html b/files/es/web/api/window/scrollto/index.html new file mode 100644 index 0000000000..ec20698673 --- /dev/null +++ b/files/es/web/api/window/scrollto/index.html @@ -0,0 +1,50 @@ +--- +title: Window.scrollTo() +slug: Web/API/Window/scrollTo +translation_of: Web/API/Window/scrollTo +--- +<div>{{ APIRef }}</div> + +<h2 id="Summary" name="Summary">Resumen</h2> + +<p>Desplaza el visor a un conjunto específico de coodenadas en el documento.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox"><code>window.scrollTo(<em>x-coord</em>, <em>y-coord</em>)</code></pre> + +<h3 id="Parameters" name="Parameters">Parámetros</h3> + +<ul> + <li><code>x-coord</code> es el pixel en el eje horizontal del documento que debe terminar posicionado en el extremo superior izquierdo.</li> + <li><code>y-coord</code> es el pixel en el eje vertical del documento que debe terminar posicionado en el extremo superior izquierdo.</li> +</ul> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre class="brush:js">window.scrollTo( 0, 1000 );</pre> + +<h2 id="Notes" name="Notes">Notas</h2> + +<p>Esta función es en efecto la misma que <a href="/en-US/docs/DOM/Window.scroll">window.scroll</a>. Para desplazamiento relativo, ver <a href="/en-US/docs/DOM/Window.scrollBy">window.scrollBy</a>, <a href="/en-US/docs/DOM/Window.scrollByLines">window.scrollByLines</a>, y <a href="/en-US/docs/DOM/Window.scrollByPages">window.scrollByPages</a>.</p> + +<p>Para desplazar el visor dentro de elementos, ver <a href="/en-US/docs/Web/API/Element/scrollTop">Element.scrollTop </a>and <a href="/en-US/docs/Web/API/Element/scrollLeft">Element.scrollLeft</a>.</p> + +<h2 id="Specifications" name="Specifications">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('CSSOM View', '#dom-window-scroll', 'window.scroll()') }}</td> + <td>{{ Spec2('CSSOM View') }}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> diff --git a/files/es/web/api/window/scrollx/index.html b/files/es/web/api/window/scrollx/index.html new file mode 100644 index 0000000000..71b0df1338 --- /dev/null +++ b/files/es/web/api/window/scrollx/index.html @@ -0,0 +1,124 @@ +--- +title: Window.scrollX +slug: Web/API/Window/scrollX +translation_of: Web/API/Window/scrollX +--- +<div>{{ APIRef() }}</div> + +<h2 id="Summary" name="Summary">Resumen</h2> + +<p>Retorna el número de pixels que el documento ha sido desplazado horizontalmente.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox">var x = window.scrollX;</pre> + +<h3 id="Parameters" name="Parameters">Parámetros</h3> + +<ul> + <li><font face="Courier New, Andale Mono, monospace"><span style="line-height: normal;">x</span></font> será el número de pixels que el documento está desplazado actualmente desde la izquierda.</li> +</ul> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre class="brush:js">// Si scrollX es mayor que 400, reinicia la posición de desplazxamiento al inicio supuerior-izquierdo del documento. +if (window.scrollX > 400) { + window.scroll(0,0); +}</pre> + +<h2 id="Notes" name="Notes">Notas</h2> + +<p><span style="line-height: 1.572;">La propiedad </span><code style="font-size: 14px;">pageXOffset</code><span style="line-height: 1.572;"> es un alias de la propiedad </span><code style="font-size: 14px;">scrollX</code><span style="line-height: 1.572;">:</span></p> + +<pre>window.pageXOffset == window.scrollX; // siempre true</pre> + +<p>Para compatibilidad cruzada entre navegadores, use <code>window.pageXOffset</code> en lugar de <code>window.scrollX</code>. <strong>Adicionalmente</strong>, versiones más antiguas de Internet Explorer (< 9) no soportan ninguna de las dos propiedades y deben ser sorteadas examinando otras propiedade no estandar. Un ejemplo totalmente compatible:</p> + +<pre class="brush:js">var x = (window.pageXOffset !== undefined) + ? window.pageXOffset + : (document.documentElement || document.body.parentNode || document.body).scrollLeft; + +var y = (window.pageYOffset !== undefined) + ? window.pageYOffset + : (document.documentElement || document.body.parentNode || document.body).scrollTop;</pre> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Observaciones</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('CSSOM View', '#dom-window-scrollx', 'window.scrollX') }}</td> + <td>{{ Spec2('CSSOM View') }}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Prestación</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>9.0</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile" style="line-height: 19.0909080505371px;"> +<table class="compat-table"> + <tbody> + <tr> + <th>Prestación</th> + <th>Android</th> + <th>Android Webview</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also" name="See_also">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/DOM/window.scrollY" title="window.scrollX | Document Object Model (DOM) | MDN">window.scrollY</a></li> +</ul> diff --git a/files/es/web/api/window/scrolly/index.html b/files/es/web/api/window/scrolly/index.html new file mode 100644 index 0000000000..81b8275746 --- /dev/null +++ b/files/es/web/api/window/scrolly/index.html @@ -0,0 +1,61 @@ +--- +title: Window.scrollY +slug: Web/API/Window/scrollY +tags: + - API + - Propiedad + - Rerencia + - Scroll Vertical +translation_of: Web/API/Window/scrollY +--- +<div>{{APIRef}}</div> + +<h2 id="Summary" name="Summary">Sumario</h2> + +<p>Retorna el número de píxeles que han sido desplazados en el documento mediante el scroll vertical.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox">var y = window.scrollY;</pre> + +<ul> + <li>y es el número de píxeles que se han desplazado actualmente desde el extremo superior de la página.</li> +</ul> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre class="brush:js">// Asegurate de bajar a la segunda página +if (window.scrollY) { + window.scroll(0, 0); // Restablece la posición de desplazamiento en la parte superior izquierda del documento +} + +window.scrollByPages(1);</pre> + +<h2 id="Notes" name="Notes">Notas</h2> + +<p>Usa esta propiedad para verificar que al documento no se le ha hecho scroll, si estás usando funciones relativas de scroll como {{domxref("window.scrollBy")}}, {{domxref("window.scrollByLines")}}, o {{domxref("window.scrollByPages")}}.</p> + +<p>La propiedad <code>pageYOffset</code> es un alias para la propiedad <code>scrollY</code>:</p> + +<pre>window.pageYOffset == window.scrollY; // Siempre verdadero</pre> + +<p>Para compatibilidad entre navegadores, es recomendable usar window.pageYOffset en vez de window.scrollY. <strong>Adicionalmente</strong>, tener en cuenta que versiones más viejas de Internet Explorer (<9) no soportan del todo la propiedad y debe ser solucionado usando propiedades no estandarizadas . Un ejemplo totalmente compatible entre navegadores:</p> + +<pre class="brush:js">var supportPageOffset = window.pageXOffset !== undefined; +var isCSS1Compat = ((document.compatMode || "") === "CSS1Compat"); + +var x = supportPageOffset ? window.pageXOffset : isCSS1Compat ? document.documentElement.scrollLeft : document.body.scrollLeft; +var y = supportPageOffset ? window.pageYOffset : isCSS1Compat ? document.documentElement.scrollTop : document.body.scrollTop; +</pre> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<ul> + <li>CSSOM View Module: <a href="http://dev.w3.org/csswg/cssom-view/#dom-window-scrolly">window.scrollY</a> (Editor's Draft)</li> +</ul> + +<h2 id="See_also" name="See_also">Ver también</h2> + +<ul> + <li>{{domxref("window.scrollX")}}</li> +</ul> diff --git a/files/es/web/api/window/sessionstorage/index.html b/files/es/web/api/window/sessionstorage/index.html new file mode 100644 index 0000000000..870cb2dbd8 --- /dev/null +++ b/files/es/web/api/window/sessionstorage/index.html @@ -0,0 +1,143 @@ +--- +title: Window.sessionStorage +slug: Web/API/Window/sessionStorage +tags: + - Almacenaje + - Propiedad + - Referencia + - Sesion +translation_of: Web/API/Window/sessionStorage +--- +<p>{{APIRef()}}</p> + +<p>La propiedad <code>sessionStorage</code> permite acceder a un objeto {{domxref("Storage")}} asociado a la sesión actual. La propiedad sessionStorage es similar a <a href="/en-US/docs/Web/API/Window.localStorage"><code>localStorage</code></a>, la única diferencia es que la información almacenada en localStorage no posee tiempo de expiración, por el contrario la información almacenada en sessionStorage es eliminada al finalizar la sesion de la página. La sesión de la página perdura mientras el navegador se encuentra abierto, y se mantiene por sobre las recargas y reaperturas de la página. <strong>Abrir una página en una nueva pestaña o ventana iniciará una nueva sesión</strong>, lo que difiere en la forma en que trabajan las cookies de sesión<strong>.</strong></p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="brush: js">// Almacena la información en sessionStorage +sessionStorage.setItem('key', 'value'); + +// Obtiene la información almacenada desde sessionStorage +var data = sessionStorage.getItem('key');</pre> + +<h3 id="Valor">Valor </h3> + +<p>Un objeto de tipo {{domxref("Storage")}}.</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>El siguiente código accede al objeto {{domxref("Storage")}} del la sesión actual del domino y le añade un elemento utilizando {{domxref("Storage.setItem()")}}.</p> + +<pre class="brush: js">sessionStorage.setItem('myCat', 'Tom');</pre> + +<p>El siguiente ejemplo graba de forma automática el contenido de un campo de texto, y si el navegador es actualizado accidentalmente, restaura el contenido del campo de texto para no perder lo escrito.</p> + +<pre class="brush: js">// Obtiene el campo de texto que vamos a moniterear +var field = document.getElementById("field"); + +// Verificamos si tenemos algún valor auto guardado +// (esto solo ocurrirá si la página es recargada accidentalmente) +if (sessionStorage.getItem("autosave")) { + // Restaura el contenido al campo de texto + field.value = sessionStorage.getItem("autosave"); +} + +// Espera por cambios en el campo de texto +field.addEventListener("change", function() { + // Almacena el resultado en el objeto de almacenamiento de sesión + sessionStorage.setItem("autosave", field.value); +});</pre> + +<p> </p> + +<div class="note"> +<p><strong>Nota</strong>: Por favor diríjase al artículo <a href="/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API">Usando la API de Web Storage</a> para un ejemplo completo.</p> +</div> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('Web Storage', '#the-sessionstorage-attribute', 'sessionStorage')}}</td> + <td>{{Spec2('Web Storage')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>localStorage</td> + <td>4</td> + <td>3.5</td> + <td>8</td> + <td>10.50</td> + <td>4</td> + </tr> + <tr> + <td>sessionStorage</td> + <td>5</td> + <td>2</td> + <td>8</td> + <td>10.50</td> + <td>4</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>2.1</td> + <td>{{ CompatUnknown }}</td> + <td>8</td> + <td>11</td> + <td>iOS 3.2</td> + </tr> + </tbody> +</table> +</div> + +<p>Todos los navegadores tienen distintos niveles de capacidad para localStorage y para sessionStorage. Aquí encontraras un <a class="external" href="http://dev-test.nemikor.com/web-storage/support-test/" title="http://dev-test.nemikor.com/web-storage/support-test/">resumen detallado de todas las capacidades de almacenamiento para diversos navegadores</a>.</p> + +<div class="note"> +<p><strong>Nota: </strong>desde iOS 5.1, Safari Mobile almacena los datos de localStorage en un directorio de cache, el cual esta sujeto a limpezas ocacionales, por orden del sistema operativo, generalmente si el espacio es reducido.</p> +</div> + +<h2 id="Vea_También">Vea También</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API">Usando la API de Web Storage</a></li> + <li><a href="/en-US/docs/Web/API/Window.localStorage">Window.localStorage</a></li> +</ul> diff --git a/files/es/web/api/window/showmodaldialog/index.html b/files/es/web/api/window/showmodaldialog/index.html new file mode 100644 index 0000000000..1e0f24f2a3 --- /dev/null +++ b/files/es/web/api/window/showmodaldialog/index.html @@ -0,0 +1,95 @@ +--- +title: Window.showModalDialog() +slug: Web/API/Window/showModalDialog +translation_of: Web/API/Window/showModalDialog +--- +<div>{{ Fx_minversion_header(3) }} {{ deprecated_header() }}{{APIRef}}</div> + +<p>El método <strong><code>Window.showModalDialog()</code></strong> crea y visualiza una caja de diálogo modal, conteniendo el documento HTML especificado.</p> + +<div class="note"> +<p><strong><em>Esta prestación va a desaparecer. Por favor ajuste sus sitios Web y aplicaciones.</em></strong></p> + +<p>El soporte ha sido eliminado en <a href="http://blog.chromium.org/2014/07/disabling-showmodaldialog.html">Chrome 37</a>. Pero se añadió temporalmente un <a href="http://www.chromium.org/administrators/policy-list-3#EnableDeprecatedWebPlatformFeatures">ajuste de Política Coporativa para rehabilitar showModalDialog</a>. Este método showModalDialog() fue eliminado definitivamente en Chrome 43.</p> + +<p>Mozilla ha anunciado que eliminará el soporte para este método ({{bug(981796)}}). Sin plazo específico, debería ser antes de Firefox 46. Esto quiere decir que la función estará fuera de uso sobre mediados de junio de 2016. Una revisión ESR podría soportarla aun por algunas meses más.</p> +</div> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox"><var>valRetorno</var> = window.showModalDialog(<var>uri</var>[, <var>argumentos</var>][, <var>opciones</var>]); +</pre> + +<p>donde</p> + +<ul> + <li><code>valRetorno</code> es un valor indicando la propiedad returnValue establecida por la ventana del documento especificado por la <code>uri</code>.</li> + <li><code>uri</code> is es la URI del documento a visualizar en la caja de diálogo.</li> + <li><code>argumentos</code> es un parámetro adicional, que contiene valores que deberían ser pasados a la caja de diálogo; estos son puestos a disposición en el la propiedad <code><a href="/en-US/docs/DOM/window.dialogArguments">window.dialogArguments</a></code> del objeto <code><a href="/en-US/docs/DOM/window">window</a></code>.</li> + <li><code>opciones</code> es una cadena adicional que especifica ornamentaciones de ventana para la caja de diálogo, usando uno o más de los siguientes valores separados por punto y coma:</li> +</ul> + +<table class="standard-table"> + <tbody> + <tr> + <th>Sintaxis</th> + <th>Descripción</th> + </tr> + <tr> + <td><code>center: {on | off | yes | no | 1 | 0 }</code></td> + <td>Si el valor de este argumento es <code>on</code>, <code>yes</code>, ó 1, la ventana de diálogo será centrada en el escritorio; en caso contrario será oculta. El valor por defecto es <code>yes</code>.</td> + </tr> + <tr> + <td><code>dialogheight: <em>height</em></code></td> + <td>Especifica la altura de la caja de diálogo; por defecto, el tamaño es especificado en pixels.</td> + </tr> + <tr> + <td><code>dialogleft: <em>left</em></code></td> + <td>Especifica la posición horizontal de la caja de diálogo respecto de la esquina superior izquierda del escritorio.</td> + </tr> + <tr> + <td><code>dialogwidth: <em>width</em></code></td> + <td>Especifica la anchura de la caja de diálogo; por defecto el tamaño es especificado en pixels.</td> + </tr> + <tr> + <td><code>dialogtop: <em>top</em></code></td> + <td>Especifica la posición vertical de la caja de diálogo, respcto de la esquina superior izquierda del escritorio.</td> + </tr> + <tr> + <td><code>resizable: {on | off | yes | no | 1 | 0 }</code></td> + <td>Si el valor de este argumentoes <code>on</code>, <code>yes</code>, ó 1, la ventana de diálogo podrá ser redimensionada por el usuario; en caso controario su tamaño será fijo. El valor por defecto es <code>no</code>.</td> + </tr> + <tr> + <td><code>scroll: {on | off | yes | no | 1 | 0 }</code></td> + <td>Si el valor de este argumento es <code>on</code>, <code>yes</code>, ó 1, la ventana de diálogo tendrá barras de desplazamiento; en caso contrario su tamaño será fijo. El valor por defecto es <code>no</code>.</td> + </tr> + </tbody> +</table> + +<p>{{Note("Firefox no implementa los argumentos <code>dialogHide</code>, <code>edge</code>, <code>status</code>, ó <code>unadorned</code>.")}}</p> + +<h2 id="Compatibility" name="Compatibility">Compatibilidad con navegadores</h2> + +<p>Introducido por Microsoft Internet Explorer 4. Soporte añadido a Firefox en Firefox 3 (desaconsejado en Fx 28), y a Safari en Safari 5.1. Ver <a href="https://bugs.webkit.org/show_bug.cgi?id=151885">WebKit bug 151885</a> para posible futura eliminación de Safari.</p> + +<h2 id="Examples" name="Examples">Ejemplos</h2> + +<p><a href="/samples/domref/showModalDialog.html">Probar <code>showModalDialog()</code></a>.</p> + +<h2 id="Notes" name="Notes">Notas</h2> + +<p><code>showModalDialog()</code> está siendo estandarizado actualmente como parte de HTML5. El tercer argumento (para opciones adicionales) no está presente en la versión HTML5, y es (seguramente) ignorado por Safari and Chrome.</p> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<ul> + <li><a href="https://msdn.microsoft.com/en-us/library/ms536759(VS.85).aspx">MSDN page for <code>showModalDialog</code></a></li> + <li><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#dialogs-implemented-using-separate-documents">Diálogos HTML5 implementados usando documentos separados</a></li> +</ul> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{HTMLElement("dialog")}}, un sustituo para <code>window.showModalDialog()</code>.</li> + <li><a href="https://github.com/niutech/showModalDialog">showModalDialog Polyfill</a> usando un {{HTMLElement("dialog")}} y <a href="/en-US/docs/Web/JavaScript/Reference/Statements/function*">generadores</a></li> +</ul> diff --git a/files/es/web/api/window/sidebar/index.html b/files/es/web/api/window/sidebar/index.html new file mode 100644 index 0000000000..280b5dcce3 --- /dev/null +++ b/files/es/web/api/window/sidebar/index.html @@ -0,0 +1,56 @@ +--- +title: Window.sidebar +slug: Web/API/Window/sidebar +tags: + - DOM + - NeedsTranslation + - Non-standard + - Property + - Reference + - TopicStub + - Window +translation_of: Web/API/Window/sidebar +--- +<div>{{APIRef}} {{Non-standard_header}}</div> + +<p>Returns a sidebar object, which contains several methods for registering add-ons with the browser.</p> + +<h2 id="Notes" name="Notes">Notes</h2> + +<p>The sidebar object returned has the following methods:</p> + +<table class="fullwidth-table"> + <tbody> + <tr> + <th>Method</th> + <th>Description (SeaMonkey)</th> + <th>Description (Firefox)</th> + </tr> + <tr> + <td><code>addPanel(<var>title</var>, <var>contentURL</var>, "")</code></td> + <td>Adds a sidebar panel.</td> + <td rowspan="2">Obsolete since Firefox 23 (only present in SeaMonkey).<br> + End users can use the "load this bookmark in the sidebar" option instead. Also see <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Creating_a_Firefox_sidebar">Creating a Firefox sidebar.</a></td> + </tr> + <tr> + <td><code>addPersistentPanel(<var>title</var>, <var>contentURL</var>, "")</code></td> + <td>Adds a sidebar panel, which is able to work in the background.</td> + </tr> + <tr> + <td><code>AddSearchProvider(<em>descriptionURL)</em></code></td> + <td colspan="2">Installs a search provider (OpenSearch). <a href="/en-US/docs/Web/API/Window/sidebar/Adding_search_engines_from_Web_pages#Installing_OpenSearch_plugins" title="Adding_search_engines_from_web_pages">Adding OpenSearch search engines </a>contains more details. Added in Firefox 2.</td> + </tr> + <tr> + <td><code>addSearchEngine(<var>engineURL</var>, <var>iconURL</var>, <var>suggestedTitle</var>, <var>suggestedCategory</var>)</code> {{Obsolete_inline(44)}}</td> + <td colspan="2">Installs a search engine (Sherlock). <a href="/en-US/docs/Web/API/Window/sidebar/Adding_search_engines_from_Web_pages#Installing_Sherlock_plugins" title="Adding_search_engines_from_web_pages">Adding Sherlock search engines </a>contains more details.</td> + </tr> + <tr> + <td><code>IsSearchProviderInstalled(<em>descriptionURL)</em></code></td> + <td colspan="2">Indicates if a specific search provider (OpenSearch) is installed.</td> + </tr> + </tbody> +</table> + +<h2 id="Specification" name="Specification">Specification</h2> + +<p>Mozilla-specific. Not part of any standard.</p> diff --git a/files/es/web/api/window/statusbar/index.html b/files/es/web/api/window/statusbar/index.html new file mode 100644 index 0000000000..bd0b2eaa6c --- /dev/null +++ b/files/es/web/api/window/statusbar/index.html @@ -0,0 +1,72 @@ +--- +title: Window.statusbar +slug: Web/API/Window/statusbar +translation_of: Web/API/Window/statusbar +--- +<div>{{APIRef}}</div> + +<h2 id="Resumen">Resumen</h2> + +<p>Retorna el objeto statusbar, la visibilidad se puede alternar en la ventana.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><var>objRef</var> = window.statusbar +</pre> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>El siguiente ejemplo HTML muestra una forma de utilizar la propiedad visible de los diversos objetos de "bar", y tambien el cambio de privilegios nesesarios para escribir en la propiedad visible para cada una de las ventanas existentes.</p> + +<pre class="brush:html"><!DOCTYPE html> +<html lang="en"> +<head> +<meta charset="UTF-8" /> +<title>Various DOM Tests</title> + +<script> +// cambia el estado de la barra en la ventana existente +netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserWrite"); +window.statusbar.visible=!window.statusbar.visible; +</script> + +</head> +<body> + <p>Various DOM Tests</p> +</body> +</html> +</pre> + +<h2 id="Notas">Notas</h2> + +<p>Al cargar la pagina del ejemplo anterior se muestra el siguiente cuadro de dialogo:<img alt="" src="https://mdn.mozillademos.org/files/550/Modify_any_open_window_dialog.png" style="height: 262px; width: 607px;"></p> + +<p>Para alternar la visibilidad de las barras, debe de firmar sus scripts o abilitar los privilegios apropiados, como en el ejemplo anterior. Tenga en cuenta que cambiar la visibilidad de manera dinamica de las barras de herramientas puede cambiar el tamaño de la ventana de forma dramatica y afectando de manera significativa el rendimiento de su pagina.</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', 'browsers.html#dom-window-statusbar', 'Window.statusbar')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', 'browsers.html#dom-window-statusbar', 'Window.statusbar')}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="See_also" name="See_also">Ver tambien</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Window.locationbar">window.locationbar</a>, <a href="/en-US/docs/Web/API/Window.menubar">window.menubar</a>, <a href="/en-US/docs/Web/API/Window.personalbar">window.personalbar</a>, <a href="/en-US/docs/Web/API/Window.scrollbars">window.scrollbars</a>, <a href="/en-US/docs/Web/API/Window.toolbar">window.toolbar</a></li> +</ul> diff --git a/files/es/web/api/window/url/index.html b/files/es/web/api/window/url/index.html new file mode 100644 index 0000000000..7758a161b9 --- /dev/null +++ b/files/es/web/api/window/url/index.html @@ -0,0 +1,101 @@ +--- +title: Window.URL +slug: Web/API/Window/URL +tags: + - API + - DOM + - Propiedad + - Referencia + - Referência DOM + - WebAPI +translation_of: Web/API/URL +--- +<p>{{ApiRef("Window")}}{{SeeCompatTable}}</p> + +<p>La propiedad <strong><code>Window.URL</code></strong> devuelve un objeto que proporciona métodos estáticos usados para crear y gestionar objetos de URLs. Además puede ser llamado como un constructor para construir objetos {{domxref("URL")}}.</p> + +<p>{{AvailableInWorkers}}</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<p>Llamando a un método estático:</p> + +<pre class="syntaxbox"><code><var>img</var>.src = URL.{{domxref("URL.createObjectURL", "createObjectURL")}}(<var>blob</var>);</code></pre> + +<p>Construyendo un nuevo objeto:</p> + +<pre class="syntaxbox"><code>var <var>url</var> = new {{domxref("URL.URL", "URL")}}("../cats/", "https://www.example.com/dogs/");</code></pre> + +<h2 id="Especificación">Especificación</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('URL', '#dom-url', 'URL')}}</td> + <td>{{Spec2('URL')}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>8.0<sup>[2]</sup></td> + <td>{{CompatGeckoDesktop("2.0")}}<sup>[1]</sup><br> + {{CompatGeckoDesktop("19.0")}}</td> + <td>10.0</td> + <td>15.0<sup>[2]</sup></td> + <td>6.0<sup>[2]</sup><br> + 7.0</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatVersionUnknown}}<sup>[2]</sup></td> + <td>{{CompatGeckoMobile("14.0")}}<sup>[1]</sup><br> + {{CompatGeckoMobile("19.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>15.0<sup>[2]</sup></td> + <td>6.0<sup>[2]</sup></td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Desde Gecko 2 (Firefox 4) hasta Gecko 18 incluidos, Gecko devuelve un objeto con el tipo interno no estandar <code>nsIDOMMozURLProperty</code>. En la práctica, esto no hace ninguna diferencia.</p> + +<p>[2] Implementado bajo el nombre no estandar <code>webkitURL</code>.</p> diff --git a/files/es/web/api/windowbase64/atob/index.html b/files/es/web/api/windowbase64/atob/index.html new file mode 100644 index 0000000000..aa9eeead07 --- /dev/null +++ b/files/es/web/api/windowbase64/atob/index.html @@ -0,0 +1,111 @@ +--- +title: WindowBase64.atob() +slug: Web/API/WindowBase64/atob +translation_of: Web/API/WindowOrWorkerGlobalScope/atob +--- +<p>{{APIRef}}</p> + +<p>La función <strong>WindowBase64.atob() </strong>descodifica una cadena de datos que ha sido codificada utilizando la codificación en base-64. Puedes utilizar el método {{domxref("window.btoa()")}} para codificar y transmitir datos que, de otro modo podrían generar problemas de comunicación. Luego de ser transmitidos se puede usar el método window.atob() para decodificar los datos de nuevo. Por ejemplo, puedes codificar, transmitir y decodificar los caracteres de control como valores ASCII 0 a 31.</p> + +<p>For use with Unicode or UTF-8 strings, see <a href="/en-US/docs/Web/JavaScript/Base64_encoding_and_decoding#The_.22Unicode_Problem.22">this note at Base64 encoding and decoding</a> and <a href="/en-US/docs/Web/API/window.btoa#Unicode_Strings">this note at <code>window.btoa()</code></a>.</p> + +<h2 id="Syntax" name="Syntax">Syntax</h2> + +<pre class="syntaxbox">var decodedData = window.atob(<em>encodedData</em>);</pre> + +<h2 id="Example" name="Example">Example</h2> + +<pre class="brush:js">var encodedData = window.btoa("Hello, world"); // encode a string +var decodedData = window.atob(encodedData); // decode the string</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('HTML WHATWG', '#dom-windowbase64-atob', 'WindowBase64.atob()')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>No change since the latest snapshot, {{SpecName("HTML5.1")}}.</td> + </tr> + <tr> + <td>{{SpecName('HTML5.1', '#dom-windowbase64-atob', 'WindowBase64.atob()')}}</td> + <td>{{Spec2('HTML5.1')}}</td> + <td>Snapshot of {{SpecName("HTML WHATWG")}}. No change.</td> + </tr> + <tr> + <td>{{SpecName("HTML5 W3C", "#dom-windowbase64-atob", "WindowBase64.atob()")}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>Snapshot of {{SpecName("HTML WHATWG")}}. Creation of <code>WindowBase64</code> (properties where on the target before it).</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="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>{{CompatGeckoDesktop(1)}}[1][2]</td> + <td>10</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>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile(1)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] <code>atob()</code> is also available to XPCOM components implemented in JavaScript, even though <code><a href="/en-US/docs/DOM/window">window</a></code> is not the global object in components.</p> + +<p>[2] Starting with <a href="/en-US/Firefox/Releases/27/Site_Compatibility">Firefox 27</a>, this <code>atob()</code> method ignores all space characters in the argument to comply with the latest HTML5 spec. ({{ bug(711180) }})</p> + +<h2 id="See_also" name="See_also">See also</h2> + +<ul> + <li><a href="/Web/API/WindowBase64/Base64_encoding_and_decoding">Base64 encoding and decoding</a></li> + <li><a href="/en-US/docs/data_URIs"><code>data</code> URIs</a></li> + <li>{{domxref("window.btoa()")}}</li> + <li><a href="/en-US/docs/Components.utils.importGlobalProperties">Components.utils.importGlobalProperties</a></li> +</ul> diff --git a/files/es/web/api/windowbase64/base64_codificando_y_decodificando/index.html b/files/es/web/api/windowbase64/base64_codificando_y_decodificando/index.html new file mode 100644 index 0000000000..c8747777cd --- /dev/null +++ b/files/es/web/api/windowbase64/base64_codificando_y_decodificando/index.html @@ -0,0 +1,345 @@ +--- +title: Base64 codificando y decodificando +slug: Web/API/WindowBase64/Base64_codificando_y_decodificando +translation_of: Glossary/Base64 +--- +<p><strong>Base64</strong> es un grupo de esquemas de <a href="https://es.wikipedia.org/wiki/Codificaci%C3%B3n_de_binario_a_texto">codificación de binario a texto</a> que representa los datos binarios mediante una cadena ASCII, traduciéndolos en una representación radix-64. El término <em>Base64</em> se origina de un <a href="https://es.wikipedia.org/wiki/Multipurpose_Internet_Mail_Extensions#Content-Transfer-Encoding">sistema de codificación de transmisión de contenido MIME</a> específico.</p> + +<p>Los esquemas de codificación Base64 son comúnmente usados cuando se necesita codificar datos binarios para que sean almacenados y transferidos sobre un medio diseñado para tratar con datos textuales. Esto es para asegurar que los datos se mantienen intactos y sin modificaciones durante la transmisión. Base64 es comúnmente usado en muchas aplicaciones, incluyendo la escritura de emails vía <a href="https://es.wikipedia.org/wiki/Multipurpose_Internet_Mail_Extensions">MIME</a> y el almacenamiento de datos complejos en <a href="/es/docs/XML">XML</a>.</p> + +<p>En JavaScript hay dos funciones para decodificar y codificar cadenas base64, respectivamente:</p> + +<ul> + <li>{{domxref("WindowBase64.atob","atob()")}}</li> + <li>{{domxref("WindowBase64.btoa","btoa()")}}</li> +</ul> + +<p>La función <code>atob()</code> decodifica una cadena de datos que ha sido codificada usando la codificación en base 64. Por el contrario, la función <code>btoa()</code> crea una cadena ASCII codificada en base 64 a partir de una "cadena" de datos binarios.</p> + +<p>Ambas funciones trabajan sobre cadenas de texto. Si desea trabajar con <a href="/es/docs/Web/JavaScript/Referencia/Objetos_globales/ArrayBuffer">ArrayBuffers</a>, lea <a href="/es/docs/Web/API/WindowBase64/Base64_codificando_y_decodificando$edit#Solution_.232_.E2.80.93_rewriting_atob%28%29_and_btoa%28%29_using_TypedArrays_and_UTF-8">este párrafo</a>.</p> + + + +<table class="topicpage-table"> + <tbody> + <tr> + <td> + <h2 class="Documentation" id="Documentation" name="Documentation">Documentación</h2> + + <dl> + <dt><a href="https://developer.mozilla.org/en-US/docs/data_URIs" title="https://developer.mozilla.org/en-US/docs/data_URIs"><code>data</code> URIs</a></dt> + <dd><small><code>Los URIs de</code> datos, definidos por <a class="external" href="http://tools.ietf.org/html/rfc2397" title="http://tools.ietf.org/html/rfc2397">RFC 2397</a>, permiten a los creadores de contenido introducir pequeños ficheros en línea en documentos.</small></dd> + <dt><a href="https://es.wikipedia.org/wiki/Base64" title="https://en.wikipedia.org/wiki/Base64">Base64</a></dt> + <dd><small>Artículo en Wikipedia sobre el sistema de codificación Base64.</small></dd> + <dt>{{domxref("WindowBase64.atob","atob()")}}</dt> + <dd><small>Decodifica una cadena de datos que ha sido codificada utilizando base-64.</small></dd> + <dt>{{domxref("WindowBase64.btoa","btoa()")}}</dt> + <dd><small>Crea una cadena ASCII codificada en base 64 a partir de una "cadena" de datos binarios.</small></dd> + <dt><a href="#The_.22Unicode_Problem.22">The "Unicode Problem"</a></dt> + <dd><small>En la mayoría de navegadores, llamar a <code>btoa()</code> con una cadena Unicode causará una excepción <code>Character Out Of Range</code>. Este párrafo muestra algunas soluciones.</small></dd> + <dt><a href="/en-US/docs/URIScheme" title="/en-US/docs/URIScheme">URIScheme</a></dt> + <dd><small>Lista de esquemas URI soportados por Mozilla.</small></dd> + <dt><a href="/en-US/docs/Web/JavaScript/Typed_arrays/StringView" title="/en-US/docs/Web/JavaScript/Typed_arrays/StringView"><code>StringView</code></a></dt> + <dd>En este artículo está publicada una librería hecha por nosotros con los siguientes objetivos:</dd> + <dd> + <ul> + <li>crear una interfaz al estilo de <a class="external" href="http://en.wikipedia.org/wiki/C_%28programming_language%29" title="http://en.wikipedia.org/wiki/C_%28programming_language%29">C</a> para cadenas (es decir, arrays de códigos de caracteres —<a href="/en-US/docs/Web/JavaScript/Typed_arrays/ArrayBufferView" title="/en-US/docs/Web/JavaScript/Typed_arrays/ArrayBufferView"> <code>ArrayBufferView</code></a> en JavaScript) basada en la interfaz <a href="/en-US/docs/Web/JavaScript/Typed_arrays/ArrayBuffer" title="/en-US/docs/Web/JavaScript/Typed_arrays/ArrayBuffer"><code>ArrayBuffer</code></a> de JavaScript.</li> + <li>crear una colección de métodos para los que los objetos parecidos a cadenas (de ahora en adelante, <code>stringView</code>s) funcionen estrictamente en arrays de números más que en cadenas JavaScript inmutables.</li> + <li>trabajar con otras codificaciones Unicode diferentes de las <a href="/en-US/docs/Web/API/DOMString" title="/en-US/docs/Web/API/DOMString"><code>DOMString</code></a>s UTF-16 por defecto de JavaScript.</li> + </ul> + </dd> + </dl> + + <p><span class="alllinks"><a href="/en-US/docs/tag/Base64">Ver todo...</a></span></p> + </td> + <td> + <h2 class="Tools" id="Tools" name="Tools">Herramientas</h2> + + <ul> + <li><a href="#Solution_.232_.E2.80.93_rewriting_atob()_and_btoa()_using_TypedArrays_and_UTF-8">Reescribir atob() y btoa() usando TypedArrays y UTF-8</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Typed_arrays/StringView" title="/en-US/docs/Web/JavaScript/Typed_arrays/StringView"><code>StringView</code>, una representación parecida a C de cadenas basadas en arrays tipados</a><span class="alllinks"><a href="/en-US/docs/tag/Base64">View All...</a></span></li> + </ul> + + <h2 class="Related_Topics" id="Related_Topics" name="Related_Topics">Temas relacionados</h2> + + <ul> + <li><a href="/en-US/docs/Web/JavaScript/Typed_arrays/ArrayBuffer"><code>ArrayBuffer</code></a></li> + <li><a href="/en-US/docs/Web/JavaScript/Typed_arrays">Vectores o arrays tipados</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Typed_arrays/ArrayBufferView">ArrayBufferView</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Typed_arrays/Uint8Array"><code>Uint8Array</code></a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays/StringView" title="/en-US/docs/Web/JavaScript/Typed_arrays/StringView"><code>StringView</code></a><a href="/en-US/docs/Web/JavaScript/Typed_arrays/StringView" title="/en-US/docs/Web/JavaScript/Typed_arrays/StringView">, una representación parecida a C de cadenas basadas en arrays tipados</a></li> + <li><a href="/en-US/docs/Web/API/DOMString" title="/en-US/docs/Web/API/DOMString"><code>DOMString</code></a></li> + <li><a href="/en-US/docs/URI" title="/en-US/docs/URI"><code>URI</code></a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI" title="/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI"><code>encodeURI()</code></a></li> + </ul> + </td> + </tr> + </tbody> +</table> + + + +<h2 id="El_Problema_Unicode">El "Problema Unicode"</h2> + +<p>Como las <a href="/en-US/docs/Web/API/DOMString" title="/en-US/docs/Web/API/DOMString"><code>DOMString</code></a>s son cadenas codificadas en 16 bits, en la mayoría de navegadores llamar a <code>window.btoa</code> sobre una cadena Unicode resultará en una excepción <code>Character Out Of Range </code>si un carácter excede el rango de los caracteres ASCII de 8 bits. Hay dos posibles métodos para resolver este problema:</p> + +<ul> + <li>el primero es escapar la cadena completa y, entonces, codificarla;</li> + <li>el segundo es convertir la <a href="/en-US/docs/Web/API/DOMString" title="/en-US/docs/Web/API/DOMString"><code>DOMString</code></a> UTF-16 en un array de caracteres UTF-8 y codificarla.</li> +</ul> + +<p>Aquí están los dos posibles métodos:</p> + +<h3 id="Solución_1_–_escapar_la_cadena_antes_de_codificarla">Solución #1 – escapar la cadena antes de codificarla</h3> + +<pre class="brush:js notranslate">function utf8_to_b64( str ) { + return window.btoa(unescape(encodeURIComponent( str ))); +} + +function b64_to_utf8( str ) { + return decodeURIComponent(escape(window.atob( str ))); +} + +// Uso: +utf8_to_b64('✓ à la mode'); // "4pyTIMOgIGxhIG1vZGU=" +b64_to_utf8('4pyTIMOgIGxhIG1vZGU='); // "✓ à la mode"</pre> + +<p>Esta solución ha sido propuesta por <a href="http://ecmanaut.blogspot.com/2006/07/encoding-decoding-utf8-in-javascript.html">Johan Sundström</a>.</p> + +<p>Otra posible solución sin utilizar las funciones 'unscape' y 'escape', ya obsoletas.</p> + +<pre class="brush:js notranslate">function b64EncodeUnicode(str) { + return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) { + return String.fromCharCode('0x' + p1); + })); +} + b64EncodeUnicode('✓ à la mode'); // "4pyTIMOgIGxhIG1vZGU=" +</pre> + +<h3 id="Solución_2_–_reescribir_atob_y_btoa_usando_TypedArrays_y_UTF-8">Solución #2 – reescribir <code>atob()</code> y <code>btoa()</code> usando <code>TypedArray</code>s y UTF-8</h3> + +<div class="note"><strong>Nota:</strong> El siguiente código también es útil para obtener un <a href="/en-US/docs/Web/JavaScript/Typed_arrays/ArrayBuffer">ArrayBuffer</a> a partir de una cadena <em>Base64</em> y/o viceversa (<a href="#Appendix.3A_Decode_a_Base64_string_to_Uint8Array_or_ArrayBuffer" title="#Appendix.3A_Decode_a_Base64_string_to_Uint8Array_or_ArrayBuffer">véase abajo</a>). <strong>Para una librería completa de arrays tipados, vea <a href="/en-US/docs/Web/JavaScript/Typed_arrays/StringView" title="/en-US/docs/Web/JavaScript/Typed_arrays/StringView">este artículo</a></strong>.</div> + +<pre class="brush: js notranslate">"use strict"; + +/*\ +|*| +|*| Base64 / binary data / UTF-8 strings utilities +|*| +|*| https://developer.mozilla.org/en-US/docs/Web/JavaScript/Base64_encoding_and_decoding +|*| +\*/ + +/* Decodificación de cadena base64 en array de bytes */ + +function b64ToUint6 (nChr) { + + return nChr > 64 && nChr < 91 ? + nChr - 65 + : nChr > 96 && nChr < 123 ? + nChr - 71 + : nChr > 47 && nChr < 58 ? + nChr + 4 + : nChr === 43 ? + 62 + : nChr === 47 ? + 63 + : + 0; + +} + +function base64DecToArr (sBase64, nBlocksSize) { + + var + sB64Enc = sBase64.replace(/[^A-Za-z0-9\+\/]/g, ""), nInLen = sB64Enc.length, + nOutLen = nBlocksSize ? Math.ceil((nInLen * 3 + 1 >> 2) / nBlocksSize) * nBlocksSize : nInLen * 3 + 1 >> 2, taBytes = new Uint8Array(nOutLen); + + for (var nMod3, nMod4, nUint24 = 0, nOutIdx = 0, nInIdx = 0; nInIdx < nInLen; nInIdx++) { + nMod4 = nInIdx & 3; + nUint24 |= b64ToUint6(sB64Enc.charCodeAt(nInIdx)) << 18 - 6 * nMod4; + if (nMod4 === 3 || nInLen - nInIdx === 1) { + for (nMod3 = 0; nMod3 < 3 && nOutIdx < nOutLen; nMod3++, nOutIdx++) { + taBytes[nOutIdx] = nUint24 >>> (16 >>> nMod3 & 24) & 255; + } + nUint24 = 0; + + } + } + + return taBytes; +} + +/* Codificación de array en una cadena Base64 */ + +function uint6ToB64 (nUint6) { + + return nUint6 < 26 ? + nUint6 + 65 + : nUint6 < 52 ? + nUint6 + 71 + : nUint6 < 62 ? + nUint6 - 4 + : nUint6 === 62 ? + 43 + : nUint6 === 63 ? + 47 + : + 65; + +} + +function base64EncArr (aBytes) { + + var nMod3 = 2, sB64Enc = ""; + + for (var nLen = aBytes.length, nUint24 = 0, nIdx = 0; nIdx < nLen; nIdx++) { + nMod3 = nIdx % 3; + if (nIdx > 0 && (nIdx * 4 / 3) % 76 === 0) { sB64Enc += "\r\n"; } + nUint24 |= aBytes[nIdx] << (16 >>> nMod3 & 24); + if (nMod3 === 2 || aBytes.length - nIdx === 1) { + sB64Enc += String.fromCharCode(uint6ToB64(nUint24 >>> 18 & 63), uint6ToB64(nUint24 >>> 12 & 63), uint6ToB64(nUint24 >>> 6 & 63), uint6ToB64(nUint24 & 63)); + nUint24 = 0; + } + } + + return sB64Enc.substr(0, sB64Enc.length - 2 + nMod3) + (nMod3 === 2 ? '' : nMod3 === 1 ? '=' : '=='); + +} + +/* De array UTF-8 a DOMString y viceversa */ + +function UTF8ArrToStr (aBytes) { + + var sView = ""; + + for (var nPart, nLen = aBytes.length, nIdx = 0; nIdx < nLen; nIdx++) { + nPart = aBytes[nIdx]; + sView += String.fromCharCode( + nPart > 251 && nPart < 254 && nIdx + 5 < nLen ? /* six bytes */ + /* (nPart - 252 << 30) may be not so safe in ECMAScript! So...: */ + (nPart - 252) * 1073741824 + (aBytes[++nIdx] - 128 << 24) + (aBytes[++nIdx] - 128 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128 + : nPart > 247 && nPart < 252 && nIdx + 4 < nLen ? /* five bytes */ + (nPart - 248 << 24) + (aBytes[++nIdx] - 128 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128 + : nPart > 239 && nPart < 248 && nIdx + 3 < nLen ? /* four bytes */ + (nPart - 240 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128 + : nPart > 223 && nPart < 240 && nIdx + 2 < nLen ? /* three bytes */ + (nPart - 224 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128 + : nPart > 191 && nPart < 224 && nIdx + 1 < nLen ? /* two bytes */ + (nPart - 192 << 6) + aBytes[++nIdx] - 128 + : /* nPart < 127 ? */ /* one byte */ + nPart + ); + } + + return sView; + +} + +function strToUTF8Arr (sDOMStr) { + + var aBytes, nChr, nStrLen = sDOMStr.length, nArrLen = 0; + + /* mapeando... */ + + for (var nMapIdx = 0; nMapIdx < nStrLen; nMapIdx++) { + nChr = sDOMStr.charCodeAt(nMapIdx); + nArrLen += nChr < 0x80 ? 1 : nChr < 0x800 ? 2 : nChr < 0x10000 ? 3 : nChr < 0x200000 ? 4 : nChr < 0x4000000 ? 5 : 6; + } + + aBytes = new Uint8Array(nArrLen); + + /* transcripción... */ + + for (var nIdx = 0, nChrIdx = 0; nIdx < nArrLen; nChrIdx++) { + nChr = sDOMStr.charCodeAt(nChrIdx); + if (nChr < 128) { + /* un byte */ + aBytes[nIdx++] = nChr; + } else if (nChr < 0x800) { + /* dos bytes */ + aBytes[nIdx++] = 192 + (nChr >>> 6); + aBytes[nIdx++] = 128 + (nChr & 63); + } else if (nChr < 0x10000) { + /* tres bytes */ + aBytes[nIdx++] = 224 + (nChr >>> 12); + aBytes[nIdx++] = 128 + (nChr >>> 6 & 63); + aBytes[nIdx++] = 128 + (nChr & 63); + } else if (nChr < 0x200000) { + /* cuatro bytes */ + aBytes[nIdx++] = 240 + (nChr >>> 18); + aBytes[nIdx++] = 128 + (nChr >>> 12 & 63); + aBytes[nIdx++] = 128 + (nChr >>> 6 & 63); + aBytes[nIdx++] = 128 + (nChr & 63); + } else if (nChr < 0x4000000) { + /* cinco bytes */ + aBytes[nIdx++] = 248 + (nChr >>> 24); + aBytes[nIdx++] = 128 + (nChr >>> 18 & 63); + aBytes[nIdx++] = 128 + (nChr >>> 12 & 63); + aBytes[nIdx++] = 128 + (nChr >>> 6 & 63); + aBytes[nIdx++] = 128 + (nChr & 63); + } else /* if (nChr <= 0x7fffffff) */ { + /* seis bytes */ + aBytes[nIdx++] = 252 + (nChr >>> 30); + aBytes[nIdx++] = 128 + (nChr >>> 24 & 63); + aBytes[nIdx++] = 128 + (nChr >>> 18 & 63); + aBytes[nIdx++] = 128 + (nChr >>> 12 & 63); + aBytes[nIdx++] = 128 + (nChr >>> 6 & 63); + aBytes[nIdx++] = 128 + (nChr & 63); + } + } + + return aBytes; + +} +</pre> + +<h4 id="Tests">Tests</h4> + +<pre class="brush: js notranslate">/* Tests */ + +var sMyInput = "Base 64 \u2014 Mozilla Developer Network"; + +var aMyUTF8Input = strToUTF8Arr(sMyInput); + +var sMyBase64 = base64EncArr(aMyUTF8Input); + +alert(sMyBase64); + +var aMyUTF8Output = base64DecToArr(sMyBase64); + +var sMyOutput = UTF8ArrToStr(aMyUTF8Output); + +alert(sMyOutput);</pre> + +<h4 id="Apéndice_Decodificar_una_cadena_Base64_en_Uint8Array_o_ArrayBuffer">Apéndice: Decodificar una cadena <em>Base64</em> en <a href="/en-US/docs/Web/JavaScript/Typed_arrays/Uint8Array">Uint8Array</a> o <a href="/en-US/docs/Web/JavaScript/Typed_arrays/ArrayBuffer">ArrayBuffer</a></h4> + +<p>Estas funciones nos permiten crear también <a href="/en-US/docs/Web/JavaScript/Typed_arrays/Uint8Array">uint8Arrays</a> o <a href="/en-US/docs/Web/JavaScript/Typed_arrays/ArrayBuffer">arrayBuffers</a> a partir de cadenas codificadas en base 64:</p> + +<pre class="brush: js notranslate">var myArray = base64DecToArr("QmFzZSA2NCDigJQgTW96aWxsYSBEZXZlbG9wZXIgTmV0d29yaw=="); // "Base 64 \u2014 Mozilla Developer Network" + +var myBuffer = base64DecToArr("QmFzZSA2NCDigJQgTW96aWxsYSBEZXZlbG9wZXIgTmV0d29yaw==").buffer; // "Base 64 \u2014 Mozilla Developer Network" + +alert(myBuffer.byteLength);</pre> + +<div class="note"><strong>Nota:</strong> La función <code>base64DecToArr(sBase64[, <em>nBlocksSize</em>])</code> devuelve un <a href="/en-US/docs/Web/JavaScript/Typed_arrays/Uint8Array"><code>uint8Array</code></a> de bytes. Si tu objetivo es construir un búfer de datos crudos de 16, 32 o 64 bits, usa el argumento <code>nBlocksSize</code>, que es el número de bytes de los que la propiedad <code>uint8Array.buffer.bytesLength</code> debe devolver un múltiplo (1 u omitido para ASCII, <a href="/en-US/docs/Web/API/DOMString/Binary">cadenas binarias</a> o cadenas UTF-8 codificacas, 2 para cadenas UTF-16, 4 para cadenas UTF-32).</div> + +<p>Para una librería más completa, véase <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays/StringView" title="/en-US/docs/Web/JavaScript/Typed_arrays/StringView"><code>StringView</code></a><a href="/en-US/docs/Web/JavaScript/Typed_arrays/StringView" title="/en-US/docs/Web/JavaScript/Typed_arrays/StringView">, una representación parecida a C de cadenas basadas en arrays tipados</a>.</p> + +<h2 id="Véase_también">Véase también</h2> + +<ul> + <li>{{domxref("WindowBase64.atob","atob()")}}</li> + <li>{{domxref("WindowBase64.btoa","btoa()")}}</li> + <li><a href="/en-US/docs/data_URIs" title="/en-US/docs/data_URIs"><code>data</code> URIs</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Typed_arrays/ArrayBuffer">ArrayBuffer</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Typed_arrays">TypedArrays</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Typed_arrays/ArrayBufferView">ArrayBufferView</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Typed_arrays/Uint8Array">Uint8Array</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays/StringView" title="/en-US/docs/Web/JavaScript/Typed_arrays/StringView"><code>StringView</code> – a C-like representation of strings based on typed arrays</a></li> + <li><a href="/en-US/docs/Web/API/DOMString" title="/en-US/docs/Web/API/DOMString">DOMString</a></li> + <li><a href="/en-US/docs/URI" title="/en-US/docs/URI"><code>URI</code></a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI" title="/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI"><code>encodeURI()</code></a></li> + <li><a href="/en-US/docs/XPCOM_Interface_Reference/nsIURIFixup" title="/en-US/docs/XPCOM_Interface_Reference/nsIURIFixup"><code>nsIURIFixup()</code></a></li> + <li><a href="https://en.wikipedia.org/wiki/Base64" title="https://en.wikipedia.org/wiki/Base64"><code>Base64 on Wikipedia</code></a></li> +</ul> diff --git a/files/es/web/api/windowbase64/index.html b/files/es/web/api/windowbase64/index.html new file mode 100644 index 0000000000..bdce1f982f --- /dev/null +++ b/files/es/web/api/windowbase64/index.html @@ -0,0 +1,108 @@ +--- +title: WindowBase64 +slug: Web/API/WindowBase64 +tags: + - API + - HTML-DOM + - Helper + - NeedsTranslation + - TopicStub + - WindowBase64 +translation_of: Web/API/WindowOrWorkerGlobalScope +--- +<p>{{APIRef}}</p> +<p>The <code><strong>WindowBase64</strong></code> helper contains utility methods to convert data to and from base64, a binary-to-text encoding scheme. For example it is used in <a href="/en-US/docs/data_URIs">data URIs</a>.</p> +<p>There is no object of this type, though the context object, either the {{domxref("Window")}} for regular browsing scope, or the {{domxref("WorkerGlobalScope")}} for workers, implements it.</p> +<h2 id="Properties">Properties</h2> +<p><em>This helper neither defines nor inherits any properties.</em></p> +<h2 id="Methods">Methods</h2> +<p><em>This helper does not inherit any methods.</em></p> +<dl> + <dt> + {{domxref("WindowBase64.atob()")}}</dt> + <dd> + Decodes a string of data which has been encoded using base-64 encoding.</dd> + <dt> + {{domxref("WindowBase64.btoa()")}}</dt> + <dd> + Creates a base-64 encoded ASCII string from a string of binary data.</dd> +</dl> +<h2 id="Specifications">Specifications</h2> +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('HTML WHATWG', '#windowbase64', 'WindowBase64')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>No change since the latest snapshot, {{SpecName("HTML5.1")}}.</td> + </tr> + <tr> + <td>{{SpecName('HTML5.1', '#windowbase64', 'WindowBase64')}}</td> + <td>{{Spec2('HTML5.1')}}</td> + <td>Snapshot of {{SpecName("HTML WHATWG")}}. No change.</td> + </tr> + <tr> + <td>{{SpecName("HTML5 W3C", "#windowbase64", "WindowBase64")}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>Snapshot of {{SpecName("HTML WHATWG")}}. Creation of <code>WindowBase64</code> (properties where on the target before it).</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>Firefox (Gecko)</th> + <th>Chrome</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatGeckoDesktop(1)}} [1]</td> + <td>{{CompatVersionUnknown}}</td> + <td>10.0</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>Firefox Mobile (Gecko)</th> + <th>Android</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatGeckoMobile(1)}}</td> + <td rowspan="1">{{CompatVersionUnknown}}</td> + <td rowspan="1">{{CompatVersionUnknown}}</td> + <td rowspan="1">{{CompatVersionUnknown}}</td> + <td rowspan="1">{{CompatVersionUnknown}}</td> + </tr> + </tbody> + </table> +</div> +<p>[1] <code>atob()</code> is also available to XPCOM components implemented in JavaScript, even though {{domxref("Window")}} is not the global object in components.</p> +<h2 id="See_also">See also</h2> +<ul> + <li><a href="/Web/API/WindowBase64/Base64_encoding_and_decoding">Base64 encoding and decoding</a></li> + <li>{{domxref("Window")}}, {{domxref("WorkerGlobalScope")}}, {{domxref("DedicatedWorkerGlobalScope")}}, {{domxref("SharedWorkerGlobalScope")}}, and {{domxref("ServiceWorkerGlobalScope")}}</li> +</ul> diff --git a/files/es/web/api/windoweventhandlers/index.html b/files/es/web/api/windoweventhandlers/index.html new file mode 100644 index 0000000000..9a1ab057e9 --- /dev/null +++ b/files/es/web/api/windoweventhandlers/index.html @@ -0,0 +1,184 @@ +--- +title: WindowEventHandlers +slug: Web/API/WindowEventHandlers +tags: + - API +translation_of: Web/API/WindowEventHandlers +--- +<div>{{APIRef("HTML DOM")}}</div> + +<p><strong><code>WindowEventHandlers</code></strong> describes the event handlers common to several interfaces like {{domxref("Window")}}, or {{domxref("HTMLBodyElement")}} and {{domxref("HTMLFrameSetElement")}}. Each of these interfaces can implement more event handlers.</p> + +<p><code>WindowEventHandlers</code> is a not an interface and no object of this type can be created.</p> + +<h2 id="Properties">Properties</h2> + +<p><em>The events properties, of the form <code>onXYZ</code>, are defined on the {{domxref("WindowEventHandlers")}}, and implemented by {{domxref("Window")}}, and {{domxref("WorkerGlobalScope")}} for Web Workers.</em></p> + +<dl> + <dt>{{domxref("WindowEventHandlers.onafterprint")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("afterprint")}} event is raised.</dd> + <dt>{{domxref("WindowEventHandlers.onbeforeprint")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("beforeprint")}} event is raised.</dd> + <dt>{{domxref("WindowEventHandlers.onbeforeunload")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("beforeunload")}} event is raised.</dd> + <dt>{{domxref("WindowEventHandlers.onhashchange")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("hashchange")}} event is raised.</dd> + <dt>{{domxref("WindowEventHandlers.onlanguagechange")}} {{experimental_inline}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("languagechange")}} event is raised.</dd> + <dt>{{domxref("WindowEventHandlers.onmessage")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("message")}} event is raised.</dd> + <dt>{{domxref("WindowEventHandlers.onoffline")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("offline")}} event is raised.</dd> + <dt>{{domxref("WindowEventHandlers.ononline")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("online")}} event is raised.</dd> + <dt>{{domxref("WindowEventHandlers.onpagehide")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pagehide")}} event is raised.</dd> + <dt>{{domxref("WindowEventHandlers.onpageshow")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pageshow")}} event is raised.</dd> + <dt>{{domxref("WindowEventHandlers.onpopstate")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("popstate")}} event is raised.</dd> + <dt>{{domxref("WindowEventHandlers.onresize")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("resize")}} event is raised.</dd> + <dt>{{domxref("WindowEventHandlers.onstorage")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("storage")}} event is raised.</dd> + <dt>{{domxref("WindowEventHandlers.onunload")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("unload")}} event is raised.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<p><em>This interface defines no method.</em></p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('HTML WHATWG', '#windoweventhandlers', 'GlobalEventHandlers')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>No change since the latest snapshot, {{SpecName("HTML5.1")}}.</td> + </tr> + <tr> + <td>{{SpecName('HTML5.1', '#windoweventhandlers', 'GlobalEventHandlers')}}</td> + <td>{{Spec2('HTML5.1')}}</td> + <td>Snapshot of {{SpecName("HTML WHATWG")}}. Added <code>onlanguage</code> since the {{SpecName("HTML 5")}} snapshot.</td> + </tr> + <tr> + <td>{{SpecName("HTML5 W3C", "#windoweventhandlers", "GlobalEventHandlers")}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>Snapshot of {{SpecName("HTML WHATWG")}}. Creation of <code>WindowEventHandlers</code> (properties where on the target before it).</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>Firefox (Gecko)</th> + <th>Chrome</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>onhashchange</code></td> + <td>{{CompatGeckoDesktop(1.9.2)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>onlanguage</code>{{experimental_inline}}</td> + <td>{{CompatGeckoDesktop(32)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>onstorage</code></td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Firefox Mobile (Gecko)</th> + <th>Android</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td rowspan="1">{{CompatUnknown}}</td> + <td rowspan="1">{{CompatUnknown}}</td> + <td rowspan="1">{{CompatUnknown}}</td> + <td rowspan="1">{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>onhashchange</code></td> + <td>{{CompatGeckoMobile(1.9.2)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>onlanguage</code>{{experimental_inline}}</td> + <td>{{CompatGeckoMobile(32)}}</td> + <td rowspan="1">{{CompatUnknown}}</td> + <td rowspan="1">{{CompatUnknown}}</td> + <td rowspan="1">{{CompatUnknown}}</td> + <td rowspan="1">{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>onstorage</code></td> + <td>{{CompatNo}}</td> + <td rowspan="1">{{CompatUnknown}}</td> + <td rowspan="1">{{CompatUnknown}}</td> + <td rowspan="1">{{CompatUnknown}}</td> + <td rowspan="1">{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{domxref("Window")}} and {{domxref("WorkerGlobalScope")}}</li> +</ul> diff --git a/files/es/web/api/windoweventhandlers/onbeforeunload/index.html b/files/es/web/api/windoweventhandlers/onbeforeunload/index.html new file mode 100644 index 0000000000..308096a56a --- /dev/null +++ b/files/es/web/api/windoweventhandlers/onbeforeunload/index.html @@ -0,0 +1,81 @@ +--- +title: Window.onbeforeunload +slug: Web/API/WindowEventHandlers/onbeforeunload +translation_of: Web/API/WindowEventHandlers/onbeforeunload +--- +<div> + {{ApiRef}}</div> +<h2 id="Summary" name="Summary">Introducción</h2> +<p>Evento que se ejecuta antes de abandonar la página, justo antes de que se ejecute {{domxref("window.onunload","window.onunload")}}. El documento aún está visible y {{domxref("event.preventDefault","el evento aún se puede cancelar")}}.</p> +<h2 id="Syntax" name="Syntax">Sintaxis</h2> +<pre class="syntaxbox">window.onbeforeunload = <var>funcRef</var></pre> +<ul> + <li><code>funcRef</code> es una referencia a una función o una función anónima.</li> + <li>La función debe asignar una cadena de texto como propiedad <code>returnValue</code> del objeto Event y devolver la misma cadena.</li> + <li>Nota: en Firefox 4 y superiores la cadena de texto no se muestra al usuario (ver {{bug("588292")}}).</li> +</ul> +<h2 id="Example" name="Example">Ejemplo</h2> +<pre class="brush:js">window.onbeforeunload = function(e) { + return 'Texto de aviso'; +}; +</pre> +<h2 id="Notas">Notas</h2> +<p><span id="result_box" lang="es"><span class="hps">Cuando</span> <span class="hps">este evento</span> <span class="hps">devuelve un</span> <span class="hps">valor que no sea</span> <span class="hps">nulo,</span> <span class="hps">se solicita al usuario</span> <span class="hps">que confirme que quiere abandonar la página</span><span class="hps">.</span> <span class="hps">En la mayoría de</span> <span class="hps">los navegadores</span><span>, el valor</span> <span class="hps">de retorno del evento</span> <span class="hps">se muestra en</span> <span class="hps">este cuadro de diálogo</span><span>.</span></span></p> +<p>Desde el 25 de mayo de 2011, los estados de la <a href="http://www.w3.org/TR/html5-diff/#changes-2011-05-25" title="http://www.w3.org/TR/html5-diff/#changes-2011-05-25">especificación HTML5</a> que llaman a los métodos {{domxref("window.showModalDialog()")}}, {{domxref("window.alert()")}}, {{domxref("window.confirm()")}} y {{domxref("window.prompt()")}} pueden ser ignorados en este evento.</p> +<p>Se <em>puede</em> y se <em>debería</em> controlar este evento con {{domxref("EventTarget.addEventListener","window.addEventListener()")}} y el <a href="/en-US/docs/Mozilla_event_reference/beforeunload" title="Mozilla_event_reference/unload">evento <code>beforeunload</code></a> (más información en los enlaces).</p> +<h2 id="Compatibilidad_con_los_navegadores">Compatibilidad con los navegadores</h2> +<div> + {{CompatibilityTable}}</div> +<div id="compat-desktop"> + <table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>1</td> + <td>1</td> + <td>4</td> + <td>12</td> + <td>3</td> + </tr> + </tbody> + </table> +</div> +<div id="compat-mobile"> + <table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> + </table> +</div> +<h2 id="Specification" name="Specification">Especificación</h2> +<p>Este evento fue introducido originalmente por Microsoft en Internet Explorer 4 y estandarizado en la especificación HTML5.</p> +<ul> + <li>{{spec("http://dev.w3.org/html5/spec-LC/history.html#unloading-documents", "Especificación HTML5: <em>Browsing the Web, Unloading documents</em>", "LC")}} (en inglés)</li> +</ul> +<h2 id="See also" name="See also">Ver también</h2> +<ul> + <li><a href="http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx">MSDN: evento onbeforeunload</a> (en inglés)</li> +</ul> diff --git a/files/es/web/api/windoweventhandlers/onhashchange/index.html b/files/es/web/api/windoweventhandlers/onhashchange/index.html new file mode 100644 index 0000000000..282176df2b --- /dev/null +++ b/files/es/web/api/windoweventhandlers/onhashchange/index.html @@ -0,0 +1,165 @@ +--- +title: WindowEventHandlers.onhashchange +slug: Web/API/WindowEventHandlers/onhashchange +tags: + - HTML-DOM + - JavaScript + - Propiedades + - Referencia + - WindowEventHandlers + - eventos +translation_of: Web/API/WindowEventHandlers/onhashchange +--- +<div> +<div>{{APIRef("HTML DOM")}}</div> +</div> + +<p>El evento <strong>hashchange</strong> se dispara cuando la almohadilla ha cambiado (ver {{domxref("Window.location", "location.hash")}}).</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">window.onhashchange = funcRef; +</pre> + +<p><strong>ó</strong></p> + +<pre class="syntaxbox"><body onhashchange="funcRef();"> +</pre> + +<p><strong>ó</strong></p> + +<pre class="syntaxbox">window.addEventListener("hashchange", funcRef, false); +</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code>funcRef</code></dt> + <dd>Una referencia a una función.</dd> +</dl> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush:js">if ("onhashchange" in window) { + alert("¡El navegador soporta el evento hashchange!"); +} + +function locationHashChanged() { + if (location.hash === "#somecoolfeature") { + somecoolfeature(); + } +} + +window.onhashchange = locationHashChanged; +</pre> + +<h2 id="El_evento_hashchange">El evento hashchange</h2> + +<p>El evento <code>hashchange</code> enviado, tiene los siguientes campos:</p> + +<table class="standard-table"> + <tbody> + <tr> + <td class="header">Campo</td> + <td class="header">Tipo</td> + <td class="header">Descripción</td> + </tr> + <tr> + <td><code>newURL</code> {{gecko_minversion_inline("6.0")}}</td> + <td><code>DOMString</code></td> + <td>La URL nueva hacia la cual la ventana está navegando.</td> + </tr> + <tr> + <td><code>oldURL</code> {{gecko_minversion_inline("6.0")}}</td> + <td><code>DOMString</code></td> + <td>La URL anterior desde la cual la ventana navegó.</td> + </tr> + </tbody> +</table> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificacion</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('HTML WHATWG', '#windoweventhandlers', 'GlobalEventHandlers')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('HTML5.1', '#windoweventhandlers', 'GlobalEventHandlers')}}</td> + <td>{{Spec2('HTML5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName("HTML5 W3C", "#windoweventhandlers", "GlobalEventHandlers")}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">Compatibilidad en 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>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte Basico</td> + <td>5.0</td> + <td>{{CompatGeckoDesktop("1.9.2")}}</td> + <td> + <p>8.0</p> + + <p><code style="font-size: 14px;">los atributos oldURL</code>/<code style="font-size: 14px;">newURL no estan soportados.</code></p> + </td> + <td>10.6</td> + <td>5.0</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>Soporte Basico</td> + <td>2.2</td> + <td>{{CompatGeckoMobile("1.9.2")}}</td> + <td>9.0</td> + <td>11.0</td> + <td>5.0</td> + </tr> + </tbody> +</table> +</div> + +<ul> + <li><a href="/en-US/docs/DOM/Manipulating_the_browser_history" title="DOM/Manipulating the browser history">Manipulando el historial del navegador</a>, metodos <a href="/en-US/docs/DOM/window.history" title="DOM/window.history">history.pushState() y history.replaceState()</a>, evento <a href="/en-US/docs/DOM/window.onpopstate" title="DOM/window.onpopstate">popstate</a>.</li> +</ul> diff --git a/files/es/web/api/windoweventhandlers/onpopstate/index.html b/files/es/web/api/windoweventhandlers/onpopstate/index.html new file mode 100644 index 0000000000..5ee8539dbd --- /dev/null +++ b/files/es/web/api/windoweventhandlers/onpopstate/index.html @@ -0,0 +1,74 @@ +--- +title: WindowEventHandlers.onpopstate +slug: Web/API/WindowEventHandlers/onpopstate +translation_of: Web/API/WindowEventHandlers/onpopstate +--- +<div>{{APIRef}}</div> + +<p>La propiedad <strong><code>onpopstate</code></strong> del <a href="/en-US/docs/Glossary/Mixin">mixin</a> {{domxref("WindowEventHandlers")}} es el {{domxref("EventHandler")}} para procesar eventos <code><a href="/en-US/docs/Web/API/Window/popstate_event">popstate</a></code> de la ventana.</p> + +<p>Se evnía un evento <code>popstate</code> a la ventana cada vez que la entrada activa de la historia cambia entre otra otras dos entradas del mismo documento. Si la entrada de la historia fue creada al llamar a <code>history.pushState()</code>, o fue afectada por una llamada a <code>history.replaceState()</code>, la propiedad <code>state</code> del evento <code>popstate</code> contendrá una copia del objeto de estado de la entrada de la hisotria.</p> + +<div class="note"> +<p><strong>Nota</strong>: Llamar a <code>history.pushState()</code> o a <code>history.replaceState()</code> no dispararán un evento <code>popstate</code>. El evento <code>popstate</code> solamente se dispará realizando una acción de navegador, tal como pulsar el botón volver (o llamando a <code>history.back()</code> en JavaScript), mientras se navega entre dos entradas de la historia de un mismo documento.</p> +</div> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox">window.onpopstate = <em>funcRef</em>; +</pre> + +<ul> + <li><code>funcRef</code> es una función manejadora (handler).</li> +</ul> + +<h2 id="The_popstate_event" name="The_popstate_event">El evento popstate</h2> + +<p>Por ejemplo, la página en <code>http://example.com/example.html</code> ejecutando el código siguiente, generará alertas como se indica.:</p> + +<pre class="brush:js">window.onpopstate = function(event) { + alert("location: " + document.location + ", state: " + JSON.stringify(event.state)); +}; + +history.pushState({page: 1}, "title 1", "?page=1"); +history.pushState({page: 2}, "title 2", "?page=2"); +history.replaceState({page: 3}, "title 3", "?page=3"); +history.back(); // alerts "location: http://example.com/example.html?page=1, state: {"page":1}" +history.back(); // alerts "location: http://example.com/example.html, state: null +history.go(2); // alerts "location: http://example.com/example.html?page=3, state: {"page":3} +</pre> + +<p>Tenga en cuenta que, a pesar de que la entrada original (para <code>http://example.com/example.html</code>) no tiene un objeto de estado asociado, el evento <code>popstate</code> se dispara igualemente cuando se activa la entrada después de la segunda llamada a <code>history.back()</code>.</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('HTML WHATWG', 'webappapis.html#handler-window-onpopstate', 'onpopstate')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + + + +<p>{{Compat("api.WindowEventHandlers.onpopstate")}}</p> + +<h2 id="See_also" name="See_also">Vea también</h2> + +<ul> + <li>{{domxref("window.history")}}</li> + <li><a href="/en-US/docs/Web/Guide/DOM/Manipulating_the_browser_history">Manipulando la historia del navegador</a></li> + <li><a href="/en-US/docs/Web/Guide/DOM/Manipulating_the_browser_history/Example">Ejemplo de navegación con Ajax</a></li> +</ul> diff --git a/files/es/web/api/windoworworkerglobalscope/caches/index.html b/files/es/web/api/windoworworkerglobalscope/caches/index.html new file mode 100644 index 0000000000..c8d3a71b97 --- /dev/null +++ b/files/es/web/api/windoworworkerglobalscope/caches/index.html @@ -0,0 +1,127 @@ +--- +title: WindowOrWorkerGlobalScope.caches +slug: Web/API/WindowOrWorkerGlobalScope/caches +translation_of: Web/API/WindowOrWorkerGlobalScope/caches +--- +<p>{{APIRef()}}{{SeeCompatTable}}</p> + +<p>La propiedad de sólo-lectura <code><strong>caches</strong></code>, de la interfaz {{domxref("WindowOrWorkerGlobalScope")}}, devuelve el objeto {{domxref("CacheStorage")}} asociado al contexto actual. Este objeto habilita funcionalidades como guardar assets para su utilización <em>offline</em>, y generar respuestas personalizadas a las peticiones.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var <em>myCacheStorage</em> = self.caches; // or just caches +</pre> + +<h3 id="Valor">Valor</h3> + +<p>Un objeto {{domxref("CacheStorage")}}.</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>El siguiente ejemplo muestra la forma en la que utilizarías una cache en un contexto de <a href="/en-US/docs/Web/API/Service_Worker_API">service worker</a> para guardar assets <em>offline</em>.</p> + +<pre class="brush: js">this.addEventListener('install', function(event) { + event.waitUntil( + caches.open('v1').then(function(cache) { + return cache.addAll( + '/sw-test/', + '/sw-test/index.html', + '/sw-test/style.css', + '/sw-test/app.js', + '/sw-test/image-list.js', + '/sw-test/star-wars-logo.jpg', + '/sw-test/gallery/', + '/sw-test/gallery/bountyHunters.jpg', + '/sw-test/gallery/myLittleVader.jpg', + '/sw-test/gallery/snowTroopers.jpg' + ); + }) + ); +});</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('Service Workers', '#self-caches', 'caches')}}</td> + <td>{{Spec2('Service Workers')}}</td> + <td>Definido en un <code>WindowOrWorkerGlobalScope</code> parcial en la última especificación.</td> + </tr> + <tr> + <td>{{SpecName('Service Workers')}}</td> + <td>{{Spec2('Service Workers')}}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_Navegadores">Compatibilidad de Navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>40.0</td> + <td>{{CompatGeckoDesktop(42)}}<br> + {{CompatGeckoDesktop(52)}}<sup>[1]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Chrome para Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile(42)}}<br> + {{CompatGeckoMobile(52)}}<sup>[1]</sup></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] las <code>caches</code> se definen ahora en el mixin {{domxref("WindowOrWorkerGlobalScope")}}.</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/ServiceWorker_API">Service Workers</a></li> + <li><a href="/en-US/docs/Web/API/Web_Workers_API">Web Workers</a></li> + <li>{{domxref("CacheStorage")}}</li> + <li>{{domxref("Cache")}}</li> +</ul> diff --git a/files/es/web/api/windoworworkerglobalscope/createimagebitmap/index.html b/files/es/web/api/windoworworkerglobalscope/createimagebitmap/index.html new file mode 100644 index 0000000000..e24e4b11f4 --- /dev/null +++ b/files/es/web/api/windoworworkerglobalscope/createimagebitmap/index.html @@ -0,0 +1,108 @@ +--- +title: self.createImageBitmap() +slug: Web/API/WindowOrWorkerGlobalScope/createImageBitmap +tags: + - API + - Canvas + - DOM + - Referencia + - WindowOrWorkerGlobalScope + - createImageBitmap + - metodo +translation_of: Web/API/WindowOrWorkerGlobalScope/createImageBitmap +--- +<div>{{APIRef("Canvas API")}}</div> + +<p>El método <code><strong>createImageBitmap()</strong></code> crea un <em>bitmap</em> a partir de un recurso especificado, opcionalmente recortado para mostrar únicamente una porción de este. El método existe a nivel global como parte, tanto de las ventanas (<em>window</em>), como de los <em>workers</em>. Este admite una variedad de tipos de entrada, y devuelve una {{domxref("Promise")}} que es resuelta con un {{domxref("ImageBitmap")}}.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">createImageBitmap(<em>image</em>[, options]).then(function(response) { ... }); +createImageBitmap(<em>image, sx, sy, sw, sh</em>[, options]).then(function(response) { ... });</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code>image</code></dt> + <dd>Un recurso/imagen origen, que puede uno de los siguientes elementos: {{HTMLElement("img")}}, SVG {{SVGElement("image")}}, {{HTMLElement("video")}}, {{HTMLElement("canvas")}}, {{domxref("HTMLImageElement")}}, {{domxref("SVGImageElement")}}, {{domxref("HTMLVideoElement")}}, {{domxref("HTMLCanvasElement")}}, {{domxref("Blob")}}, {{domxref("ImageData")}}, {{domxref("ImageBitmap")}}, o {{domxref("OffscreenCanvas")}}.</dd> + <dt><code>sx</code></dt> + <dd>La coordenada x del rectángulo que será usado para la extracción del <code>ImageBitmap</code>.</dd> + <dt><code>sy</code></dt> + <dd>La coordenada y del rectángulo que será usado para la extracción del <code>ImageBitmap</code>.</dd> + <dt><code>sw</code></dt> + <dd>La anchura del rectángulo que será usado para extraer el <code>ImageBitmap</code>. El valor podría ser negativo.</dd> + <dt><code>sh</code></dt> + <dd>La altura del rectángulo que será usado para extraer el <code>ImageBitmap</code>. El valor podría ser negativo.</dd> + <dt><code>options</code> {{optional_inline}}</dt> + <dd>Un objeto que proporciona opciones para la extracción de la imagen. Las opciones posibles son: + <ul> + <li><code>imageOrientation</code>: Especifica si la imagen debe ser extraida tal y como se muestra, o debe ser volteada verticalmente. Las valores posibles: <code>none</code> (por defecto) o <code>flipY</code>.</li> + <li><code>premultiplyAlpha</code>: Especifica si los canales de color del mapa de bits generado deben premultiplicarse por el canal alpha. Uno de: <code>none</code>, <code>premultiply</code>, o <code>default</code> (por defecto).</li> + <li><code>colorSpaceConversion</code>: Especifica si la imagen debe ser decodificada usando conversión del espacio de color. Uno de: <code>none</code> o <code>default</code> (por defecto). El valor <code>default</code> indica que se usará la implementación que haya disponible.</li> + <li><code>resizeWidth</code>: Un entero largo que especifica la anchura final.</li> + <li><code>resizeHeight</code>: Un entero largo que especifica la altura final.</li> + <li><code>resizeQuality</code>: Especifica que algorítmo debe ser usado en el redimensionado para alcanzar las dimensiones deseadas. Uno de estos valores: <code>pixelated</code>, <code>low</code> (por defecto), <code>medium</code>, o <code>high</code>.</li> + </ul> + </dd> +</dl> + +<h3 id="Valor_devuelto">Valor devuelto</h3> + +<p>Una {{domxref("Promise")}} que es resuelta con un objeto {{domxref("ImageBitmap")}}, el cual contiene los datos del mapa de bits generado para el rectángulo dado.</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<h3 id="Creando_sprites_desde_un_sprite_sheet">Creando <em>sprites</em> desde un <em>sprite sheet</em></h3> + +<p>El siguiente ejemplo carga un<em> sprite sheet</em>, extrae los <em>sprites</em>, y muestra cada uno de ellos en el <em>canvas</em>. Un <em>sprite sheet</em> es una imagen que contiene multiples imágenes más pequeñas, que finalmente son utilizadas de manera individual.</p> + +<pre class="brush: js language-js">var canvas = document.getElementById('myCanvas'), +ctx = canvas.getContext('2d'), +image = new Image(); + +// Esperar que el sprite sheet se cargue +image.onload = function() { + Promise.all([ + // Recortar dos sprites del conjunto + createImageBitmap(image, 0, 0, 32, 32), + createImageBitmap(image, 32, 0, 32, 32) + ]).then(function(sprites) { + // Pintar cada uno de los sprites en el canvas + ctx.drawImage(sprites[0], 0, 0); + ctx.drawImage(sprites[1], 32, 32); + }); +} + +// Cargar el sprite sheet desde un archivo de imagen +image.src = 'sprites.png'; +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col"> Comentario</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', "webappapis.html#dom-createimagebitmap", "createImageBitmap")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + + + +<p>{{Compat("api.WindowOrWorkerGlobalScope.createImageBitmap")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("CanvasRenderingContext2D.drawImage()")}}</li> + <li>{{domxref("ImageData")}}</li> +</ul> diff --git a/files/es/web/api/windoworworkerglobalscope/fetch/index.html b/files/es/web/api/windoworworkerglobalscope/fetch/index.html new file mode 100644 index 0000000000..9540fe5d05 --- /dev/null +++ b/files/es/web/api/windoworworkerglobalscope/fetch/index.html @@ -0,0 +1,177 @@ +--- +title: WindowOrWorkerGlobalScope.fetch() +slug: Web/API/WindowOrWorkerGlobalScope/fetch +tags: + - API + - Experimental + - Fetch + - Fetch API + - GlobalFetch + - Petición + - Referencia + - metodo + - solicitud +translation_of: Web/API/WindowOrWorkerGlobalScope/fetch +--- +<div>{{APIRef("Fetch API")}}</div> + +<p>El método <code><strong>fetch()</strong></code> del mixin {{domxref("WindowOrWorkerGlobalScope")}} lanza el proceso de solicitud de un recurso de la red. Esto devuelve una promesa que resuelve al objeto {{domxref("Response")}} que representa la respuesta a la solicitud realizada.</p> + +<p>Tanto {{domxref("Window")}} como {{domxref("WorkerGlobalScope")}} implementan <code>WorkerOrGlobalScope</code>, por lo que el método <code>fetch()</code> está disponible en prácticamente cualquier contexto desde el que se pueda necesitar solicitar un recurso.</p> + +<p>Una promesa {{domxref("WindowOrWorkerGlobalScope.fetch","fetch()")}} se rechaza con un {{jsxref("TypeError")}} cuando sucede un error en la red, aunque normalmente significa un tema de permisos o similar. Una comprobación más precisa de una solicitud con <code>fetch()</code> debería comprobar que la promesa se resuelve, y que la propiedad {{domxref("Response.ok")}} tiene valor <code>true</code>. Un estatus HTTP 404 no constituye un error de red.</p> + +<p>El método <code>fetch()</code> es controlado por la directiva <code>connect-src</code> de la <a href="/en-US/docs/Security/CSP/CSP_policy_directives">Política de Seguridad de Contenido (Content Security Policy)</a> en lugar de la directiva del recurso que se solicita.</p> + +<div class="note"> +<p><strong>Nota</strong>: Los parámetros del método <code>fetch()</code> son indénticos a los del constructor de {{domxref("Request.Request","Request()")}}.</p> +</div> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">Promise<Response> fetch(input[, init]);</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><em>input</em></dt> + <dd>Define el recurso que se quiere solicitar. Puede ser: + <ul> + <li>Un {{domxref("USVString")}} con la URL del recurso a solicitar. Algunos navegadores aceptan los esquemas <code>blob:</code> y <code>data:</code>.</li> + <li>Un objeto {{domxref("Request")}}.</li> + </ul> + </dd> + <dt><em>init</em> {{optional_inline}}</dt> + <dd>Objeto de opciones que contiene configuraciones para personalizar la solicitud. Estas opciones pueden ser: + <ul> + <li><code>method</code>: El método de solicitud, p.ej., <code>GET</code>, <code>POST</code>.</li> + <li><code>headers</code>: Cualquier cabecera que se quiera añadir a la solicitud, contenidas en un objeto {{domxref("Headers")}} o un objeto literal con valores {{domxref("ByteString")}}.</li> + <li><code>body</code>: Cualquier cuerpo que se quiera añadir a la solicitud: puede ser un {{domxref("Blob")}}, {{domxref("BufferSource")}}, {{domxref("FormData")}}, {{domxref("URLSearchParams")}}, u objeto {{domxref("USVString")}}. Nótese que las solicitudes con métodos <code>GET</code> o <code>HEAD</code> no pueden tener cuerpo.</li> + <li><code>mode</code>: El modo a usar en la solicitud, p.ej., <code>cors</code>, <code>no-cors</code>, o <code>same-origin</code>.</li> + <li><code>credentials</code>: Las credenciales que se quieran utilizar para la solicitud: <code>omit</code>, <code>same-origin</code>, o <code>include</code>. Para enviar automáticamente las cookies del dominio actual, debe indicarse esta opción. Desde Chrome 50, esta propiedad también acepta una instancia de {{domxref("FederatedCredential")}} o de {{domxref("PasswordCredential")}}.</li> + <li><code>cache</code>: El modo de caché a utilizar en la solicitud: <code>default</code>, <code>no-store</code>, <code>reload</code>, <code>no-cache</code>, <code>force-cache</code>, o <code>only-if-cached</code>.</li> + <li><code>redirect</code>: El modo de redirección a usar: <code>follow</code> (seguir redirecciones automáticamente), <code>error</code> (abortar si sucede un error durante la redirección), o <code>manual</code> (gestionar redirecciones manualmente). El valor por defecto en Chrome es <code>follow</code> (hasta la versión 46 era <code>manual</code>).</li> + <li><code>referrer</code>: Un {{domxref("USVString")}} que especifique <code>no-referrer</code>, <code>client</code>, o una URL. El valor por defecto es <code>client</code>.</li> + <li><code>referrerPolicy</code>: Especifica el valor de la cabecera HTTP referer. Puede ser <code>no-referrer</code>, <code>no-referrer-when-downgrade</code>, <code>origin</code>, <code>origin-when-cross-origin</code>, <code>unsafe-url</code>.</li> + <li><code>integrity</code>: Contiene el valor de <a href="/en-US/docs/Web/Security/Subresource_Integrity">integridad de subrecurso (subresource integrity)</a> de la solicitud (p.ej., <code>sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=</code>).</li> + <li><code>keepalive</code>: La opción <code>keepalive</code> se puede usar para permitir que recurso dure más que la página. Las solicitudes con el indicador <code>keepalive</code> son un reemplazo de la API {{domxref("Navigator.sendBeacon()")}}. </li> + <li><code>signal</code>: Una instancia de objeto {{domxref("AbortSignal")}}; permite comunicarse con con una solicitud vigente y abortarla si se desea via {{domxref("AbortController")}}.</li> + </ul> + </dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>Una {{domxref("Promise")}} que resuelve a un objeto {{domxref("Response")}}.</p> + +<h3 id="Excepciones">Excepciones</h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col"><strong>Tipo</strong></th> + <th scope="col"><strong>Descriptción</strong></th> + </tr> + </thead> + <tbody> + <tr> + <td><code>AbortError</code></td> + <td>Se abortó la solicitud (mediante {{domxref("AbortController.abort()")}}).</td> + </tr> + <tr> + <td><code>TypeError</code></td> + <td>Desde <a href="/en-US/docs/Mozilla/Firefox/Releases/43">Firefox 43</a>, <code>fetch()</code> lanza un <code>TypeError</code> si la URL tiene credenciales, como en <code>http://usuario:clave@ejemplo.com</code>.</td> + </tr> + </tbody> +</table> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>En el ejemplo de <a href="https://github.com/mdn/fetch-examples/tree/master/fetch-request">solicitud con Request</a> (ver <a href="https://mdn.github.io/fetch-examples/fetch-request/">Fetch Request live</a>) creamos un nuevo objeto {{domxref("Request")}} usando el constructor pertinente, y realizamos una solicitud usando <code>fetch()</code>. Dado que estamos solicitando una imagen, ejecutamos {{domxref("Body.blob()")}} en la respuesta para darle el tipo MIME correspondiente para que sea gestionada apropiadamente, luego creamos un objeto URL de ella para mostrarla en un elemento {{htmlelement("img")}}.</p> + +<pre class="brush: js">var miImagen = document.querySelector('img'); + +var miSolicitud = new Request('flores.jpg'); + +fetch(miSolicitud).then(function(respuesta) { + return respuesta.blob(); +}).then(function(respuesta) { + var objeto = URL.createObjectURL(respuesta); + miImagen.src = objeto; +});</pre> + +<p>En el ejemplo de <a href="https://github.com/mdn/fetch-examples/blob/master/fetch-with-init-then-request/index.html">solicitud con inicializador y Request</a> (ver <a href="https://mdn.github.io/fetch-examples/fetch-with-init-then-request/">Fetch Request init live</a>) hacemos lo mismo pero además pasamos un objeto inicializador cuando invocamos el <code>fetch()</code>:</p> + +<pre class="brush: js">var miImagen = document.querySelector('img'); + +var misCabeceras = new Headers(); +misCabeceras.append('Content-Type', 'image/jpeg'); + +var miInicializador = { method: 'GET', + headers: misCabeceras, + mode: 'cors', + cache: 'default' }; + +var miSolicitud = new Request('flores.jpg'); + +fetch(miSolicitud,miInicializador).then(function(respuesta) { + ... +});</pre> + +<p>Nótese que también podríamos pasar el objeto inicializador con el constructor de <code>Request</code> para conseguir el mismo efecto, p.ej.:</p> + +<pre class="brush: js">var miSolicitud = new Request('flores.jpg', miInicializador);</pre> + +<p>También se puede usar un objeto literal a modo de <code>headers</code> en <code>init</code>.</p> + +<pre class="brush: js">var miInicializador = { method: 'GET', + headers: { + 'Content-Type': 'image/jpeg' + }, + mode: 'cors', + cache: 'default' }; + +var myRequest = new Request('flowers.jpg', miInicializador); +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentarios</th> + </tr> + <tr> + <td>{{SpecName('Fetch','#fetch-method','fetch()')}}</td> + <td>{{Spec2('Fetch')}}</td> + <td>Definida parcialmente en <code>WindowOrWorkerGlobalScope</code> en la especificación más reciente.</td> + </tr> + <tr> + <td>{{SpecName('Fetch','#dom-global-fetch','fetch()')}}</td> + <td>{{Spec2('Fetch')}}</td> + <td>Definición inicial</td> + </tr> + <tr> + <td>{{SpecName('Credential Management')}}</td> + <td>{{Spec2('Credential Management')}}</td> + <td>Añade una instancia de {{domxref("FederatedCredential")}} o {{domxref("PasswordCredential")}} como valor posible para <code>init.credentials</code>.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + + + +<p>{{Compat("api.WindowOrWorkerGlobalScope.fetch")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Fetch_API">Fetch API</a></li> + <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">Control de acceso HTTP (CORS)</a></li> + <li><a href="/en-US/docs/Web/HTTP">HTTP</a></li> +</ul> diff --git a/files/es/web/api/windoworworkerglobalscope/index.html b/files/es/web/api/windoworworkerglobalscope/index.html new file mode 100644 index 0000000000..b45747a2b3 --- /dev/null +++ b/files/es/web/api/windoworworkerglobalscope/index.html @@ -0,0 +1,169 @@ +--- +title: WindowOrWorkerGlobalScope +slug: Web/API/WindowOrWorkerGlobalScope +tags: + - API + - DOM + - DOM API + - NeedsTranslation + - Service Worker + - TopicStub + - Window + - WindowOrWorkerGlobalScope + - Worker + - WorkerGlobalScope +translation_of: Web/API/WindowOrWorkerGlobalScope +--- +<div>{{ApiRef()}}</div> + +<p>El mixin <strong><code>WindowOrWorkerGlobalScope</code></strong> describe diversas características comunes a las interfaces {{domxref("Window")}} y {{domxref("WorkerGlobalScope")}}. Cada una de estas interfaces pueden, por supuesto, añadir más funcionalidades sobre las listadas a continuación.</p> + +<div class="note"> +<p><strong>Nota</strong>: <code>WindowOrWorkerGlobalScope</code> es un mixin y no una interface; no se puede crear un objeto de tipo <code>WindowOrWorkerGlobalScope</code>.</p> +</div> + +<h2 id="Propiedades">Propiedades</h2> + +<p>Estas propiedades se definen en el mixin {{domxref("WindowOrWorkerGlobalScope")}}, y son implementadas por {{domxref("Window")}} y {{domxref("WorkerGlobalScope")}}.</p> + +<div id="Properties"> +<dl> + <dt>{{domxref("WindowOrWorkerGlobalScope.caches")}} {{readOnlyinline}}</dt> + <dd>Devuelve el objeto {{domxref("CacheStorage")}}, asociado al contexto actual. Este objeto habilita funcionalidades como guardar assets para su utilización <em>offline</em>, y generar respuestas personalizadas a las peticiones.</dd> + <dt>{{domxref("WindowOrWorkerGlobalScope.indexedDB")}} {{readonlyInline}}</dt> + <dd>Proporciona un mecanismo para que las aplicaciones puedan acceder asíncronamente a las capacidades de las bases de datos indexadas.; devuelve un objeto {{domxref("IDBFactory")}}.</dd> + <dt>{{domxref("WindowOrWorkerGlobalScope.isSecureContext")}} {{readOnlyinline}}</dt> + <dd>Devuelve un booleano indicando si el contexto actual es seguro (<code>true</code>) o no (<code>false</code>).</dd> + <dt>{{domxref("WindowOrWorkerGlobalScope.origin")}} {{readOnlyinline}}</dt> + <dd>Devuelve el origen del objeto global, serializado como un string. (Esto no parece estar implementado todavía en ningun navegador).</dd> +</dl> +</div> + +<h2 id="Métodos">Métodos</h2> + +<p>Estas propiedades se definen en el mixin {{domxref("WindowOrWorkerGlobalScope")}}, y son implementadas por {{domxref("Window")}} y {{domxref("WorkerGlobalScope")}}.</p> + +<dl> + <dt>{{domxref("WindowOrWorkerGlobalScope.atob()")}}</dt> + <dd>Decodifica un string de datos que ha sido codificado utlizando codificación en base-64.</dd> + <dt>{{domxref("WindowOrWorkerGlobalScope.btoa()")}}</dt> + <dd>Crea un string ASCII codificado en base-64 desde un string de datos binarios.</dd> + <dt>{{domxref("WindowOrWorkerGlobalScope.clearInterval()")}}</dt> + <dd>Procesa el set de ejecución repetida utilizando {{domxref("WindowOrWorkerGlobalScope.setInterval()")}}.</dd> + <dt>{{domxref("WindowOrWorkerGlobalScope.clearTimeout()")}}</dt> + <dd>Cancela el retraso del set de ejecuión utilizando {{domxref("WindowOrWorkerGlobalScope.setTimeout()")}}.</dd> + <dt>{{domxref("WindowOrWorkerGlobalScope.createImageBitmap()")}}</dt> + <dd>Acepta variedad de recursos de imagen, y devuelve una {{domxref("Promise")}} que se resuelve como un {{domxref("ImageBitmap")}}. Opcionalmente, la fuente se recorta como un rectángulo de pixels con origen en (sx, sy) con ancho sw, y altura sh.</dd> + <dt>{{domxref("WindowOrWorkerGlobalScope.fetch()")}}</dt> + <dd>Comienza el proceso de búsqueda de un recurso desde la red.</dd> + <dt>{{domxref("WindowOrWorkerGlobalScope.setInterval()")}}</dt> + <dd>Programa la repetición de la ejecución de una función dado un número de lapsos en milisegundos.</dd> + <dt>{{domxref("WindowOrWorkerGlobalScope.setTimeout()")}}</dt> + <dd>Programa la ejecución de una función dada una cantidad de tiempo.</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("HTML WHATWG",'webappapis.html#windoworworkerglobalscope-mixin', '<code>WindowOrWorkerGlobalScope</code> mixin')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>Aquí es donde se define el mixin principal.</td> + </tr> + <tr> + <td>{{SpecName('Fetch','#fetch-method','fetch()')}}</td> + <td>{{Spec2('Fetch')}}</td> + <td>Definición del método <code>fetch().</code></td> + </tr> + <tr> + <td>{{SpecName('Service Workers', '#self-caches', 'caches')}}</td> + <td>{{Spec2('Service Workers')}}</td> + <td>Definición de la propiedad <code>caches</code>.</td> + </tr> + <tr> + <td>{{SpecName('IndexedDB 2', '#dom-windoworworkerglobalscope-indexeddb', 'indexedDB')}}</td> + <td>{{Spec2('IndexedDB 2')}}</td> + <td>Definición de la propiedad <code>indexedDB</code>.</td> + </tr> + <tr> + <td>{{SpecName('Secure Contexts', 'webappapis.html#dom-origin', 'isSecureContext')}}</td> + <td>{{Spec2('Secure Contexts')}}</td> + <td>Definición de la propiedad <code>isSecureContext.</code></td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_Navegadores">Compatibilidad de Navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Firefox (Gecko)</th> + <th>Chrome</th> + <th>Edge</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatGeckoDesktop(52)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android Webview</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>Android</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome para Android</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile(52)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p> </p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("Window")}}</li> + <li>{{domxref("WorkerGlobalScope")}}</li> +</ul> diff --git a/files/es/web/api/windoworworkerglobalscope/indexeddb/index.html b/files/es/web/api/windoworworkerglobalscope/indexeddb/index.html new file mode 100644 index 0000000000..e6ef3fe5cd --- /dev/null +++ b/files/es/web/api/windoworworkerglobalscope/indexeddb/index.html @@ -0,0 +1,141 @@ +--- +title: WindowOrWorkerGlobalScope.indexedDB +slug: Web/API/WindowOrWorkerGlobalScope/indexedDB +translation_of: Web/API/WindowOrWorkerGlobalScope/indexedDB +--- +<p>{{ APIRef() }}</p> + +<p>La propiedad <strong><code>indexedDB</code></strong> del mixin {{domxref("WindowOrWorkerGlobalScope")}} proporciona un mecanismo para que las aplicaciones puedan acceder asíncronamente a las capacidades de las bases de datos indexadas.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="brush: js">var DBOpenRequest = self.indexedDB.open('toDoList');</pre> + +<h3 id="Valor">Valor</h3> + +<p>Un objeto {{domxref("IDBFactory")}}.</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush: js;highlight:[3]">var db; +function openDB() { + var DBOpenRequest = window.indexedDB.open('toDoList'); + DBOpenRequest.onsuccess = function(e) { + db = DBOpenRequest.result; + } +}</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('IndexedDB 2', '#dom-windoworworkerglobalscope-indexeddb', 'indexedDB')}}</td> + <td>{{Spec2('IndexedDB 2')}}</td> + <td>Definido en un <code>WindowOrWorkerGlobalScope</code> parcial en la última especificación.</td> + </tr> + <tr> + <td>{{SpecName('IndexedDB', '#widl-IDBEnvironment-indexedDB', 'indexedDB')}}</td> + <td>{{Spec2('IndexedDB')}}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">Compatibilidad de Navegadores</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>23{{property_prefix("webkit")}}<br> + 24</td> + <td>{{CompatVersionUnknown}}</td> + <td>10 {{property_prefix("moz")}}<br> + {{CompatGeckoDesktop("16.0")}}<br> + {{CompatGeckoDesktop("52.0")}}<sup>[1]</sup></td> + <td>10, parcial</td> + <td>15</td> + <td>7.1</td> + </tr> + <tr> + <td>Disponible en los workers</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("37.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>4.4</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("22.0")}}<br> + {{CompatGeckoMobile("52.0")}}<sup>[1]</sup></td> + <td>1.0.1</td> + <td>10</td> + <td>22</td> + <td>8</td> + </tr> + <tr> + <td>Disponible en los workers</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("37.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] <code>indexedDB</code> se define ahora en el mixin {{domxref("WindowOrWorkerGlobalScope")}}.</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB">Utilización de IndexedDB</a></li> + <li>Iniciando transacciones: {{domxref("IDBDatabase")}}</li> + <li>Usando transacciones: {{domxref("IDBTransaction")}}</li> + <li>Estableciendo un rango de claves: {{domxref("IDBKeyRange")}}</li> + <li>Recuperación y edición de tus datos: {{domxref("IDBObjectStore")}}</li> + <li>Utilización de cursores: {{domxref("IDBCursor")}}</li> + <li>Ejemplo de referencia: <a class="external" href="https://github.com/mdn/to-do-notifications/tree/gh-pages">To-do Notifications</a> (<a class="external" href="http://mdn.github.io/to-do-notifications/">ver ejemplo <em>live</em></a>.)</li> +</ul> diff --git a/files/es/web/api/windoworworkerglobalscope/issecurecontext/index.html b/files/es/web/api/windoworworkerglobalscope/issecurecontext/index.html new file mode 100644 index 0000000000..a99c499c7c --- /dev/null +++ b/files/es/web/api/windoworworkerglobalscope/issecurecontext/index.html @@ -0,0 +1,86 @@ +--- +title: WindowOrWorkerGlobalScope.isSecureContext +slug: Web/API/WindowOrWorkerGlobalScope/isSecureContext +translation_of: Web/API/WindowOrWorkerGlobalScope/isSecureContext +--- +<p>{{APIRef()}}{{SeeCompatTable}}</p> + +<p>La propiedad de sólo-lectura <code><strong>isSecureContext</strong></code>, de la interface {{domxref("WindowOrWorkerGlobalScope")}} Devuelve un booleano indicando si el contexto actual es seguro (<code>true</code>) or not (<code>false</code>).</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">var <em>isItSecure</em> = self.isSecureContext; // or just isSecureContext +</pre> + +<h3 id="Valor">Valor</h3> + +<p>Un {{domxref("Boolean")}}.</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('Secure Contexts', 'webappapis.html#dom-origin', 'WindowOrWorkerGlobalScope.isSecureContext')}}</td> + <td>{{Spec2('Secure Contexts')}}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_Navegadores">Compatibilidad de Navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatChrome(55)}}</td> + <td>{{CompatGeckoDesktop(52)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android Webview</th> + <th>Chrome para Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatChrome(55)}}</td> + <td>{{CompatChrome(55)}}</td> + <td>{{CompatGeckoMobile(52)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> diff --git a/files/es/web/api/windowtimers/clearinterval/index.html b/files/es/web/api/windowtimers/clearinterval/index.html new file mode 100644 index 0000000000..14a1b0d1b8 --- /dev/null +++ b/files/es/web/api/windowtimers/clearinterval/index.html @@ -0,0 +1,43 @@ +--- +title: WindowTimers.clearInterval() +slug: Web/API/WindowTimers/clearInterval +translation_of: Web/API/WindowOrWorkerGlobalScope/clearInterval +--- +<div> +<div>{{APIRef("HTML DOM")}}</div> +</div> + +<p>Cancela una acción reiterativa que se inició mediante una llamada a {{domxref("window.setInterval", "setInterval")}}.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox"><em>window</em>.clearInterval(<var>intervalID</var>) +</pre> + +<p><code>intervalID</code> es el identificador de la acción reiterativa que se desea cancelar. Este ID se obtiene a partir de <code>setInterval()</code>.</p> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<p>Vea el <a href="/en-US/docs/DOM/window.setInterval#Example" title="DOM/window.setInterval#Example">ejemplo de<code> setInterval()</code></a>.</p> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<table class="standard-table"> + <tbody> + <tr> + <td>{{SpecName('HTML WHATWG', 'timers.html#timers', 'clearInterval')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + </tr> + </tbody> +</table> + +<h2 id="See_also" name="See_also">Vea también</h2> + +<ul> + <li><a href="/en-US/docs/JavaScript/Timers" title="JavaScript/Timers">JavaScript timers</a></li> + <li>{{domxref("WindowTimers.setTimeout")}}</li> + <li>{{domxref("WindowTimers.setInterval")}}</li> + <li>{{domxref("WindowTimers.clearTimeout")}}</li> + <li>{{domxref("window.requestAnimationFrame")}}</li> + <li><a href="/en-US/docs/JavaScript/Timers/Daemons" title="JavaScript/Timers/Daemons"><em>Daemons</em> management</a></li> +</ul> diff --git a/files/es/web/api/windowtimers/cleartimeout/index.html b/files/es/web/api/windowtimers/cleartimeout/index.html new file mode 100644 index 0000000000..0df5242672 --- /dev/null +++ b/files/es/web/api/windowtimers/cleartimeout/index.html @@ -0,0 +1,63 @@ +--- +title: window.clearTimeout +slug: Web/API/WindowTimers/clearTimeout +translation_of: Web/API/WindowOrWorkerGlobalScope/clearTimeout +--- +<div>{{ApiRef}}</div> + +<h2 id="Summary" name="Summary">Resumen</h2> + +<p>Borra el retraso asignado por {{domxref("window.setTimeout","window.setTimeout()")}}.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox">window.clearTimeout(<em>timeoutID</em>) +</pre> + +<ul> + <li><code>timeoutID</code> es el ID del timeout que desee borrar, retornado por {{domxref("window.setTimeout","window.setTimeout()")}}.</li> +</ul> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<p>Ejecute el script de abajo en el contexto de una página web y haga clic en la página una vez. Verá un mensaje emergente en un segundo. Si permanece haciendo clic en la página cada segundo, la alerta nunca aparece.</p> + +<pre class="brush: js">var alarm = { + remind: function(aMessage) { + alert(aMessage); + delete this.timeoutID; + }, + + setup: function() { + this.cancel(); + var self = this; + this.timeoutID = window.setTimeout(function(msg) {self.remind(msg);}, 1000, "Wake up!"); + }, + + cancel: function() { + if(typeof this.timeoutID == "number") { + window.clearTimeout(this.timeoutID); + delete this.timeoutID; + } + } +}; +window.onclick = function() { alarm.setup() };</pre> + +<h2 id="Notes" name="Notes">Notas</h2> + +<p>Pasar un ID inválido a <code>clearTimeout</code> no tiene ningún efecto (y no lanza una excepción).</p> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<p>DOM Nivel 0. Especificado en <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#dom-windowtimers-cleartimeout" title="http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#dom-windowtimers-cleartimeout">HTML5</a>.</p> + +<h2 id="See_also" name="See_also">Vea también</h2> + +<ul> + <li><a href="/en-US/docs/JavaScript/Timers" title="JavaScript/Timers">JavaScript timers</a></li> + <li>{{domxref("window.setTimeout")}}</li> + <li>{{domxref("window.setInterval")}}</li> + <li>{{domxref("window.clearInterval")}}</li> + <li>{{domxref("window.requestAnimationFrame")}}</li> + <li><a href="/en-US/docs/JavaScript/Timers/Daemons" title="JavaScript/Timers/Daemons"><em>Daemons</em> management</a></li> +</ul> diff --git a/files/es/web/api/windowtimers/index.html b/files/es/web/api/windowtimers/index.html new file mode 100644 index 0000000000..3516b78c0d --- /dev/null +++ b/files/es/web/api/windowtimers/index.html @@ -0,0 +1,118 @@ +--- +title: WindowTimers +slug: Web/API/WindowTimers +tags: + - API +translation_of: Web/API/WindowOrWorkerGlobalScope +--- +<div>{{APIRef("HTML DOM")}}</div> + +<p><code><strong>WindowTimers</strong></code> contains utility methods to set and clear timers.</p> + +<p>There is no object of this type, though the context object, either the {{domxref("Window")}} for regular browsing scope, or the {{domxref("WorkerGlobalScope")}} for workers, implements it.</p> + +<h2 id="Properties">Properties</h2> + +<p><em>This interface do not define any property, nor inherit any.</em></p> + +<h2 id="Methods">Methods</h2> + +<p><em>This interface do not inherit any method.</em></p> + +<dl> + <dt>{{domxref("WindowTimers.clearInterval()")}}</dt> + <dd>Cancels the repeated execution set using {{domxref("WindowTimers.setInterval()")}}.</dd> + <dt>{{domxref("WindowTimers.clearTimeout()")}}</dt> + <dd>Cancels the repeated execution set using {{domxref("WindowTimers.setTimeout()")}}.</dd> + <dt>{{domxref("WindowTimers.setInterval()")}}</dt> + <dd>Schedules the execution of a function each X milliseconds.</dd> + <dt>{{domxref("WindowTimers.setTimeout()")}}</dt> + <dd>Sets a delay for executing a function.</dd> +</dl> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('HTML WHATWG', '#windowtimers', 'WindowTimers')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>No change since the latest snapshot, {{SpecName("HTML5.1")}}.</td> + </tr> + <tr> + <td>{{SpecName('HTML5.1', '#windowtimers', 'WindowTimers')}}</td> + <td>{{Spec2('HTML5.1')}}</td> + <td>Snapshot of {{SpecName("HTML WHATWG")}}. No change.</td> + </tr> + <tr> + <td>{{SpecName("HTML5 W3C", "#windowtimers", "WindowTimers")}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>Snapshot of {{SpecName("HTML WHATWG")}}. Creation of <code>WindowBase64</code> (properties where on the target before it).</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>Firefox (Gecko)</th> + <th>Chrome</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatGeckoDesktop(1)}}</td> + <td>1.0</td> + <td>4.0</td> + <td>4.0</td> + <td>1.0</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Firefox Mobile (Gecko)</th> + <th>Android</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatGeckoMobile(1)}}</td> + <td rowspan="1">{{CompatVersionUnknown}}</td> + <td rowspan="1">{{CompatVersionUnknown}}</td> + <td rowspan="1">{{CompatVersionUnknown}}</td> + <td rowspan="1">{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p> </p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{domxref("Window")}}, {{domxref("WorkerGlobalScope")}}, {{domxref("DedicatedWorkerGlobalScope")}}, {{domxref("SharedWorkerGlobalScope")}}, and {{domxref("ServiceWorkerGlobalScope")}}</li> +</ul> diff --git a/files/es/web/api/windowtimers/setinterval/index.html b/files/es/web/api/windowtimers/setinterval/index.html new file mode 100644 index 0000000000..fe41612dd6 --- /dev/null +++ b/files/es/web/api/windowtimers/setinterval/index.html @@ -0,0 +1,692 @@ +--- +title: WindowTimers.setInterval() +slug: Web/API/WindowTimers/setInterval +tags: + - API + - DOM + - Gecko + - Intervalos + - Method + - Temporizadores + - Temporizadores de JavaScript + - WindowTimers + - setInterval +translation_of: Web/API/WindowOrWorkerGlobalScope/setInterval +--- +<div>{{APIRef("HTML DOM")}}</div> + +<div>Ejecuta una función o un fragmento de código de forma repetitiva cada vez que termina el periodo de tiempo determinado. Devuelve un ID de proceso.</div> + +<div></div> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox notranslate"><em>var procesoID</em> = window.setInterval(<em>función</em>, <em>intervaloDeTiempo</em>[, <em>parámetro1</em>, <em>parámetro2</em>, ... , parámetroN]); +<em>var procesoID</em> = window.setInterval(<em>código</em>, <em>intervaloDeTiempo</em>); +</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code>función</code></dt> + <dd>La {{jsxref("function")}} que será ejecutada cada <code>intervaloDeTiempo</code> milisegundos.</dd> + <dt><code>código</code></dt> + <dd>Una sintaxis opcional permite introducir una cadena en lugar de una función, la cual es evaluada y ejecutada cada <code>intervaloDeTiempo</code> milisegundos. Se recomienda evitar esta sintaxis por la misma razón por la que el comando {{jsxref("eval", "eval()")}} conlleva problemas de seguridad.</dd> + <dt><code>intervaloDeTiempo</code></dt> + <dd>El tiempo en milisegundos (1/1000 de segundo, ms) que se debe esperar entre cada ejecución de la función o del código. Si el valor es menor que 10, se usará 10 en su lugar. El tiempo entre cada ejecución puede ser mayor al que indicamos, para mayor información puedes revisar el siguiente artículo: {{SectionOnPage("/en-US/docs/Web/API/WindowTimers/setTimeout", "Reasons for delays longer than specified")}}.</dd> + <dt> + <div class="note">El parámetro <strong>intervaloDeTiempo</strong> es convertido en un entero de 32 bits con signo en el IDL, por lo que el valor más grande que puede tener es 2,147,483,647 milisegundos, aproximadamente 24.8 días.</div> + </dt> + <dt><code>parámetro1, ..., parámetroN</code> {{optional_inline}}</dt> + <dd>Parámetros adicionales que se pasan a la función a ejecutar.</dd> +</dl> + +<div class="note"> +<p>En Internet Explorer 9 y anteriores no es posible pasar más parámetros mediante esta sintaxis. Si quieres activar esta funcionalidad en dichos navegadores deberás usar un polyfill (entra en la sección <a href="#Callback_arguments">Callback arguments</a>).</p> +</div> + +<h3 id="Valor_de_Retorno">Valor de Retorno</h3> + +<p>El valor de retorno <code>procesoID</code> es un valor numérico distinto de cero que identifica al temporizador que fue creado al llamar <code>setInterval()</code>; este valor puede ser usado como parámetro en la función {{domxref("Window.clearInterval()")}} para detener el temporizador. Las funciones <code>setInterval()</code> y {{domxref("WindowTimers.setTimeout", "setTimeout()")}} comparten la misma pila de IDs, por lo que, técnicamente, los comandos <code>clearInterval()</code> y {{domxref("WindowTimers.clearTimeout", "clearTimeout()")}} pueden usarse indiscriminadamente. Sin embargo, por motivos de claridad y mantenimiento, es importante usarlos como corresponde.</p> + +<div class="blockIndicator note"> +<p><strong>Nota:</strong> El argumento <code>intervaloDeTiempo</code> se convierte aun entero con signo de 32 bits. Esto limita efectivamente al <code>intervaloDeTiempo</code> a valores de 2147483647 ms, ya que se especifica como entero con signo en el IDL.</p> +</div> + +<h2 id="Ejemplos">Ejemplos</h2> + +<h3 id="Ejemplo_1_Sintaxis_básica">Ejemplo 1: Sintaxis básica</h3> + +<p>El siguiente ejemplo muestra la sintaxis básica.</p> + +<pre class="brush:js notranslate">var intervalID = window.setInterval(miFuncion, 500, 'Parametro 1', 'Parametro 2'); + +function miFuncion(a,b) { + // Aquí va tu código + // Los parámetros son opcionales completamente + console.log(a); + console.log(b); +} +</pre> + +<h3 id="Ejemplo_2_Alternando_dos_colores">Ejemplo 2: Alternando dos colores</h3> + +<p>El siguiente ejemplo se llama a la función <code>flashtext()</code> una vez por segundo hasta que se presiona el botón Detener.</p> + +<pre class="brush:html notranslate"><!DOCTYPE html> +<html> +<head> + <meta charset="UTF-8" /> + <title>Ejemplo de setInterval/clearInterval</title> + <script> + var nIntervId; + + function cambiaDeColor() { + nIntervId = setInterval(flasheaTexto, 1000); + } + + function flasheaTexto() { + var oElem = document.getElementById('mi_mensaje'); + oElem.style.color = oElem.style.color == 'red' ? 'blue' : 'red'; + //oElem.style.color ... es un operador ternario o condicional + } + + function detenerCambioDeColor() { + clearInterval(nIntervId); + } + </script> +</head> +<body onload="cambiaDeColor();"> + <div id="mi_mensaje"> + <p>¡Hola mundo!</p> + </div> + <button onclick="detenerCambioDeColor();">Detener</button> +</body> +</html> +</pre> + +<h3 id="Ejemplo_3_Simulando_una_máquina_de_escribir">Ejemplo 3: Simulando una máquina de escribir</h3> + +<p>El siguiente ejemplo simula una máquina de escribir, primero borra el contenido de una lista de nodos (<code><a href="/en-US/docs/DOM/NodeList">NodeList</a>)</code> que coinciden con un grupo de selectores y después lo escribe lentamente.</p> + +<pre class="brush:html notranslate"><!DOCTYPE html> +<html> +<head> +<meta charset="UTF-8" /> +<title>Máquina de Escribir con JavaScript</title> +<script> + function maquinaEscribir (sSelector, nRate) { + + function limpiar () { + clearInterval(nIntervId); + bTyping = false; + bStart = true; + oCurrent = null; + aSheets.length = nIdx = 0; + } + + function desplazarse (oSheet, nPos, bEraseAndStop) { + if (!oSheet.hasOwnProperty("parts") || aMap.length < nPos) { return true; } + + var oRel, bExit = false; + + if (aMap.length === nPos) { aMap.push(0); } + + while (aMap[nPos] < oSheet.parts.length) { + oRel = oSheet.parts[aMap[nPos]]; + + desplazarse(oRel, nPos + 1, bEraseAndStop) ? aMap[nPos]++ : bExit = true; + + if (bEraseAndStop && (oRel.ref.nodeType - 1 | 1) === 3 && oRel.ref.nodeValue) { + bExit = true; + oCurrent = oRel.ref; + sPart = oCurrent.nodeValue; + oCurrent.nodeValue = ""; + } + + oSheet.ref.appendChild(oRel.ref); + if (bExit) { return false; } + } + + aMap.length--; + return true; + } + + function mecanografear () { + if (sPart.length === 0 && desplazarse(aSheets[nIdx], 0, true) && nIdx++ === aSheets.length - 1) { limpiar(); return; } + + oCurrent.nodeValue += sPart.charAt(0); + sPart = sPart.slice(1); + } + + function Hoja (oNode) { + this.ref = oNode; + if (!oNode.hasChildNodes()) { return; } + this.parts = Array.prototype.slice.call(oNode.childNodes); + + for (var nChild = 0; nChild < this.parts.length; nChild++) { + oNode.removeChild(this.parts[nChild]); + this.parts[nChild] = new Hoja(this.parts[nChild]); + } + } + + var + nIntervId, oCurrent = null, bTyping = false, bStart = true, + nIdx = 0, sPart = "", aSheets = [], aMap = []; + + this.rate = nRate || 100; + + this.ejecuta = function () { + if (bTyping) { return; } + if (bStart) { + var aItems = document.querySelectorAll(sSelector); + + if (aItems.length === 0) { return; } + for (var nItem = 0; nItem < aItems.length; nItem++) { + aSheets.push(new Hoja(aItems[nItem])); + /* Uncomment the following line if you have previously hidden your elements via CSS: */ + // aItems[nItem].style.visibility = "visible"; + } + + bStart = false; + } + + nIntervId = setInterval(mecanografear, this.rate); + bTyping = true; + }; + + this.pausa = function () { + clearInterval(nIntervId); + bTyping = false; + }; + + this.finaliza = function () { + oCurrent.nodeValue += sPart; + sPart = ""; + for (nIdx; nIdx < aSheets.length; desplazarse(aSheets[nIdx++], 0, false)); + limpiar(); + }; + } + + /* usage: */ + var oTWExample1 = new maquinaEscribir(/* elements: */ "#article, h1, #info, #copyleft", /* frame rate (optional): */ 15); + + /* default frame rate is 100: */ + var oTWExample2 = new maquinaEscribir("#controls"); + + /* you can also change the frame rate value modifying the "rate" property; for example: */ + // oTWExample2.rate = 150; + + onload = function () { + oTWExample1.ejecuta(); + oTWExample2.ejecuta(); + }; +</script> +<style type="text/css"> +span.intLink, a, a:visited { + cursor: pointer; + color: #000000; + text-decoration: underline; +} + +#info { + width: 180px; + height: 150px; + float: right; + background-color: #eeeeff; + padding: 4px; + overflow: auto; + font-size: 12px; + margin: 4px; + border-radius: 5px; + /* visibility: hidden; */ +} +</style> +</head> + +<body> + +<p id="copyleft" style="font-style: italic; font-size: 12px; text-align: center;">CopyLeft 2012 by <a href="https://developer.mozilla.org/" target="_blank">Mozilla Developer Network</a></p> +<p id="controls" style="text-align: center;">[&nbsp;<span class="intLink" onclick="oTWExample1.ejecuta();">Ejecutar</span> | <span class="intLink" onclick="oTWExample1.pausa();">Pausar</span> | <span class="intLink" onclick="oTWExample1.finaliza();">Terminar</span>&nbsp;]</p> +<div id="info"> +Vivamus blandit massa ut metus mattis in fringilla lectus imperdiet. Proin ac ante a felis ornare vehicula. Fusce pellentesque lacus vitae eros convallis ut mollis magna pellentesque. Pellentesque placerat enim at lacus ultricies vitae facilisis nisi fringilla. In tincidunt tincidunt tincidunt. +</div> +<h1>Maquina de Escribir en JavaScript </h1> + +<div id="article"> +<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam ultrices dolor ac dolor imperdiet ullamcorper. Suspendisse quam libero, luctus auctor mollis sed, malesuada condimentum magna. Quisque in ante tellus, in placerat est. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec a mi magna, quis mattis dolor. Etiam sit amet ligula quis urna auctor imperdiet nec faucibus ante. Mauris vel consectetur dolor. Nunc eget elit eget velit pulvinar fringilla consectetur aliquam purus. Curabitur convallis, justo posuere porta egestas, velit erat ornare tortor, non viverra justo diam eget arcu. Phasellus adipiscing fermentum nibh ac commodo. Nam turpis nunc, suscipit a hendrerit vitae, volutpat non ipsum.</p> +<form> +<p>Phasellus ac nisl lorem: <input type="text" /><br /> +<textarea style="width: 400px; height: 200px;">Nullam commodo suscipit lacus non aliquet. Phasellus ac nisl lorem, sed facilisis ligula. Nam cursus lobortis placerat. Sed dui nisi, elementum eu sodales ac, placerat sit amet mauris. Pellentesque dapibus tellus ut ipsum aliquam eu auctor dui vehicula. Quisque ultrices laoreet erat, at ultrices tortor sodales non. Sed venenatis luctus magna, ultricies ultricies nunc fringilla eget. Praesent scelerisque urna vitae nibh tristique varius consequat neque luctus. Integer ornare, erat a porta tempus, velit justo fermentum elit, a fermentum metus nisi eu ipsum. Vivamus eget augue vel dui viverra adipiscing congue ut massa. Praesent vitae eros erat, pulvinar laoreet magna. Maecenas vestibulum mollis nunc in posuere. Pellentesque sit amet metus a turpis lobortis tempor eu vel tortor. Cras sodales eleifend interdum.</textarea></p> +<p><input type="submit" value="Send" /> +</form> +<p>Duis lobortis sapien quis nisl luctus porttitor. In tempor semper libero, eu tincidunt dolor eleifend sit amet. Ut nec velit in dolor tincidunt rhoncus non non diam. Morbi auctor ornare orci, non euismod felis gravida nec. Curabitur elementum nisi a eros rutrum nec blandit diam placerat. Aenean tincidunt risus ut nisi consectetur cursus. Ut vitae quam elit. Donec dignissim est in quam tempor consequat. Aliquam aliquam diam non felis convallis suscipit. Nulla facilisi. Donec lacus risus, dignissim et fringilla et, egestas vel eros. Duis malesuada accumsan dui, at fringilla mauris bibStartum quis. Cras adipiscing ultricies fermentum. Praesent bibStartum condimentum feugiat.</p> +<p>Nam faucibus, ligula eu fringilla pulvinar, lectus tellus iaculis nunc, vitae scelerisque metus leo non metus. Proin mattis lobortis lobortis. Quisque accumsan faucibus erat, vel varius tortor ultricies ac. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nec libero nunc. Nullam tortor nunc, elementum a consectetur et, ultrices eu orci. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque a nisl eu sem vehicula egestas.</p> +</div> +</body> +</html> +</pre> + +<p><a href="/files/3997/typewriter.html">Observa este ejemplo en acción</a>. Ver más: <a href="/en-US/docs/DOM/window.clearInterval"><code>clearInterval()</code></a>.</p> + +<h2 id="Argumentos_de_Callback">Argumentos de Callback</h2> + +<p>Como se mencionó previamente Internet Explorer version 9 y anteriores no soportan el pasar argumentos a la función Callback en <code>setTimeout()</code> ni en <code>setInterval()</code>. El siguiente código específico de Internet Explorer muestra un método de superar esta limitante. Para usarlo basta añadir el código marcado al inicio de tu script.</p> + +<pre class="brush:js notranslate">/*\ +|*| +|*| IE-specific polyfill that enables the passage of arbitrary arguments to the +|*| callback functions of javascript timers (HTML5 standard syntax). +|*| +|*| https://developer.mozilla.org/en-US/docs/Web/API/window.setInterval +|*| https://developer.mozilla.org/User:fusionchess +|*| +|*| Syntax: +|*| var timeoutID = window.setTimeout(func, delay[, param1, param2, ...]); +|*| var timeoutID = window.setTimeout(code, delay); +|*| var intervalID = window.setInterval(func, delay[, param1, param2, ...]); +|*| var intervalID = window.setInterval(code, delay); +|*| +\*/ + +if (document.all && !window.setTimeout.isPolyfill) { + var __nativeST__ = window.setTimeout; + window.setTimeout = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) { + var aArgs = Array.prototype.slice.call(arguments, 2); + return __nativeST__(vCallback instanceof Function ? function () { + vCallback.apply(null, aArgs); + } : vCallback, nDelay); + }; + window.setTimeout.isPolyfill = true; +} + +if (document.all && !window.setInterval.isPolyfill) { + var __nativeSI__ = window.setInterval; + window.setInterval = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) { + var aArgs = Array.prototype.slice.call(arguments, 2); + return __nativeSI__(vCallback instanceof Function ? function () { + vCallback.apply(null, aArgs); + } : vCallback, nDelay); + }; + window.setInterval.isPolyfill = true; +} +</pre> + +<p>Otra posible solución es el usar funciones anónimas para llamar al Callback, aunque esta solución es un poco más cara. Ejemplo:</p> + +<pre class="brush:js notranslate">var intervalID = setInterval(function() { myFunc("one", "two", "three"); }, 1000);</pre> + +<p>También puedes hacer uso de <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind">function's bind</a>. Ejemplo:</p> + +<pre class="brush:js notranslate">var intervalID = setInterval(function(arg1) {}.bind(undefined, 10), 1000);</pre> + +<p>{{h3_gecko_minversion("Inactive tabs", "5.0")}}</p> + +<p>A partir de Gecko 5.0 {{geckoRelease("5.0")}}, los intervalos no se disparan más de una vez por segundo en las pestañas inactivas.</p> + +<h2 id="Problemas_usando_this">Problemas usando "<a href="/en-US/docs/Web/JavaScript/Reference/Operators/this"><code>this</code></a>"</h2> + +<p>Cuando pasas el método de un objeto a la función <code>setInterval()</code> éste es invocado fuera de su contexto. Esto puede crear un valor de <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this"><code>this</code></a> que puede no ser el esperado. Este problema es abordado en detalle en <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this#As_an_object_method">JavaScript reference</a>.</p> + +<h3 id="Explicación">Explicación</h3> + +<p>Cuando <code>setInterval() o setTimeOut()</code> ejecuta un determinado código o función, ésta corre en un contexto de ejecución separado al de la función en la que se creó dicho temporizador. Por esta razón a la palabra clave <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this"><code>this</code></a> se le asigna el valor del objeto <code>window</code> (o el objeto <code>global</code>), no es igual que usar <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this"><code>this</code></a> dentro de una fuinción que invoque a <code>setTimeOut()</code>. Observa el siguiente ejemplo (que utiliza <code>setTimeOut()</code> en lugar de <code>setInterval()</code> – el problema, de hecho, es el mismo para ambos temporizadores):</p> + +<pre class="brush:js notranslate">miArreglo = ["cero", "uno", "dos"]; + +miArreglo.miMetodo = function (sPropiedad) { + alert(arguments.length > 0 ? this[sPropiedad] : this); +}; + +miArreglo.miMetodo(); // imprime "cero,uno,dos" +miArreglo.miMetodo(1); // imprime "uno" +setTimeout(miArreglo.miMetodo, 1000); // imprime "[object Window]" despues de 1 segundo +setTimeout(miArreglo.miMetodo, 1500, "1"); // imprime "undefined" despues de 1,5 segundos +// tratemos de pasar el objeto 'this' +setTimeout.call(miArreglo, miArreglo.miMetodo, 2000); // error: "NS_ERROR_XPC_BAD_OP_ON_WN_PROTO: Illegal operation on WrappedNative prototype object" +setTimeout.call(miArreglo, miArreglo.miMetodo, 2500, 2); // same error</pre> + +<p>Como puedes ver no hay forma de pasar el objeto <code>this</code> a la función de Callback en la versión anterior de JavaScript.</p> + +<h3 id="Una_posible_solución">Una posible solución</h3> + +<p>Una posible alternativa para resolver ésto es reemplazar las dos funciones globales nativas <code>setTimeout()</code> y <code>setInterval()</code> con las siguientes funciones no nativas que permiten su ejecución a través del método <a href="/en-US/docs/JavaScript/Reference/Global_Objects/Function/call"><code>Function.prototype.call</code></a>. El siguiente ejemplo muestra una posible sustitución:</p> + +<pre class="brush:js notranslate">// Permite el pase del objeto 'this' a través de temporizadores JavaScript + +var __nativeST__ = window.setTimeout, __nativeSI__ = window.setInterval; + +window.setTimeout = function (vCallback, nDelay /*, argumentoAPasar1, argumentuAPasar2, etc. */) { + var oThis = this, aArgs = Array.prototype.slice.call(arguments, 2); + return __nativeST__(vCallback instanceof Function ? function () { + vCallback.apply(oThis, aArgs); + } : vCallback, nDelay); +}; + +window.setInterval = function (vCallback, nDelay /*, argumentoAPasar1, argumentoAPasar2, etc. */) { + var oThis = this, aArgs = Array.prototype.slice.call(arguments, 2); + return __nativeSI__(vCallback instanceof Function ? function () { + vCallback.apply(oThis, aArgs); + } : vCallback, nDelay); +}; +</pre> + +<div class="note">Estos dos reemplazos también permiten el camino estándar en HTML5 de pasar argumentos arbitrarios a las funciones de Callback de los temporizadores dentro de IE. Por lo tanto, pueden utilizarse como rellenos (polyfills) <em>no estándar</em>. Para más información vea <a href="#Callback_arguments">callback arguments paragraph</a>.</div> + +<p>Prueba de nueva funcionalidad:</p> + +<pre class="brush:js notranslate">miArreglo = ["cero", "uno", "dos"]; + +miArreglo.miMetodo = function (sProperty) { + alert(arguments.length > 0 ? this[sProperty] : this); +}; + +setTimeout(alert, 1500, "Hola Mundo!"); // la utilizacion estandar de setTimeout y de setInterval se mantiene, pero... +setTimeout.call(miArreglo, miArreglo.miMetodo, 2000); // imprime "cero,uno,dos" despues de 2 segundos +setTimeout.call(miArreglo, miArreglo.miMetodo, 2500, 2); // imprime "dos" despues de 2,5 segundos +</pre> + +<p>Otra solución más compleja está en la siguiente liga de <a href="#A_little_framework">framework</a>.</p> + +<div class="note">JavaScript 1.8.5 introduce el método <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind">Function.prototype.bind()</a></code>, el cual permite especificar el valor de <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this"><code>this</code></a> para todas sus llamadas en una determinada función. Esto permite sobrellevar facilmente diferentes problemas de contexto con el uso de la palabra <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this"><code>this</code></a>. También, ES2015 soporta <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">arrow functions</a>, dentro del lenguaje nos permite escribir cosas como setInterval( () => this.myMethod) si estamos dentro del método de miArreglo .</div> + +<h2 id="MiniDaemon_-_Un_framework_para_administrar_temporizadores">MiniDaemon - Un framework para administrar temporizadores</h2> + +<p>En proyectos que requieren muchos temporizadores puede volverse complicado el seguimiento de todos los eventos generados. Una forma de facilitar la administración de timers es guardando sus estados en un objeto. El siguiente ejemplo muestra este tipo de abstracción, la arquitectura del constructor evita explicitamente el uso de cerraduras. También ofrece un camino alternativo para pasar el objeto <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this"><code>this</code></a> a la función de Callback (observa la sección Problemas usando "<a href="/en-US/docs/Web/JavaScript/Reference/Operators/this"><code>this</code></a>" para más detalles). Puedes consultar también el siguiente código en<a href="https://github.com/madmurphy/minidaemon.js"> GitHub</a>.</p> + +<div class="note">Para una versión más modular de este (<code><em>Daemon)</em></code>puedes verlo en <a href="/en-US/Add-ons/Code_snippets/Timers/Daemons">JavaScript Daemons Management</a>. Aquí encontrarás una versión mas complicada que se reduce a una colección escalable de métodos para el constructor <code><em>Daemon</em></code>. Éste constructor no es más que un clon del <code><em>MiniDaemon</em></code> con soporte para las funciones <em>init</em> y <em>onstart</em> declarables durante la instanciación del mismo. Por esto el <strong><code><em>MiniDaemon</em></code> framework </strong>se mantiene como el camino recomendado para realizar animaciones simples.</div> + +<h3 id="minidaemon.js">minidaemon.js</h3> + +<pre class="brush:js notranslate">/*\ +|*| +|*| :: MiniDaemon :: +|*| +|*| Revision #2 - September 26, 2014 +|*| +|*| https://developer.mozilla.org/en-US/docs/Web/API/window.setInterval +|*| https://developer.mozilla.org/User:fusionchess +|*| https://github.com/madmurphy/minidaemon.js +|*| +|*| This framework is released under the GNU Lesser General Public License, version 3 or later. +|*| http://www.gnu.org/licenses/lgpl-3.0.html +|*| +\*/ + +function MiniDaemon (oOwner, fTask, nRate, nLen) { + if (!(this && this instanceof MiniDaemon)) { return; } + if (arguments.length < 2) { throw new TypeError("MiniDaemon - not enough arguments"); } + if (oOwner) { this.owner = oOwner; } + this.task = fTask; + if (isFinite(nRate) && nRate > 0) { this.rate = Math.floor(nRate); } + if (nLen > 0) { this.length = Math.floor(nLen); } +} + +MiniDaemon.prototype.owner = null; +MiniDaemon.prototype.task = null; +MiniDaemon.prototype.rate = 100; +MiniDaemon.prototype.length = Infinity; + + /* These properties should be read-only */ + +MiniDaemon.prototype.SESSION = -1; +MiniDaemon.prototype.INDEX = 0; +MiniDaemon.prototype.PAUSED = true; +MiniDaemon.prototype.BACKW = true; + + /* Global methods */ + +MiniDaemon.forceCall = function (oDmn) { + oDmn.INDEX += oDmn.BACKW ? -1 : 1; + if (oDmn.task.call(oDmn.owner, oDmn.INDEX, oDmn.length, oDmn.BACKW) === false || oDmn.isAtEnd()) { oDmn.pause(); return false; } + return true; +}; + + /* Instances methods */ + +MiniDaemon.prototype.isAtEnd = function () { + return this.BACKW ? isFinite(this.length) && this.INDEX < 1 : this.INDEX + 1 > this.length; +}; + +MiniDaemon.prototype.synchronize = function () { + if (this.PAUSED) { return; } + clearInterval(this.SESSION); + this.SESSION = setInterval(MiniDaemon.forceCall, this.rate, this); +}; + +MiniDaemon.prototype.pause = function () { + clearInterval(this.SESSION); + this.PAUSED = true; +}; + +MiniDaemon.prototype.start = function (bReverse) { + var bBackw = Boolean(bReverse); + if (this.BACKW === bBackw && (this.isAtEnd() || !this.PAUSED)) { return; } + this.BACKW = bBackw; + this.PAUSED = false; + this.synchronize(); +}; +</pre> + +<div class="note">MiniDaemon pasa argumentos a la función callback. Si quieres trabajar con ellos en navegadores que no soportan nativamente esta característica, usa uno de los métodos propuestos arriba.</div> + +<h3 id="Sintaxis_2">Sintaxis</h3> + +<p><code>var myDaemon = new MiniDaemon(<em>thisObject</em>, <em>callback</em>[</code><code>, <em>rate</em></code><code>[, <em>length</em>]]);</code></p> + +<h3 id="Descripción">Descripción</h3> + +<p>Regresa un <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object">Objecto</a></code> que contiene la información necesaria para una animación (como el objeto <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this"><code>this</code></a>, la función de Callback, la duración y el frame-rate).</p> + +<h4 id="Parámetros_2">Parámetros</h4> + +<dl> + <dt><code>thisObject</code></dt> + <dd>El valor de la palabra <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this"><code>this</code></a> sobre el cual funcionará la función de <em>Callback. </em>Puede ser un <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object"><code>objecto</code></a> o <code>null</code>.</dd> + <dt><code>callback</code></dt> + <dd>La función que se invocará repetidas veces. Dicha función se invocará con tres parámetros: <em>index</em> que corresponde al valor iterativo de cada invocación, <em>length</em> que es el número total de invocaciones asignadas al <em>daemon</em> (puede ser un valor finito o <a href="/en-US/docs/JavaScript/Reference/Global_Objects/Infinity"><code>Infinity</code></a>) y <em>backwards</em> (valor booleano que expresa cuando el valor de <em>index</em> es creciente o decreciente). Es similar a <em>callback</em>.call(<em>thisObject</em>, <em>index</em>, <em>length</em>, <em>backwards</em>). Si la función de Callback regresa un valor false el deamon se detiene.</dd> + <dt><code>rate (optional)</code></dt> + <dd>El tiempo minimo en milisegundos que transcurre entre cada invocación. El valor por omisión es 100.</dd> + <dt><code>length (optional)</code></dt> + <dd>El número total de invocaciones. Puede ser un valor entero positivo o <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Infinity"><code>Infinity</code></a>. El valor por omisión es <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Infinity">Infinity</a>.</code></dd> +</dl> + +<h4 id="Propiedades_de_la_intancia_MiniDaemon"><code>Propiedades de la intancia MiniDaemon</code> </h4> + +<dl> + <dt><code>myDaemon.owner</code></dt> + <dd>El objeto <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this"><code>this</code></a> sobre el cual se ejecuta el daemon (lectura/escritura). Puede ser un <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object"><code>objecto</code></a> o <code>null</code>.</dd> + <dt><code>myDaemon.task</code></dt> + <dd>La función que se invocará repetidas veces. Dicha función se invocará con tres parámetros: <em>index</em> que corresponde al valor iterativo de cada invocación, <em>length</em> que es el número total de invocaciones asignadas al <em>daemon</em> (puede ser un valor finito o <a href="/en-US/docs/JavaScript/Reference/Global_Objects/Infinity"><code>Infinity</code></a>) y <em>backwards</em> (valor booleano que expresa cuando el valor de <em>index</em> es creciente o decreciente). Es similar a <em>callback</em>.call(<em>thisObject</em>, <em>index</em>, <em>length</em>, <em>backwards</em>). Si la función de Callback regresa un valor false el deamon se detiene.</dd> + <dt><code>myDaemon.rate</code></dt> + <dd>El tiempo minimo en milisegundos que transcurre entre cada invocación. El valor por omición es 100 (lectura/escritura).</dd> + <dt><code>myDaemon.length</code></dt> + <dd>El número total de invocaciones. Puede ser un valor entero positivo o <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Infinity"><code>Infinity</code></a>. El valor por omición es <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Infinity">Infinity</a> </code>(lectura/escritura).</dd> +</dl> + +<h4 id="MiniDaemon_instances_methods"><code>MiniDaemon</code> instances methods</h4> + +<dl> + <dt><code>myDaemon.isAtEnd()</code></dt> + <dd>Regresa un valor boleano que expresa cuando el <em>daemon</em> está en posición de inicio/fin o no.</dd> + <dt><code>myDaemon.synchronize()</code></dt> + <dd>Sincroniza el tiempo de un deamon iniciado con el tiempo de su invocación.</dd> + <dt><code>myDaemon.pause()</code></dt> + <dd>Pausa el deamon.</dd> + <dt><code>myDaemon.start([<em>reverse</em>])</code></dt> + <dd>Inicia el daemon hacia adelante "forward" (el indice de cada invocación se incrementa) o hacia atrás "backwards" (el índice de cada invocación se decrementa).</dd> +</dl> + +<h4 id="Métodos_del_objeto_global_del_MiniDaemon">Métodos del objeto global del <code>MiniDaemon</code></h4> + +<dl> + <dt><code>MiniDaemon.forceCall(<em>minidaemon</em>)</code></dt> + <dd>Fuerza una sola función callback a la función <code><em>minidaemon</em>.task</code> en lugar del hecho de que se ha alcanzado el final o no. En cualquier caso la propiedad INDEX interna crece o decrece según la dirección del proceso.</dd> +</dl> + +<h3 id="Ejemplo_de_uso">Ejemplo de uso</h3> + +<p>Tu página HTML:</p> + +<pre class="brush:html notranslate"><!DOCTYPE html> +<html> +<head> + <meta charset="UTF-8" /> + <title>MiniDaemin Example - MDN</title> + <script type="text/javascript" src="minidaemon.js"></script> + <style type="text/css"> + #sample_div { + visibility: hidden; + } + </style> +</head> + +<body> + <p> + <input type="button" onclick="fadeInOut.start(false /* optional */);" value="fade in" /> + <input type="button" onclick="fadeInOut.start(true);" value="fade out"> + <input type="button" onclick="fadeInOut.pause();" value="pause" /> + </p> + + <div id="sample_div">Some text here</div> + + <script type="text/javascript"> + function opacity (nIndex, nLength, bBackwards) { + this.style.opacity = nIndex / nLength; + if (bBackwards ? nIndex === 0 : nIndex === 1) { + this.style.visibility = bBackwards ? "hidden" : "visible"; + } + } + + var fadeInOut = new MiniDaemon(document.getElementById("sample_div"), opacity, 300, 8); + </script> +</body> +</html></pre> + +<p><a href="/files/3995/minidaemon_example.html" title="MiniDaemon Example">Prueba este ejemplo</a></p> + +<h2 id="Notas">Notas</h2> + +<p>La función<code> setInterval()</code> es usada frecuentemente para asignar una pausa para ejecutar funciones recurrentes, como por ejemplo pintar el siguiente cuadro de una animación.</p> + +<p>Puedes cancelar el ciclo iniciado por un <code>setInterval() </code>usando el comando <a href="/en-US/docs/Web/API/WindowTimers/clearInterval"><code>window.clearInterval()</code></a>.</p> + +<p>Si solo deseas ejecutar el ciclo una sola vez despues de una pausa usa en su lugar la función <a href="/en-US/docs/Web/API/WindowTimers/setTimeout"><code>window.setTimeout()</code></a>.</p> + +<h3 id="Asegúrate_que_el_tiempo_de_ejecución_sea_menor_que_la_frecuencia">Asegúrate que el tiempo de ejecución sea menor que la frecuencia</h3> + +<p>Si existe la posibilidad de que tu función o el código a ejecutarse una y otra vez exeda el tiempo marcado en cada intervalo es recomendado que uses recursivamente el nombre de tu función usando <code><a href="/en-US/docs/Web/API/WindowTimers/setTimeout">window.setTimeout</a></code>. Por ejemplo, si usas <code>setInterval </code>para hacer llamadas a un servidor remoto cada 5 segundos, la latencia en la red, un servidor que no responde, o cualquier otro tipo de contratiempo puede generar una pausa mayor a la que indicaste. De esta forma terminarás con solicitudes XHR apiladas que no se resolverán necesariamente en orden.</p> + +<p>En estos casos llamadas con un patrón de <code>setTimeout()</code> recursivo es preferible:</p> + +<pre class="brush:js notranslate">(function loop(){ + setTimeout(function() { + // Your logic here + + loop(); + }, delay); +})(); +</pre> + +<p>En este fragmento de código, la función <code>loop()</code> es declarada y es ejecutada inmediatamente. La función <code>loop()</code> es invocada de forma recursiva dentro de <code>setTimeout()</code> despues de cada ejecución. Si bien este patrón no garantiza una ejecución a intervalos fijos, si garantiza que nunca se ejecutará un paso sin que se haya finalizado el anterior. </p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th>Especificaciones</th> + <th>Estatus</th> + <th>Comentarios</th> + </tr> + <tr> + <td>{{SpecName("HTML WHATWG", "webappapis.html#dom-setinterval", "WindowTimers.setInterval()")}}</td> + <td>{{Spec2("HTML WHATWG")}}</td> + <td>Definición inicial (DOM Level 0)</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad">Compatibilidad</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)<sup>[2]</sup></th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>1.0</td> + <td>{{CompatGeckoDesktop("1")}}</td> + <td>4.0</td> + <td>4.0</td> + <td>1.0</td> + </tr> + <tr> + <td>Soporta parámetros para callback<sup>[1]</sup></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>10.0</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</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>Soporte básico</td> + <td>1.0</td> + <td>1.0</td> + <td>{{CompatGeckoMobile("1")}}</td> + <td>6.0</td> + <td>6.0</td> + <td>1.0</td> + </tr> + <tr> + <td>Soporta parámetros para callback<sup>[1]</sup></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Whether it supports the optional parameters when in its first form or not.</p> + +<p>[2] Anterior a Firefox 13, Firefox pasaba un parametro adicional al callback, indicando el "actual lateness" del timeout en milisegundos. Este parámetro no estandar dejó de usarse en versiones posteriores a Firefox 13. No es recomendable que extensiones basadas en XPCOM para Firefox usen setInterval(), ya que las actualizaciones pueden causar el que el objeto {{domxref("Window")}} se actualice perdiendo los temporizadores. Deberás usar en su lugar {{interface("nsITimer")}}.</p> + +<h2 id="Ver_más">Ver más</h2> + +<ul> + <li><a href="/en-US/Add-ons/Code_snippets/Timers">JavaScript timers</a></li> + <li>{{domxref("WindowTimers.setTimeout")}}</li> + <li>{{domxref("WindowTimers.clearTimeout")}}</li> + <li>{{domxref("WindowTimers.clearInterval")}}</li> + <li>{{domxref("window.requestAnimationFrame")}}</li> + <li><a href="/en-US/Add-ons/Code_snippets/Timers/Daemons"><em>Daemons</em> management</a></li> +</ul> diff --git a/files/es/web/api/windowtimers/settimeout/index.html b/files/es/web/api/windowtimers/settimeout/index.html new file mode 100644 index 0000000000..1180d9f8af --- /dev/null +++ b/files/es/web/api/windowtimers/settimeout/index.html @@ -0,0 +1,340 @@ +--- +title: WindowOrWorkerGlobalScope.setTimeout +slug: Web/API/WindowTimers/setTimeout +tags: + - API + - HTML DOM + - WindowOrWorkerGlobalScope + - setTimeout +translation_of: Web/API/WindowOrWorkerGlobalScope/setTimeout +--- +<div>{{APIRef("HTML DOM")}}</div> + +<p>El método <strong><code>setTimeout()</code></strong> del mixin {{domxref("WindowOrWorkerGlobalScope")}} establece un temporizador que ejecuta una función o una porción de código después de que transcurre un tiempo establecido.</p> + + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox"><em>var idTemporizador</em> = <em>scope</em>.setTimeout(<em>funcion</em>[, <em>retraso</em>, <em>parametro1</em>, <em>parametro2</em>, ...]); +<em>var</em> <em>idTimeout</em> = <em>scope</em>.setTimeout(<em>funcion</em>[, <em>retraso</em>]); +<em>var idTimeout</em> = <em>scope</em>.setTimeout(<em>codigo</em>[, <em>retraso</em>]); +</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code>funcion</code></dt> + <dd>Una {{jsxref("function")}} para ejecutar después de que expire el temporizador.</dd> + <dt><code>codigo</code></dt> + <dd>Una sintaxis opcional que le permite incluir una cadena en lugar de una función, la cual es compilada y ejecutada cuando el temporizador expira. Esta sintaxis <strong>no se recomienda</strong> por las mismas razones que hacen del uso de {{jsxref("Global_Objects/eval", "eval()")}} un riesgo de seguridad.</dd> + <dt><code>retraso</code> {{optional_inline}}</dt> + <dd>Tiempo, en milisegundos (milésimas de segundo), que el temporizador debe esperar antes de ejecutar la función o el código. Si se omite este parámetro se usa el valor 0. Tenga en cuenta que el retraso real puede ser más prolongado; ver más abajo {{anch("Reasons for delays longer than specified")}}.</dd> + <dt><code>param1, ..., paramN</code> {{optional_inline}}</dt> + <dd>Parámetros adicionales que se pasan a la función especificada por <em>func</em> una vez el temporizador expira.</dd> +</dl> + +<div class="note"><strong>Nota:</strong> Pasar parámetros adicionales a la función en la primera sintaxis no funciona en Internet Explorer 9 o inferior. Si quiere habilitar esta funcionalidad en ese navegador, debe usar un código de compatibilidad (vea la sección <a href="#Callback_arguments">Callback arguments</a>).</div> + +<h3 id="Valor_retornado">Valor retornado</h3> + +<p>El valor retornado <code>IDtemporizador</code> es númerico y no es cero; identifica el temporizador creado con la llamada a <code>setTimeout()</code>; este valor puede pasarse a {{domxref("WindowOrWorkerGlobalScope.clearTimeout()")}} para cancelar el temporizador.</p> + +<p>Puede ser útil advertir que <code>setTimeout()</code> y {{domxref("WindowOrWorkerGlobalScope.setInterval", "setInterval()")}} comparten la misma piscina de IDs, y que tanto <code>clearTimeout()</code> como {{domxref("WindowOrWorkerGlobalScope.clearInterval", "clearInterval()")}} pueden intercambiarse. Por claridad, sin embargo, debe hacerlos coincidir para evitar confusiones cuando mantenga su código.</p> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<p>El siguiente ejemplo establece dos botenes simples en una página web y los engancha a las rutinas <code>setTimeout()</code> y <code>clearTimeout()</code>. Presionando el primer botón establecerá un temporizador que llama un diálogo de alerta después de dos segundos y guarda el id del temporizador para usarlo con <code>clearTimeout()</code>. Opcionalmente puede cancelar este temporizador presionando el segundo botón.</p> + +<h3 id="Contenido_HTML">Contenido HTML</h3> + +<pre class="brush: html"><p>Ejemplo funcional</p> +<button onclick="delayedAlert();">Muestra una caja de alerta después de dos segundos</button> +<p></p> +<button onclick="clearAlert();">Cancela la alerta antes de que ocurra</button> +</pre> + +<h3 id="Contenido_JavaScript">Contenido JavaScript</h3> + +<pre class="brush: js">var timeoutID; + +function delayedAlert() { + timeoutID = window.setTimeout(slowAlert, 2000); +} + +function slowAlert() { + alert("That was really slow!"); +} + +function clearAlert() { + window.clearTimeout(timeoutID); +} +</pre> + +<p>{{ EmbedLiveSample('Example') }}</p> + +<p>Vea también <a href="/en-US/docs/DOM/window.clearTimeout#Example" title="en-US/docs/DOM/window.clearTimeout#Example"><code>clearTimeout()</code> example</a>.</p> + +<h2 id="Callback_arguments">Callback arguments</h2> + +<p>Si necesita pasar un argumento a su función callback, pero necesita que funcione en Internet Explorer, que no soporta el envío de parámetros adicionales (ni con <code>setTimeout()</code> o <code>setInterval()</code>) usted puede incluir este código de compatibilidad <em>IE-specific</em> que habilitará la funcionalidad estándar de HTML5 para pasar los parámetros adicionales en ese navegador para ambos temporizadores solamente insertandolo al inicio de sus scripts.</p> + +<pre class="brush: js">/*\ +|*| +|*| IE-specific polyfill which enables the passage of arbitrary arguments to the +|*| callback functions of JavaScript timers (HTML5 standard syntax). +|*| +|*| https://developer.mozilla.org/en-US/docs/DOM/window.setInterval +|*| +|*| Syntax: +|*| var timeoutID = window.setTimeout(func, delay, [param1, param2, ...]); +|*| var timeoutID = window.setTimeout(code, delay); +|*| var intervalID = window.setInterval(func, delay[, param1, param2, ...]); +|*| var intervalID = window.setInterval(code, delay); +|*| +\*/ + +if (document.all && !window.setTimeout.isPolyfill) { + var __nativeST__ = window.setTimeout; + window.setTimeout = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) { + var aArgs = Array.prototype.slice.call(arguments, 2); + return __nativeST__(vCallback instanceof Function ? function () { + vCallback.apply(null, aArgs); + } : vCallback, nDelay); + }; + window.setTimeout.isPolyfill = true; +} + +if (document.all && !window.setInterval.isPolyfill) { + var __nativeSI__ = window.setInterval; + window.setInterval = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) { + var aArgs = Array.prototype.slice.call(arguments, 2); + return __nativeSI__(vCallback instanceof Function ? function () { + vCallback.apply(null, aArgs); + } : vCallback, nDelay); + }; + window.setInterval.isPolyfill = true; +} +</pre> + +<h2 id="Arreglo_solo_para_IE">Arreglo solo para IE</h2> + +<p>Si quiere una solución completamente no intrusiva con otros navegadores móviles o de escritorio, incluyendo IE 9 y superior, puede usar los comentarios condicionales de JavaScript:</p> + +<pre class="brush: js">/*@cc_on + // conditional IE < 9 only fix + @if (@_jscript_version <= 6) + (function(f){ + window.setTimeout =f(window.setTimeout); + window.setInterval =f(window.setInterval); + })(function(f){return function(c,t){var a=[].slice.call(arguments,2);return f(function(){c.apply(this,a)},t)}}); + @end +@*/ +</pre> + +<p>O usar un enfoque más limpio basado en el condicional para IE de HTML:</p> + +<pre class="brush: html"><!--[if lt IE 9]><script> +(function(f){ +window.setTimeout =f(window.setTimeout); +window.setInterval =f(window.setInterval); +})(function(f){return function(c,t){ +var a=[].slice.call(arguments,2);return f(function(){c.apply(this,a)},t)} +}); +</script><![endif]--> +</pre> + +<p>Otra posibilidad es usar una función anónima para llamar el callback, pero esta solución es un poco más costosa. Ejemplo:</p> + +<pre class="brush: js">var intervalID = setTimeout(function() { myFunc("uno", "dos", "tres"); }, 1000); +</pre> + +<p>Sin embargo, otra posibilidad es usar <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind" title="/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind">function's bind</a>. Ejemplo:</p> + +<pre class="brush: js">setTimeout(function(arg1){}.bind(undefined, 10)); +</pre> + +<h2 id="El_problema_this">El problema "<code>this</code>"</h2> + +<p>Cuando pasa un método a <code>setTimeout()</code> (o cualquier otra función , por el estilo), podría ser invocada con el valor de <code>this</code> equivocado. Este problema es explicado en detalle en la <a href="/en-US/docs/JavaScript/Reference/Operators/this#Method_binding" title="en-US/docs/Core_JavaScript_1.5_Reference/Operators/Special_Operators/this_Operator#Method_binding">referencia de JavaScript</a>.</p> + +<h3 id="Explicación">Explicación</h3> + +<p>El código ejecutado por <code>setTimeout()</code> corre en un contexto de ejecución diferente al de la función por la que fue llamado. Como consecuencia, la palabra clave <code>this para la función llamada </code>será asignado al objeto <code>window</code> (o <code>global</code>); no tendrá el mismo valor del <code>this</code> de la función que llamó al <code>setTimeout</code>. Vea el siguiente ejemplo:</p> + +<pre class="brush: js">myArray = ["cero", "uno", "dos"]; +myArray.myMethod = function (sProperty) { + alert(arguments.length > 0 ? this[sProperty] : this); +}; + +myArray.myMethod(); // imprime "cero,uno,dos" +myArray.myMethod(1); // imprime "uno" +setTimeout(myArray.myMethod, 1000); // imprime "[object Window]" después de 1 segundo +setTimeout(myArray.myMethod, 1500, "1"); // imprime "undefined" después de 1.5 segundos +// intentemos pasar el objeto 'this' +setTimeout.call(myArray, myArray.myMethod, 2000); // error: "NS_ERROR_XPC_BAD_OP_ON_WN_PROTO: Illegal operation on WrappedNative prototype object" +setTimeout.call(myArray, myArray.myMethod, 2500, 2); // mismo error</pre> + +<p>Como puedes ver no hay forma de pasar el objeto <code>this</code> a la función callback.</p> + +<h3 id="Una_posible_solución">Una posible solución</h3> + +<p>Una posible forma de resolver el problema del "<code>this</code>" es reemplazar las dos funciones globales nativas <code>setTimeout()</code> or <code>setInterval()por dos no-nativas<em> </em> </code>que permitan su invocación a través del método <a href="en-US/docs/JavaScript/Reference/Global_Objects/Function/call" title="en-US/docs/JavaScript/Reference/Global_Objects/Function/call"><code>Function.prototype.call</code></a>. El siguiente ejemplo muestra un posible reemplazo:</p> + +<pre class="brush: js">// Enable the passage of the 'this' object through the JavaScript timers + +var __nativeST__ = window.setTimeout, __nativeSI__ = window.setInterval; + +window.setTimeout = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) { + var oThis = this, aArgs = Array.prototype.slice.call(arguments, 2); + return __nativeST__(vCallback instanceof Function ? function () { + vCallback.apply(oThis, aArgs); + } : vCallback, nDelay); +}; + +window.setInterval = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) { + var oThis = this, aArgs = Array.prototype.slice.call(arguments, 2); + return __nativeSI__(vCallback instanceof Function ? function () { + vCallback.apply(oThis, aArgs); + } : vCallback, nDelay); +};</pre> + +<div class="note"><strong>Nota:</strong> Estos dos reemplazos habilitarán el estándar HTML5 para el paso de argumentos arbitrarios a las funciones callback de los temporizadores en IE. Pueden usarse como polyfills también. Vea el párrafo <a href="#Callback_arguments">Callback arguments</a>.</div> + +<p>Prueba de la nueva característica:</p> + +<pre class="brush: js">myArray = ["zero", "one", "two"]; +myArray.myMethod = function (sProperty) { + alert(arguments.length > 0 ? this[sProperty] : this); +}; + +setTimeout(alert, 1500, "Hello world!"); // the standard use of setTimeout and setInterval is preserved, but... +setTimeout.call(myArray, myArray.myMethod, 2000); // prints "zero,one,two" after 2 seconds +setTimeout.call(myArray, myArray.myMethod, 2500, 2); // prints "two" after 2.5 seconds +</pre> + +<p>No hay soluciones nativas <em>ad hoc</em> a este problema.</p> + +<div class="note"><strong>Nota:</strong> JavaScript 1.8.5 introduce el método <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind" title="en-US/docs/JavaScript/Reference/Global Objects/Function/bind">Function.prototype.bind(</a></code>, que permite especificar el valor que debería usarse como <code>this</code> para todas las llamadas a una función dada. Esto permite evitar fácilmente los problemas en los que no es claro que será, dependiendo del contexto desde el cual la función sea llamada.</div> + +<h2 id="Notas">Notas</h2> + +<p>Puede cancelar el temporizador usando <code><a href="/en-US/docs/DOM/window.clearTimeout" title="en-US/docs/DOM/window.clearTimeout">window.clearTimeout()</a></code>. Si desea tener una función llamada repetidamente (p.e., cada N milisegundos), considere usar <code><a href="/en-US/docs/DOM/window.setInterval" title="en-US/docs/DOM/window.setInterval">window.setInterval()</a></code>.</p> + +<p>Es importante notar que la función o fragmento de código no puede ser ejecutado hasta que el hilo que llamó <code>setTimeout()</code>haya terminado.</p> + +<h3 id="Pasando_cadenas_literales">Pasando cadenas literales</h3> + +<p>Pasando una cadena en vez de una función a <code>setTimeout()</code>pasa lo mismo que al usar <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/eval#Don.27t_use_eval.21" title="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/eval">eval</a>. </code></p> + +<pre class="brush: js">// Correcto +window.setTimeout(function() { + alert("Hello World!"); +}, 500); + +// Incorrecto +window.setTimeout("alert(\"Hello World!\");", 500); + +</pre> + +<p>Las cadenas literales son evaluadas en el contexto global, así que los símbolos locales en el contexto donde <code>setTimeout()</code> fue llamado no estarán disponibles cuando la cadena es evaluada como código.</p> + +<h3 id="Minimum_maximum_delay_and_timeout_nesting">Minimum/ maximum delay and timeout nesting</h3> + +<p><a class="external" href="http://code.google.com/p/chromium/issues/detail?id=792#c10" title="http://code.google.com/p/chromium/issues/detail?id=792#c10">Historically</a> browsers implement <code>setTimeout()</code> "clamping": successive <code>setTimeout()</code> calls with <code>delay</code> smaller than the "minimum delay" limit are forced to use at least the minimum delay. The minimum delay, <code>DOM_MIN_TIMEOUT_VALUE</code>, is 4 ms (stored in a preference in Firefox: <code>dom.min_timeout_value</code>), with a <code>DOM_CLAMP_TIMEOUT_NESTING_LEVEL</code> of 5ms.</p> + +<p>In fact, 4ms is <a class="external" href="http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#timers">specified by the HTML5 spec</a> and is consistent across browsers released in 2010 and onward. Prior to {{ geckoRelease("5.0") }}, the minimum timeout value for nested timeouts was 10 ms.</p> + +<p>In addition to "clamping", the timeout can also fire later when the page (or the OS/browser itself) is busy with other tasks.</p> + +<p>To implement a 0 ms timeout in a modern browser, you can use {{ domxref("window.postMessage()") }} as <a class="external" href="http://dbaron.org/log/20100309-faster-timeouts" title="http://dbaron.org/log/20100309-faster-timeouts">described here</a>.</p> + +<p>Browsers including Internet Explorer, Chrome, Safari, and Firefox store the delay as a 32-bit signed Integer internally. This causes an Integer overflow when using delays larger than 2147483647, resulting in the timeout being executed immediately.</p> + +<h4 id="Inactive_tabs">Inactive tabs</h4> + +<p>In {{ geckoRelease("5.0") }} and Chrome 11, timeouts are clamped to firing no more often than once per second (1000ms) in inactive tabs; see {{ bug(633421) }} for more information about this in Mozilla or <a class="external" href="http://crbug.com/66078" title="http://crbug.com/66078">crbug.com/66078</a> for details about this in Chrome.</p> + +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>1.0</td> + <td>{{ CompatGeckoDesktop("1") }}</td> + <td>4.0</td> + <td>4.0</td> + <td>1.0</td> + </tr> + <tr> + <td>Soporta parámetros para callback*1</td> + <td>{{ CompatVersionUnknown }}</td> + <td>{{ CompatVersionUnknown }}</td> + <td>10.0</td> + <td>{{ CompatVersionUnknown }}</td> + <td>{{ CompatUnknown }}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</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>Soporte básico</td> + <td>1.0</td> + <td>1.0</td> + <td>{{ CompatGeckoMobile("1") }}</td> + <td>6.0</td> + <td>6.0</td> + <td>1.0</td> + </tr> + <tr> + <td>Soporta parámetros para callback*1</td> + <td>{{ CompatUnknown }}</td> + <td>{{ CompatUnknown }}</td> + <td>{{ CompatUnknown }}</td> + <td>{{ CompatUnknown }}</td> + <td>{{ CompatUnknown }}</td> + <td>{{ CompatUnknown }}</td> + </tr> + </tbody> +</table> +</div> + +<p>*1 Whether it supports the optional parameters when in its first form or not.</p> + +<h2 id="Specification" name="Specification">Especificación</h2> + +<p>Parte del DOM nivel 0, como se especifica en <a class="external" href="http://www.whatwg.org/specs/web-apps/current-work/multipage/browsers.html#timers" title="http://www.whatwg.org/specs/web-apps/current-work/multipage/browsers.html#timers">HTML5</a>.</p> + +<h2 id="See_also" name="See_also">Vea también</h2> + +<ul> + <li><a href="/en-US/docs/JavaScript/Timers" title="/en-US/docs/JavaScript/Timers">JavaScript timers</a></li> + <li><a href="/en-US/docs/Mozilla/JavaScript_code_modules/Timer.jsm" title="/en-US/docs/Mozilla/JavaScript_code_modules/Timer.jsm">Timer.jsm</a></li> + <li>{{domxref("window.setInterval")}}</li> + <li>{{domxref("window.requestAnimationFrame")}}</li> + <li><a href="/en-US/docs/JavaScript/Timers/Daemons" title="/en-US/docs/JavaScript/Timers/Daemons"><em>Daemons</em> management</a></li> +</ul> diff --git a/files/es/web/api/worker/index.html b/files/es/web/api/worker/index.html new file mode 100644 index 0000000000..4be8325629 --- /dev/null +++ b/files/es/web/api/worker/index.html @@ -0,0 +1,155 @@ +--- +title: Worker +slug: Web/API/Worker +tags: + - API + - DOM + - Interface + - NeedsTranslation + - Reference + - TopicStub + - Web Workers + - Worker + - Workers +translation_of: Web/API/Worker +--- +<p>{{APIRef("Web Workers API")}}</p> + +<p>The <strong><code>Worker</code></strong> interface of the <a href="/en-US/docs/Web/API/Web_Workers_API">Web Workers API</a> represents a background task that can be easily created and can send messages back to its creator. Creating a worker is as simple as calling the <code>Worker()</code> constructor and specifying a script to be run in the worker thread.</p> + +<p>Workers may in turn spawn new workers as long as those workers are hosted within the same origin as the parent page (Note: nested workers are <a href="https://groups.google.com/a/chromium.org/forum/#!topic/blink-dev/5R3B4RN4GHU">currently not implemented in Blink</a>). In addition workers may use <a class="internal" href="/en/DOM/XMLHttpRequest" title="En/XMLHttpRequest"><code>XMLHttpRequest</code></a> for network I/O, with the stipulation that the <code>responseXML</code> and <code>channel</code> attributes on <code>XMLHttpRequest</code> always return <code>null</code>.</p> + +<p>Not <a href="/En/DOM/Worker/Functions_available_to_workers" title="En/DOM/Worker/Functions available to workers">all interfaces and functions are available</a> to the script associated with a <code>Worker</code>.</p> + +<p>In Firefox, if you want to use workers in extensions and would like to have access to <a href="/en/js-ctypes" title="en/js-ctypes">js-ctypes</a>, you should use the {{ domxref("ChromeWorker") }} object instead.</p> + +<h2 id="Properties">Properties</h2> + +<p><em>Inherits properties from its parent, {{domxref("EventTarget")}}, and implements properties from {{domxref("AbstractWorker")}}.</em></p> + +<h3 id="Event_handlers">Event handlers</h3> + +<dl> + <dt>{{domxref("AbstractWorker.onerror")}}</dt> + <dd>An {{ domxref("EventListener") }} called whenever an {{domxref("ErrorEvent")}} of type <code>error</code> bubbles through to the worker. This is inherited from {{domxref("AbstractWorker")}}.</dd> + <dt>{{domxref("Worker.onmessage")}}</dt> + <dd>An {{ domxref("EventListener") }} called whenever a {{domxref("MessageEvent")}} of type <code>message</code> bubbles through the worker — i.e. when a message is sent to the parent document from the worker via {{domxref("DedicatedWorkerGlobalScope.postMessage")}}. The message is stored in the event's {{domxref("MessageEvent.data", "data")}} property.</dd> +</dl> + +<h2 id="Constructors">Constructors</h2> + +<dl> + <dt>{{domxref("Worker.Worker", "Worker()")}}</dt> + <dd>Creates a dedicated web worker that executes the script at the specified URL. Workers can also be constructed using <a href="/en-US/docs/Web/API/Blob">Blobs</a>.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<p><em>Inherits methods from its parent, {{domxref("EventTarget")}}, and implements properties from {{domxref("AbstractWorker")}}.</em></p> + +<dl> + <dt>{{domxref("Worker.postMessage()")}}</dt> + <dd>Sends a message — which can consist of <code>any</code> JavaScript object — to the worker's inner scope.</dd> + <dt>{{domxref("Worker.terminate()")}}</dt> + <dd>Immediately terminates the worker. This does not offer the worker an opportunity to finish its operations; it is simply stopped at once. ServiceWorker instances do not support this method.</dd> +</dl> + +<h2 id="Example">Example</h2> + +<p>The following code snippet shows creation of a {{domxref("Worker")}} object using the {{domxref("Worker.Worker", "Worker()")}} constructor and usage of the object:</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'); +}</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" href="http://mdn.github.io/simple-web-worker/">run dedicated worker</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', "#worker", "Worker")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>No change from {{SpecName("Web Workers")}}.</td> + </tr> + <tr> + <td>{{SpecName('Web Workers', "#worker", "Worker")}}</td> + <td>{{Spec2('Web Workers')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p>Support varies for different types of workers. See each worker type's page for specifics.</p> + +<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>4</td> + <td>3.5</td> + <td>10.0</td> + <td>10.6</td> + <td>4</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> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>4.4</td> + <td>3.5</td> + <td>1.0.1</td> + <td>10.0</td> + <td>11.5</td> + <td>5.1</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a class="internal" href="/En/Using_web_workers" title="en/Using DOM workers">Using web workers</a></li> + <li><a href="/En/DOM/Worker/Functions_available_to_workers" title="https://developer.mozilla.org/En/DOM/Worker/Functions_available_to_workers">Functions available to workers</a></li> + <li>Other kind of workers: {{ domxref("SharedWorker") }} and <a href="/en-US/docs/Web/API/ServiceWorker_API">ServiceWorker</a>.</li> + <li>Non-standard, Gecko-specific workers: {{ domxref("ChromeWorker") }}, used by extensions.</li> +</ul> diff --git a/files/es/web/api/worker/postmessage/index.html b/files/es/web/api/worker/postmessage/index.html new file mode 100644 index 0000000000..c47fe400fc --- /dev/null +++ b/files/es/web/api/worker/postmessage/index.html @@ -0,0 +1,206 @@ +--- +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/worker/terminate/index.html b/files/es/web/api/worker/terminate/index.html new file mode 100644 index 0000000000..d557989f25 --- /dev/null +++ b/files/es/web/api/worker/terminate/index.html @@ -0,0 +1,107 @@ +--- +title: Worker.terminate() +slug: Web/API/Worker/terminate +translation_of: Web/API/Worker/terminate +--- +<p>{{APIRef("Web Workers API")}}</p> + +<p>El método <code><strong>terminate()</strong></code> de la interfaz {{domxref("Worker")}} termina inmediatamente el {{domxref("Worker")}}. Esto no ofrece la oportunidad de finalizar las operaciones que estuviera realizando el worker, termina la ejecución por completo.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="brush: js">myWorker.terminate();</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<p>Ninguno.</p> + +<h3 id="Retorna">Retorna</h3> + +<p>Nada.</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>El siguiente extracto de código muestra la creación de un objeto {{domxref("Worker")}} usando el constructor de {{domxref("Worker.Worker", "Worker()")}} y éste es inmediatamente terminado.</p> + +<pre class="brush: js">var myWorker = new Worker('worker.js'); + +myWorker.terminate(); +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', "#dom-worker-terminate", "Worker.postMessage()")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>No change from {{SpecName("Web Workers")}}.</td> + </tr> + <tr> + <td>{{SpecName('Web Workers', "#dom-worker-terminate", "Worker.postMessage()")}}</td> + <td>{{Spec2('Web Workers')}}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>4</td> + <td>3.5</td> + <td>10.0</td> + <td>10.6</td> + <td>4</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</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>Soporte básico</td> + <td>4.4</td> + <td>3.5</td> + <td>1.0.1</td> + <td>10.0</td> + <td>11.5</td> + <td>5.1</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Mirar_también">Mirar también</h2> + +<p>La interfaz {{domxref("Worker")}} a la que pertenece.</p> diff --git a/files/es/web/api/xmlhttprequest/abort/index.html b/files/es/web/api/xmlhttprequest/abort/index.html new file mode 100644 index 0000000000..de73cb1a5d --- /dev/null +++ b/files/es/web/api/xmlhttprequest/abort/index.html @@ -0,0 +1,120 @@ +--- +title: XMLHttpRequest.abort() +slug: Web/API/XMLHttpRequest/abort +tags: + - AJAX + - API + - HTTP + - HttpRequest + - Referencia + - XHR + - XMLHttpRequest + - abortar + - metodo +translation_of: Web/API/XMLHttpRequest/abort +--- +<p>{{APIRef('XMLHttpRequest')}}</p> + +<p>El método <strong>XMLHttpRequest.abort()</strong> aborta la petición si ha sido enviada. Cuando una petición se aborta, readyState se asigna a 0 (UNSENT), pero el evento <a href="/en-US/docs/Web/Events/readystatechange">readystatechange</a> no se lanza.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">xhrInstance.abort();</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<p>Ninguno.</p> + +<h3 id="Valor_de_retorno">Valor de retorno</h3> + +<p>Vacío.</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush: js">var xhr = new XMLHttpRequest(), + method = "GET", + url = "https://developer.mozilla.org/"; +xhr.open(method,url,true); + +xhr.send(); + +xhr.abort(); +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('XMLHttpRequest', '#the-abort()-method')}}</td> + <td>{{Spec2('XMLHttpRequest')}}</td> + <td>WHATWG living standard</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Mejora</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatChrome(1)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatIe('5')}}<sup>[1]</sup><br> + {{CompatIe('7')}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatSafari('1.2')}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Mejora</th> + <th>Android</th> + <th>Chrome para Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatUnknown}}</td> + <td>1.0</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] This feature was implemented via ActiveXObject(). Internet Explorer implementa el estándar XMLHttpRequest desde la versión 7.</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest">Uso de XMLHttpRequest</a></li> +</ul> diff --git a/files/es/web/api/xmlhttprequest/formdata/index.html b/files/es/web/api/xmlhttprequest/formdata/index.html new file mode 100644 index 0000000000..2ca830daf7 --- /dev/null +++ b/files/es/web/api/xmlhttprequest/formdata/index.html @@ -0,0 +1,84 @@ +--- +title: FormData +slug: Web/API/XMLHttpRequest/FormData +tags: + - API + - FormData + - Interfaz + - Referencia + - XMLHttpRequest +translation_of: Web/API/FormData +--- +<p>{{APIRef("XMLHttpRequest")}}</p> + +<p>La interfaz <strong><code>FormData</code></strong> proporciona una manera sencilla de construir un conjunto de parejas clave/valor que representan los campos de un formulario y sus valores, que pueden ser enviados fácilmente con el método {{domxref("XMLHttpRequest.send()")}}. Utiliza el mismo formato que usaría un formulario si el tipo de codificación fuera <code>"multipart/form-data"</code>.</p> + +<p>También puede pasarse directamente al constructor de {{domxref("URLSearchParams")}} si se quieren generar parámetros de consulta de la misma forma en que lo haría un {{HTMLElement("form")}} si usara un envío <code>GET</code> simple.</p> + +<p>Un objeto que implementa <code>FormData</code> puede usarse directamente en una estructura {{jsxref("Statements/for...of", "for...of")}}, en lugar de {{domxref('FormData.entries()', 'entries()')}}: <code>for (var p of myFormData)</code> es equivalente a <code>for (var p of myFormData.entries())</code>.</p> + +<div class="note"> +<p><strong>Nota</strong>: Esta característica está disponible en <a href="/es/docs/Web/API/Web_Workers_API">Web Workers</a>.</p> +</div> + +<h2 id="Constructor">Constructor</h2> + +<dl> + <dt>{{domxref("FormData.FormData","FormData()")}}</dt> + <dd>Crea un nuevo objeto <code>FormData</code>.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<dl> + <dt>{{domxref("FormData.append()")}}</dt> + <dd>Agrega un nuevo valor a una clave existente dentro de un objeto <code>FormData</code>, o añade la clave si aún no existe.</dd> + <dt>{{domxref("FormData.delete()")}}</dt> + <dd>Elimina una pareja clave/valor de un objeto <code>FormData</code>.</dd> + <dt>{{domxref("FormData.entries()")}}</dt> + <dd>Devuelve un {{jsxref("Iteration_protocols","iterator")}} que permite recorrer todas las parejas clave/valor contenidas en este objeto.</dd> + <dt>{{domxref("FormData.get()")}}</dt> + <dd>Devuelve el primer valor asociado con una clave dada en un objeto <code>FormData</code>.</dd> + <dt>{{domxref("FormData.getAll()")}}</dt> + <dd>Devuelve un array con todos los valores asociados con una clave dada en un objeto <code>FormData</code>.</dd> + <dt>{{domxref("FormData.has()")}}</dt> + <dd>Devuelve un booleano que indica si un objeto <code>FormData</code> contiene una clave determinada.</dd> + <dt>{{domxref("FormData.keys()")}}</dt> + <dd>Devuelve un {{jsxref("Iteration_protocols", "iterator")}} que permite recorrer todas las claves de las parejas clave/valor contenidas en este objeto.</dd> + <dt>{{domxref("FormData.set()")}}</dt> + <dd>Establece un nuevo valor para una clave existente dentro de un objeto <code>FormData</code>, o agrega la clave/valor si aún no existe.</dd> + <dt>{{domxref("FormData.values()")}}</dt> + <dd>Devuelve un {{jsxref("Iteration_protocols", "iterator")}} que permite recorrer todos los valores contenidos en este objeto.</dd> +</dl> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('XMLHttpRequest','#interface-formdata','FormData')}}</td> + <td>{{Spec2('XMLHttpRequest')}}</td> + <td>FormData definido en XHR spec</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + + + +<p>{{Compat("api.FormData")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("XMLHTTPRequest")}}</li> + <li><a href="/en/DOM/XMLHttpRequest/Using_XMLHttpRequest" title="En/Using XMLHttpRequest">Utilización de XMLHttpRequest</a></li> + <li><a href="/es/docs/Web/Guide/Usando_Objetos_FormData" title="en/DOM/XMLHttpRequest/FormData/Using_FormData_objects">Usando objetos FormData</a></li> + <li>{{HTMLElement("Form")}}</li> +</ul> diff --git a/files/es/web/api/xmlhttprequest/index.html b/files/es/web/api/xmlhttprequest/index.html new file mode 100644 index 0000000000..243b3220e6 --- /dev/null +++ b/files/es/web/api/xmlhttprequest/index.html @@ -0,0 +1,428 @@ +--- +title: XMLHttpRequest +slug: Web/API/XMLHttpRequest +tags: + - AJAX + - Todas_las_Categorías + - XMLHttpRequest + - páginas_a_traducir +translation_of: Web/API/XMLHttpRequest +--- +<p><code>XMLHttpRequest</code> es un objeto <a class="internal" href="/en/JavaScript" title="En/JavaScript">JavaScript</a> que fue diseñado por Microsoft y adoptado por Mozilla, Apple y Google. Actualmente es un <a class="external" href="http://www.w3.org/TR/XMLHttpRequest/" title="http://www.w3.org/TR/XMLHttpRequest/">estándar de la W3C</a>. Proporciona una forma fácil de obtener información de una URL sin tener que recargar la página completa. Una página web puede actualizar sólo una parte de la página sin interrumpir lo que el usuario está haciendo. <code style="font-size: 14px;">XMLHttpRequest</code> es ampliamente usado en la programación AJAX.</p> + +<p><span style="line-height: 1.5;">A pesar de su nombre, </span><code style="font-size: 14px;">XMLHttpRequest</code><span style="line-height: 1.5;"> puede ser usado para recibir cualquier tipo de dato, no solo XML, y admite otros formatos además de </span><a href="/en/HTTP" style="line-height: 1.5;" title="en/HTTP">HTTP</a><span style="line-height: 1.5;"> (incluyendo </span><code style="font-size: 14px;">file</code><span style="line-height: 1.5;"> y </span><code style="font-size: 14px;">ftp</code><span style="line-height: 1.5;">).</span></p> + +<p>Para crear una instancia de <code>XMLHttpRequest</code>, debes hacer lo siguiente:</p> + +<pre>var req = new XMLHttpRequest(); +</pre> + +<p>Para obtener más información de cómo usar <code>XMLHttpRequest</code>, mira <a class="internal" href="/Es/XMLHttpRequest/Using_XMLHttpRequest" title="En/Using XMLHttpRequest">Usar XMLHttpRequest</a>.</p> + +<div class="note"><strong>Nota:</strong> De forma predeterminada, Firefox 3 limita la cantidad de conexiones de <code>XMLHttpRequest</code> por servidor a 6 (las versiones previas limitan a 2 conexiones por servidor). Algunos sitios web interactivos pueden mantener una conexión <code>XMLHttpRequest</code> abierta, así que abrir múltiples sesiones a esos sitios puede derivar en congelamientos del navegador de una forma que la ventana no se actualiza y los controles no responden. Este valor puede ser cambiado al editar la preferencia <code>network.http.max-persistent-connections-per-server</code> en <code><a class="linkification-ext" href="/about:config" title="Linkification: about:config">about:config</a></code>.</div> + +<h2 id="Resumen_del_método">Resumen del método</h2> + +<table class="standard-table"> + <tbody> + <tr> + <td><code>void <a class="internal" href="/en/XMLHttpRequest#abort()" title="/En/XMLHttpRequest#abort()">abort</a>();</code></td> + </tr> + <tr> + <td><code>string <a class="internal" href="/en/XMLHttpRequest#getAllResponseHeaders()" title="/en/XMLHttpRequest#getAllResponseHeaders()">getAllResponseHeaders</a>();</code></td> + </tr> + <tr> + <td><code>ACString <a class="internal" href="/en/XMLHttpRequest#getResponseHeader()" title="/en/XMLHttpRequest#getResponseHeader()">getResponseHeader</a>(in AUTF8String header);</code></td> + </tr> + <tr> + <td><code>[noscript] void <a class="internal" href="/en/XMLHttpRequest#init()" title="/en/XMLHttpRequest#init()">init</a>(in nsIPrincipal principal, in nsIScriptContext scriptContext, in nsPIDOMWindow ownerWindow);</code></td> + </tr> + <tr> + <td><code>void <a class="internal" href="/en/XMLHttpRequest#open()" title="/en/XMLHttpRequest#open()">open</a>(in AUTF8String method, in AUTF8String url);</code></td> + </tr> + <tr> + <td><code>[noscript] void <a class="internal" href="/en/XMLHttpRequest#openRequest()" title="/en/XMLHttpRequest#openRequest()">openRequest</a>(in AUTF8String method, in AUTF8String url, in boolean async, in AString user, in AString password);</code></td> + </tr> + <tr> + <td><code>void <a class="internal" href="/en/XMLHttpRequest#overrideMimeType()" title="/en/XMLHttpRequest#overrideMimeType()">overrideMimeType</a>(in AUTF8String mimetype);</code></td> + </tr> + <tr> + <td><code>void <a class="internal" href="/en/XMLHttpRequest#send()" title="/en/XMLHttpRequest#send()">send</a>([optional] in nsIVariant body);</code></td> + </tr> + <tr> + <td><code>void <a class="internal" href="/en/XMLHttpRequest#sendAsBinary()" title="/en/XMLHttpRequest#sendAsBinary()">sendAsBinary</a>(in DOMString body); {{ fx_minversion_inline(3) }}</code></td> + </tr> + <tr> + <td><code>void <a class="internal" href="/en/XMLHttpRequest#setRequestHeader()" title="/en/XMLHttpRequest#setRequestHeader()">setRequestHeader</a>(in AUTF8String header, in AUTF8String value);</code></td> + </tr> + </tbody> +</table> + +<h2 id="Propiedades">Propiedades</h2> + +<table class="standard-table"> + <tbody> + <tr> + <td class="header">Atributo</td> + <td class="header">Tipo</td> + <td class="header">Descripción</td> + </tr> + <tr> + <td><code>channel</code></td> + <td>{{ Interface("nsIChannel") }}</td> + <td>El canal es usado por el objeto cuando se produce el pedido. Esto da <code>null</code> si el canal aún no fue creado. En el caso de un pedido de múltiples partes, este es el canal inicial, no las diferentes partes del pedido múltiple. <strong>Es necesario tener privilegios elevados para acceder; sólo lectura.</strong> {{ Non-standard_inline() }}</td> + </tr> + <tr> + <td><code>mozBackgroundRequest</code></td> + <td><code>booleano</code></td> + <td> + <p>Indica si el objeto representa o no un pedido de un servicio de fondo. Si es <code>true</code>, no se asocia una carga de grupo con el pedido, y los diálogos de seguridad no se muestran al usuario. <strong>Es necesario tener privilegios elevados para acceder. </strong>{{ Non-standard_inline() }}</p> + + <p>En los casos en que un diálogo de seguridad debe ser mostrado (como en una autentficación o la notificación de un certificado no válido), el pedido simplemente falla.</p> + </td> + </tr> + <tr> + <td><code>mozResponseArrayBuffer</code> {{ non-standard_inline() }}</td> + <td><a href="/en/JavaScript_typed_arrays/ArrayBuffer" title="en/JavaScript typed arrays/ArrayBuffer"><code>ArrayBuffer</code></a></td> + <td>La respuesta al pedido en la forma de un arreglo de JavaScript. Esto es NULL si el pedido no fue exitoso o si todavía no ha sido enviado. <strong>Sólo lectura.</strong></td> + </tr> + <tr> + <td><code>multipart</code></td> + <td><code>booleano</code></td> + <td> + <p>Indica cuando se espera que la respuesta sea o no una serie de mútiples documentos XML. Si se define como <code>true</code>, el tipo de contenido de la respuesta inicial debe ser <code>multipart/x-mixed-replace</code> u ocurrirá un error. Todos los pedidos deben ser asincrónicos.</p> + + <p>Esto permite el uso del push del servidor; para cada documento XML que se escribe para este pedido, se crea un nuevo XMLDOMdocument y se llama al manejador <code>onload</code> entre cada documento.</p> + + <div class="note"><strong>Nota:</strong> Cuando esto se elige, el manejador <code>onload</code> y otros manejadores de eventos no son reiniciados después de que el primer XMLdocument es cargado, y el manejador <code>onload</code> es llamado después de que cada parte de la respuesta es recibida.</div> + </td> + </tr> + <tr id="onreadystatechange"> + <td> + <p><code>onreadystatechange</code></p> + </td> + <td>{{ Interface("nsIDOMEventListener") }}</td> + <td> + <p>Una función del objeto JavaScript que se llama cuando el atributo <code>readyState</code> cambia. El callback se llama desde la interfaz del usuario.</p> + + <div class="warning"><strong>Aviso: </strong>Esto no debe ser usado desde código nativo. Tampoco debes usarlo con pedidos sincrónicos.</div> + </td> + </tr> + <tr id="readyState"> + <td><code>readyState</code></td> + <td><code>long</code></td> + <td> + <p>El estado del pedido:</p> + + <table class="standard-table"> + <tbody> + <tr> + <td class="header">Valor</td> + <td class="header">Estado</td> + <td class="header">Descripción</td> + </tr> + <tr> + <td><code>0</code></td> + <td><code>UNINITIALIZED</code></td> + <td>todavía no se llamó a <code>open()</code>.</td> + </tr> + <tr> + <td><code>1</code></td> + <td><code>LOADING</code></td> + <td>todavía no se llamó a <code>send()</code>.</td> + </tr> + <tr> + <td><code>2</code></td> + <td><code>LOADED</code></td> + <td><code>send()</code> ya fue invocado, y los encabezados y el estado están disponibles.</td> + </tr> + <tr> + <td><code>3</code></td> + <td><code>INTERACTIVE</code></td> + <td>Descargando; <code>responseText</code> contiene información parcial.</td> + </tr> + <tr> + <td><code>4</code></td> + <td><code>COMPLETED</code></td> + <td>La operación está terminada.</td> + </tr> + </tbody> + </table> + </td> + </tr> + <tr id="responseText"> + <td><code>responseText</code></td> + <td><code>AString</code></td> + <td>La respuesta al pedido como texto, o <code>null</code> si el pedido no fue exitoso o todavía no se envió. <strong>Sólo lectura.</strong></td> + </tr> + <tr id="responseXML"> + <td><code>responseXML</code></td> + <td><code>nsIDOMDocument</code></td> + <td> + <p>La respuesta al pedido como un objeto DOM<code><a class="internal" href="/en/DOM/document" title="En/DOM/Document">Document</a></code>, o <code>null</code> si el pedido no fue exitoso, aún no fue enviado o no puede ser analizado como XML. La respuesta es analizada como si fuera <code>text/xml</code>. <strong>Sólo lectura.</strong></p> + + <div class="note"><strong>Nota:</strong> Si el servidor no aplica el encabezado de tipo de contenido <code>text/xml</code>, puedes usar <code>overrideMimeType()</code> para forzar a <code>XMLHttpRequest</code> a analizarlo como XML igualmente.</div> + </td> + </tr> + <tr id="status"> + <td><code>status</code></td> + <td><code>unsigned long</code></td> + <td>El estado de la respuesta al pedido. Éste es el código HTTPresult (por ejemplo, <code>status</code> es 200 por un pedido exitoso). <strong>Sólo lectura.</strong></td> + </tr> + <tr> + <td><code>statusText</code></td> + <td><code>AUTF8String</code></td> + <td>La cadena de respuesta que devuelve el HTTPserver. A diferencia de <code>status</code>, este incluye el texto completo del mensaje de respuesta ("<code>200 OK</code>", por ejemplo). <strong>Sólo lectura.</strong></td> + </tr> + <tr> + <td><code>upload</code></td> + <td>{{ Interface("nsIXMLHttpRequestUpload") }}</td> + <td>El proceso de subida puede ser rastreado al agregar un registro de evento a <code>upload</code>. {{ fx_minversion_inline(3.5) }}</td> + </tr> + <tr> + <td><code>withCredentials</code></td> + <td><code>booleano</code></td> + <td> + <p>Indica cuando el pedido de Access-Control entre sitios debe o no ser realizado usando credenciales como cookies o encabezados de autorización. {{ fx_minversion_inline(3.5) }}</p> + + <div class="note"><strong>Nota:</strong> Esto nunca afecta los pedidos en para el propio sitio.</div> + + <p>El valor predeterminado es <code>false</code>.</p> + </td> + </tr> + </tbody> +</table> + +<h2 id="Métodos">Métodos</h2> + +<h3 id="abort()">abort()</h3> + +<p>Aborta el pedido si éste ya fue enviado.</p> + +<pre>void abort(); +</pre> + +<h6 id="Parámetros">Parámetros</h6> + +<p>Ninguno.</p> + +<h3 id="getAllResponseHeaders()">getAllResponseHeaders()</h3> + +<p>Devuelve todos los encabezados de respuesta como una cadena.</p> + +<div class="note"><strong>Nota:</strong> Para pedidos multi partes, esto devuelve los encabezados de la parte <em>actual</em> del pedido, no del canal original.</div> + +<pre>string getAllResponseHeaders(); +</pre> + +<h6 id="Parámetros_2">Parámetros</h6> + +<p>Ninguno.</p> + +<h6 id="Valor_devuelto">Valor devuelto</h6> + +<p>El texto de todos los encabezados de respuesta, o <code>null</code> si no se ha recibido ninguna respuesta.</p> + +<h3 id="getResponseHeader()">getResponseHeader()</h3> + +<p>Devuelve el texto de un encabezado específico.</p> + +<pre>ACString getResponseHeader( + in AUTF8String header +); +</pre> + +<h6 id="Parámetros_3">Parámetros</h6> + +<dl> + <dt><code>header</code></dt> + <dd>El nombre del encabezado buscado.</dd> +</dl> + +<h6 id="Valor_devuelto_2">Valor devuelto</h6> + +<p>Una cadena que contiene el texto de un encabezado específico, o <code>null</code> tanto si la respuesta no se ha recibido o el encabezado no existe en la respuesta.</p> + +<h3 id="init()">init()</h3> + +<p>Inicializa el objeto para que sea usado desde código C++.</p> + +<div class="warning"><strong>Aviso:</strong> Este método <em>no</em> debe ser llamado desde JavaScript.</div> + +<pre>[noscript] void init( + in nsIPrincipal principal, + in nsIScriptContext scriptContext, + in nsPIDOMWindow ownerWindow +); +</pre> + +<h6 id="Parámetros_4">Parámetros</h6> + +<dl> + <dt><code>principal</code></dt> + <dd>El principal para usar en el pedido; no debe ser <code>null</code>.</dd> + <dt><code>scriptContext</code></dt> + <dd>El contexto del programa que usará en el pedido; no debe ser <code>null</code>.</dd> + <dt><code>ownerWindow</code></dt> + <dd>La ventana asociada con el pedido; puede ser <code>null</code>.</dd> +</dl> + +<h3 id="open()">open()</h3> + +<p>Inicializa el pedido. Este método es para ser usado desde código JavaScript, para inicializar un pedido desde código nativo, debes usar <a class="internal" href="/en/XMLHttpRequest#openRequest()" title="/en/XMLHttpRequest#openRequest()"><code>openRequest()</code></a>.</p> + +<div class="note"><strong>Nota:</strong> Llamar a este método en un pedido activo (uno para el cual <code>open()</code> o <code>openRequest()</code> ya han sido llamados) es equivalente a usar <code>abort()</code>.</div> + +<pre>void open( + in AUTF8String method, + in AUTF8String url, + [optional] in boolean async, + [optional] in AString user, + [optional] in AString password +); +</pre> + +<h6 id="Parámetros_5">Parámetros</h6> + +<dl> + <dt><code>method</code></dt> + <dd>El método HTTP a usar: tanto "POST" o "GET". Se ignora para urls que no son de HTTP.</dd> + <dt><code>url</code></dt> + <dd>La URL a la que se envía el pedido.</dd> + <dt><code>async</code></dt> + <dd><span id="result_box" lang="es"><span>Un parámetro booleano opcional, predeterminado es <code>true</code>, que indica si se debe o no realizar la operación de forma asíncrona.</span> <span>Si este valor es <code>false</code>, el método <code>send()</code> no se devuelve hasta que se reciba la respuesta completa.</span> <span>Si es <code>true</code>, la notificación de una transacción completada se proporciona mediante los oyentes de eventos.</span> <span>Esto debe ser <code>true</code> si el atributo <code>multipart</code> es verdadero o se lanzará una excepción.</span></span></dd> + <dt><code>user</code></dt> + <dd><span id="result_box" lang="es"><span>El nombre de usuario es opcional solo es usado con fines de autenticación,</span> <span>de forma predeterminada es una cadena vacía.</span></span></dd> + <dt><code>password</code></dt> + <dd><span id="result_box" lang="es"><span>La contraseña es opcional solo es usado con fines de autenticación,</span> <span>de forma predeterminada es una cadena vacía.</span></span></dd> +</dl> + +<h3 id="openRequest()">openRequest()</h3> + +<p>Inicia la peticion, este metodo est</p> + +<p><span id="result_box" lang="es"><span>Inicializa la peticion.</span> <span>Este método se utiliza desde el código nativo,</span> <span>para inicializar una solicitud desde el código JavaScript, utilice <code>open ()</code> en su lugar.</span></span></p> + +<div class="note"><strong>Nota:</strong> Calling this method an already active request (one for which <code>open()</code>or <code>openRequest()</code>has already been called) is the equivalent of calling <code>abort()</code>.</div> + +<pre>void open( + in AUTF8String method, + in AUTF8String url, + in boolean async, + in AString user, + in AString password +); +</pre> + +<h6 id="Parameters">Parameters</h6> + +<dl> + <dt><code>method</code></dt> + <dd>The HTTPmethod to use; either "POST"or "GET". Ignored for non-HTTPURLs.</dd> + <dt><code>url</code></dt> + <dd>The URLto which to send the request.</dd> + <dt><code>async</code></dt> + <dd>An optional boolean parameter, defaulting to <code>true</code>, indicating whether or not to perform the operation asynchronously. If this value is <code>false</code>, the <code>send()</code>method does not return until the response is received. If <code>true</code>, notification of a completed transaction is provided using event listeners. This <em>must</em> be true if the <code>multipart</code> attribute is <code>true</code>, or an exception will be thrown.</dd> + <dt><code>user</code></dt> + <dd>The optional user name to use for authentication purposes; by default, this is an empty string.</dd> + <dt><code>password</code></dt> + <dd>The optional password to use for authentication purposes; by default, this is an empty string.</dd> +</dl> + +<h3 id="overrideMimeType()">overrideMimeType()</h3> + +<p>Overrides the MIMEtype returned by the server.</p> + +<div class="note"><strong>Note:</strong> This method must be called before <code>send()</code>.</div> + +<pre>void overrideMimeType( + in AUTF8String mimetype +); +</pre> + +<h6 id="Parameters_2">Parameters</h6> + +<dl> + <dt><code>mimetype</code></dt> + <dd>The type that should be used instead of the one returned by the server, if any.</dd> +</dl> + +<h3 id="send()">send()</h3> + +<p>Sends the request. If the request is asynchronous (which is the default), this method returns as soon as the request is sent. If the request is synchronous, this method doesn't return until the response has arrived.</p> + +<div class="note"><strong>Note:</strong> Any event listeners you wish to set must be set before calling <code>send()</code>.</div> + +<pre>void send( + [optional] in nsIVariant body +); +</pre> + +<h6 id="Parameters_3">Parameters</h6> + +<dl> + <dt><code>body</code></dt> + <dd>This may be an <code>nsIDocument</code>, <code>nsIInputStream</code>, or a string (an <code>nsISupportsString</code> if called from native code) that is used to populate the body of a POST request. Starting with Gecko 1.9.2, you may also specify an DOM{{ domxref("File") }} , and starting with Gecko 2.0 {{ geckoRelease("2.0") }} you may also specify a <a href="/en/XMLHttpRequest/FormData" title="en/XMLHttpRequest/FormData"><code>FormData</code></a> object.</dd> +</dl> + +<h6 id="Notes">Notes</h6> + +<p>If the body is an <code>nsIDOMDocument</code>, it is serialized before being sent.</p> + +<p>If it's an <code>nsIInputStream</code>, it must be compatible with <code>nsIUploadChannel</code>'s <code>setUploadStream()</code>method. In that case, a Content-Length header is added to the request, with its value obtained using <code>nsIInputStream</code>'s <code>available()</code>method. Any headers included at the top of the stream are treated as part of the message body. The stream's MIMEtype should be specified by setting the Content-Type header using the <a class="internal" href="/en/XMLHttpRequest#setRequestHeader()" title="/en/XMLHttpRequest#setRequestHeader()"><code>setRequestHeader()</code></a>method prior to calling <code>send()</code>.</p> + +<h3 id="sendAsBinary()">sendAsBinary()</h3> + +<p>A variant of the <code>send()</code>method that sends binary data.</p> + +<pre>void sendAsBinary( + in DOMString body +); +</pre> + +<h6 id="Parameters_4">Parameters</h6> + +<dl> + <dt><code>body</code></dt> + <dd>The request body as a DOMstring. This data is converted to a string of single-byte characters by truncation (removing the high-order byte of each character).</dd> +</dl> + +<h3 id="setRequestHeader()">setRequestHeader()</h3> + +<p>Sets the value of an HTTPrequest header.</p> + +<div class="note"><strong>Note:</strong> You must call <a class="internal" href="/en/XMLHttpRequest#open()" title="/en/XMLHttpRequest#open()"><code>open()</code></a>before using this method.</div> + +<pre>void setRequestHeader( + in AUTF8String header, + in AUTF8String value +); +</pre> + +<h6 id="Parameters_5">Parameters</h6> + +<dl> + <dt><code>header</code></dt> + <dd>The name of the header whose value is to be set.</dd> + <dt><code>value</code></dt> + <dd>The value to set as the body of the header.</dd> +</dl> + +<h2 id="Implementation_notes">Implementation notes</h2> + +<p><code>XMLHttpRequest</code> is implemented in Gecko using the {{ interface("nsIJSXMLHttpRequest") }} and {{ interface("nsIXMLHttpRequest") }} interfaces.</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a class="internal" href="/En/XMLHttpRequest/Using_XMLHttpRequest" title="En/Using XMLHttpRequest">Using XMLHttpRequest</a></li> + <li><a href="/en/XMLHttpRequest/FormData" title="en/XMLHttpRequest/FormData"><code>FormData</code></a></li> + <li><a href="/en/AJAX/Getting_Started" title="en/AJAX/Getting_Started">MDC AJAX introduction</a></li> + <li><a class="external" href="http://www.peej.co.uk/articles/rich-user-experience.html">XMLHttpRequest - REST and the Rich User Experience</a></li> + <li><a class="external" href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/xmlsdk/html/xmobjxmlhttprequest.asp">Microsoft documentation</a></li> + <li><a class="external" href="http://developer.apple.com/internet/webcontent/xmlhttpreq.html">Apple developers' reference</a></li> + <li><a class="external" href="http://jibbering.com/2002/4/httprequest.html">"Using the XMLHttpRequest Object" (jibbering.com)</a></li> + <li><a class="external" href="http://www.w3.org/TR/XMLHttpRequest/">The XMLHttpRequest Object: W3C Working Draft</a></li> +</ul> + +<p>{{ languages( { "es": "es/XMLHttpRequest", "fr": "fr/XMLHttpRequest", "it": "it/XMLHttpRequest", "ja": "ja/XMLHttpRequest", "ko": "ko/XMLHttpRequest", "pl": "pl/XMLHttpRequest", "zh-cn": "cn/XMLHttpRequest" } ) }}</p> diff --git a/files/es/web/api/xmlhttprequest/onreadystatechange/index.html b/files/es/web/api/xmlhttprequest/onreadystatechange/index.html new file mode 100644 index 0000000000..7f35ad3e88 --- /dev/null +++ b/files/es/web/api/xmlhttprequest/onreadystatechange/index.html @@ -0,0 +1,109 @@ +--- +title: XMLHttpRequest.onreadystatechange +slug: Web/API/XMLHttpRequest/onreadystatechange +translation_of: Web/API/XMLHttpRequest/onreadystatechange +--- +<div>{{APIRef}}</div> + +<p>Un <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventHandler" title="A possible way to get notified of Events of a particular type (such as click) for a given object is to specify an event handler using:"><code>EventHandler</code></a> que es invocado cada vez que cambia el atributo <code>readyState</code>. La retrollamada (callback) es invocada desde el hilo (thread) perteneciente a la interfaz de usuario. La propiedad <strong><code>XMLHttpRequest.onreadystatechange</code></strong> contiene el manejador del evento que es invocado cuando se dispara el evento {{event("readystatechange")}}, lo cual sucede cada vez que cambia el valor de la propiedad {{domxref("XMLHttpRequest.readyState", "readyState")}} de {{domxref("XMLHttpRequest")}}. La retrollamada (callback) es invocada desde el hilo perteneciente a la interfaz de usuario.</p> + +<div class="warning"> +<p><strong>Aviso:</strong> No debería ser usado con peticiones síncronas ni tampoco en código nativo.</p> +</div> + +<p>El evento <code>readystatechange</code> no se disparará cuando una petición <code>XMLHttpRequest</code> sea cancelada mediante el método <a href="/en-US/docs/Web/API/XMLHttpRequest/abort">abort()</a>.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox"><em>XMLHttpRequest</em>.onreadystatechange = <em>callback</em>;</pre> + +<h3 id="Valores">Valores</h3> + +<ul> + <li><code><em>callback</em></code> es la función de retrollamada que será ejecutada (invocada) cuando cambie el valor de la propiedad <code>readyState</code>.</li> +</ul> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre class="brush: js">var xhr = new XMLHttpRequest(), + method = "GET", + url = "https://developer.mozilla.org/"; + +xhr.open(<em>method</em>, <em>url</em>, true); +xhr.onreadystatechange = function () { + if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) { + console.log(xhr.responseText); + } + }; +xhr.send();</pre> + +<h2 id="Especificaciones">Especificaciones</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('XMLHttpRequest', '#handler-xhr-onreadystatechange')}}</td> + <td>{{Spec2('XMLHttpRequest')}}</td> + <td>WHATWG living standard</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores_Web">Compatibilidad con navegadores Web</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>{{CompatChrome(1)}}</td> + <td>{{CompatGeckoDesktop(1.0)}}</td> + <td>{{CompatIe(7)}}<sup>[1]</sup></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatSafari(1.2)}}</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>{{CompatUnknown}}</td> + <td>1.0</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Las versiones 5 y 6 admiten llamadas AJAX usando <code>ActiveXObject()</code>.</p> diff --git a/files/es/web/api/xmlhttprequest/responsetext/index.html b/files/es/web/api/xmlhttprequest/responsetext/index.html new file mode 100644 index 0000000000..d119565243 --- /dev/null +++ b/files/es/web/api/xmlhttprequest/responsetext/index.html @@ -0,0 +1,104 @@ +--- +title: XMLHttpRequest.responseText +slug: Web/API/XMLHttpRequest/responseText +translation_of: Web/API/XMLHttpRequest/responseText +--- +<div>{{draft}}</div> + +<div>{{APIRef('XMLHttpRequest')}}</div> + +<p>La propiedad <strong><code>XMLHttpRequest.responseText</code></strong> devuelve un <strong><code>DOMString</code></strong> que contiene la respuesta a la consulta como un texto o null si la consulta no tuvo exito o aun no ha sido completada. la propiedad <strong><code>responseText</code> </strong> tendra una respuesta parcial como retorno aunque la consulta no haya sido completada. si <strong>responseType</strong> contiene algo que no sea un string vacio o un "text", el acceso a <strong>responseText</strong> sera <strong>throw <code>InvalidStateError</code> exception</strong>.</p> + +<h2 id="Ejemplo._Lanza_una_excepción_InvalidStateError">Ejemplo. Lanza una excepción <strong><code>InvalidStateError</code></strong></h2> + +<pre class="brush: js">var xhr = new XMLHttpRequest(); +xhr.open('GET', '/server', true); + +// If specified, responseType must be empty string or "text" +xhr.responseType = 'text'; + +xhr.onload = function () { + if (xhr.readyState === xhr.DONE) { + if (xhr.status === 200) { + console.log(xhr.response); + console.log(xhr.responseText); + } + } +}; + +xhr.send(null);</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificaciones</th> + <th scope="col">estado</th> + <th scope="col">Comentarios</th> + </tr> + <tr> + <td>{{SpecName('XMLHttpRequest', '#the-responsetext-attribute')}}</td> + <td>{{Spec2('XMLHttpRequest')}}</td> + <td>WHATWG living standard</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}<sup>[1]</sup></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</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>Edge</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>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Anteriores a IE 10, El valo de XMLHttpRequest.responseText debe ser leido una vez que la consulta fuera completada.</p> 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 new file mode 100644 index 0000000000..28675abd79 --- /dev/null +++ b/files/es/web/api/xmlhttprequest/synchronous_and_asynchronous_requests/index.html @@ -0,0 +1,232 @@ +--- +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> diff --git a/files/es/web/api/xmlhttprequest/timeout/index.html b/files/es/web/api/xmlhttprequest/timeout/index.html new file mode 100644 index 0000000000..a9fec94792 --- /dev/null +++ b/files/es/web/api/xmlhttprequest/timeout/index.html @@ -0,0 +1,67 @@ +--- +title: XMLHttpRequest.timeout +slug: Web/API/XMLHttpRequest/timeout +tags: + - AJAX + - Propiedad + - Referencia + - XHR + - XHR asincrónico + - XMLHttpRequest + - XMLHttpRequest asincrónico + - tiempo de espera + - timeout +translation_of: Web/API/XMLHttpRequest/timeout +--- +<div>{{APIRef('XMLHttpRequest')}}</div> + +<p>La propiedad <code><strong>XMLHttpRequest.timeout</strong></code> es un <code>unsigned long</code> que representa el número de milisegundos que puede tomar una solicitud antes de que se finalice automáticamente. El valor por defecto es 0, lo que significa que no hay tiempo de espera (<em>timeout</em>). <em>Timeout</em> no debe utilizarse para solicitudes XMLHttpRequests sincrónicas usadas en un {{Glossary('document environment')}}, pues generará una excepción <code>InvalidAccessError</code>. Cuando ocurre un tiempo de espera, se dispara un evento <a href="/en-US/docs/Web/Events/timeout">timeout</a>. {{gecko_minversion_inline("12.0")}}</p> + +<dl> + <dd> + <div class="note"><strong>Nota:</strong> No puede usar un <em>timeout</em> para solicitudes sincrónicas con una ventana propietaria (<em>owning window</em>).</div> + </dd> + <dd><a href="/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests#Example_using_a_timeout">Uso de <em>timeout</em> con una solicitud asincrónica</a></dd> +</dl> + +<p>En Internet Explorer, la propiedad <em>timeout</em> se puede establecer solo después de llamar al método <a href="/en-US/docs/Web/API/XMLHttpRequest/open">open()</a> y antes de llamar al método <a href="/en-US/docs/Web/API/XMLHttpRequest/send">send()</a>.</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush: js">var xhr = new XMLHttpRequest(); +xhr.open('GET', '/server', true); + +xhr.timeout = 2000; // tiempo en milisegundos + +xhr.onload = function () { + // Solicitud finalizada. Haz el procesamiento aquí. +}; + +xhr.ontimeout = function (e) { + // Tiempo de espera del XMLHttpRequest agotado. Haz algo aquí. +}; + +xhr.send(null);</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('XMLHttpRequest', '#the-timeout-attribute')}}</td> + <td>{{Spec2('XMLHttpRequest')}}</td> + <td>WHATWG living standard</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<div class="hidden">La tabla de compatibilidad en esta página se genera a partir de datos estructurados. Si desea contribuir con los datos, consulte <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> y envíenos un <em>pull request</em>.</div> + +<p>{{Compat("api.XMLHttpRequest.timeout")}}</p> diff --git a/files/es/web/api/xmlhttprequest/using_xmlhttprequest/index.html b/files/es/web/api/xmlhttprequest/using_xmlhttprequest/index.html new file mode 100644 index 0000000000..c3d2b48e7f --- /dev/null +++ b/files/es/web/api/xmlhttprequest/using_xmlhttprequest/index.html @@ -0,0 +1,447 @@ +--- +title: Using XMLHttpRequest +slug: Web/API/XMLHttpRequest/Using_XMLHttpRequest +translation_of: Web/API/XMLHttpRequest/Using_XMLHttpRequest +--- +<p>{{APIRef("XMLHttpRequest")}}</p> + +<p><span class="seoSummary">En esta guía le echaremos un vistazo a cómo usar {{domxref("XMLHttpRequest")}} para enviar solicitudes <a href="https://wiki.developer.mozilla.org/en-US/docs/Web/HTTP">HTTP</a> con el objetivo de intercambiar datos entre el sitio web y el servidor.</span> Se incluyen ejemplos, tanto para los casos de uso comunes de <code>XMLHttpRequest</code>, como para los más inusuales.</p> + +<p>Para enviar una solicitud HTTP, cree un objeto <code>XMLHttpRequest</code>, abra una URL y envíe la solicitud. Una vez que la transacción haya sido completada, el objeto contendrá información útil tal como el cuerpo de la respuesta y el estado <a href="/en-US/docs/Web/HTTP/Status">HTTP</a> del resultado.</p> + +<pre class="brush: js">function reqListener () { + console.log(this.responseText); +} + +var oReq = new XMLHttpRequest(); +oReq.addEventListener("load", reqListener); +oReq.open("GET", "http://www.example.org/example.txt"); +oReq.send();</pre> + +<h2 id="Solicitudes_Síncronas_y_Asíncronas">Solicitudes Síncronas y Asíncronas</h2> + +<p><code>XMLHttpRequest</code> soporta tanto comunicaciones síncronas como asíncronas.</p> + +<div class="note"><strong>Nota:</strong> No deberias usar <code>XMLHttpRequests</code> síncronas porque, dada la naturaleza inherentemente asíncrona del intercambio de datos en las redes, hay multiples formas en que la memoria y eventos se puedan perder usando solicitudes síncronas.</div> + +<p>En versiones de Firefox anteriores a Firefox 3, (solicitudes) <code>XMLHttpRequest</code> síncronas bloqueaban la interfaz de usuario. Con tal de permitirle al usuario terminar solicitudes congeladas, Firefox 3 ya no lo hace.</p> + +<h3 id="Ejemplo_Solicitud_síncrona">Ejemplo: Solicitud síncrona</h3> + +<p>Este ejemplo demuestra como hacer una solicitud síncrona.</p> + +<pre class="script deki-transform">var req = new XMLHttpRequest(); +req.open('GET', 'http://www.mozilla.org/', false); +req.send(null); +if (req.status == 200) + dump(req.responseText);</pre> + +<p>En la línea 1 se instancia un objeto <code>XMLHttpRequest</code>. Después en la línea 2 se abre una nueva solicitud, especificando que una solicitud <code>GET</code> se utilizará para extraer la pagina de inicio de Mozilla.org, y que la operación no debe ser asíncrona.</p> + +<p>En la línea 3 se envía la solicitud. El parámetro <code>null</code> indica que la solicitud <code>GET</code> no necesita contenido en el cuerpo.</p> + +<p>En la línea 4 se verifica el código de estatus después de que la transacción se completa. Si el resultado es 200 -- El código HTTP para resultado "OK"-- el contenido de texto del documento se escribe en la consola.</p> + +<h3 id="Ejemplo_Solicitudes_síncronas_no-HTTP">Ejemplo: Solicitudes síncronas no-HTTP</h3> + +<p>A pesar de su nombre, <code>XMLHttpRequest</code> se puede usar para hacer solicitudes que no sean de HTTP. Este ejemplo muestra como usarlo para extraer un archivo del sistemas de archivos local.</p> + +<pre class="script">var req = new XMLHttpRequest(); +req.open('GET', '<a class="linkification-ext" title="Linkification: file:///home/user/file.json">file:///home/user/file.json</a>', false); +req.send(null); +if(req.status == 0) + dump(req.responseText);</pre> + +<p>La clave aqui es notar que el estado del resultado se compara con 0 en lugar de 200. Esto es porque los esquemas <code>file</code> y <code>ftp</code> no usan los codigos de resultado de HTTP.</p> + +<h3 id="Ejemplo_Solicitudes_asíncronas">Ejemplo: Solicitudes asíncronas</h3> + +<p>Si usas <code>XMLHttpRequest</code> desde una extensión, deberias usarla asíncronamente. En este caso, recibiras una llamada de regreso cuando se hallan recibido los datos, lo cual permite al navegador continuar trabajando con normalidad mientras se maneja tu solicitud.</p> + +<pre class="script">var req = new XMLHttpRequest(); +req.open('GET', 'http://www.mozilla.org/', true); +req.onreadystatechange = function (aEvt) { + if (req.readyState == 4) { + if(req.status == 200) + dump(req.responseText); + else + dump("Error loading page\n"); + } +}; +req.send(null); </pre> + +<p>La linea 2 especifica <code>true</code> en su tercer parametro indicando que la solicitud debe manejarse asíncronamente.</p> + +<p>Line 3 crea un objeto función para manejar eventos y lo asigna al atributo de la solicitud <code>onreadystatechange</code>. Este manejador observa el <code>readyState</code> de la solicitud verificando si la transacción se ha completado en la linea 4, si así es, y el estatus HTTP es 200, imprime el contenido recibido. Si ocurrió un error, se muestra un mensaje de error.</p> + +<p>La linea 11 de hecho inicia la solicitud. La función onreadystatechange es llamada siempre que el estado de una solicitud cambia.</p> + +<h2 id="Analizando_y_Manipulando_el_Texto_de_Respuesta_HTML">Analizando y Manipulando el Texto de Respuesta HTML</h2> + +<p>Si usas <code>XMLHttpRequest para obtener el contenido de una página</code> HTML remota, el <code>responseText </code>(texto de la respuesta) sera una cadena que contenga una "sopa" de etiquetas HTML, lo que puede ser dificil de analizar y manipular. Existen tres maneras principales de analizar estas cadenas HTML</p> + +<ol> + <li><a href="/en/Code_snippets/HTML_to_DOM#Safely_parsing_simple_HTML.c2.a0to_DOM" title="https://developer.mozilla.org/en/Code_snippets/HTML_to_DOM#Safely_parsing_simple_HTML.c2.a0to_DOM">Analizar con nsIScriptableUnescapeHTML </a>repidamente convertira la cadena HTML en DOM, al mismo tiempo que tira javascript y otros elementos avanzados, incluyendo la etiqueta <code><head></code> de la página.</li> + <li><a href="/es/Referencia_de_JavaScript_1.5/Objetos_globales/RegExp" title="es/Referencia de JavaScript 1.5/Objetos globales/RegExp">RegExp </a>se puede usar si de antemano conoces el HTML que vendra en el <code>responseText</code>. Quizas quieras remover los saltos de linea, si usas RegExp para escanear considerandolos. Sin embargo, este metodo es un "ultimo recurso" ya que si el HTML cambia ligeramente, posiblemente fallara.</li> + <li><a href="/en/Code_snippets/HTML_to_DOM#Using_a_hidden_iframe_element_to_parse_HTML_to_a_window%27s_DOM" title="https://developer.mozilla.org/en/Code_snippets/HTML_to_DOM#Using_a_hidden_iframe_element_to_parse_HTML_to_a_window's_DOM">Usar un hidden chrome o un content-level iframe</a> para cargar toda la pagina también se puede hacer para manipularla luego como DOM, sin embargo existen <a href="/En/Displaying_web_content_in_an_extension_without_security_issues" title="En/Displaying_web_content_in_an_extension_without_security_issues">riesgos de seguridad al dar a código remoto este nivel de acceso privilegiado</a>, que puede causar <a class="link-https" href="https://addons.mozilla.org/en-US/developers/docs/policies/reviews" title="https://addons.mozilla.org/en-US/developers/docs/policies/reviews">problemas </a>en la revisión de tu addon. Por ejemplo, si una pagina ejecuta el comando común "<code>document.location = redirecttothispage.html</code>" para cargar, esto se interpretara como cambiar la locación del navegador (<code>document.location</code> en una extensión) en contraposición a la locación de una página web (<code>content.document.location</code> en una extensión), y en consecuecia destruir todos los componentes del navegador. Alternativamente, y de algun modo mas seguro, una cadena <code>responseText adquirida mediante</code> <code>XMLHttpRequest se puede analizar con</code> RegExp para remover problemas de javascript, luego cargada en un iframe oculto previamente establecido:</li> +</ol> + +<pre>document.getElementById('hiddenXULiframe').contentWindow.document.body.innerHTML = req.responseText +</pre> + +<h2 id="Using_FormData_objects">Using FormData objects</h2> + +<p>{{ gecko_minversion_header("2") }}</p> + +<p>The <a href="/en/XMLHttpRequest/FormData" title="en/XMLHttpRequest/FormData"><code>FormData</code></a> object lets you compile a set of key/value pairs to send using <code>XMLHttpRequest</code>. It's primarily intended for use in sending form data, but can be used independently from forms in order to transmit keyed data. The transmitted data is in the same format that the form's <code>submit()</code> method would use to send the data if the form's encoding type were set to "multipart/form-data".</p> + +<h3 id="Creating_a_FormData_object_from_scratch">Creating a FormData object from scratch</h3> + +<p>You can build a <code>FormData</code> object yourself, instantiating it then appending fields to it by calling its <a href="/en/XMLHttpRequest/FormData#append()" title="en/XMLHttpRequest/FormData#append()"><code>append()</code></a> method, like this:</p> + +<pre class="deki-transform">var formData = new FormData(); + +formData.append("username", "Groucho"); +formData.append("accountnum", 123456); +formData.append("afile", fileInputElement.files[0]); + +var xhr = new XMLHttpRequest(); +xhr.open("POST", "http://foo.com/submitform.php"); +xhr.send(formData); +</pre> + +<p>This example builds a <code>FormData</code> object containing values for fields named "username" and "accountnum", then uses the <code>XMLHttpRequest</code> method <a href="/en/XMLHttpRequest#send()" title="en/XMLHttpRequest#send()"><code>send()</code></a> to send the form's data.</p> + +<h3 id="Retrieving_a_FormData_object_from_an_HTML_form">Retrieving a FormData object from an HTML form</h3> + +<p>To construct a <code>FormData</code> object that contains the data from an existing {{ HTMLElement("form") }}, specify that form element when creating the <code>FormData</code> object:</p> + +<pre>newFormData = new FormData(someFormElement); +</pre> + +<p>For example:</p> + +<pre class="deki-transform">var formElement = document.getElementById("myFormElement"); +var xhr = new XMLHttpRequest(); +xhr.open("POST", "submitform.php"); +xhr.send(new FormData(formElement)); +</pre> + +<p>You can also add data to the <code>FormData</code> object between retrieving it from a form and sending it, like this:</p> + +<pre class="deki-transform">var formElement = document.getElementById("myFormElement"); +formData = new FormData(formElement); +formData.append("serialnumber", serialNumber++); +xhr.send(formData); +</pre> + +<p>This lets you augment the form's data before sending it along, to include additional information that's not necessarily user editable on the form.</p> + +<h3 id="Sending_files_using_a_FormData_object">Sending files using a FormData object</h3> + +<p>You can also send files using <code>FormData</code>. Simply include an {{ HTMLElement("input") }} element of type "file":</p> + +<pre class="deki-transform"><form enctype="multipart/form-data" method="post" name="fileinfo" id="fileinfo"> + <label>Your email address:</label> + <input type="email" autocomplete="on" autofocus name="userid" placeholder="email" required size="32" maxlength="64"><br /> + <label>Custom file ID:</label> + <input type="text" name="fileid" size="12" maxlength="32"><br /> + <label>File to stash:</label> + <input type="file" name="file" required> +</form> +<div id="output"></div> +<a href="javascript:sendForm()">Stash the file!</a> +</pre> + +<p>Then you can send it using code like the following:</p> + +<pre class="deki-transform">function sendForm() { + var output = document.getElementById("output"); + var data = new FormData(document.getElementById("fileinfo")); + + data.append("CustomField", "This is some extra data"); + + var xhr = new XMLHttpRequest(); + xhr.open("POST", "stash.pl", false) + xhr.send(data); + if (xhr.status == 200) { + output.innerHTML += "Uploaded!<br />"; + } else { + output.innerHTML += "Error " + xhr.status + " occurred uploading your file.<br />"; + } +} +</pre> + +<p>Note that this example is directing the output to a Perl CGI script running on the server, and handles HTTP errors, although not prettily.</p> + +<h2 id="Handling_binary_data">Handling binary data</h2> + +<p>Although <code>XMLHttpRequest</code> is most commonly used to send and receive textual data, it can be used to send and receive binary content.</p> + +<h3 id="Receiving_binary_data">Receiving binary data</h3> + +<p>The <code>load_binary_resource()</code> function shown below loads binary data from the specified URL, returning it to the caller.</p> + +<pre class="script">function load_binary_resource(url) { + var req = new XMLHttpRequest(); + req.open('GET', url, false); + //XHR binary charset opt by Marcus Granado 2006 [http://mgran.blogspot.com] + req.overrideMimeType('text/plain; charset=x-user-defined'); + req.send(null); + if (req.status != 200) return ''; + return req.responseText; +} +</pre> + +<p>The magic happens in line 5, which overrides the MIME type, forcing Firefox to treat it as plain text, using a user-defined character set. This tells Firefox not to parse it, and to let the bytes pass through unprocessed.</p> + +<pre class="script">var filestream = load_binary_resource(url); +var abyte = filestream.charCodeAt(x) & 0xff; // throw away high-order byte (f7)</pre> + +<p>The example above fetches the byte at offset <code>x</code> within the loaded binary data. The valid range for <code>x</code> is from 0 to <code>filestream.length-1</code>.</p> + +<p>See <a class="external" href="http://mgran.blogspot.com/2006/08/downloading-binary-streams-with.html">downloading binary streams with XMLHttpRequest</a> for a detailed explanation. See also <a href="/en/Code_snippets/Downloading_Files" title="en/Code_snippets/Downloading_Files">downloading files</a>.</p> + +<h3 id="Receiving_binary_data_using_JavaScript_typed_arrays">Receiving binary data using JavaScript typed arrays</h3> + +<p>{{ gecko_minversion_header("2.0") }}</p> + +<p>Gecko 2.0 {{ geckoRelease("2.0") }} adds a Gecko-specific <code>mozResponseArrayBuffer</code> property to the XMLHttpRequest object, which contains a <a href="/en/JavaScript_typed_arrays" title="en/JavaScript typed arrays">JavaScript typed array</a> representing the raw binary contents of the response from the server. This lets you read the binary data without taking any special steps.</p> + +<pre class="deki-transform">var xhr = new XMLHttpRequest(); +xhr.open("GET", "binary_file", false); +xhr.send(null); + +buffer = xhr.mozResponseArrayBuffer; +if (buffer) { + var byteArray = new UInt8Array(buffer); + for (var i=0; i<byteArray.byteLength; i++) { + // do something with each byte in the array + } +} +</pre> + +<p>This example reads a binary file and interprets it as 8-bit unsigned integers.</p> + +<h3 id="Sending_binary_data">Sending binary data</h3> + +<p>This example transmits binary content asynchronously, using the <code>POST</code> method.</p> + +<pre class="script">var req = new XMLHttpRequest(); +req.open("POST", url, true); +// set headers and mime-type appropriately +req.setRequestHeader("Content-Length", 741); +req.sendAsBinary(aBody);</pre> + +<p>Line 4 sets the Content-Length header to 741, indicating that the data is 741 bytes long. Obviously you need to change this value based on the actual size of the data being sent.</p> + +<p>Line 5 uses the <code>sendAsBinary()</code> method to initiate the request.</p> + +<p>You can also send binary content by passing an instance of the {{ interface("nsIFileInputStream") }} to <a class="internal" href="/en/XMLHttpRequest#send()" title="/En/XMLHttpRequest#send()"><code>send()</code></a>. In that case, you don't have to set the Content-Length header yourself, as the information is fetched from the stream automatically:</p> + +<pre class="script">// Make a stream from a file. +var stream = Components.classes["@mozilla.org/network/file-input-stream;1"] + .createInstance(Components.interfaces.nsIFileInputStream); +stream.init(file, 0x04 | 0x08, 0644, 0x04); // file is an nsIFile instance + +// Try to determine the MIME type of the file +var mimeType = "text/plain"; +try { + var mimeService = Components.classes["@mozilla.org/mime;1"] + .getService(Components.interfaces.nsIMIMEService); + mimeType = mimeService.getTypeFromFile(file); // file is an nsIFile instance +} +catch(e) { /* eat it; just use text/plain */ } + +// Send +var req = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"] + .createInstance(Components.interfaces.nsIXMLHttpRequest); +req.open('PUT', url, false); /* synchronous! */ +req.setRequestHeader('Content-Type', mimeType); +req.send(stream); +</pre> + +<h2 id="Monitoring_progress">Monitoring progress</h2> + +<p><code>XMLHttpRequest</code> provides the ability to listen to various events that can occur while the request is being processed. This includes periodic progress notifications, error notifications, and so forth.</p> + +<h3 id="In_Firefox_3.5_and_later">In Firefox 3.5 and later</h3> + +<p>Firefox 3.5 adds support for DOM progress event monitoring of <code>XMLHttpRequest</code> transfers; this follows the Web API <a class="external" href="http://dev.w3.org/2006/webapi/progress/Progress.html" title="http://dev.w3.org/2006/webapi/progress/Progress.html">specification for progress events</a>.</p> + +<pre class="script">var req = new XMLHttpRequest(); + +req.addEventListener("progress", updateProgress, false); +req.addEventListener("load", transferComplete, false); +req.addEventListener("error", transferFailed, false); +req.addEventListener("abort", transferCanceled, false); + +req.open(); + +... + +// progress on transfers from the server to the client (downloads) +function updateProgress(evt) { + if (evt.lengthComputable) { + var percentComplete = evt.loaded / evt.total; + ... + } else { + // Unable to compute progress information since the total size is unknown + } +} + +function transferComplete(evt) { + alert("The transfer is complete."); +} + +function transferFailed(evt) { + alert("An error occurred while transferring the file."); +} + +function transferCanceled(evt) { + alert("The transfer has been canceled by the user."); +} +</pre> + +<p>Lines 3-6 add event listeners for the various events that are sent while performing a data transfer using <code>XMLHttpRequest</code>. See {{ interface("nsIDOMProgressEvent") }} and {{ interface("nsIXMLHttpRequestEventTarget") }} for details on these events.</p> + +<div class="note">Note: You need to add the event listeners before calling <code>open()</code> on the request. Otherwise the progress events will not fire.</div> + +<p>The progress event handler, specified by the <code>updateProgress()</code> function in this example, receives the total number of bytes to transfer as well as the number of bytes transferred so far in the event's <code>total</code> and <code>loaded</code> fields. However, if the <code>lengthComputable</code> field is false, the total length is not known and will be zero.</p> + +<p>Progress events exist for both download and upload transfers. The download events are fired on the <code>XMLHttpRequest</code> object itself, as shown in the above sample. The upload events are fired on the <code>XMLHttpRequest.upload</code> object, as shown below:</p> + +<pre class="script">var req = new XMLHttpRequest(); + +req.upload.addEventListener("progress", updateProgress, false); +req.upload.addEventListener("load", transferComplete, false); +req.upload.addEventListener("error", transferFailed, false); +req.upload.addEventListener("abort", transferCanceled, false); + +req.open();</pre> + +<div class="note"><strong>Note:</strong> Progress events are not available for the <code>file:</code> protocol.</div> + +<h3 id="In_Firefox_3_and_earlier">In Firefox 3 and earlier</h3> + +<p>If, for example, you wish to provide progress information to the user while the document is being received, you can use code like this:</p> + +<pre class="script">function onProgress(e) { + var percentComplete = (e.position / e.totalSize)*100; + // ... +} + +function onError(e) { + alert("Error " + e.target.status + " occurred while receiving the document."); +} + +function onLoad(e) { + // ... +} +// ... +var req = new XMLHttpRequest(); +req.onprogress = onProgress; // or req.addEventListener("progress", onProgress, false); +req.open("GET", url, true); +req.onload = onLoad; // or req.addEventListener("load", onLoad, false); +req.onerror = onError; // or req.addEventListener("error", onError, false); +req.send(null); +</pre> + +<p>The <code>onprogress</code> event's attributes, <code>position</code> and <code>totalSize</code>, indicate the current number of bytes received and the total number of bytes expected, respectively.</p> + +<p>All of these events have their <code>target</code> attribute set to the <code>XMLHttpRequest</code> they correspond to.</p> + +<div class="note"><strong>Note:</strong> <a href="/en/Firefox_3_for_developers" title="en/Firefox_3_for_developers">Firefox 3</a> properly ensures that the values of the <code>target</code>, <code>currentTarget</code>, and <code>this</code> fields of the event object are set to reference the correct objects when calling event handlers for XML documents represented by <code>XMLDocument</code>. See {{ Bug(198595) }} for details.</div> + +<h2 id="Cross-site_XMLHttpRequest">Cross-site XMLHttpRequest</h2> + +<div class="geckoVersionNote"> +<p>Este artículo cubre características introducidas en Firefox 3.5.</p> +</div> + +<p>Firefox 3.5 supports cross-site requests by implementing the web applications working group's <a class="internal" href="/En/HTTP_access_control" title="en/HTTP access control">Access Control for Cross-Site Requests</a> standard. As long as the server is configured to allow requests from your web application's origin, <code>XMLHttpRequest</code> will work. Otherwise, an <code>INVALID_ACCESS_ERR</code> exception is thrown.</p> + +<h2 id="Bypassing_the_cache">Bypassing the cache</h2> + +<p>Normally, <code>XMLHttpRequest</code> tries to retrieve content from the cache, if it's available. To bypass this, do the following:</p> + +<pre class="script">var req = new XMLHttpRequest(); +req.open('GET', url, false); +<strong>req.channel.loadFlags |= Components.interfaces.nsIRequest.LOAD_BYPASS_CACHE;</strong> +req.send(null);</pre> + +<div class="note"><strong>Note:</strong> This approach will only work in Gecko-based software, as the <code>channel</code> attribute is Gecko-specific.</div> + +<p>An alternate, cross-browser compatible approach is to append a timestamp to the URL, being sure to include a "?" or "&" as appropriate. For example:</p> + +<pre>http://foo.com/bar.html</pre> + +<p>becomes</p> + +<pre>http://foo.com/bar.html?12345</pre> + +<p>and</p> + +<pre>http://foo.com/bar.html?foobar=baz</pre> + +<p>becomes</p> + +<pre>http://foo.com/bar.html?foobar=baz&12345</pre> + +<p>Since the local cache is indexed by URL, this causes every request to be unique, thereby bypassing the cache.</p> + +<p>You can automatically adjust URLs using the following code:</p> + +<pre class="script">var req = new XMLHttpRequest(); +req.open("GET", url += (url.match(/\?/) == null ? "?" : "&") + (new Date()).getTime(), false); +req.send(null); </pre> + +<h2 id="Security">Security</h2> + +<p>{{ fx_minversion_note(3, "Versions of Firefox prior to Firefox 3 allowed you to set the preference <code>capability.policy..XMLHttpRequest.open</code> to <code>allAccess</code> to give specific sites cross-site access. This is no longer supported.") }}</p> + +<h2 id="Downloading_JSON_and_JavaScript_from_extensions">Downloading JSON and JavaScript from extensions</h2> + +<p>For security reasons, extensions should never use <code><a href="/en/JavaScript/Reference/Global_Objects/eval" title="en/Core_JavaScript_1.5_Reference/Global_Functions/eval">eval()</a></code> to parse JSON or JavaScript code downloaded from the web. See <a href="/en/Downloading_JSON_and_JavaScript_in_extensions" title="en/Downloading_JSON_and_JavaScript_in_extensions">Downloading JSON and JavaScript in extensions</a> for details.</p> + +<h2 id="Using_XMLHttpRequest_from_JavaScript_modules_XPCOM_components">Using XMLHttpRequest from JavaScript modules / XPCOM components</h2> + +<p>Instantiating <code>XMLHttpRequest</code> from a <a href="/en/JavaScript_code_modules/Using" title="https://developer.mozilla.org/en/JavaScript_code_modules/Using_JavaScript_code_modules">JavaScript module</a> or an XPCOM component works a little differently; it can't be instantiated using the <code>XMLHttpRequest()</code> constructor. The constructor is not defined inside components and the code results in an error. You'll need to create and use it using a different syntax.</p> + +<p>Instead of this:</p> + +<pre class="script">var req = new XMLHttpRequest(); +req.onprogress = onProgress; +req.onload = onLoad; +req.onerror = onError; +req.open("GET", url, true); +req.send(null); +</pre> + +<p>Do this:</p> + +<pre class="script">var req = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"] + .createInstance(Components.interfaces.nsIXMLHttpRequest); +req.onprogress = onProgress; +req.onload = onLoad; +req.onerror = onError; +req.open("GET", url, true); +req.send(null); +</pre> + +<p>For C++ code you would need to <code>QueryInterface</code> the component to an <code>nsIEventTarget</code> in order to add event listeners, but chances are in C++ using a channel directly would be better.</p> + +<h2 id="See_also">See also</h2> + +<ol> + <li><a href="/en/AJAX/Getting_Started" title="en/AJAX/Getting_Started">MDC AJAX introduction</a></li> + <li><a class="internal" href="/En/HTTP_access_control" title="En/HTTP access control">HTTP access control</a></li> + <li><a class="internal" href="/En/How_to_check_the_security_state_of_an_XMLHTTPRequest_over_SSL" title="En/How to check the security state of an XMLHTTPRequest over SSL">How to check the security state of an XMLHTTPRequest over SSL</a></li> + <li><a class="external" href="http://www.peej.co.uk/articles/rich-user-experience.html">XMLHttpRequest - REST and the Rich User Experience</a></li> + <li><a class="external" href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/xmlsdk/html/xmobjxmlhttprequest.asp">Microsoft documentation</a></li> + <li><a class="external" href="http://developer.apple.com/internet/webcontent/xmlhttpreq.html">Apple developers' reference</a></li> + <li><a class="external" href="http://jibbering.com/2002/4/httprequest.html">"Using the XMLHttpRequest Object" (jibbering.com)</a></li> + <li><a class="external" href="http://www.w3.org/TR/XMLHttpRequest/">The XMLHttpRequest Object: W3C Working Draft</a></li> + <li><a class="external" href="http://dev.w3.org/2006/webapi/progress/Progress.html" title="http://dev.w3.org/2006/webapi/progress/Progress.html">Web Progress Events specification</a></li> + <li><a class="external" href="http://www.bluishcoder.co.nz/2009/06/05/reading-ogg-files-with-javascript.html" title="http://www.bluishcoder.co.nz/2009/06/05/reading-ogg-files-with-javascript.html">Reading Ogg files with JavaScript (Chris Double)</a></li> +</ol> diff --git a/files/es/web/api/xmlhttprequesteventtarget/index.html b/files/es/web/api/xmlhttprequesteventtarget/index.html new file mode 100644 index 0000000000..f53063d82b --- /dev/null +++ b/files/es/web/api/xmlhttprequesteventtarget/index.html @@ -0,0 +1,68 @@ +--- +title: XMLHttpRequestEventTarget +slug: Web/API/XMLHttpRequestEventTarget +tags: + - AJAX + - API + - NeedsBrowserCompatibility + - NeedsContent + - NeedsTranslation + - Reference + - TopicStub + - XMLHttpRequest +translation_of: Web/API/XMLHttpRequestEventTarget +--- +<p>{{APIRef("XMLHttpRequest")}}</p> + +<p><code>XMLHttpRequestEventTarget</code> is the interface that describes the event handlers you can implement in an object that will handle events for an {{ domxref("XMLHttpRequest") }}.</p> + +<p>{{InheritanceDiagram}}</p> + +<h2 id="Properties">Properties</h2> + +<dl> + <dt>{{ domxref("XMLHttpRequestEventTarget.onabort") }}</dt> + <dd>Contains the function to call when a request is aborted and the {{event('abort')}} event is received by this object.</dd> + <dt>{{ domxref("XMLHttpRequestEventTarget.onerror") }}</dt> + <dd>Contains the function to call when a request encounters an error and the {{event('error')}} event is received by this object.</dd> + <dt>{{ domxref("XMLHttpRequestEventTarget.onload") }}</dt> + <dd>Contains the function to call when an HTTP request returns after successfully fetching content and the {{event('load')}} event is received by this object.</dd> + <dt>{{ domxref("XMLHttpRequestEventTarget.onloadstart") }}</dt> + <dd>Contains the function that gets called when the HTTP request first begins loading data and the {{event('loadstart')}} event is received by this object.</dd> + <dt>{{ domxref("XMLHttpRequestEventTarget.onprogress") }}</dt> + <dd>Contains the function that is called periodically with information about the progress of the request and the {{event('progress')}} event is received by this object.</dd> + <dt>{{ domxref("XMLHttpRequestEventTarget.ontimeout") }}</dt> + <dd>Contains the function that is called if the event times out and the {{event("timeout")}} event is received by this object; this only happens if a timeout has been previously established by setting the value of the <code>XMLHttpRequest</code> object's <code>timeout</code> attribute.</dd> + <dt>{{ domxref("XMLHttpRequestEventTarget.onloadend") }}</dt> + <dd>Contains the function that is called when the load is completed, even if the request failed, and the {{event('loadend')}} event is received by this object.</dd> +</dl> + +<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('XMLHttpRequest')}}</td> + <td>{{Spec2('XMLHttpRequest')}}</td> + <td>WHATWG living standard</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("api.XMLHttpRequestEventTarget")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{ domxref("XMLHttpRequest") }}</li> + <li><a href="/en/DOM/XMLHttpRequest/Using_XMLHttpRequest" title="Using XMLHttpRequest">Using XMLHttpRequest</a></li> +</ul> diff --git a/files/es/web/api/xmlhttprequesteventtarget/onload/index.html b/files/es/web/api/xmlhttprequesteventtarget/onload/index.html new file mode 100644 index 0000000000..c6d6f78974 --- /dev/null +++ b/files/es/web/api/xmlhttprequesteventtarget/onload/index.html @@ -0,0 +1,55 @@ +--- +title: XMLHttpRequestEventTarget.onload +slug: Web/API/XMLHttpRequestEventTarget/onload +translation_of: Web/API/XMLHttpRequestEventTarget/onload +--- +<div>{{APIRef("XMLHttpRequest")}}</div> + +<p>El evento <strong><code>XMLHttpRequestEventTarget.onload</code> </strong>es la función que se llama cuando una transacción del {{domxref("XMLHttpRequest")}} es ejecutada correctamente.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox"><em>XMLHttpRequest</em>.onload = <em>callback</em>;</pre> + +<h3 id="Valores"> Valores</h3> + +<ul> + <li><code><em>callback</em></code> is the function to be executed when the request completes successfully. It receives a {{domxref("ProgressEvent")}} object as its first argument. The value of <em>this</em> (i.e. the context) is the same {{domxref("XMLHttpRequest")}} this callback is related to.</li> + <li><code><em>callback</em></code> es la función a ser ejecutada cuando la petición se complete. Ésta recive un objeto {{domxref("ProgressEvent")}} como su primer argumento. El valor de esto (ej: el contexto) es el mismo {{domxref("XMLHttpRequest")}} al que el callback está relacionado.</li> +</ul> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre class="brush: js">var xmlhttp = new XMLHttpRequest(), + method = 'GET', + url = 'https://developer.mozilla.org/'; + +xmlhttp.open(<em>method</em>, <em>url</em>, true); +xmlhttp.onload = function () { + // Hacer algo con la información recivida ( found in xmlhttp.response ) +}; +xmlhttp.send(); +</pre> + +<h2 id="Especificaciones">Especificaciones</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('XMLHttpRequest', '#handler-xhr-onload')}}</td> + <td>{{Spec2('XMLHttpRequest')}}</td> + <td>WHATWG living standard</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("api.XMLHttpRequestEventTarget.onload")}}</p> |