diff options
Diffstat (limited to 'files')
55 files changed, 0 insertions, 11114 deletions
diff --git a/files/es/_redirects.txt b/files/es/_redirects.txt index 6973e1efe2..8783b96121 100644 --- a/files/es/_redirects.txt +++ b/files/es/_redirects.txt @@ -111,7 +111,6 @@ /es/docs/CSS/list-style-type /es/docs/Web/CSS/list-style-type /es/docs/CSS/margin-right /es/docs/Web/CSS/margin-right /es/docs/CSS/max-height /es/docs/Web/CSS/max-height -/es/docs/CSS/max-width /es/docs/Web/CSS/max-width /es/docs/CSS/min-height /es/docs/Web/CSS/min-height /es/docs/CSS/min-width /es/docs/Web/CSS/min-width /es/docs/CSS/none /es/docs/Web/CSS/float @@ -185,7 +184,6 @@ /es/docs/CSS:list-style-type /es/docs/Web/CSS/list-style-type /es/docs/CSS:margin-right /es/docs/Web/CSS/margin-right /es/docs/CSS:max-height /es/docs/Web/CSS/max-height -/es/docs/CSS:max-width /es/docs/Web/CSS/max-width /es/docs/CSS:min-height /es/docs/Web/CSS/min-height /es/docs/CSS:min-width /es/docs/Web/CSS/min-width /es/docs/CSS:none /es/docs/Web/CSS/float @@ -231,14 +229,12 @@ /es/docs/DOM/CameraCapabilities.flashModes /es/docs/Web/API/CameraCapabilities/flashModes /es/docs/DOM/CssRule /es/docs/Web/API/CSSRule /es/docs/DOM/CssRule.cssText /es/docs/Web/API/CSSRule/cssText -/es/docs/DOM/CssRule.parentStyleSheet /es/docs/Web/API/CSSRule/parentStyleSheet /es/docs/DOM/CssRule.selectorText /es/docs/Web/API/CSSStyleRule/selectorText /es/docs/DOM/Document.styleSheets /es/docs/Web/API/Document/styleSheets /es/docs/DOM/Element.setAttribute /es/docs/Web/API/Element/setAttribute /es/docs/DOM/HTMLAudioElement /es/docs/Web/API/HTMLAudioElement /es/docs/DOM/HTMLTableElement /es/docs/Web/API/HTMLTableElement /es/docs/DOM/Manipulando_el_historial_del_navegador /es/docs/Web/API/History_API -/es/docs/DOM/Manipulando_el_historial_del_navegador/Ejemplo /es/docs/Web/API/History_API/Example /es/docs/DOM/Manipulating_the_browser_history /es/docs/Web/API/History_API /es/docs/DOM/MozSocial.closePanel /es/docs/Web/API/MozSocial/closePanel /es/docs/DOM/MozSocial.getAttention /es/docs/Web/API/MozSocial/getAttention @@ -327,7 +323,6 @@ /es/docs/DOM/range /es/docs/Web/API/Range /es/docs/DOM/range.collapsed /es/docs/Web/API/Range/collapsed /es/docs/DOM/range.commonAncestorContainer /es/docs/Web/API/Range/commonAncestorContainer -/es/docs/DOM/range.intersectsNode /es/docs/Web/API/Range/intersectsNode /es/docs/DOM/style /es/docs/Web/API/HTMLStyleElement /es/docs/DOM/table /es/docs/Web/API/HTMLTableElement /es/docs/DOM/window /es/docs/Web/API/Window @@ -338,7 +333,6 @@ /es/docs/DOM/window.navigator.registerProtocolHandler /es/docs/Web/API/Navigator/registerProtocolHandler /es/docs/DOM/window.navigator.vibrate /es/docs/Web/API/Navigator/vibrate /es/docs/DOM/window.onload /es/docs/Web/API/GlobalEventHandlers/onload -/es/docs/DOM/window.onunload /es/docs/Web/API/WindowEventHandlers/onunload /es/docs/DOM/window.requestAnimationFrame /es/docs/Web/API/Window/requestAnimationFrame /es/docs/DOM:Selection:addRange /es/docs/Web/API/Selection/addRange /es/docs/DOM:Selection:anchorNode /es/docs/Web/API/Selection/anchorNode @@ -395,7 +389,6 @@ /es/docs/DOM:range /es/docs/Web/API/Range /es/docs/DOM:range.collapsed /es/docs/Web/API/Range/collapsed /es/docs/DOM:range.commonAncestorContainer /es/docs/Web/API/Range/commonAncestorContainer -/es/docs/DOM:range.intersectsNode /es/docs/Web/API/Range/intersectsNode /es/docs/DOM:selection /es/docs/Web/API/Selection /es/docs/DOM:style /es/docs/Web/API/HTMLStyleElement /es/docs/DOM:table /es/docs/Web/API/HTMLTableElement @@ -1243,7 +1236,6 @@ /es/docs/Learn/Herramientas_y_pruebas/GitHub /es/docs/Learn/Tools_and_testing/GitHub /es/docs/Learn/Herramientas_y_pruebas/Lado-del-cliente_JavaScript_frameworks /es/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks /es/docs/Learn/Herramientas_y_pruebas/Lado-del-cliente_JavaScript_frameworks/React_getting_started /es/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started -/es/docs/Learn/Herramientas_y_pruebas/Lado-del-cliente_JavaScript_frameworks/Vue_primeros_pasos /es/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_getting_started /es/docs/Learn/Herramientas_y_pruebas/Understanding_client-side_tools /es/docs/Learn/Tools_and_testing/Understanding_client-side_tools /es/docs/Learn/JavaScript/Building_blocks/Bucle_codigo /es/docs/Learn/JavaScript/Building_blocks/Looping_code /es/docs/Learn/JavaScript/Building_blocks/Construyendo_tu_propia_funcion /es/docs/Learn/JavaScript/Building_blocks/Build_your_own_function @@ -1554,7 +1546,6 @@ /es/docs/SVG /es/docs/Web/SVG /es/docs/SVG/Tutorial /es/docs/Web/SVG/Tutorial /es/docs/SVG/Tutorial/Getting_Started /es/docs/Web/SVG/Tutorial/Getting_Started -/es/docs/SVG_In_HTML_Introduction /es/docs/Web/SVG/Tutorial/SVG_In_HTML_Introduction /es/docs/SVG_en_Firefox /es/docs/Web/SVG/SVG_1.1_Support_in_Firefox /es/docs/Screening_duplicate_bugs /es/docs/QA/Screening_duplicate_bugs /es/docs/Seguridad_en_Firefox_2 /es/docs/Mozilla/Firefox/Releases/2/Security_changes @@ -1637,7 +1628,6 @@ /es/docs/Web/API/Geolocation.clearWatch /es/docs/Web/API/Geolocation/clearWatch /es/docs/Web/API/Geolocation.getCurrentPosition /es/docs/Web/API/Geolocation/getCurrentPosition /es/docs/Web/API/Geolocation.watchPosition /es/docs/Web/API/Geolocation/watchPosition -/es/docs/Web/API/GlobalEventHandlers/onunload /es/docs/Web/API/WindowEventHandlers/onunload /es/docs/Web/API/HTMLElement/focus /es/docs/orphaned/Web/API/HTMLOrForeignElement/focus /es/docs/Web/API/HTMLElement/invalid_event /es/docs/Web/API/HTMLInputElement/invalid_event /es/docs/Web/API/HTMLOrForeignElement/focus /es/docs/orphaned/Web/API/HTMLOrForeignElement/focus @@ -1663,7 +1653,6 @@ /es/docs/Web/API/Position /es/docs/Web/API/GeolocationPosition /es/docs/Web/API/RandomSource/Obtenervaloresaleatorios /es/docs/Web/API/Crypto/getRandomValues /es/docs/Web/API/SubtleCrypto/encrypt /es/docs/Web/HTTP/Headers/Digest -/es/docs/Web/API/WebGL_API/Animating_objects_with_WebGL /es/docs/Web/API/WebGL_API/Tutorial/Animating_objects_with_WebGL /es/docs/Web/API/WebGL_API/Getting_started_with_WebGL /es/docs/Web/API/WebGL_API/Tutorial/Getting_started_with_WebGL /es/docs/Web/API/WebGL_API/Tutorial/Objetos_3D_utilizando_WebGL /es/docs/Web/API/WebGL_API/Tutorial/Creating_3D_objects_using_WebGL /es/docs/Web/API/WebGL_API/Tutorial/Wtilizando_texturas_en_WebGL /es/docs/Web/API/WebGL_API/Tutorial/Using_textures_in_WebGL @@ -1803,7 +1792,6 @@ /es/docs/Web/CSS/transform-function/translateZ /es/docs/Web/CSS/transform-function/translateZ() /es/docs/Web/CSS/var /es/docs/Web/CSS/var() /es/docs/Web/Events/DOMContentLoaded /es/docs/Web/API/Window/DOMContentLoaded_event -/es/docs/Web/Events/abort /es/docs/Web/API/HTMLMediaElement/abort_event /es/docs/Web/Events/animationend /es/docs/Web/API/HTMLElement/animationend_event /es/docs/Web/Events/beforeunload /es/docs/Web/API/Window/beforeunload_event /es/docs/Web/Events/blur /es/docs/Web/API/Element/blur_event @@ -1832,7 +1820,6 @@ /es/docs/Web/Guide/HTML /es/docs/Learn/HTML /es/docs/Web/Guide/HTML/Canvas_tutorial /es/docs/Web/API/Canvas_API/Tutorial /es/docs/Web/Guide/HTML/Canvas_tutorial/Advanced_animations /es/docs/Web/API/Canvas_API/Tutorial/Advanced_animations -/es/docs/Web/Guide/HTML/Canvas_tutorial/Applying_styles_and_colors /es/docs/Web/API/Canvas_API/Tutorial/Applying_styles_and_colors /es/docs/Web/Guide/HTML/Canvas_tutorial/Basic_animations /es/docs/Web/API/Canvas_API/Tutorial/Basic_animations /es/docs/Web/Guide/HTML/Canvas_tutorial/Basic_usage /es/docs/Web/API/Canvas_API/Tutorial/Basic_usage /es/docs/Web/Guide/HTML/Canvas_tutorial/Dibujando_formas /es/docs/Web/API/Canvas_API/Tutorial/Drawing_shapes @@ -2160,7 +2147,6 @@ /es/docs/Web/JavaScript/Referencia /es/docs/Web/JavaScript/Reference /es/docs/Web/JavaScript/Referencia/Acerca_de /es/docs/Web/JavaScript/Reference/About /es/docs/Web/JavaScript/Referencia/Características_Desaprobadas /es/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features -/es/docs/Web/JavaScript/Referencia/Características_Desaprobadas/The_legacy_Iterator_protocol /es/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features/The_legacy_Iterator_protocol /es/docs/Web/JavaScript/Referencia/Características_Despreciadas /es/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features /es/docs/Web/JavaScript/Referencia/Classes /es/docs/Web/JavaScript/Reference/Classes /es/docs/Web/JavaScript/Referencia/Classes/Class_fields /es/docs/Web/JavaScript/Reference/Classes/Public_class_fields @@ -2256,7 +2242,6 @@ /es/docs/Web/JavaScript/Referencia/Objetos_globales/Date/getSeconds /es/docs/Web/JavaScript/Reference/Global_Objects/Date/getSeconds /es/docs/Web/JavaScript/Referencia/Objetos_globales/Date/getTime /es/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime /es/docs/Web/JavaScript/Referencia/Objetos_globales/Date/getUTCFullYear /es/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCFullYear -/es/docs/Web/JavaScript/Referencia/Objetos_globales/Date/getUTCHours /es/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCHours /es/docs/Web/JavaScript/Referencia/Objetos_globales/Date/now /es/docs/Web/JavaScript/Reference/Global_Objects/Date/now /es/docs/Web/JavaScript/Referencia/Objetos_globales/Date/parse /es/docs/Web/JavaScript/Reference/Global_Objects/Date/parse /es/docs/Web/JavaScript/Referencia/Objetos_globales/Date/setFullYear /es/docs/Web/JavaScript/Reference/Global_Objects/Date/setFullYear @@ -2327,7 +2312,6 @@ /es/docs/Web/JavaScript/Referencia/Objetos_globales/Math/exp /es/docs/Web/JavaScript/Reference/Global_Objects/Math/exp /es/docs/Web/JavaScript/Referencia/Objetos_globales/Math/expm1 /es/docs/Web/JavaScript/Reference/Global_Objects/Math/expm1 /es/docs/Web/JavaScript/Referencia/Objetos_globales/Math/floor /es/docs/Web/JavaScript/Reference/Global_Objects/Math/floor -/es/docs/Web/JavaScript/Referencia/Objetos_globales/Math/fround /es/docs/Web/JavaScript/Reference/Global_Objects/Math/fround /es/docs/Web/JavaScript/Referencia/Objetos_globales/Math/hypot /es/docs/Web/JavaScript/Reference/Global_Objects/Math/hypot /es/docs/Web/JavaScript/Referencia/Objetos_globales/Math/log /es/docs/Web/JavaScript/Reference/Global_Objects/Math/log /es/docs/Web/JavaScript/Referencia/Objetos_globales/Math/log10 /es/docs/Web/JavaScript/Reference/Global_Objects/Math/log10 @@ -2366,7 +2350,6 @@ /es/docs/Web/JavaScript/Referencia/Objetos_globales/NumberFormat/format /es/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/format /es/docs/Web/JavaScript/Referencia/Objetos_globales/Object /es/docs/Web/JavaScript/Reference/Global_Objects/Object /es/docs/Web/JavaScript/Referencia/Objetos_globales/Object/__defineGetter__ /es/docs/Web/JavaScript/Reference/Global_Objects/Object/__defineGetter__ -/es/docs/Web/JavaScript/Referencia/Objetos_globales/Object/__lookupGetter__ /es/docs/Web/JavaScript/Reference/Global_Objects/Object/__lookupGetter__ /es/docs/Web/JavaScript/Referencia/Objetos_globales/Object/assign /es/docs/Web/JavaScript/Reference/Global_Objects/Object/assign /es/docs/Web/JavaScript/Referencia/Objetos_globales/Object/constructor /es/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor /es/docs/Web/JavaScript/Referencia/Objetos_globales/Object/create /es/docs/Web/JavaScript/Reference/Global_Objects/Object/create @@ -2593,7 +2576,6 @@ /es/docs/Web/Reference/Events /es/docs/Web/Events /es/docs/Web/Reference/Events/DOMContentLoaded /es/docs/Web/API/Window/DOMContentLoaded_event /es/docs/Web/Reference/Events/DOMSubtreeModified /es/docs/Web/Events/DOMSubtreeModified -/es/docs/Web/Reference/Events/abort /es/docs/Web/API/HTMLMediaElement/abort_event /es/docs/Web/Reference/Events/animationend /es/docs/Web/API/HTMLElement/animationend_event /es/docs/Web/Reference/Events/beforeunload /es/docs/Web/API/Window/beforeunload_event /es/docs/Web/Reference/Events/blur /es/docs/Web/API/Element/blur_event @@ -2619,7 +2601,6 @@ /es/docs/Web/Security/Securing_your_site/desactivar_autocompletado_formulario /es/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion /es/docs/Web/Tutoriales /es/docs/Web/Tutorials /es/docs/Web/WebGL /es/docs/Web/API/WebGL_API -/es/docs/Web/WebGL/Animating_objects_with_WebGL /es/docs/Web/API/WebGL_API/Tutorial/Animating_objects_with_WebGL /es/docs/Web/WebGL/Getting_started_with_WebGL /es/docs/Web/API/WebGL_API/Tutorial/Getting_started_with_WebGL /es/docs/Web/XML/Introducción_a_XML /es/docs/Web/XML/XML_introduction /es/docs/Web/XPath/Ejes /es/docs/Web/XPath/Axes @@ -2668,7 +2649,6 @@ /es/docs/WebAPI/Pointer_Lock /es/docs/Web/API/Pointer_Lock_API /es/docs/WebAPI/Using_geolocation /es/docs/Web/API/Geolocation_API /es/docs/WebGL /es/docs/Web/API/WebGL_API -/es/docs/WebGL/Animating_objects_with_WebGL /es/docs/Web/API/WebGL_API/Tutorial/Animating_objects_with_WebGL /es/docs/WebRTC/Introduction /es/docs/Web/API/WebRTC_API/Session_lifetime /es/docs/WebRTC/MediaStream_API /es/docs/Web/API/Media_Streams_API /es/docs/WebRTC/Peer-to-peer_communications_with_WebRTC /es/docs/Web/Guide/API/WebRTC/Peer-to-peer_communications_with_WebRTC diff --git a/files/es/_wikihistory.json b/files/es/_wikihistory.json index 0b33de87c6..e87c40ab52 100644 --- a/files/es/_wikihistory.json +++ b/files/es/_wikihistory.json @@ -76,12 +76,6 @@ "SuperHostile" ] }, - "Games/Techniques/3D_on_the_web": { - "modified": "2019-03-18T21:23:46.780Z", - "contributors": [ - "wbamberg" - ] - }, "Games/Techniques/WebRTC_data_channels": { "modified": "2019-03-23T22:04:08.435Z", "contributors": [ @@ -2067,12 +2061,6 @@ "editorUOC" ] }, - "Learn/CSS/CSS_layout/Positioning": { - "modified": "2020-07-16T22:26:42.380Z", - "contributors": [ - "fr3dth" - ] - }, "Learn/CSS/CSS_layout/Responsive_Design": { "modified": "2020-07-16T22:27:27.257Z", "contributors": [ @@ -3080,12 +3068,6 @@ "Enesimus" ] }, - "Learn/JavaScript/Client-side_web_APIs/Fetching_data": { - "modified": "2020-07-16T22:32:57.121Z", - "contributors": [ - "Dsabillon" - ] - }, "Learn/JavaScript/Client-side_web_APIs/Introduction": { "modified": "2020-07-16T22:32:44.249Z", "contributors": [ @@ -3632,13 +3614,6 @@ "maringenio" ] }, - "Learn/Server-side/Express_Nodejs/mongoose": { - "modified": "2020-07-16T22:38:20.335Z", - "contributors": [ - "danimrprofe", - "rmon_vfer" - ] - }, "Learn/Server-side/Express_Nodejs/skeleton_website": { "modified": "2020-07-16T22:38:03.936Z", "contributors": [ @@ -3712,12 +3687,6 @@ "spaceinvadev" ] }, - "Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_getting_started": { - "modified": "2020-09-17T18:53:24.146Z", - "contributors": [ - "Faem0220" - ] - }, "Learn/Tools_and_testing/Cross_browser_testing": { "modified": "2020-07-16T22:38:59.665Z", "contributors": [ @@ -3857,17 +3826,6 @@ "LeoHirsch" ] }, - "MDN/Contribute/Howto/Document_a_CSS_property": { - "modified": "2020-02-19T19:43:18.253Z", - "contributors": [ - "jswisher", - "SphinxKnight", - "wbamberg", - "teoli", - "stephaniehobson", - "MauricioGil" - ] - }, "MDN/Contribute/Howto/Tag": { "modified": "2019-03-23T23:15:01.953Z", "contributors": [ @@ -4096,13 +4054,6 @@ "grxdipgra" ] }, - "Mozilla/Add-ons/WebExtensions/API/webNavigation": { - "modified": "2020-10-15T21:52:47.862Z", - "contributors": [ - "wbamberg", - "tanclony" - ] - }, "Mozilla/Add-ons/WebExtensions/Add_a_button_to_the_toolbar": { "modified": "2019-03-18T21:05:11.701Z", "contributors": [ @@ -4138,12 +4089,6 @@ "hecaxmmx" ] }, - "Mozilla/Add-ons/WebExtensions/Extending_the_developer_tools": { - "modified": "2020-09-27T05:32:44.293Z", - "contributors": [ - "omaralonsog" - ] - }, "Mozilla/Add-ons/WebExtensions/Implement_a_settings_page": { "modified": "2019-03-18T21:06:46.901Z", "contributors": [ @@ -4158,12 +4103,6 @@ "hecaxmmx" ] }, - "Mozilla/Add-ons/WebExtensions/Internationalization": { - "modified": "2020-06-29T22:25:32.104Z", - "contributors": [ - "hugojavierduran9" - ] - }, "Mozilla/Add-ons/WebExtensions/Modify_a_web_page": { "modified": "2019-03-18T21:02:55.354Z", "contributors": [ @@ -4490,12 +4429,6 @@ "JoaLop" ] }, - "Mozilla/Firefox/Releases/62": { - "modified": "2019-03-18T21:26:40.295Z", - "contributors": [ - "laptou" - ] - }, "Mozilla/Firefox/Releases/63": { "modified": "2019-03-18T21:22:18.650Z", "contributors": [ @@ -4509,19 +4442,6 @@ "Smartloony" ] }, - "Mozilla/Firefox/Releases/67": { - "modified": "2019-06-27T23:25:44.498Z", - "contributors": [ - "erickton", - "marcorichetta" - ] - }, - "Mozilla/Firefox/Releases/68": { - "modified": "2019-07-14T03:15:02.367Z", - "contributors": [ - "Gummox" - ] - }, "Mozilla/Firefox/Releases/9": { "modified": "2019-12-13T20:33:17.732Z", "contributors": [ @@ -5209,15 +5129,6 @@ "HenryGR" ] }, - "Web/API/CSSRule/parentStyleSheet": { - "modified": "2019-03-23T23:58:10.522Z", - "contributors": [ - "fscholz", - "arunpandianp", - "teoli", - "HenryGR" - ] - }, "Web/API/CSSStyleDeclaration": { "modified": "2019-03-23T22:44:46.721Z", "contributors": [ @@ -5410,12 +5321,6 @@ "elagat" ] }, - "Web/API/Canvas_API/Tutorial/Applying_styles_and_colors": { - "modified": "2020-05-15T18:35:37.655Z", - "contributors": [ - "dimaio77" - ] - }, "Web/API/Canvas_API/Tutorial/Basic_animations": { "modified": "2019-10-10T16:52:52.102Z", "contributors": [ @@ -5603,9 +5508,6 @@ "oderflaj" ] }, - "Web/API/Constraint_validation": { - "modified": "2019-04-22T15:33:44.796Z" - }, "Web/API/Crypto": { "modified": "2020-10-15T22:27:12.417Z", "contributors": [ @@ -5671,16 +5573,6 @@ "Nachec" ] }, - "Web/API/DataTransfer": { - "modified": "2019-03-23T23:17:03.398Z", - "contributors": [ - "wbamberg", - "nmarmon", - "vmv", - "fscholz", - "yonatanalexis22" - ] - }, "Web/API/DeviceMotionEvent": { "modified": "2020-10-15T22:22:26.832Z", "contributors": [ @@ -5919,12 +5811,6 @@ "iarah" ] }, - "Web/API/Document/evaluate": { - "modified": "2019-03-23T22:10:41.891Z", - "contributors": [ - "bryan3561" - ] - }, "Web/API/Document/execCommand": { "modified": "2019-03-23T22:59:11.227Z", "contributors": [ @@ -6586,12 +6472,6 @@ "SoftwareRVG" ] }, - "Web/API/Element/shadowRoot": { - "modified": "2020-10-15T22:21:04.049Z", - "contributors": [ - "quintero_japon" - ] - }, "Web/API/Element/tagName": { "modified": "2019-03-23T23:53:26.081Z", "contributors": [ @@ -6867,12 +6747,6 @@ "BrodaNoel" ] }, - "Web/API/File/type": { - "modified": "2020-10-15T22:26:46.640Z", - "contributors": [ - "IsraelFloresDGA" - ] - }, "Web/API/File/webkitRelativePath": { "modified": "2019-03-23T22:06:35.128Z", "contributors": [ @@ -7123,12 +6997,6 @@ "ehecatl" ] }, - "Web/API/GlobalEventHandlers/onloadedmetadata": { - "modified": "2020-10-15T22:34:40.071Z", - "contributors": [ - "winxde" - ] - }, "Web/API/GlobalEventHandlers/onlostpointercapture": { "modified": "2019-03-23T22:25:49.190Z", "contributors": [ @@ -7242,24 +7110,6 @@ "djrm" ] }, - "Web/API/HTMLContentElement": { - "modified": "2019-03-23T22:10:28.345Z", - "contributors": [ - "dkocho4" - ] - }, - "Web/API/HTMLContentElement/getDistributedNodes": { - "modified": "2019-03-23T22:10:26.488Z", - "contributors": [ - "dkocho4" - ] - }, - "Web/API/HTMLContentElement/select": { - "modified": "2019-03-23T22:10:36.116Z", - "contributors": [ - "dkocho4" - ] - }, "Web/API/HTMLDivElement": { "modified": "2019-03-23T22:03:41.348Z", "contributors": [ @@ -7307,12 +7157,6 @@ "lauramacdaleno" ] }, - "Web/API/HTMLElement/innerText": { - "modified": "2020-10-15T22:31:46.481Z", - "contributors": [ - "hugojavierduran9" - ] - }, "Web/API/HTMLElement/input_event": { "modified": "2020-10-15T22:17:41.989Z", "contributors": [ @@ -7395,12 +7239,6 @@ "jhonarielgj" ] }, - "Web/API/HTMLHtmlElement": { - "modified": "2019-03-23T22:27:47.579Z", - "contributors": [ - "raecillacastellana" - ] - }, "Web/API/HTMLImageElement": { "modified": "2019-03-23T22:42:00.195Z", "contributors": [ @@ -7456,15 +7294,6 @@ "mannypinillo" ] }, - "Web/API/HTMLMediaElement/abort_event": { - "modified": "2019-04-30T13:47:43.431Z", - "contributors": [ - "wbamberg", - "ExE-Boss", - "fscholz", - "balboag" - ] - }, "Web/API/HTMLMediaElement/canplay_event": { "modified": "2019-03-18T20:49:26.430Z", "contributors": [ @@ -7650,12 +7479,6 @@ "translatoon" ] }, - "Web/API/History_API/Example": { - "modified": "2019-03-23T22:29:32.414Z", - "contributors": [ - "maitret" - ] - }, "Web/API/IDBCursor": { "modified": "2019-09-04T06:41:50.466Z", "contributors": [ @@ -7759,19 +7582,6 @@ "pablodonoso" ] }, - "Web/API/KeyboardEvent/getModifierState": { - "modified": "2020-10-15T22:04:42.428Z", - "contributors": [ - "leoderja" - ] - }, - "Web/API/KeyboardEvent/key": { - "modified": "2020-10-15T22:10:09.653Z", - "contributors": [ - "isaacanet", - "aleju92" - ] - }, "Web/API/KeyboardEvent/metaKey": { "modified": "2019-03-23T22:47:47.329Z", "contributors": [ @@ -7970,12 +7780,6 @@ "maedca" ] }, - "Web/API/Navigator/mediaDevices": { - "modified": "2020-12-11T22:18:56.380Z", - "contributors": [ - "daniellimabel" - ] - }, "Web/API/Navigator/registerProtocolHandler": { "modified": "2019-03-23T23:53:04.318Z", "contributors": [ @@ -8271,12 +8075,6 @@ "chrisdavidmills" ] }, - "Web/API/PushManager/permissionState": { - "modified": "2019-03-23T22:39:59.979Z", - "contributors": [ - "maedca" - ] - }, "Web/API/PushManager/supportedContentEncodings": { "modified": "2020-10-15T22:03:55.545Z", "contributors": [ @@ -8344,15 +8142,6 @@ "edhzsz" ] }, - "Web/API/Range/intersectsNode": { - "modified": "2019-03-23T23:53:59.214Z", - "contributors": [ - "fscholz", - "khalid32", - "Mgjbot", - "DR" - ] - }, "Web/API/Range/setStart": { "modified": "2019-03-23T22:13:01.685Z", "contributors": [ @@ -8595,12 +8384,6 @@ "marc2684" ] }, - "Web/API/ServiceWorkerRegistration": { - "modified": "2020-10-15T22:05:45.607Z", - "contributors": [ - "ExE-Boss" - ] - }, "Web/API/Service_Worker_API": { "modified": "2019-03-23T22:09:38.478Z", "contributors": [ @@ -8611,16 +8394,6 @@ "chrisdavidmills" ] }, - "Web/API/Service_Worker_API/Using_Service_Workers": { - "modified": "2019-03-23T22:09:43.848Z", - "contributors": [ - "JasonGlez", - "Vergara", - "GabrielSchlomo", - "Anibalismo", - "darioperez" - ] - }, "Web/API/Storage": { "modified": "2019-03-23T22:37:04.835Z", "contributors": [ @@ -8891,14 +8664,6 @@ "COBRILL4" ] }, - "Web/API/WebGL_API/Tutorial/Animating_objects_with_WebGL": { - "modified": "2019-03-23T23:20:38.388Z", - "contributors": [ - "fscholz", - "teoli", - "luziiann" - ] - }, "Web/API/WebGL_API/Tutorial/Animating_textures_in_WebGL": { "modified": "2019-03-23T22:34:48.400Z", "contributors": [ @@ -9480,12 +9245,6 @@ "Grijander81" ] }, - "Web/API/Window/sidebar": { - "modified": "2019-03-23T22:02:56.395Z", - "contributors": [ - "IsaacSchemm" - ] - }, "Web/API/Window/statusbar": { "modified": "2019-03-23T22:14:36.556Z", "contributors": [ @@ -9520,14 +9279,6 @@ "jccuevas" ] }, - "Web/API/WindowEventHandlers/onunload": { - "modified": "2019-03-23T23:39:28.498Z", - "contributors": [ - "fscholz", - "khalid32", - "Sheppy" - ] - }, "Web/API/WindowOrWorkerGlobalScope": { "modified": "2019-03-23T22:16:40.400Z", "contributors": [ @@ -9706,15 +9457,6 @@ "mmednik" ] }, - "Web/API/XMLHttpRequestEventTarget": { - "modified": "2020-10-15T22:26:08.879Z" - }, - "Web/API/XMLHttpRequestEventTarget/onload": { - "modified": "2020-10-15T22:26:03.172Z", - "contributors": [ - "Akafadam" - ] - }, "Web/API/console/assert": { "modified": "2019-03-23T22:47:53.587Z", "contributors": [ @@ -11035,12 +10777,6 @@ "MilkSnake" ] }, - "Web/CSS/@viewport": { - "modified": "2019-03-18T21:16:54.012Z", - "contributors": [ - "cvrebert" - ] - }, "Web/CSS/Adjacent_sibling_combinator": { "modified": "2019-03-23T22:39:30.908Z", "contributors": [ @@ -11283,12 +11019,6 @@ "ocamachor" ] }, - "Web/CSS/CSS_Grid_Layout/CSS_Grid_Layout_and_Accessibility": { - "modified": "2019-06-05T03:51:45.202Z", - "contributors": [ - "blanchart" - ] - }, "Web/CSS/CSS_Grid_Layout/Realizing_common_layouts_using_CSS_Grid_Layout": { "modified": "2019-03-18T21:34:10.349Z", "contributors": [ @@ -13173,15 +12903,6 @@ "teffcode" ] }, - "Web/CSS/max-width": { - "modified": "2020-10-15T21:16:38.209Z", - "contributors": [ - "SphinxKnight", - "teoli", - "HenryGR", - "Mgjbot" - ] - }, "Web/CSS/min()": { "modified": "2020-12-03T10:19:50.144Z", "contributors": [ @@ -15813,12 +15534,6 @@ "rewin23" ] }, - "Web/HTTP/CORS/Errors/CORSNotSupportingCredentials": { - "modified": "2020-03-25T19:41:08.379Z", - "contributors": [ - "pablogalvezfotografiadeportiva" - ] - }, "Web/HTTP/CORS/Errors/CORSPreflightDidNotSucceed": { "modified": "2019-10-08T04:58:57.176Z", "contributors": [ @@ -15900,12 +15615,6 @@ "gabriel-ar" ] }, - "Web/HTTP/Headers/Accept-Charset": { - "modified": "2020-10-15T22:13:56.858Z", - "contributors": [ - "ArnoldFZ" - ] - }, "Web/HTTP/Headers/Accept-Ranges": { "modified": "2020-10-15T21:52:24.088Z", "contributors": [ @@ -16358,12 +16067,6 @@ "qpdian" ] }, - "Web/HTTP/Status/301": { - "modified": "2020-10-15T22:24:06.781Z", - "contributors": [ - "nullxx" - ] - }, "Web/HTTP/Status/302": { "modified": "2020-10-15T21:59:00.277Z", "contributors": [ @@ -17158,12 +16861,6 @@ "DSN XP" ] }, - "Web/JavaScript/Reference/Deprecated_and_obsolete_features/The_legacy_Iterator_protocol": { - "modified": "2020-03-12T19:42:42.667Z", - "contributors": [ - "clystian" - ] - }, "Web/JavaScript/Reference/Errors": { "modified": "2020-03-12T19:45:01.208Z", "contributors": [ @@ -17280,12 +16977,6 @@ "Luis_Armando" ] }, - "Web/JavaScript/Reference/Errors/Precision_range": { - "modified": "2020-08-10T12:14:52.122Z", - "contributors": [ - "Sgewux" - ] - }, "Web/JavaScript/Reference/Errors/Property_access_denied": { "modified": "2020-03-12T19:46:35.795Z", "contributors": [ @@ -18087,12 +17778,6 @@ "e.g.m.g." ] }, - "Web/JavaScript/Reference/Global_Objects/Date/getUTCHours": { - "modified": "2019-03-23T22:23:56.170Z", - "contributors": [ - "eltrikiman" - ] - }, "Web/JavaScript/Reference/Global_Objects/Date/now": { "modified": "2019-03-23T23:48:17.746Z", "contributors": [ @@ -18632,12 +18317,6 @@ "harleshinn" ] }, - "Web/JavaScript/Reference/Global_Objects/Math/fround": { - "modified": "2020-10-15T22:21:30.568Z", - "contributors": [ - "Itaiu" - ] - }, "Web/JavaScript/Reference/Global_Objects/Math/hypot": { "modified": "2020-10-15T22:01:35.023Z", "contributors": [ @@ -18925,13 +18604,6 @@ "p1errot" ] }, - "Web/JavaScript/Reference/Global_Objects/Object/__lookupGetter__": { - "modified": "2020-10-15T21:59:55.328Z", - "contributors": [ - "al-shmlan", - "jerssonjgar" - ] - }, "Web/JavaScript/Reference/Global_Objects/Object/assign": { "modified": "2020-10-15T21:34:18.548Z", "contributors": [ @@ -20904,12 +20576,6 @@ "Sheppy" ] }, - "Web/Media/Formats/Containers": { - "modified": "2020-07-15T09:47:51.166Z", - "contributors": [ - "hugojavierduran9" - ] - }, "Web/OpenSearch": { "modified": "2019-03-24T00:00:08.096Z", "contributors": [ @@ -20936,12 +20602,6 @@ "c-torres" ] }, - "Web/Performance/How_browsers_work": { - "modified": "2020-09-10T10:11:23.592Z", - "contributors": [ - "sancarbar" - ] - }, "Web/Performance/Optimizing_startup_performance": { "modified": "2019-04-04T17:42:18.542Z", "contributors": [ @@ -21197,15 +20857,6 @@ "d-go" ] }, - "Web/SVG/Tutorial/SVG_In_HTML_Introduction": { - "modified": "2019-03-23T23:21:05.945Z", - "contributors": [ - "chrisdavidmills", - "matrimonio", - "verma21", - "marelin" - ] - }, "Web/SVG/Tutorial/Tools_for_SVG": { "modified": "2019-03-20T13:46:46.393Z", "contributors": [ diff --git a/files/es/games/techniques/3d_on_the_web/index.html b/files/es/games/techniques/3d_on_the_web/index.html deleted file mode 100644 index 3944c617c6..0000000000 --- a/files/es/games/techniques/3d_on_the_web/index.html +++ /dev/null @@ -1,113 +0,0 @@ ---- -title: 3D games on the Web -slug: Games/Techniques/3D_on_the_web -tags: - - Games - - Graphics - - NeedsContent - - NeedsExample - - NeedsTranslation - - TopicStub - - WebGL - - WebVR - - three.js -translation_of: Games/Techniques/3D_on_the_web ---- -<div>{{GamesSidebar}}</div><p class="summary">For rich gaming experiences on the Web the weapon of choice is WebGL, which is rendered on HTML {{htmlelement("canvas")}}. WebGL is basically an OpenGL ES 2.0 for the Web — it's a JavaScript API providing tools to build rich interactive animations and of course also games. You can generate and render dynamic 3D graphics with JavaScript that is hardware accelerated.</p> - -<h2 id="Documentation_and_browser_support">Documentation and browser support</h2> - -<p>The <a href="/en-US/docs/Web/API/WebGL_API">WebGL</a> project documentation and specification is maintained by the <a href="https://www.khronos.org/">Khronos Group</a>, not the W3C as with most of the Web APIs. Support on modern browsers is very good, even on mobile, so you don't have to worry about that too much. The main browsers are all supporting WebGL and all you need to focus on is optimizing the performance on the devices you use.</p> - -<p>There's an ongoing effort on releasing WebGL 2.0 (based on OpenGL ES 3.0) in the near future, which will bring many improvements and will help developers build games for the modern Web using current, powerful hardware.</p> - -<h2 id="Explaining_basic_3D_theory">Explaining basic 3D theory</h2> - -<p>The basics of 3D theory centers around shapes represented in a 3D space, with a coordinate system being used to calculate their positions. See our <a href="https://developer.mozilla.org/en-US/docs/Games/Techniques/3D_on_the_web/Basic_theory">Explaining basic 3D theory</a> article for all the information you need.</p> - -<h2 id="Advanced_concepts">Advanced concepts</h2> - -<p>You can do a lot more with WebGL. There are some advanced concepts which you should dive into and learn more about — like shaders, collision detection, or the latest hot topic — virtual reality on the web.</p> - -<h3 id="Shaders">Shaders</h3> - -<p>It's worth mentioning shaders, which are a separate story on their own. Shaders use GLSL, a special OpenGL Shading Language with syntax similar to C that is executed directly by the graphics pipeline. They can be split into Vertex Shaders and Fragment Shaders (or Pixel Shaders) — the former transforms shape positions to real 3D drawing coordinates, while the latter computes rendering colors and other attributes. You should definitely check out <a href="/en-US/docs/Games/Techniques/3D_on_the_web/GLSL_Shaders">GLSL Shaders</a> article to learn more about them.</p> - -<h3 id="Collision_Detection">Collision Detection</h3> - -<p>It's hard to imagine a game without the collision detection — we always need to work out when something is hitting something else. We have information available for your to learn from:</p> - -<ul> - <li><a href="/en-US/docs/Games/Techniques/2D_collision_detection">2D collision detection</a></li> - <li><a href="/en-US/docs/Games/Techniques/3D_collision_detection">3D collision detection</a></li> -</ul> - -<h3 id="WebVR">WebVR</h3> - -<p>The concept of virtual reality is not new, but it's storming onto the web thanks to hardware advancements such as the <a href="https://www.oculus.com/en-us/rift/">Oculus Rift</a>, and the (currently experimental) <a href="/en-US/docs/Web/API/WebVR_API">WebVR API</a> for capturing information form VR hardware and making it available for use in JavaScript applications. For more, read <a href="/en-US/docs/Games/Techniques/3D_on_the_web/WebVR">WebVR — Virtual Reality for the Web</a>.</p> - -<p>There's also the <a href="/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_A-Frame">Building up a basic demo with A-Frame</a> article showing you how easy it is to build 3D environments for virtual reality using the <a href="http://aframe.io/">A-Frame</a> framework.</p> - -<h2 id="The_rise_of_libraries_and_frameworks">The rise of libraries and frameworks</h2> - -<p>Coding raw WebGL is fairly complex, but you'll want to get to grips with it in the long run, as your projects get more advanced (see our <a href="/en-US/docs/Web/API/WebGL_API">WebGL documentation</a> to get started.) For real world projects you'll probably also make use of a framework to speed up development and help you manage the project you're working on. Using a framework for 3D games also helps optimize the performance as a lot is taken care of by the tools you use, so you can focus on building the game itself.</p> - -<p>The most popular JavaScript 3D library is <a href="http://threejs.org/">Three.js</a>, a multi-purpose tool that makes common 3D techniques simpler to implement. There are other popular game development libraries and frameworks worth checking too; <a href="https://aframe.io">A-Frame</a>, <a href="https://playcanvas.com/">PlayCanvas</a> and <a href="http://www.babylonjs.com/">Babylon.js</a> are among the most recognizable ones with rich documentation, online editors and active communities.</p> - -<h3 id="Building_up_a_basic_demo_with_A-Frame">Building up a basic demo with A-Frame</h3> - -<p>A-Frame is a web framework for building 3D and VR experiences. Under the hood, it is a three.js framework with a declarative entity-component pattern, meaning we can build scenes with just HTML. See the <a href="/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_A-Frame">Building up a basic demo with A-Frame</a> subpage for the step-by-step process of creating the demo.</p> - -<h3 id="Building_up_a_basic_demo_with_Babylon.js">Building up a basic demo with Babylon.js</h3> - -<p><span class="seosummary">Babylon.js is one of the most popular 3D game engines used by developers. As with any other 3D library it provides built-in functions to help you implement common 3D functionality more quickly. See the <a href="/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_Babylon.js">Building up a basic demo with Babylon.js</a> subpage for the basics of using Babylon.js, including setting up a development environment, structuring the necessary HTML, and writing the JavaScript code.</span></p> - -<h3 id="Building_up_a_basic_demo_with_PlayCanvas">Building up a basic demo with PlayCanvas</h3> - -<p>PlayCanvas is a popular 3D WebGL game engine open sourced on GitHub, with an editor available online and good documentation. See the <a href="/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_PlayCanvas">Building up a basic demo with PlayCanvas</a> subpage for high level details, and further articles showing how to create demos using the PlayCanvas library, and the online editor.</p> - -<h3 id="Building_up_a_basic_demo_with_Three.js">Building up a basic demo with Three.js</h3> - -<p>Three.js, as any other library, gives you a huge advantage: instead of writing hundreds of lines of WebGL code to build anything interesting you can use built-in helper functions to do it a lot easier and faster. See the <a href="https://developer.mozilla.org/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_Three.js">Building up a basic demo with Three.js</a> subpage for the step-by-step process of creating the demo.</p> - -<h3 id="Other_tools">Other tools</h3> - -<p>Both <a href="http://unity3d.com/">Unity</a> and <a href="https://www.unrealengine.com/">Unreal</a> can export your game to <a href="/en-US/docs/Web/API/WebGL_API">WebGL</a> with <a href="/en-US/docs/Games/Tools/asm.js">asm.js</a>, so you're free to use their tools and techniques to build games that will be exported to the web.</p> - -<p><img alt="" src="http://end3r.github.io/MDN-Games-3D/A-Frame/img/shapes.png" style="border-style: solid; border-width: 1px; display: block; margin: 0px auto;"></p> - -<h2 id="Where_to_go_next">Where to go next</h2> - -<p>With this article we just scratched the surface of what's possible with currently available technologies. You can build immersive, beautiful and fast 3D games on the Web using WebGL, and the libraries and frameworks build on top of it.</p> - -<h3 id="Source_code">Source code</h3> - -<p>You can find all the source code for this series <a href="http://end3r.github.io/MDN-Games-3D/">demos on GitHub</a>.</p> - -<h3 id="APIs">APIs</h3> - -<ul> - <li><a href="/en-US/docs/Web/API/Canvas_API">Canvas API</a></li> - <li><a href="/en-US/docs/Web/API/WebGL_API">WebGL API</a></li> - <li><a href="/en-US/docs/Web/API/WebVR_API">WebVR API</a></li> -</ul> - -<h3 id="Frameworks">Frameworks</h3> - -<ul> - <li><a href="http://threejs.org/">Three.js</a></li> - <li><a href="https://github.com/WhitestormJS/whs.js">Whitestorm.js</a> (based on Three.js)</li> - <li><a href="https://playcanvas.com/">PlayCanvas</a></li> - <li><a href="http://www.babylonjs.com/">Babylon.js</a></li> - <li><a href="http://aframe.io/">A-Frame</a></li> -</ul> - -<h3 id="Tutorials">Tutorials</h3> - -<ul> - <li><a href="https://developer.mozilla.org/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_Three.js">Building up a basic demo with Three.js</a></li> - <li><a href="https://developer.mozilla.org/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_Whitestorm.js">Building up a basic demo with Whitestorm.js</a></li> - <li><a href="/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_PlayCanvas">Building up a basic demo with PlayCanvas</a></li> - <li><a href="/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_Babylon.js">Building up a basic demo with Babylon.js</a></li> - <li><a href="/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_A-Frame">Building up a basic demo with A-Frame</a></li> -</ul> diff --git a/files/es/learn/css/css_layout/positioning/index.html b/files/es/learn/css/css_layout/positioning/index.html deleted file mode 100644 index 3deb33b91f..0000000000 --- a/files/es/learn/css/css_layout/positioning/index.html +++ /dev/null @@ -1,469 +0,0 @@ ---- -title: Positioning -slug: Learn/CSS/CSS_layout/Positioning -translation_of: Learn/CSS/CSS_layout/Positioning ---- -<div>{{LearnSidebar}}</div> - -<div>{{PreviousMenuNext("Learn/CSS/CSS_layout/Floats", "Learn/CSS/CSS_layout/Practical_positioning_examples", "Learn/CSS/CSS_layout")}}</div> - -<p class="summary">El posicionamiento permite sacar elementos del flujo normal del diseño del documento, y hacer que se comporten de manera distinta, por ejemplo sentarse encima de otro o permanecer en el mismo lugar dentro de la ventana navegador. Este artículo explica los diferentes valores {{cssxref("position")}}, y como usarlos.</p> - -<table class="learn-box standard-table"> - <tbody> - <tr> - <th scope="row">Requisitos:</th> - <td>HTML básico (Aprende <a href="/en-US/docs/Learn/HTML/Introduction_to_HTML"> Introducción a HTML</a>), y una idea de cómo trabaja CSS (Aprende <a href="/en-US/docs/Learn/CSS/Introduction_to_CSS">Introducción a CSS</a>.)</td> - </tr> - <tr> - <th scope="row">Objetivos:</th> - <td>Entender como trabajar con posicionamiento CSS.</td> - </tr> - </tbody> -</table> - -<h2 id="Flujo_del_Documento">Flujo del Documento</h2> - -<p>El posicionamiento es un tema bastante complejo, así que antes de profundizar en el código volvamos a examinar y ampliar un poco la teoría del diseño para darnos una idea de cómo funciona esto.</p> - -<p>First of all, individual element boxes are laid out by taking the elements' content, then adding any padding, border and margin around them — it's that <a href="/en-US/docs/Learn/CSS/Introduction_to_CSS/Box_model">box model</a> thing again, which we looked at earlier. By default, a block level element's content is 100% of the width of its parent element, and as tall as its content. Inline elements are all tall as their content, and as wide as their content. You can't set width or height on inline elements — they just sit inside the content of block level elements. If you want to control the size of an inline element in this manner, you need to set it to behave like a block level element with <code>display: block;</code>.</p> - -<p>That explains individual elements, but what about how elements interact with one another? The <strong>normal layout flow</strong> (mentioned in the layout introduction article) is the system by which elements are placed inside the browser's viewport. By default, block level elements are laid out vertically in the viewport — each one will appear on a new line below the last one, and they will be separated by any margin that is set on them.</p> - -<p>Inline elements behave differently — they don't appear on new lines; instead, they sit on the same line as one another and any adjacent (or wrapped) text content, as long as there is space for them to do so inside the width of the parent block level element. If there isn't space, then the overflowing text or elements will move down to a new line.</p> - -<p>If two adjacent elements both have margin set on them and the two margins touch, the larger of the two remains, and the smaller one disappears — this is called <a href="/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing">margin collapsing</a>, and we have met this before too.</p> - -<p>Let's look at a simple example that explains all this:</p> - -<pre class="brush: html"><h1>Basic document flow</h1> - -<p>I am a basic block level element. My adjacent block level elements sit on new lines below me.</p> - -<p>By default we span 100% of the width of our parent element, and we are as tall as our child content. Our total width and height is our content + padding + border width/height.</p> - -<p>We are separated by our margins. Because of margin collapsing, we are separated by the width of one of our margins, not both.</p> - -<p>inline elements <span>like this one</span> and <span>this one</span> sit on the same line as one another, and adjacent text nodes, if there is space on the same line. Overflowing inline elements will <span>wrap onto a new line if possible (like this one containing text)</span>, or just go on to a new line if not, much like this image will do: <img src="https://mdn.mozillademos.org/files/13360/long.jpg"></p></pre> - -<pre class="brush: css">body { - width: 500px; - margin: 0 auto; -} - -p { - background: aqua; - border: 3px solid blue; - padding: 10px; - margin: 10px; -} - -span { - background: red; - border: 1px solid black; -}</pre> - -<p>{{ EmbedLiveSample('Document_flow', '100%', 500) }}</p> - -<p>We will be revisiting this example a number of times as we go through this article, as we show the effects of the different positioning options available to us.</p> - -<p>We'd like you to follow along with the exercises on your local computer, if possible — grab a copy of <code><a href="http://mdn.github.io/learning-area/css/css-layout/positioning/0_basic-flow.html">0_basic-flow.html</a></code> from our Github repo (<a href="https://github.com/mdn/learning-area/blob/master/css/css-layout/positioning/0_basic-flow.html">source code here</a>) and use that as a starting point.</p> - -<h2 id="Introducing_positioning">Introducing positioning</h2> - -<p>The whole idea of positioning is to allow us to override the basic document flow behaviour described above, to produce interesting effects. What if you want to slightly alter the position of some boxes inside a layout from their default layout flow position, to give a slightly quirky, distressed feel? Positioning is your tool. Or if you want to create a UI element that floats over the top of other parts of the page, and/or always sits in the same place inside the browser window no matter how much the page is scrolled? Positioning makes such layout work possible.</p> - -<p>There are a number of different types of positioning that you can put into effect on HTML elements. To make a specific type of positioning active on an element, we use the {{cssxref("position")}} property.</p> - -<h3 id="Static_positioning">Static positioning</h3> - -<p>Static positioning is the default that every element gets — it just means "put the element into its normal position in the document layout flow — nothing special to see here."</p> - -<p>To demonstrate this, and get your example set up for future sections, first add a <code>class</code> of <code>positioned</code> to the second {{htmlelement("p")}} in the HTML:</p> - -<pre class="brush: html"><p class="positioned"> ... </p></pre> - -<p>Now add the following rule to the bottom of your CSS:</p> - -<pre class="brush: css">.positioned { - position: static; - background: yellow; -}</pre> - -<p>If you now save and refresh, you'll see no difference at all, except for the updated background color of the 2nd paragraph. This is fine — as we said before, static positioning is the default behaviour!</p> - -<div class="note"> -<p><strong>Note</strong>: You can see the example at this point live at <code><a href="http://mdn.github.io/learning-area/css/css-layout/positioning/1_static-positioning.html">1_static-positioning.html</a></code> (<a href="https://github.com/mdn/learning-area/blob/master/css/css-layout/positioning/1_static-positioning.html">see source code</a>).</p> -</div> - -<h3 id="Relative_positioning">Relative positioning</h3> - -<p>Relative positioning is the first position type we'll take a look at. This is very similar to static positioning, except that once the positioned element has taken its place in the normal layout flow, you can then modify its final position, including making it overlap other elements on the page. Go ahead and update the position declaration in your code:</p> - -<pre class="brush: css">position: relative;</pre> - -<p>If you save and refresh at this stage, you won't see a change in the result at all — so how do you modify the element's position? You need to use the {{cssxref("top")}}, {{cssxref("bottom")}}, {{cssxref("left")}}, and {{cssxref("right")}} properties, which we'll explain in the next section.</p> - -<h3 id="Introducing_top_bottom_left_and_right">Introducing top, bottom, left, and right</h3> - -<p>{{cssxref("top")}}, {{cssxref("bottom")}}, {{cssxref("left")}}, and {{cssxref("right")}} are used alongside {{cssxref("position")}} to specify exactly where to move the positioned element to. To try this out, add the following declarations to the <code>.positioned</code> rule in your CSS:</p> - -<pre>top: 30px; -left: 30px;</pre> - -<div class="note"> -<p><strong>Note</strong>: The values of these properties can take any <a href="/en-US/docs/Learn/CSS/Introduction_to_CSS/Values_and_units">units</a> you'd logically expect — pixels, mm, rems, %, etc.</p> -</div> - -<p>If you now save and refresh, you'll get a result something like this:</p> - -<div class="hidden"> -<pre class="brush: html"><h1>Relative positioning</h1> - -<p>I am a basic block level element. My adjacent block level elements sit on new lines below me.</p> - -<p class="positioned">By default we span 100% of the width of our parent element, and we are as tall as our child content. Our total width and height is our content + padding + border width/height.</p> - -<p>We are separated by our margins. Because of margin collapsing, we are separated by the width of one of our margins, not both.</p> - -<p>inline elements <span>like this one</span> and <span>this one</span> sit on the same line as one another, and adjacent text nodes, if there is space on the same line. Overflowing inline elements <span>wrap onto a new line if possible — like this one containing text</span>, or just go on to a new line if not, much like this image will do: <img src="https://mdn.mozillademos.org/files/13360/long.jpg"></p></pre> - -<pre class="brush: css">body { - width: 500px; - margin: 0 auto; -} - -p { - background: aqua; - border: 3px solid blue; - padding: 10px; - margin: 10px; -} - -span { - background: red; - border: 1px solid black; -} - -.positioned { - position: relative; - background: yellow; - top: 30px; - left: 30px; -}</pre> -</div> - -<p>{{ EmbedLiveSample('Introducing_top_bottom_left_and_right', '100%', 500) }}</p> - -<p>Cool, huh? Ok, so this probably wasn't what you were expecting — why has it moved to the bottom and right if we specified top and left? Illogical as it may initially sound, this is just the way that relative positioning works — you need to think of an invisible force that pushes the side of the positioned box, moving it in the opposite direction. So for example, if you specify <code>top: 30px;</code>, a force pushes the top of the box, causing it to move downwards by 30px.</p> - -<div class="note"> -<p><strong>Note</strong>: You can see the example at this point live at <code><a href="http://mdn.github.io/learning-area/css/css-layout/positioning/2_relative-positioning.html">2_relative-positioning.html</a></code> (<a href="https://github.com/mdn/learning-area/blob/master/css/css-layout/positioning/2_relative-positioning.html">see source code</a>).</p> -</div> - -<h3 id="Absolute_positioning">Absolute positioning</h3> - -<p>Absolute positioning brings very different results. Let's try changing the position declaration in your code as follows:</p> - -<pre>position: absolute;</pre> - -<p>If you now save and refresh, you should see something like so:</p> - -<div class="hidden"> -<pre class="brush: html"><h1>Absolute positioning</h1> - -<p>I am a basic block level element. My adjacent block level elements sit on new lines below me.</p> - -<p class="positioned">By default we span 100% of the width of our parent element, and we are as tall as our child content. Our total width and height is our content + padding + border width/height.</p> - -<p>We are separated by our margins. Because of margin collapsing, we are separated by the width of one of our margins, not both.</p> - -<p>inline elements <span>like this one</span> and <span>this one</span> sit on the same line as one another, and adjacent text nodes, if there is space on the same line. Overflowing inline elements <span>wrap onto a new line if possible — like this one containing text</span>, or just go on to a new line if not, much like this image will do: <img src="https://mdn.mozillademos.org/files/13360/long.jpg"></p></pre> - -<pre class="brush: css">body { - width: 500px; - margin: 0 auto; -} - -p { - background: aqua; - border: 3px solid blue; - padding: 10px; - margin: 10px; -} - -span { - background: red; - border: 1px solid black; -} - -.positioned { - position: absolute; - background: yellow; - top: 30px; - left: 30px; -}</pre> -</div> - -<p>{{ EmbedLiveSample('Absolute_positioning', '100%', 420) }}</p> - -<p>First of all, note that the gap where the positioned element should be in the document flow is no longer there — the first and third elements have closed together like it no longer exists! Well, in a way, this is true. An absolutely positioned element no longer exists in the normal document layout flow. Instead, it sits on its own layer separate from everything else. This is very useful — it means that we can create isolated UI features that don't interfere with the position of other elements on the page — for example popup information boxes and control menus, rollover panels, UI features that can be dragged and dropped anywhere on the page, and so on.</p> - -<p>Second, notice that the position of the element has changed — this is because {{cssxref("top")}}, {{cssxref("bottom")}}, {{cssxref("left")}}, and {{cssxref("right")}} behave in a different way with absolute positioning. Instead of specifying the direction the element should move in, they specify the distance the element should be from each containing element's sides. So in this case, we are saying that the absolutely positioned element should sit 30px from the top of the "containing element", and 30px from the left.</p> - -<div class="note"> -<p><strong>Note</strong>: You can use {{cssxref("top")}}, {{cssxref("bottom")}}, {{cssxref("left")}}, and {{cssxref("right")}} to resize elements if you need to. Try setting <code>top: 0; bottom: 0; left: 0; right: 0;</code> and <code>margin: 0;</code> on your positioned elements and see what happens! Put it back again afterwards...</p> -</div> - -<div class="note"> -<p><strong>Note</strong>: Yes, margins still affect positioned elements. Margin collapsing doesn't, however.</p> -</div> - -<div class="note"> -<p><strong>Note</strong>: You can see the example at this point live at <code><a href="http://mdn.github.io/learning-area/css/css-layout/positioning/3_absolute-positioning.html">3_absolute-positioning.html</a></code> (<a href="https://github.com/mdn/learning-area/blob/master/css/css-layout/positioning/3_absolute-positioning.html">see source code</a>).</p> -</div> - -<h3 id="Positioning_contexts">Positioning contexts</h3> - -<p>Which element is the "containing element" of an absolutely positioned element? By default, it is the {{htmlelement("html")}} element — the positioned element is nested inside the {{htmlelement("body")}} in the HTML source, but in the final layout, it is 30px away from the top and left of the edge of the page, which is the {{htmlelement("html")}} element. This is more accurately called the element's <strong>positioning context</strong>.</p> - -<p>We can change the <strong>positioning context</strong> — which element the absolutely positioned element is positioned relative to. This is done by setting positioning on one of the element's other ancestors — one of the elements it is nested inside (you can't position it relative to an element it is not nested inside). To demonstrate this, add the following declaration to your body rule:</p> - -<pre>position: relative;</pre> - -<p>This should give the following result:</p> - -<div class="hidden"> -<pre class="brush: html"><h1>Positioning context</h1> - -<p>I am a basic block level element. My adjacent block level elements sit on new lines below me.</p> - -<p class="positioned">Now I'm absolutely positioned relative to the <code>&lt;body&gt;</code> element, not the <code>&lt;html&gt;</code> element!</p> - -<p>We are separated by our margins. Because of margin collapsing, we are separated by the width of one of our margins, not both.</p> - -<p>inline elements <span>like this one</span> and <span>this one</span> sit on the same line as one another, and adjacent text nodes, if there is space on the same line. Overflowing inline elements <span>wrap onto a new line if possible — like this one containing text</span>, or just go on to a new line if not, much like this image will do: <img src="https://mdn.mozillademos.org/files/13360/long.jpg"></p></pre> - -<pre class="brush: css">body { - width: 500px; - margin: 0 auto; - position: relative; -} - -p { - background: aqua; - border: 3px solid blue; - padding: 10px; - margin: 10px; -} - -span { - background: red; - border: 1px solid black; -} - -.positioned { - position: absolute; - background: yellow; - top: 30px; - left: 30px; -}</pre> -</div> - -<p>{{ EmbedLiveSample('Positioning_contexts', '100%', 420) }}</p> - -<p>The positioned element now sits relative to the {{htmlelement("body")}} element.</p> - -<div class="note"> -<p><strong>Note</strong>: You can see the example at this point live at <code><a href="http://mdn.github.io/learning-area/css/css-layout/positioning/4_positioning-context.html">4_positioning-context.html</a></code> (<a href="https://github.com/mdn/learning-area/blob/master/css/css-layout/positioning/4_positioning-context.html">see source code</a>).</p> -</div> - -<h3 id="Introducing_z-index">Introducing z-index</h3> - -<p>All this absolute positioning is good fun, but there is another thing we haven't considered yet — when elements start to overlap, what determines which elements appear on top of which other elements? In the example we've seen so far, we only have one positioned element in the positioning context, and it appears on the top, since positioned elements win over non-positioned elements. What about when we have more than one?</p> - -<p>Try adding the following to your CSS, to make the first paragraph absolutely positioned too:</p> - -<pre>p:nth-of-type(1) { - position: absolute; - background: lime; - top: 10px; - right: 30px; -}</pre> - -<p>At this point you'll see the first paragraph colored green, moved out of the document flow, and positioned a bit above from where it originally was. It is also stacked below the original <code>.positioned</code> paragraph, where the two overlap. This is because the <code>.positioned</code> paragraph is the second paragraph in the source order, and positioned elements later in the source order win over positioned elements earlier in the source order.</p> - -<p>Can you change the stacking order? Yes, you can, by using the {{cssxref("z-index")}} property. "z-index" is a reference to the z-axis. You may recall from previous points in the source where we discussed web pages using horizontal (x-axis) and vertical (y-axis) coordinates to work out positioning for things like background images and drop shadow offsets. (0,0) is at the top left of the page (or element), and the x- and y-axes run across to the right and down the page (for left to right languages, anyway.)</p> - -<p>Web pages also have a z-axis — an imaginary line that runs from the surface of your screen, towards your face (or whatever else you like to have in front of the screen). {{cssxref("z-index")}} values affect where positioned elements sit on that axis — positive values move them higher up the stack, and negative values move them lower down the stack. By default, positioned elements all have a <code>z-index</code> of auto, which is effectively 0.</p> - -<p>To change the stacking order, try adding the following declaration to your <code>p:nth-of-type(1)</code> rule:</p> - -<pre>z-index: 1;</pre> - -<p>You should now see the finished example:</p> - -<div class="hidden"> -<pre class="brush: html"><h1>z-index</h1> - -<p>I am a basic block level element. My adjacent block level elements sit on new lines below me.</p> - -<p class="positioned">Now I'm absolutely positioned relative to the <code>&lt;body&gt;</code> element, not the <code>&lt;html&gt;</code> element!</p> - -<p>We are separated by our margins. Because of margin collapsing, we are separated by the width of one of our margins, not both.</p> - -<p>inline elements <span>like this one</span> and <span>this one</span> sit on the same line as one another, and adjacent text nodes, if there is space on the same line. Overflowing inline elements <span>wrap onto a new line if possible — like this one containing text</span>, or just go on to a new line if not, much like this image will do: <img src="https://mdn.mozillademos.org/files/13360/long.jpg"></p></pre> - -<pre class="brush: css">body { - width: 500px; - margin: 0 auto; - position: relative; -} - -p { - background: aqua; - border: 3px solid blue; - padding: 10px; - margin: 10px; -} - -span { - background: red; - border: 1px solid black; -} - -.positioned { - position: absolute; - background: yellow; - top: 30px; - left: 30px; -} - -p:nth-of-type(1) { - position: absolute; - background: lime; - top: 10px; - right: 30px; - z-index: 1; -} -</pre> -</div> - -<p>{{ EmbedLiveSample('Introducing_z-index', '100%', 400) }}</p> - -<p>Note that <code>z-index</code> only accepts unitless index values; you can't specify that you want one element to be 23 pixels up the Z-axis — it doesn't work like that. Higher values will go above lower values, and it is up to you what values you use. Using 2 and 3 would give the same effect as 300 and 40000.</p> - -<div class="note"> -<p><strong>Note</strong>: You can see the example at this point live at <code><a href="http://mdn.github.io/learning-area/css/css-layout/positioning/5_z-index.html">5_z-index.html</a></code> (<a href="https://github.com/mdn/learning-area/blob/master/css/css-layout/positioning/5_z-index.html">see source code</a>).</p> -</div> - -<h3 id="Fixed_positioning">Fixed positioning</h3> - -<p>There is one more type of positioning to cover — fixed. This works in exactly the same way as absolute positioning, with one key difference — whereas absolute positioning fixes an element in place relative to the {{htmlelement("html")}} element or its nearest positioned ancestor, fixed positioning fixes an element in place relative to the browser viewport itself. This means that you can create useful UI items that are fixed in place, like persisting navigation menus.</p> - -<p>Let's put together a simple example to show what we mean. First of all, delete the existing <code>p:nth-of-type(1)</code> and <code>.positioned</code> rules from your CSS.</p> - -<p>Now, update the <code>body</code> rule to remove the <code>position: relative;</code> declaration and add a fixed height, like so:</p> - -<pre>body { - width: 500px; - height: 1400px; - margin: 0 auto; -}</pre> - -<p>Now we're going to give the {{htmlelement("h1")}} element <code>position: fixed;</code>, and get it to sit at the top center of the viewport. Add the following rule to your CSS:</p> - -<pre>h1 { - position: fixed; - top: 0; - width: 500px; - margin: 0 auto; - background: white; - padding: 10px; -}</pre> - -<p>The <code>top: 0;</code> is required to make it stick to the top of the screen; we then give the heading the same width as the content column and use the faithful old <code>margin: 0 auto;</code> trick to center it. We then give it a white background and some padding, so the content won't be visible underneath it.</p> - -<p>If you save and refresh now, you'll see a fun little effect whereby the heading stays fixed, and the content appears to scroll up and disappear underneath it. But we could improve this more — at the moment some of the content starts off underneath the heading. This is because the positioned heading no longer appears in the document flow, so the rest of the content moves up to the top. We need to move it all down a bit; we can do this by setting some top margin on the first paragraph. Add this now:</p> - -<pre>p:nth-of-type(1) { - margin-top: 60px; -}</pre> - -<p>You should now see the finished example:</p> - -<div class="hidden"> -<pre class="brush: html"><h1>Fixed positioning</h1> - -<p>I am a basic block level element. My adjacent block level elements sit on new lines below me.</p> - -<p class="positioned">I'm not positioned any more...</p> - -<p>We are separated by our margins. Because of margin collapsing, we are separated by the width of one of our margins, not both.</p> - -<p>inline elements <span>like this one</span> and <span>this one</span> sit on the same line as one another, and adjacent text nodes, if there is space on the same line. Overflowing inline elements <span>wrap onto a new line if possible — like this one containing text</span>, or just go on to a new line if not, much like this image will do: <img src="https://mdn.mozillademos.org/files/13360/long.jpg"></p></pre> - -<pre class="brush: css">body { - width: 500px; - height: 1400px; - margin: 0 auto; -} - -p { - background: aqua; - border: 3px solid blue; - padding: 10px; - margin: 10px; -} - -span { - background: red; - border: 1px solid black; -} - -h1 { - position: fixed; - top: 0px; - width: 500px; - margin: 0 auto; - background: white; - padding: 10px; -} - -p:nth-of-type(1) { - margin-top: 60px; -}</pre> - -<p> </p> -</div> - -<p>{{ EmbedLiveSample('Fixed_positioning', '100%', 400) }}</p> - -<div class="note"> -<p><strong>Note</strong>: You can see the example at this point live at <code><a href="http://mdn.github.io/learning-area/css/css-layout/positioning/6_fixed-positioning.html">6_fixed-positioning.html</a></code> (<a href="https://github.com/mdn/learning-area/blob/master/css/css-layout/positioning/6_fixed-positioning.html">see source code</a>).</p> -</div> - -<h3 id="Experimental_position_sticky">Experimental: position sticky</h3> - -<p>There is a new positioning value available called <code>position: sticky</code>, support for which is not very widespread yet. This is basically a hybrid between relative and fixed position, which allows a positioned element to act like it is relatively positioned until it is scrolled to a certain threshold point (e.g. 10px from the top of the viewport), after which it becomes fixed. See our <a href="/en-US/docs/Web/CSS/position#Sticky_positioning">position: sticky reference entry</a> for more details and an example.</p> - -<h2 id="Summary">Summary</h2> - -<p>I'm sure you had fun playing with basic positioning — it is one of the essential tools behind creating complex CSS layouts and UI features. With that in mind, in the next article we'll have even more fun with positioning — there we'll go a step further and start to build up some real world useful things with it.</p> - -<p>{{PreviousMenuNext("Learn/CSS/CSS_layout/Floats", "Learn/CSS/CSS_layout/Practical_positioning_examples", "Learn/CSS/CSS_layout")}}</p> - -<p> </p> - -<h2 id="In_this_module">In this module</h2> - -<ul> - <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Introduction">Introduction to CSS layout</a></li> - <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Floats">Floats</a></li> - <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Positioning">Positioning</a></li> - <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Practical_positioning_examples">Practical positioning examples</a></li> - <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Flexbox">Flexbox</a></li> - <li><a href="/en-US/docs/Learn/CSS/CSS_layout/Grids">Grids</a></li> -</ul> - -<p> </p> diff --git a/files/es/learn/javascript/client-side_web_apis/fetching_data/index.html b/files/es/learn/javascript/client-side_web_apis/fetching_data/index.html deleted file mode 100644 index ab34b8c319..0000000000 --- a/files/es/learn/javascript/client-side_web_apis/fetching_data/index.html +++ /dev/null @@ -1,373 +0,0 @@ ---- -title: Fetching data from the server -slug: Learn/JavaScript/Client-side_web_APIs/Fetching_data -translation_of: Learn/JavaScript/Client-side_web_APIs/Fetching_data ---- -<div>{{LearnSidebar}}</div> - -<div>{{PreviousMenuNext("Learn/JavaScript/Client-side_web_APIs/Manipulating_documents", "Learn/JavaScript/Client-side_web_APIs/Third_party_APIs", "Learn/JavaScript/Client-side_web_APIs")}}</div> - -<p class="summary">Otra tarea muy común en páginas web y en aplicaciones es tomar elementos individuales de datos desde el servidor para actualizar secciones de la página web sin tener que cargar toda una nueva página. Este aparentemente pequeño detalle tiene un gran impacto en el desempeño y comportamiento de los sitios, por eso en este artículo, explicaremos el concepto y veremos las tecnologías que hacen esto posible, como ser XHLHttpRequest y FetchAPI. </p> - -<table class="learn-box standard-table"> - <tbody> - <tr> - <th scope="row">Prerequisitos:</th> - <td>JavaScript básico (ver <a href="/en-US/docs/Learn/JavaScript/First_steps">first steps</a>, <a href="/en-US/docs/Learn/JavaScript/Building_blocks">building blocks</a>, <a href="/en-US/docs/Learn/JavaScript/Objects">JavaScript objects</a>), <a href="/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Introduction">basics of Client-side APIs</a></td> - </tr> - <tr> - <th scope="row">Objetivo:</th> - <td>Aprender como extraer datos desde el servidor y usarlo para cargar contenido en la página web. </td> - </tr> - </tbody> -</table> - -<h2 id="Cúal_es_el_problema_aquí">Cúal es el problema aquí?</h2> - -<p>Originalmente cargar páginas en la web era simple — tu enviabas una solicitud de la página web al servidor, y si no había ningún problema, los servicios encargados de la página web la descargaban y mostraban en tu computadora.</p> - -<p><img alt="A basic representation of a web site architecture" src="https://mdn.mozillademos.org/files/6475/web-site-architechture@2x.png" style="display: block; height: 134px; margin: 0px auto; width: 484px;"></p> - -<p>El problema con este modelo es que si tu quieres actualizar cualquier parte de la página, por ejemplo, mostrar el nuevo set de productos o cargar una nueva página, tu tenías que cargar toda la página de nuevo. Esto es extremadamente un desperdicio y resultaba ser una experiencia pobre al usuario, especialmente cuando la página es más grande y más compleja. </p> - -<h3 id="Introduciendo_Ajax">Introduciendo Ajax</h3> - -<p>This led to the creation of technologies that allow web pages to request small chunks of data (such as <a href="/en-US/docs/Web/HTML">HTML</a>, {{glossary("XML")}}, <a href="/en-US/docs/Learn/JavaScript/Objects/JSON">JSON</a>, or plain text) and display them only when needed, helping to solve the problem described above.</p> - -<p>This is achieved by using APIs like {{domxref("XMLHttpRequest")}} or — more recently — the <a href="/en-US/docs/Web/API/Fetch_API">Fetch API</a>. These technologies allow web pages to directly handle making <a href="/en-US/docs/Web/HTTP">HTTP</a> requests for specific resources available on a server and formatting the resulting data as needed before it is displayed.</p> - -<div class="note"> -<p><strong>Note</strong>: In the early days, this general technique was known as <a href="https://developer.mozilla.org/en-US/docs/Glossary/Asynchronous">Asynchronous</a> JavaScript and XML (<a href="https://developer.mozilla.org/en-US/docs/Glossary/Ajax">Ajax</a>), because it tended to use {{domxref("XMLHttpRequest")}} to request XML data. This is normally not the case these days (you'd be more likely to use <code>XMLHttpRequest</code> or Fetch to request JSON), but the result is still the same, and the term "Ajax" is still often used to describe the technique.</p> -</div> - -<p><img alt="A simple modern architecture for web sites" src="https://mdn.mozillademos.org/files/6477/moderne-web-site-architechture@2x.png" style="display: block; height: 235px; margin: 0px auto; width: 559px;"></p> - -<p>The Ajax model involves using a web API as a proxy to more intelligently request data rather than just having the browser reload the entire page. Let's think about the significance of this:</p> - -<ol> - <li>Go to one of your favorite information-rich sites, like Amazon, YouTube, CNN, etc., and load it.</li> - <li>Now search for something, like a new product. The main content will change, but most of the surrounding information, like the header, footer, navigation menu, etc., will stay the same.</li> -</ol> - -<p>This is a really good thing because:</p> - -<ul> - <li>Page updates are a lot quicker and you don't have to wait for the page to refresh, meaning that the site feels faster and more responsive.</li> - <li>Less data is downloaded on each update, meaning less wasted bandwidth. This may not be such a big issue on a desktop on a broadband connection, but it's a major issue on mobile devices and in developing countries that don't have ubiquitous fast Internet service.</li> -</ul> - -<p>To speed things up even further, some sites also store assets and data on the user's computer when they are first requested, meaning that on subsequent visits they use the local versions instead of downloading fresh copies when the page is first loaded. The content is only reloaded from the server when it has been updated.</p> - -<p><img alt="A basic web app data flow architecture" src="https://mdn.mozillademos.org/files/6479/web-app-architecture@2x.png" style="display: block; height: 383px; margin: 0px auto; width: 562px;"></p> - -<h2 id="A_basic_Ajax_request">A basic Ajax request</h2> - -<p>Let's look at how such a request is handled, using both {{domxref("XMLHttpRequest")}} and <a href="/en-US/docs/Web/API/Fetch_API">Fetch</a>. For these examples, we'll request data out of a few different text files and use them to populate a content area.</p> - -<p>This series of files will act as our fake database; in a real application, we'd be more likely to use a server-side language like PHP, Python, or Node to request our data from a database. Here, however, we want to keep it simple and concentrate on the client-side part of this.</p> - -<h3 id="XMLHttpRequest">XMLHttpRequest</h3> - -<p><code>XMLHttpRequest</code> (which is frequently abbreviated to XHR) is a fairly old technology now — it was invented by Microsoft in the late '90s, and has been standardized across browsers for quite a long time.</p> - -<ol> - <li> - <p>To begin this example, make a local copy of <a href="https://github.com/mdn/learning-area/blob/master/javascript/apis/fetching-data/ajax-start.html">ajax-start.html</a> and the four text files — <a href="https://github.com/mdn/learning-area/blob/master/javascript/apis/fetching-data/verse1.txt">verse1.txt</a>, <a href="https://github.com/mdn/learning-area/blob/master/javascript/apis/fetching-data/verse2.txt">verse2.txt</a>, <a href="https://github.com/mdn/learning-area/blob/master/javascript/apis/fetching-data/verse3.txt">verse3.txt</a>, and <a href="https://github.com/mdn/learning-area/blob/master/javascript/apis/fetching-data/verse4.txt">verse4.txt</a> — in a new directory on your computer. In this example, we will load a different verse of the poem (which you may well recognize) via XHR when it's selected in the drop-down menu.</p> - </li> - <li> - <p>Just inside the {{htmlelement("script")}} element, add the following code. This stores a reference to the {{htmlelement("select")}} and {{htmlelement("pre")}} elements in variables and defines an {{domxref("GlobalEventHandlers.onchange","onchange")}} event handler function so that when the select's value is changed, its value is passed to an invoked function <code>updateDisplay()</code> as a parameter.</p> - - <pre class="brush: js">var verseChoose = document.querySelector('select'); -var poemDisplay = document.querySelector('pre'); - -verseChoose.onchange = function() { - var verse = verseChoose.value; - updateDisplay(verse); -};</pre> - </li> - <li> - <p>Let's define our <code>updateDisplay()</code> function. First of all, put the following beneath your previous code block — this is the empty shell of the function:</p> - - <pre class="brush: js">function updateDisplay(verse) { - -};</pre> - </li> - <li> - <p>We'll start our function by constructing a relative URL pointing to the text file we want to load, as we'll need it later. The value of the {{htmlelement("select")}} element at any time is the same as the text inside the selected {{htmlelement("option")}} (unless you specify a different value in a value attribute) — so for example "Verse 1". The corresponding verse text file is "verse1.txt", and is in the same directory as the HTML file, therefore just the file name will do.</p> - - <p>However, web servers tend to be case sensitive, and the file name doesn't have a space in it. To convert "Verse 1" to "verse1.txt" we need to convert the V to lower case, remove the space, and add .txt on the end. This can be done with {{jsxref("String.replace", "replace()")}}, {{jsxref("String.toLowerCase", "toLowerCase()")}}, and simple <a href="/en-US/docs/Learn/JavaScript/First_steps/Strings#Concatenating_strings">string concatenation</a>. Add the following lines inside your <code>updateDisplay()</code> function:</p> - - <pre class="brush: js">verse = verse.replace(" ", ""); -verse = verse.toLowerCase(); -var url = verse + '.txt';</pre> - </li> - <li> - <p>To begin creating an XHR request, you need to create a new request object using the {{domxref("XMLHttpRequest.XMLHttpRequest", "XMLHttpRequest()")}} constructor. You can call this object anything you like, but we'll call it <code>request</code> to keep things simple. Add the following below your previous lines:</p> - - <pre class="brush: js">var request = new XMLHttpRequest();</pre> - </li> - <li> - <p>Next, you need to use the {{domxref("XMLHttpRequest.open","open()")}} method to specify what <a href="/en-US/docs/Web/HTTP/Methods">HTTP request method</a> to use to request the resource from the network, and what its URL is. We'll just use the <code><a href="/en-US/docs/Web/HTTP/Methods/GET">GET</a></code> method here and set the URL as our <code>url</code> variable. Add this below your previous line:</p> - - <pre class="brush: js">request.open('GET', url);</pre> - </li> - <li> - <p>Next, we'll set the type of response we are expecting — which is defined by the request's {{domxref("XMLHttpRequest.responseType", "responseType")}} property — as <code>text</code>. This isn't strictly necessary here — XHR returns text by default — but it is a good idea to get into the habit of setting this in case you want to fetch other types of data in the future. Add this next:</p> - - <pre class="brush: js">request.responseType = 'text';</pre> - </li> - <li> - <p>Fetching a resource from the network is an {{glossary("asynchronous")}} operation, meaning that you have to wait for that operation to complete (e.g., the resource is returned from the network) before you can do anything with that response, otherwise, an error will be thrown. XHR allows you to handle this using its {{domxref("XMLHttpRequest.onload", "onload")}} event handler — this is run when the {{event("load")}} event fires (when the response has returned). When this has occurred, the response data will be available in the <code>response</code> property of the XHR request object.</p> - - <p>Add the following below your last addition. You'll see that inside the <code>onload</code> event handler we are setting the <code><a href="/en-US/docs/Web/API/Node/textContent">textContent</a></code> of the <code>poemDisplay</code> (the {{htmlelement("pre")}} element) to the value of the {{domxref("XMLHttpRequest.response", "request.response")}} property.</p> - - <pre class="brush: js">request.onload = function() { - poemDisplay.textContent = request.response; -};</pre> - </li> - <li> - <p>The above is all set up for the XHR request — it won't actually run until we tell it to, which is done using the {{domxref("XMLHttpRequest.send","send()")}} method. Add the following below your previous addition to complete the function:</p> - - <pre class="brush: js">request.send();</pre> - </li> - <li> - <p>One problem with the example as it stands is that it won't show any of the poem when it first loads. To fix this, add the following two lines at the bottom of your code (just above the closing <code></script></code> tag) to load verse 1 by default, and make sure the {{htmlelement("select")}} element always shows the correct value:</p> - - <pre class="brush: js">updateDisplay('Verse 1'); -verseChoose.value = 'Verse 1';</pre> - </li> -</ol> - -<h3 id="Serving_your_example_from_a_server">Serving your example from a server</h3> - -<p>Some browsers (including Chrome) will not run XHR requests if you just run the example from a local file. This is because of security restrictions (for more on web security, read <a href="/en-US/docs/Learn/Server-side/First_steps/Website_security">Website security</a>).</p> - -<p>To get around this, we need to test the example by running it through a local web server. To find out how to do this, read <a href="/en-US/docs/Learn/Common_questions/set_up_a_local_testing_server">How do you set up a local testing server?</a></p> - -<h3 id="Fetch">Fetch</h3> - -<p>The Fetch API is basically a modern replacement for XHR; it was introduced in browsers recently to make asynchronous HTTP requests easier to do in JavaScript, both for developers and other APIs that build on top of Fetch.</p> - -<p>Let's convert the last example to use Fetch instead.</p> - -<ol> - <li> - <p>Make a copy of your previous finished example directory. (If you didn't work through the previous exercise, create a new directory and inside it make copies of <a href="https://github.com/mdn/learning-area/blob/master/javascript/apis/fetching-data/xhr-basic.html">xhr-basic.html</a> and the four text files — <a href="https://github.com/mdn/learning-area/blob/master/javascript/apis/fetching-data/verse1.txt">verse1.txt</a>, <a href="https://github.com/mdn/learning-area/blob/master/javascript/apis/fetching-data/verse2.txt">verse2.txt</a>, <a href="https://github.com/mdn/learning-area/blob/master/javascript/apis/fetching-data/verse3.txt">verse3.txt</a>, and <a href="https://github.com/mdn/learning-area/blob/master/javascript/apis/fetching-data/verse4.txt">verse4.txt</a>.)</p> - </li> - <li> - <p>Inside the <code>updateDisplay()</code> function, find the XHR code:</p> - - <pre class="brush: js">var request = new XMLHttpRequest(); -request.open('GET', url); -request.responseType = 'text'; - -request.onload = function() { - poemDisplay.textContent = request.response; -}; - -request.send();</pre> - </li> - <li> - <p>Replace all the XHR code with this:</p> - - <pre class="brush: js">fetch(url).then(function(response) { - response.text().then(function(text) { - poemDisplay.textContent = text; - }); -});</pre> - </li> - <li> - <p>Load the example in your browser (running it through a web server) and it should work just the same as the XHR version, provided you are running a modern browser.</p> - </li> -</ol> - -<h4 id="So_what_is_going_on_in_the_Fetch_code">So what is going on in the Fetch code?</h4> - -<p>First of all, we invoke the {{domxref("WorkerOrWindowGlobalScope.fetch()","fetch()")}} method, passing it the URL of the resource we want to fetch. This is the modern equivalent of {{domxref("XMLHttpRequest.open","request.open()")}} in XHR, plus you don't need any equivalent to <code>.send()</code>.</p> - -<p>After that, you can see the {{jsxref("Promise.then",".then()")}} method chained onto the end of <code>fetch()</code> — this method is a part of {{jsxref("Promise","Promises")}}, a modern JavaScript feature for performing asynchronous operations. <code>fetch()</code> returns a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">promise</a>, which resolves to the response sent back from the server — we use <code>.then()</code> to run some follow-up code after the promise resolves, which is the function we've defined inside it. This is the equivalent of the <code>onload</code> event handler in the XHR version.</p> - -<p>This function is automatically given the response from the server as a parameter when the <code>fetch()</code> promise resolves. Inside the function we grab the response and run its {{domxref("Body.text","text()")}} method, which basically returns the response as raw text. This is the equivalent of <code>request.responseType = 'text'</code> in the XHR version.</p> - -<p>You'll see that <code>text()</code> also returns a promise, so we chain another <code>.then()</code> onto it, inside of which we define a function to receive the raw text that the <code>text()</code> promise resolves to.</p> - -<p>Inside the inner promise's function, we do much the same as we did in the XHR version — set the {{htmlelement("pre")}} element's text content to the text value.</p> - -<h3 id="Aside_on_promises">Aside on promises</h3> - -<p>Promises are a bit confusing the first time you meet them, but don't worry too much about this for now. You'll get used to them after a while, especially as you learn more about modern JavaScript APIs — most of the newer ones are heavily based on promises.</p> - -<p>Let's look at the promise structure from above again to see if we can make some more sense of it:</p> - -<pre class="brush: js">fetch(url).then(function(response) { - response.text().then(function(text) { - poemDisplay.textContent = text; - }); -});</pre> - -<p>The first line is saying "fetch the resource located at URL" (<code>fetch(url)</code>) and "then run the specified function when the promise resolves" (<code>.then(function() { ... })</code>). "Resolve" means "finish performing the specified operation at some point in the future". The specified operation, in this case, is to fetch a resource from a specified URL (using an HTTP request), and return the response for us to do something with.</p> - -<p>Effectively, the function passed into <code>then()</code> is a chunk of code that won't run immediately. Instead, it will run at some point in the future when the response has been returned. Note that you could also choose to store your promise in a variable and chain {{jsxref("Promise.then",".then()")}} onto that instead. The code below would do the same thing:</p> - -<pre class="brush: js">var myFetch = fetch(url); - -myFetch.then(function(response) { - response.text().then(function(text) { - poemDisplay.textContent = text; - }); -});</pre> - -<p>Because the <code>fetch()</code> method returns a promise that resolves to the HTTP response, any function you define inside a <code>.then()</code> chained onto the end of it will automatically be given the response as a parameter. You can call the parameter anything you like — the below example would still work:</p> - -<pre class="brush: js">fetch(url).then(function(dogBiscuits) { - dogBiscuits.text().then(function(text) { - poemDisplay.textContent = text; - }); -});</pre> - -<p>But it makes more sense to call the parameter something that describes its contents.</p> - -<p>Now let's focus just on the function:</p> - -<pre class="brush: js">function(response) { - response.text().then(function(text) { - poemDisplay.textContent = text; - }); -}</pre> - -<p>The response object has a method {{domxref("Body.text","text()")}} that takes the raw data contained in the response body and turns it into plain text — the format we want it in. It also returns a promise (which resolves to the resulting text string), so here we use another {{jsxref("Promise.then",".then()")}}, inside of which we define another function that dictates what we want to do with that text string. We are just setting the <code><a href="/en-US/docs/Web/API/Node/textContent">textContent</a></code> property of our poem's {{htmlelement("pre")}} element to equal the text string, so this works out pretty simple.</p> - -<p>It is also worth noting that you can directly chain multiple promise blocks (<code>.then()</code> blocks, but there are other types too) onto the end of one another, passing the result of each block to the next block as you travel down the chain. This makes promises very powerful.</p> - -<p>The following block does the same thing as our original example, but is written in a different style:</p> - -<pre class="brush: js">fetch(url).then(function(response) { - return response.text() -}).then(function(text) { - poemDisplay.textContent = text; -});</pre> - -<p>Many developers like this style better, as it is flatter and arguably easier to read for longer promise chains — each subsequent promise comes after the previous one, rather than being inside the previous one (which can get unwieldy). The only other difference is that we've had to include a <code><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Return_values">return</a></code> statement in front of <code>response.text()</code>, to get it to pass its result on to the next link in the chain.</p> - -<h3 id="Which_mechanism_should_you_use">Which mechanism should you use?</h3> - -<p>This really depends on what project you are working on. XHR has been around for a long time now and has very good cross-browser support. Fetch and Promises, on the other hand, are a more recent addition to the web platform, although they're supported well across the browser landscape, with the exception of Internet Explorer.</p> - -<p>If you need to support older browsers, then an XHR solution might be preferable. If however you are working on a more progressive project and aren't as worried about older browsers, then Fetch could be a good choice.</p> - -<p>You should really learn both — Fetch will become more popular as Internet Explorer declines in usage (IE is no longer being developed, in favor of Microsoft's new Edge browser), but you might need XHR for a while yet.</p> - -<h2 id="A_more_complex_example">A more complex example</h2> - -<p>To round off the article, we'll look at a slightly more complex example that shows some more interesting uses of Fetch. We have created a sample site called The Can Store — it's a fictional supermarket that only sells canned goods. You can find this <a href="https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/">example live on GitHub</a>, and <a href="https://github.com/mdn/learning-area/tree/master/javascript/apis/fetching-data/can-store">see the source code</a>.</p> - -<p><img alt="A fake ecommerce site showing search options in the left hand column, and product search results in the right hand column." src="https://mdn.mozillademos.org/files/14779/can-store.png" style="display: block; margin: 0 auto;"></p> - -<p>By default, the site displays all the products, but you can use the form controls in the left hand column to filter them by category, or search term, or both.</p> - -<p>There is quite a lot of complex code that deals with filtering the products by category and search terms, manipulating strings so the data displays correctly in the UI, etc. We won't discuss all of it in the article, but you can find extensive comments in the code (see <a href="https://github.com/mdn/learning-area/blob/master/javascript/apis/fetching-data/can-store/can-script.js">can-script.js</a>).</p> - -<p>We will however explain the Fetch code.</p> - -<p>The first block that uses Fetch can be found at the start of the JavaScript:</p> - -<pre class="brush: js">fetch('products.json').then(function(response) { - return response.json(); -}).then(function(json) { - products = json; - initialize(); -}).catch(function(err) { - console.log('Fetch problem: ' + err.message); -});</pre> - -<p>The <code>fetch()</code> function returns a <code>promise</code>. If this completes successfully, the function inside the first <code>.then()</code> block contains the <code>response</code> returned from the network.</p> - -<p>Inside this function we run {{domxref("Body.json","json()")}} on the response, not {{domxref("Body.text","text()")}}, as we want to return our response as structured JSON data, not plain text.</p> - -<p>Next, we chain another <code>.then()</code> onto the end of our first one, the success function that contains the <code>json</code> returned from the <code>response.json()</code> promise. We set this to be the value of the products global object, then run <code>initialize()</code>, which starts the process of displaying all the products in the user interface.</p> - -<p>To handle errors, we chain a <code>.catch()</code> block onto the end of the chain. This runs if the promise fails for some reason. Inside it, we include a function that is passed as a parameter, an <code>error</code> object. This <code>error</code> object can be used to report the nature of the error that has occurred, in this case we do it with a simple <code>console.log()</code>.</p> - -<p>However, a complete website would handle this error more gracefully by displaying a message on the user's screen and perhaps offering options to remedy the situation, but we don't need anything more than a simple <code>console.log()</code>.</p> - -<p>You can test the fail case yourself:</p> - -<ol> - <li>Make a local copy of the example files (download and unpack <a href="https://github.com/mdn/learning-area/blob/master/javascript/apis/fetching-data/can-store/can-store.zip?raw=true">the can-store ZIP file</a>).</li> - <li>Run the code through a web server (as described above, in {{anch("Serving your example from a server")}}).</li> - <li>Modify the path to the file being fetched, to something like 'produc.json' (make sure it is misspelled).</li> - <li>Now load the index file in your browser (via <code>localhost:8000</code>) and look in your browser developer console. You'll see a message similar to "Network request for products.json failed with response 404: File not found".</li> -</ol> - -<p>The second Fetch block can be found inside the <code>fetchBlob()</code> function:</p> - -<pre class="brush: js">fetch(url).then(function(response) { - return response.blob(); -}).then(function(blob) { - // Convert the blob to an object URL — this is basically an temporary internal URL - // that points to an object stored inside the browser - var objectURL = URL.createObjectURL(blob); - // invoke showProduct - showProduct(objectURL, product); -});</pre> - -<p>This works in much the same way as the previous one, except that instead of using {{domxref("Body.json","json()")}}, we use {{domxref("Body.blob","blob()")}}. In this case we want to return our response as an image file, and the data format we use for that is <a href="/en-US/docs/Web/API/Blob">Blob</a> (the term is an abbreviation of "Binary Large Object" and can basically be used to represent large file-like objects, such as images or video files).</p> - -<p>Once we've successfully received our blob, we create an object URL out of it using {{domxref("URL.createObjectURL()", "createObjectURL()")}}. This returns a temporary internal URL that points to an object referenced inside the browser. These are not very readable, but you can see what one looks like by opening up the Can Store app, Ctrl-/Right-clicking on an image, and selecting the "View image" option (which might vary slightly depending on what browser you are using). The object URL will be visible inside the address bar, and should be something like this:</p> - -<pre>blob:http://localhost:7800/9b75250e-5279-e249-884f-d03eb1fd84f4</pre> - -<h3 id="Challenge_An_XHR_version_of_the_Can_Store">Challenge: An XHR version of the Can Store</h3> - -<p>We'd like you to try converting the Fetch version of the app to use XHR as a useful bit of practice. Take a <a href="https://github.com/mdn/learning-area/blob/master/javascript/apis/fetching-data/can-store/can-store.zip?raw=true">copy of the ZIP file</a>, and try modifying the JavaScript as appropriate.</p> - -<p>Some helpful hints:</p> - -<ul> - <li>You might find the {{domxref("XMLHttpRequest")}} reference material useful.</li> - <li>You will basically need to use the same pattern as you saw earlier in the <a href="https://github.com/mdn/learning-area/blob/master/javascript/apis/fetching-data/xhr-basic.html">XHR-basic.html</a> example.</li> - <li>You will, however, need to add the error handling we showed you in the Fetch version of the Can Store: - <ul> - <li>The response is found in <code>request.response</code> after the <code>load</code> event has fired, not in a promise <code>then()</code>.</li> - <li>About the best equivalent to Fetch's <code>response.ok</code> in XHR is to check whether {{domxref("XMLHttpRequest.status","request.status")}} is equal to 200, or if {{domxref("XMLHttpRequest.readyState","request.readyState")}} is equal to 4.</li> - <li>The properties for getting the status and status message are the same, but they are found on the <code>request</code> (XHR) object, not the <code>response</code> object.</li> - </ul> - </li> -</ul> - -<div class="note"> -<p><strong>Note</strong>: If you have trouble with this, feel free to check your code against the finished version on GitHub (<a href="https://github.com/mdn/learning-area/blob/master/javascript/apis/fetching-data/can-store-xhr/can-script.js">see the source here</a>, and also <a href="https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store-xhr/">see it running live</a>).</p> -</div> - -<h2 id="Summary">Summary</h2> - -<p>This article shows how to start working with both XHR and Fetch to fetch data from the server.</p> - -<h2 id="See_also">See also</h2> - -<p>There are however a lot of different subjects discussed in this article, which has only really scratched the surface. For a lot more detail on these subjects, try the following articles:</p> - -<ul> - <li><a href="/en-US/docs/AJAX/Getting_Started">Ajax — Getting started</a></li> - <li><a href="/en-US/docs/Web/API/Fetch_API/Using_Fetch">Using Fetch</a></li> - <li><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promises</a></li> - <li><a href="/en-US/docs/Learn/JavaScript/Objects/JSON">Working with JSON data</a></li> - <li><a href="/en-US/docs/Web/HTTP/Overview">An overview of HTTP</a></li> - <li><a href="/en-US/docs/Learn/Server-side">Server-side website programming</a></li> -</ul> - -<div>{{PreviousMenuNext("Learn/JavaScript/Client-side_web_APIs/Manipulating_documents", "Learn/JavaScript/Client-side_web_APIs/Third_party_APIs", "Learn/JavaScript/Client-side_web_APIs")}}</div> - -<div> -<h2 id="In_this_module">In this module</h2> - -<ul> - <li><a href="/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Introduction">Introduction to web APIs</a></li> - <li><a href="/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Manipulating_documents">Manipulating documents</a></li> - <li><a href="/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Fetching_data">Fetching data from the server</a></li> - <li><a href="/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Third_party_APIs">Third party APIs</a></li> - <li><a href="/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Drawing_graphics">Drawing graphics</a></li> - <li><a href="/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Video_and_audio_APIs">Video and audio APIs</a></li> - <li><a href="/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Client-side_storage">Client-side storage</a></li> -</ul> -</div> diff --git a/files/es/learn/server-side/express_nodejs/mongoose/index.html b/files/es/learn/server-side/express_nodejs/mongoose/index.html deleted file mode 100644 index f5701c468a..0000000000 --- a/files/es/learn/server-side/express_nodejs/mongoose/index.html +++ /dev/null @@ -1,801 +0,0 @@ ---- -title: 'Express Tutorial 3: Utilizando bases de datos (con Mongoose)' -slug: Learn/Server-side/Express_Nodejs/mongoose -translation_of: Learn/Server-side/Express_Nodejs/mongoose ---- -<div>{{LearnSidebar}}</div> - -<div>{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/skeleton_website", "Learn/Server-side/Express_Nodejs/routes", "Learn/Server-side/Express_Nodejs")}}</div> - -<p class="summary">Este artículo introduce brevemente las bases de datos así como su uso en aplicaciones Node/Express. Despues, profundiza en el uso específico de <a href="http://mongoosejs.com/">Mongoose</a> en el proyecto <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Tutorial_local_library_website">LocalLibrary</a>. Explica como se declaran y utilizan los esquemas modelo-objeto, los principales campos de datos y su validación básica. También muestra brevemente algunas de las muchas formas para acceder y modificar los datos.</p> - -<table class="learn-box standard-table"> - <tbody> - <tr> - <th scope="row">Prerequisitos</th> - <td><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/skeleton_website">Express Tutorial 2: Creando un esqueleto web</a></td> - </tr> - <tr> - <th scope="row">Objetivo:</th> - <td>Ser capaz de crear, diseñar y utilizar bases de datos en Node/Express utilizando Mongoose</td> - </tr> - </tbody> -</table> - -<h2 id="Overview">Overview</h2> - -<p>Library staff will use the Local Library website to store information about books and borrowers, while library members will use it to browse and search for books, find out whether there are any copies available, and then reserve or borrow them. In order to store and retrieve information efficiently, we will store it in a <em>database</em>.</p> - -<p>Las aplicaciones Express pueden utilizar diferentes bases de datos, y existen diferentes aproximaciones que se pueden utilizar para realizar operaciones CRUD (<strong>C</strong>reate, <strong>R</strong>ead, <strong>U</strong>pdate and <strong>D</strong>elete). Este tutorial proporciona una vista general sobre algunas de las opciones disponibles, para a continuación mostrar en detalle los mecanismos elegidos en particular.</p> - -<h3 id="What_databases_can_I_use">What databases can I use?</h3> - -<p><em>Express</em> apps can use any database supported by <em>Node</em> (<em>Express</em> itself doesn't define any specific additional behaviour/requirements for database management). There are <a href="https://expressjs.com/en/guide/database-integration.html">many popular options</a>, including PostgreSQL, MySQL, Redis, SQLite, and MongoDB.</p> - -<p>When choosing a database, you should consider things like time-to-productivity/learning curve, performance, ease of replication/backup, cost, community support, etc. While there is no single "best" database, almost any of the popular solutions should be more than acceptable for a small-to-medium-sized site like our Local Library.</p> - -<p>For more information on the options see: <a href="https://expressjs.com/en/guide/database-integration.html">Database integration</a> (Express docs).</p> - -<h3 id="What_is_the_best_way_to_interact_with_a_database">What is the best way to interact with a database?</h3> - -<p>There are two approaches for interacting with a database: </p> - -<ul> - <li>Using the databases' native query language (e.g. SQL)</li> - <li>Using an Object Data Model ("ODM") / Object Relational Model ("ORM"). An ODM/ORM represents the website's data as JavaScript objects, which are then mapped to the underlying database. Some ORMs are tied to a specific database, while others provide a database-agnostic backend.</li> -</ul> - -<p>The very best <em>performance</em> can be gained by using SQL, or whatever query language is supported by the database. ODM's are often slower because they use translation code to map between objects and the database format, which may not use the most efficient database queries (this is particularly true if the ODM supports different database backends, and must make greater compromises in terms of what database features are supported).</p> - -<p>The benefit of using an ORM is that programmers can continue to think in terms of JavaScript objects rather than database semantics — this is particularly true if you need to work with different databases (on either the same or different websites). They also provide an obvious place to perform validation and checking of data.</p> - -<div class="note"> -<p><strong>Tip:</strong> Using ODM/ORMs often results in lower costs for development and maintenance! Unless you're very familiar with the native query language or performance is paramount, you should strongly consider using an ODM.</p> -</div> - -<h3 id="What_ORMODM_should_I_use">What ORM/ODM should I use?</h3> - -<p>There are many ODM/ORM solutions available on the NPM package manager site (check out the <a href="https://www.npmjs.com/browse/keyword/odm">odm</a> and <a href="https://www.npmjs.com/browse/keyword/orm">orm</a> tags for a subset!).</p> - -<p>A few solutions that were popular at the time of writing are:</p> - -<ul> - <li><a href="https://www.npmjs.com/package/mongoose">Mongoose</a>: Mongoose is a <a href="https://www.mongodb.org/">MongoDB</a> object modeling tool designed to work in an asynchronous environment.</li> - <li><a href="https://www.npmjs.com/package/waterline">Waterline</a>: An ORM extracted from the Express-based <a href="http://sailsjs.com/">Sails</a> web framework. It provides a uniform API for accessing numerous different databases, including Redis, MySQL, LDAP, MongoDB, and Postgres.</li> - <li><a href="https://www.npmjs.com/package/bookshelf">Bookshelf</a>: Features both promise-based and traditional callback interfaces, providing transaction support, eager/nested-eager relation loading, polymorphic associations, and support for one-to-one, one-to-many, and many-to-many relations. Works with PostgreSQL, MySQL, and SQLite3.</li> - <li><a href="https://www.npmjs.com/package/objection">Objection</a>: Makes it as easy as possible to use the full power of SQL and the underlying database engine (supports SQLite3, Postgres, and MySQL).</li> - <li> - <p><a href="https://www.npmjs.com/package/sequelize">Sequelize</a> is a promise-based ORM for Node.js and io.js. It supports the dialects PostgreSQL, MySQL, MariaDB, SQLite and MSSQL and features solid transaction support, relations, read replication and more.</p> - </li> -</ul> - -<p>As a general rule you should consider both the features provided and the "community activity" (downloads, contributions, bug reports, quality of documentation, etc.) when selecting a solution. At time of writing Mongoose is by far the most popular ORM, and is a reasonable choice if you're using MongoDB for your database.</p> - -<h3 id="Using_Mongoose_and_MongoDb_for_the_LocalLibrary">Using Mongoose and MongoDb for the LocalLibrary</h3> - -<p>For the <em>Local Library</em> example (and the rest of this topic) we're going to use the <a href="https://www.npmjs.com/package/mongoose">Mongoose ODM</a> to access our library data. Mongoose acts as a front end to <a href="https://www.mongodb.com/what-is-mongodb">MongoDB</a>, an open source <a href="https://en.wikipedia.org/wiki/NoSQL">NoSQL</a> database that uses a document-oriented data model. A “collection” of “documents”, in a MongoDB database, <a href="https://docs.mongodb.com/manual/core/databases-and-collections/#collections">is analogous to</a> a “table” of “rows” in a relational database.</p> - -<p>This ODM and database combination is extremely popular in the Node community, partially because the document storage and query system looks very much like JSON, and is hence familiar to JavaScript developers.</p> - -<div class="note"> -<p><strong>Tip:</strong> You don't need to know MongoDB in order to use Mongoose, although parts of the <a href="http://mongoosejs.com/docs/guide.html">Mongoose documentation</a> <em>are</em> easier to use and understand if you are already familiar with MongoDB.</p> -</div> - -<p>The rest of this tutorial shows how to define and access the Mongoose schema and models for the <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Tutorial_local_library_website">LocalLibrary website</a> example.</p> - -<h2 id="Designing_the_LocalLibrary_models">Designing the LocalLibrary models</h2> - -<p>Before you jump in and start coding the models, it's worth taking a few minutes to think about what data we need to store and the relationships between the different objects.</p> - -<p>We know that we need to store information about books (title, summary, author, genre, ISBN) and that we might have multiple copies available (with globally unique ids, availability statuses, etc.). We might need to store more information about the author than just their name, and there might be multiple authors with the same or similar names. We want to be able to sort information based on book title, author, genre, and category.</p> - -<p>When designing your models it makes sense to have separate models for every "object" (group of related information). In this case the obvious objects are books, book instances, and authors.</p> - -<p>You might also want to use models to represent selection-list options (e.g. like a drop down list of choices), rather than hard coding the choices into the website itself — this is recommended when all the options aren't known up front or may change. The obvious candidate for a model of this type is the book genre (e.g. Science Fiction, French Poetry, etc.)</p> - -<p>Once we've decided on our models and fields, we need to think about the relationships between them.</p> - -<p>With that in mind, the UML association diagram below shows the models we'll define in this case (as boxes). As discussed above, we've created models for book (the generic details of the book), book instance (status of specific physical copies of the book available in the system), and author. We have also decided to have a model for genre, so that values can be created dynamically. We've decided not to have a model for the <code>BookInstance:status</code> — we will hard code the acceptable values because we don't expect these to change. Within each of the boxes you can see the model name, the field names and types, and also the methods and their return types.</p> - -<p>The diagram also shows the relationships between the models, including their <em>multiplicities</em>. The multiplicities are the numbers on the diagram showing the numbers (maximum and minimum) of each model that may be present in the relationship. For example, the connecting line between the boxes shows that <code>Book</code> and a <code>Genre</code> are related. The numbers close to the <code>Book</code> model show that a Genre must have zero or more <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">Book</span></font> (as many as you like), while the numbers on the other end of the line next to the <code>Genre</code> show that it can have zero or more associated genre.</p> - -<div class="note"> -<p><strong>Note</strong>: As discussed in our <a href="#related_documents">Mongoose primer</a> below it is often better to have the field that defines the relationship between the documents/models in just <em>one</em> model (you can still find the reverse relationship by searching for the associated <code>_id</code> in the other model). Below we have chosen to define the relationship between Book/Genre and Book/Author in the Book schema, and the relationship between the Book/BookInstance in the BookInstance Schema. This choice was somewhat arbitrary — we could equally well have had the field in the other schema.</p> -</div> - -<p><img alt="Mongoose Library Model with correct cardinality" src="https://mdn.mozillademos.org/files/15645/Library%20Website%20-%20Mongoose_Express.png" style="height: 620px; width: 737px;"></p> - -<div class="note"> -<p><strong>Note</strong>: The next section provides a basic primer explaining how models are defined and used. As you read it, consider how we will construct each of the models in the diagram above.</p> -</div> - -<h2 id="Mongoose_primer">Mongoose primer</h2> - -<p>This section provides an overview of how to connect Mongoose to a MongoDB database, how to define a schema and a model, and how to make basic queries. </p> - -<div class="note"> -<p><strong>Note:</strong> This primer is "heavily influenced" by the <a href="https://www.npmjs.com/package/mongoose">Mongoose quick start</a> on <em>npm</em> and the <a href="http://mongoosejs.com/docs/guide.html">official documentation</a>.</p> -</div> - -<h3 id="Installing_Mongoose_and_MongoDB">Installing Mongoose and MongoDB</h3> - -<p>Mongoose is installed in your project (<strong>package.json</strong>) like any other dependency — using NPM. To install it, use the following command inside your project folder:</p> - -<pre class="brush: bash"><code>npm install mongoose</code> -</pre> - -<p>Installing <em>Mongoose</em> adds all its dependencies, including the MongoDB database driver, but it does not install MongoDB itself. If you want to install a MongoDB server then you can <a href="https://www.mongodb.com/download-center">download installers from here</a> for various operating systems and install it locally. You can also use cloud-based MongoDB instances.</p> - -<div class="note"> -<p><strong>Note:</strong> For this tutorial we'll be using the mLab cloud-based <em>database as a service</em> <a href="https://mlab.com/plans/pricing/">sandbox tier</a> to provide the database. This is suitable for development, and makes sense for the tutorial because it makes "installation" operating system independent (database-as-a-service is also one approach you might well use for your production database).</p> -</div> - -<h3 id="Connecting_to_MongoDB">Connecting to MongoDB</h3> - -<p><em>Mongoose</em> requires a connection to a MongoDB database. You can <code>require()</code> and connect to a locally hosted database with <code>mongoose.connect()</code>, as shown below.</p> - -<pre class="brush: js">//Import the mongoose module -var mongoose = require('mongoose'); - -//Set up default mongoose connection -var mongoDB = 'mongodb://127.0.0.1/my_database'; -mongoose.connect(mongoDB); -// Get Mongoose to use the global promise library -mongoose.Promise = global.Promise; -//Get the default connection -var db = mongoose.connection; - -//Bind connection to error event (to get notification of connection errors) -db.on('error', console.error.bind(console, 'MongoDB connection error:'));</pre> - -<p>You can get the default <code>Connection</code> object with <code>mongoose.connection</code>. Once connected, the open event is fired on the <code>Connection</code> instance.</p> - -<div class="note"> -<p><strong>Tip:</strong> If you need to create additional connections you can use <code>mongoose.createConnection()</code>. This takes the same form of database URI (with host, database, port, options etc.) as <code>connect()</code> and returns a <code>Connection</code> object).</p> -</div> - -<h3 id="Defining_and_creating_models">Defining and creating models</h3> - -<p>Models are <em>defined </em>using the <code>Schema</code> interface. The Schema allows you to define the fields stored in each document along with their validation requirements and default values. In addition, you can define static and instance helper methods to make it easier to work with your data types, and also virtual properties that you can use like any other field, but which aren't actually stored in the database (we'll discuss a bit further below).</p> - -<p>Schemas are then "compiled" into models using the <code>mongoose.model()</code> method. Once you have a model you can use it to find, create, update, and delete objects of the given type.</p> - -<div class="note"> -<p><strong>Note:</strong> Each model maps to a <em>collection</em> of <em>documents</em> in the MongoDB database. The documents will contain the fields/schema types defined in the model <code>Schema</code>.</p> -</div> - -<h4 id="Defining_schemas">Defining schemas</h4> - -<p>The code fragment below shows how you might define a simple schema. First you <code>require()</code> mongoose, then use the Schema constructor to create a new schema instance, defining the various fields inside it in the constructor's object parameter.</p> - -<pre class="brush: js">//Require Mongoose -var mongoose = require('mongoose'); - -//Define a schema -var Schema = mongoose.Schema; - -var SomeModelSchema = new Schema({ - a_string: String, - a_date: Date -}); -</pre> - -<p>In the case above we just have two fields, a string and a date. In the next sections we will show some of the other field types, validation, and other methods.</p> - -<h4 id="Creating_a_model">Creating a model</h4> - -<p>Models are created from schemas using the <code>mongoose.model()</code> method:</p> - -<pre class="brush: js">// Define schema -var Schema = mongoose.Schema; - -var SomeModelSchema = new Schema({ - a_string: String, - a_date: Date -}); - -<strong>// Compile model from schema -var SomeModel = mongoose.model('SomeModel', SomeModelSchema );</strong></pre> - -<p>The first argument is the singular name of the collection that will be created for your model (Mongoose will create the database collection for the above model <em>SomeModel</em> above), and the second argument is the schema you want to use in creating the model.</p> - -<div class="note"> -<p><strong>Note:</strong> Once you've defined your model classes you can use them to create, update, or delete records, and to run queries to get all records or particular subsets of records. We'll show you how to do this in the <a href="#Using_models">Using models</a> section, and when we create our views.</p> -</div> - -<h4 id="Tipos_de_esquema_(campos)">Tipos de esquema (campos)</h4> - -<p>Un esquema puede tener un número de campos arbitrario — cada uno representa un campo en los documentos almacenados en <em>MongoDB</em>. A continuación se muestra un ejemplo de esquema con varios de los tipos de campos más comunes y cómo se declaran.</p> - -<pre class="brush: js">var schema = new Schema( -{ - name: <strong>String</strong>, - binary: <strong>Buffer</strong>, - living: <strong>Boolean</strong>, - updated: { type: <strong>Date</strong>, default: Date.now }, - age: { type: <strong>Number</strong>, min: 18, max: 65, required: true }, - mixed: <strong>Schema.Types.Mixed</strong>, - _someId: <strong>Schema.Types.ObjectId</strong>, - array: <strong>[]</strong>, - ofString: [<strong>String</strong>], // You can also have an array of each of the other types too. - nested: { stuff: { type: <strong>String</strong>, lowercase: true, trim: true } } -})</pre> - -<p>Most of the <a href="http://mongoosejs.com/docs/schematypes.html">SchemaTypes</a> (the descriptors after “type:” or after field names) are self explanatory. The exceptions are:</p> - -<ul> - <li><code>ObjectId</code>: Represents specific instances of a model in the database. For example, a book might use this to represent its author object. This will actually contain the unique ID (<code>_id</code>) for the specified object. We can use the <code>populate()</code> method to pull in the associated information when needed.</li> - <li><a href="http://mongoosejs.com/docs/schematypes.html#mixed">Mixed</a>: An arbitrary schema type.</li> - <li><font face="Consolas, Liberation Mono, Courier, monospace">[]</font>: An array of items. You can perform JavaScript array operations on these models (push, pop, unshift, etc.). The examples above show an array of objects without a specified type and an array of <code>String</code> objects, but you can have an array of any type of object.</li> -</ul> - -<p>The code also shows both ways of declaring a field:</p> - -<ul> - <li>Field <em>name</em> and <em>type</em> as a key-value pair (i.e. as done with fields <code>name</code>, <code>binary </code>and <code>living</code>).</li> - <li>Field <em>name</em> followed by an object defining the <code>type</code>, and any other <em>options</em> for the field. Options include things like: - <ul> - <li>default values.</li> - <li>built-in validators (e.g. max/min values) and custom validation functions.</li> - <li>Whether the field is required</li> - <li>Whether <code>String</code> fields should automatically be set to lowercase, uppercase, or trimmed (e.g. <code>{ type: <strong>String</strong>, lowercase: true, trim: true }</code>)</li> - </ul> - </li> -</ul> - -<p>For more information about options see <a href="http://mongoosejs.com/docs/schematypes.html">SchemaTypes</a> (Mongoose docs).</p> - -<h4 id="Validation">Validation</h4> - -<p>Mongoose provides built-in and custom validators, and synchronous and asynchronous validators. It allows you to specify both the acceptable range or values and the error message for validation failure in all cases.</p> - -<p>The built-in validators include:</p> - -<ul> - <li>All <a href="http://mongoosejs.com/docs/schematypes.html">SchemaTypes</a> have the built-in <a href="http://mongoosejs.com/docs/api.html#schematype_SchemaType-required">required</a> validator. This is used to specify whether the field must be supplied in order to save a document.</li> - <li><a href="http://mongoosejs.com/docs/api.html#schema-number-js">Numbers</a> have <a href="http://mongoosejs.com/docs/api.html#schema_number_SchemaNumber-min">min</a> and <a href="http://mongoosejs.com/docs/api.html#schema_number_SchemaNumber-max">max</a> validators.</li> - <li><a href="http://mongoosejs.com/docs/api.html#schema-string-js">Strings</a> have: - <ul> - <li><a href="http://mongoosejs.com/docs/api.html#schema_string_SchemaString-enum">enum</a>: specifies the set of allowed values for the field.</li> - <li><a href="http://mongoosejs.com/docs/api.html#schema_string_SchemaString-match">match</a>: specifies a regular expression that the string must match.</li> - <li><a href="http://mongoosejs.com/docs/api.html#schema_string_SchemaString-maxlength">maxlength</a> and <a href="http://mongoosejs.com/docs/api.html#schema_string_SchemaString-minlength">minlength</a> for the string.</li> - </ul> - </li> -</ul> - -<p>The example below (slightly modified from the Mongoose documents) shows how you can specify some of the validator types and error messages:</p> - -<pre class="brush: js"><code> - var breakfastSchema = new Schema({ - eggs: { - type: Number, - min: [6, 'Too few eggs'], - max: 12, - required: [true, 'Why no eggs?'] - }, - drink: { - type: String, - enum: ['Coffee', 'Tea', 'Water',] - } - }); -</code></pre> - -<p>For complete information on field validation see <a href="http://mongoosejs.com/docs/validation.html">Validation</a> (Mongoose docs).</p> - -<h4 id="Virtual_properties">Virtual properties</h4> - -<p>Virtual properties are document properties that you can get and set but that do not get persisted to MongoDB. The getters are useful for formatting or combining fields, while setters are useful for de-composing a single value into multiple values for storage. The example in the documentation constructs (and deconstructs) a full name virtual property from a first and last name field, which is easier and cleaner than constructing a full name every time one is used in a template.</p> - -<div class="note"> -<p><strong>Note:</strong> We will use a virtual property in the library to define a unique URL for each model record using a path and the record's <code>_id</code> value.</p> -</div> - -<p>For more information see <a href="http://mongoosejs.com/docs/guide.html#virtuals">Virtuals</a> (Mongoose documentation).</p> - -<h4 id="Methods_and_query_helpers">Methods and query helpers</h4> - -<p>A schema can also have <a href="http://mongoosejs.com/docs/guide.html#methods">instance methods</a>, <a href="http://mongoosejs.com/docs/guide.html#statics">static methods</a>, and <a href="http://mongoosejs.com/docs/guide.html#query-helpers">query helpers</a>. The instance and static methods are similar, but with the obvious difference that an instance method is associated with a particular record and has access to the current object. Query helpers allow you to extend mongoose's <a href="http://mongoosejs.com/docs/queries.html">chainable query builder API</a> (for example, allowing you to add a query "byName" in addition to the <code>find()</code>, <code>findOne()</code> and <code>findById()</code> methods).</p> - -<h3 id="Using_models">Using models</h3> - -<p>Once you've created a schema you can use it to create models. The model represents a collection of documents in the database that you can search, while the model's instances represent individual documents that you can save and retrieve.</p> - -<p>We provide a brief overview below. For more information see: <a href="http://mongoosejs.com/docs/models.html">Models</a> (Mongoose docs).</p> - -<h4 id="Creating_and_modifying_documents">Creating and modifying documents</h4> - -<p>To create a record you can define an instance of the model and then call <code>save()</code>. The examples below assume SomeModel is a model (with a single field "name") that we have created from our schema.</p> - -<pre class="brush: js"><code>// Create an instance of model SomeModel -var awesome_instance = new </code>SomeModel<code>({ name: 'awesome' }); - -// Save the new model instance, passing a callback -awesome_instance.save(function (err) { - if (err) return handleError(err); - // saved! -}); -</code></pre> - -<p>Creation of records (along with updates, deletes, and queries) are asynchronous operations — you supply a callback that is called when the operation completes. The API uses the error-first argument convention, so the first argument for the callback will always be an error value (or null). If the API returns some result, this will be provided as the second argument.</p> - -<p>You can also use <code>create()</code> to define the model instance at the same time as you save it. The callback will return an error for the first argument and the newly-created model instance for the second argument.</p> - -<pre class="brush: js">SomeModel<code>.create({ name: 'also_awesome' }, function (err, awesome_instance) { - if (err) return handleError(err); - // saved! -});</code></pre> - -<p>Every model has an associated connection (this will be the default connection when you use <code>mongoose.model()</code>). You create a new connection and call <code>.model()</code> on it to create the documents on a different database.</p> - -<p>You can access the fields in this new record using the dot syntax, and change the values. You have to call <code>save()</code> or <code>update()</code> to store modified values back to the database.</p> - -<pre class="brush: js">// Access model field values using dot notation -console.log(<code>awesome_instance.name</code>); //should log '<code>also_awesome</code>' - -// Change record by modifying the fields, then calling save(). -<code>awesome_instance</code>.name="New cool name"; -<code>awesome_instance.save(function (err) { - if (err) return handleError(err); // saved! - });</code> -</pre> - -<h4 id="Searching_for_records">Searching for records</h4> - -<p>You can search for records using query methods, specifying the query conditions as a JSON document. The code fragment below shows how you might find all athletes in a database that play tennis, returning just the fields for athlete <em>name</em> and <em>age</em>. Here we just specify one matching field (sport) but you can add more criteria, specify regular expression criteria, or remove the conditions altogether to return all athletes.</p> - -<pre class="brush: js"><code>var Athlete = mongoose.model('Athlete', yourSchema); - -// find all athletes who play tennis, selecting the 'name' and 'age' fields -Athlete.find({ 'sport': 'Tennis' }, 'name age', function (err, athletes) { - if (err) return handleError(err); - // 'athletes' contains the list of athletes that match the criteria. -})</code></pre> - -<p>If you specify a callback, as shown above, the query will execute immediately. The callback will be invoked when the search completes.</p> - -<div class="note"> -<p><strong>Note:</strong> All callbacks in Mongoose use the pattern <code>callback(error, result)</code>. If an error occurs executing the query, the <code>error</code> parameter will contain an error document, and <code>result</code> will be null. If the query is successful, the <code>error</code> parameter will be null, and the <code>result</code> will be populated with the results of the query.</p> -</div> - -<p>If you don't specify a callback then the API will return a variable of type <a href="http://mongoosejs.com/docs/api.html#query-js">Query</a>. You can use this query object to build up your query and then execute it (with a callback) later using the <code>exec()</code> method.</p> - -<pre class="brush: js"><code>// find all athletes that play tennis -var query = Athlete.find({ 'sport': 'Tennis' }); - -// selecting the 'name' and 'age' fields -query.select('name age'); - -// limit our results to 5 items -query.limit(5); - -// sort by age -query.sort({ age: -1 }); - -// execute the query at a later time -query.exec(function (err, athletes) { - if (err) return handleError(err); - // athletes contains an ordered list of 5 athletes who play Tennis -})</code></pre> - -<p>Above we've defined the query conditions in the <code>find()</code> method. We can also do this using a <code>where()</code> function, and we can chain all the parts of our query together using the dot operator (.) rather than adding them separately. The code fragment below is the same as our query above, with an additional condition for the age.</p> - -<pre><code>Athlete. - find(). - where('sport').equals('Tennis'). - where('age').gt(17).lt(50). //Additional where query - limit(5). - sort({ age: -1 }). - select('name age'). - exec(callback); // where callback is the name of our callback function.</code></pre> - -<p>The <a href="http://mongoosejs.com/docs/api.html#query_Query-find">find()</a> method gets all matching records, but often you just want to get one match. The following methods query for a single record:</p> - -<ul> - <li><code><a href="http://mongoosejs.com/docs/api.html#model_Model.findById">findById()</a></code>: Finds the document with the specified <code>id</code> (every document has a unique <code>id</code>).</li> - <li><code><a href="http://mongoosejs.com/docs/api.html#query_Query-findOne">findOne()</a></code>: Finds a single document that matches the specified criteria.</li> - <li><code><a href="http://mongoosejs.com/docs/api.html#model_Model.findByIdAndRemove">findByIdAndRemove()</a></code>, <code><a href="http://mongoosejs.com/docs/api.html#model_Model.findByIdAndUpdate">findByIdAndUpdate()</a></code>, <code><a href="http://mongoosejs.com/docs/api.html#query_Query-findOneAndRemove">findOneAndRemove()</a></code>, <code><a href="http://mongoosejs.com/docs/api.html#query_Query-findOneAndUpdate">findOneAndUpdate()</a></code>: Finds a single document by <code>id</code> or criteria and either update or remove it. These are useful convenience functions for updating and removing records.</li> -</ul> - -<div class="note"> -<p><strong>Note:</strong> There is also a <code><a href="http://mongoosejs.com/docs/api.html#model_Model.count">count()</a></code> method that you can use to get the number of items that match conditions. This is useful if you want to perform a count without actually fetching the records.</p> -</div> - -<p>There is a lot more you can do with queries. For more information see: <a href="http://mongoosejs.com/docs/queries.html">Queries</a> (Mongoose docs).</p> - -<h4 id="Working_with_related_documents_—_population">Working with related documents — population</h4> - -<p>You can create references from one document/model instance to another using the <code>ObjectId</code> schema field, or from one document to many using an array of <code>ObjectIds</code>. The field stores the id of the related model. If you need the actual content of the associated document, you can use the <code><a href="http://mongoosejs.com/docs/api.html#query_Query-populate">populate()</a></code> method in a query to replace the id with the actual data.</p> - -<p>For example, the following schema defines authors and stories. Each author can have multiple stories, which we represent as an array of <code>ObjectId</code>. Each story can have a single author. The "ref" (highlighted in bold below) tells the schema which model can be assigned to this field.</p> - -<pre class="brush: js"><code>var mongoose = require('mongoose') - , Schema = mongoose.Schema - -var authorSchema = Schema({ - name : String, - stories : [{ type: Schema.Types.ObjectId, <strong>ref</strong>: 'Story' }] -}); - -var storySchema = Schema({ - author : { type: Schema.Types.ObjectId, <strong>ref</strong>: 'Author' }, - title : String -}); - -var Story = mongoose.model('Story', storySchema); -var Author = mongoose.model('Author', authorSchema);</code></pre> - -<p>We can save our references to the related document by assigning the <code>_id</code> value. Below we create an author, then a story, and assign the author id to our stories author field.</p> - -<pre class="brush: js"><code>var bob = new Author({ name: 'Bob Smith' }); - -bob.save(function (err) { - if (err) return handleError(err); - - //Bob now exists, so lets create a story - var story = new Story({ - title: "Bob goes sledding", - author: bob._id // assign the _id from the our author Bob. This ID is created by default! - }); - - story.save(function (err) { - if (err) return handleError(err); - // Bob now has his story - }); -});</code></pre> - -<p>Our story document now has an author referenced by the author document's ID. In order to get the author information in our story results we use <code>populate()</code>, as shown below.</p> - -<pre class="brush: js"><code>Story -.findOne({ title: 'Bob goes sledding' }) -.populate('author') //This populates the author id with actual author information! -.exec(function (err, story) { - if (err) return handleError(err); - console.log('The author is %s', story.author.name); - // prints "The author is Bob Smith" -});</code></pre> - -<div class="note"> -<p><strong>Note:</strong> Astute readers will have noted that we added an author to our story, but we didn't do anything to add our story to our author's <code>stories</code> array. How then can we get all stories by a particular author? One way would be to add our author to the stories array, but this would result in us having two places where the information relating authors and stories needs to be maintained.</p> - -<p>A better way is to get the <code>_id</code> of our <em>author</em>, then use <code>find()</code> to search for this in the author field across all stories.</p> - -<pre class="brush: js"><code>Story -.find({ author : bob._id }) -.exec(function (err, stories) { - if (err) return handleError(err); - // returns all stories that have Bob's id as their author. -});</code> -</pre> -</div> - -<p>This is almost everything you need to know about working with related items<em> for this tutorial</em>. For more detailed information see <a href="http://mongoosejs.com/docs/populate.html">Population</a> (Mongoose docs).</p> - -<h3 id="One_schemamodel_per_file">One schema/model per file</h3> - -<p>While you can create schemas and models using any file structure you like, we highly recommend defining each model schema in its own module (file), exporting the method to create the model. This is shown below:</p> - -<pre class="brush: js"><code>// File: ./models/somemodel.js - -//Require Mongoose -var mongoose = require('mongoose'); - -//Define a schema -var Schema = mongoose.Schema; - -var SomeModelSchema = new Schema({ - a_string : String, - a_date : Date, -}); - -<strong>//Export function to create "SomeModel" model class -module.exports = mongoose.model('SomeModel', SomeModelSchema );</strong></code></pre> - -<p>You can then require and use the model immediately in other files. Below we show how you might use it to get all instances of the model.</p> - -<pre class="brush: js"><code>//Create a SomeModel model just by requiring the module -var SomeModel = require('../models/somemodel') - -// Use the SomeModel object (model) to find all SomeModel records -SomeModel.find(callback_function);</code></pre> - -<h2 id="Setting_up_the_MongoDB_database">Setting up the MongoDB database</h2> - -<p>Now that we understand something of what Mongoose can do and how we want to design our models, it's time to start work on the <em>LocalLibrary</em> website. The very first thing we want to do is set up a MongoDb database that we can use to store our library data.</p> - -<p>For this tutorial we're going to use <a href="https://mlab.com/welcome/">mLab</a>'s free cloud-hosted "<a href="https://mlab.com/plans/pricing/">sandbox</a>" database. This database tier is not considered suitable for production websites because it has no redundancy, but it is great for development and prototyping. We're using it here because it is free and easy to set up, and because mLab is a popular <em>database as a service</em> vendor that you might reasonably choose for your production database (other popular choices at the time of writing include <a href="https://www.compose.com/">Compose</a>, <a href="https://scalegrid.io/pricing.html">ScaleGrid</a> and <a href="https://www.mongodb.com/cloud/atlas">MongoDB Atlas</a>).</p> - -<div class="note"> -<p><strong>Note:</strong> If you prefer you can set up a MongoDb database locally by downloading and installing the <a href="https://www.mongodb.com/download-center">appropriate binaries for your system</a>. The rest of the instructions in this article would be similar, except for the database URL you would specify when connecting.</p> -</div> - -<p>You will first need to <a href="https://mlab.com/signup/">create an account</a> with mLab (this is free, and just requires that you enter basic contact details and acknowledge their terms of service). </p> - -<p>After logging in, you'll be taken to the <a href="https://mlab.com/home">home</a> screen:</p> - -<ol> - <li>Click <strong>Create New</strong> in the <em>MongoDB Deployments</em> section.<img alt="" src="https://mdn.mozillademos.org/files/14446/mLabCreateNewDeployment.png" style="height: 415px; width: 1000px;"></li> - <li>This will open the <em>Cloud Provider Selection </em>screen.<br> - <img alt="MLab - screen for new deployment" src="https://mdn.mozillademos.org/files/15661/mLab_new_deployment_form_v2.png" style="height: 931px; width: 1297px;"><br> - - <ul> - <li>Select the SANDBOX (Free) plan from the Plan Type section. </li> - <li>Select any provider from the <em>Cloud Provider </em>section. Different providers offer different regions (displayed below the selected plan type).</li> - <li>Click the <strong>Continue</strong> button.</li> - </ul> - </li> - <li>This will open the <em>Select Region</em> screen. - <p><img alt="Select new region screen" src="https://mdn.mozillademos.org/files/15662/mLab_new_deployment_select_region_v2.png" style="height: 570px; width: 1293px;"></p> - - <ul> - <li> - <p>Select the region closest to you and then <strong>Continue</strong>.</p> - </li> - </ul> - </li> - <li> - <p>This will open the <em>Final Details</em> screen.<br> - <img alt="New deployment database name" src="https://mdn.mozillademos.org/files/15663/mLab_new_deployment_final_details.png" style="height: 569px; width: 1293px;"></p> - - <ul> - <li> - <p>Enter the name for the new database as <code>local_library</code> and then select <strong>Continue</strong>.</p> - </li> - </ul> - </li> - <li> - <p>This will open the <em>Order Confirmation</em> screen.<br> - <img alt="Order confirmation screen" src="https://mdn.mozillademos.org/files/15664/mLab_new_deployment_order_confirmation.png" style="height: 687px; width: 1290px;"></p> - - <ul> - <li> - <p>Click <strong>Submit Order</strong> to create the database.</p> - </li> - </ul> - </li> - <li> - <p>You will be returned to the home screen. Click on the new database you just created to open its details screen. As you can see the database has no collections (data).<br> - <img alt="mLab - Database details screen" src="https://mdn.mozillademos.org/files/15665/mLab_new_deployment_database_details.png" style="height: 700px; width: 1398px;"><br> - <br> - The URL that you need to use to access your database is displayed on the form above (shown for this database circled above). In order to use this you need to create a database user that you can specify in the URL.</p> - </li> - <li>Click the <strong>Users</strong> tab and select the <strong>Add database user</strong> button.</li> - <li>Enter a username and password (twice), and then press <strong>Create</strong>. Do not select <em>Make read only</em>.<br> - <img alt="" src="https://mdn.mozillademos.org/files/14454/mLab_database_users.png" style="height: 204px; width: 600px;"></li> -</ol> - -<p>You have now created the database, and have an URL (with username and password) that can be used to access it. This will look something like: <code>mongodb://your_user_namer:your_password@ds119748.mlab.com:19748/local_library</code>.</p> - -<h2 id="Install_Mongoose">Install Mongoose</h2> - -<p>Open a command prompt and navigate to the directory where you created your <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/skeleton_website">skeleton Local Library website</a>. Enter the following command to install Mongoose (and its dependencies) and add it to your <strong>package.json</strong> file, unless you have already done so when reading the <a href="#Installing_Mongoose_and_MongoDB">Mongoose Primer</a> above.</p> - -<pre class="brush: bash">npm install mongoose -</pre> - -<h2 id="Connect_to_MongoDB">Connect to MongoDB</h2> - -<p>Open <strong>/app.js</strong> (in the root of your project) and copy the following text below where you declare the <em>Express application object</em> (after the line <code>var app = express();</code>). Replace the database url string ('<em>insert_your_database_url_here</em>') with the location URL representing your own database (i.e. using the information <a href="#Setting_up_the_MongoDB_database">from mLab</a>).</p> - -<pre class="brush: js">//Set up mongoose connection -var mongoose = require('mongoose'); -var mongoDB = '<em>insert_your_database_url_here</em>'; -mongoose.connect(mongoDB); -mongoose.Promise = global.Promise; -var db = mongoose.connection; -db.on('error', console.error.bind(console, 'MongoDB connection error:'));</pre> - -<p>As discussed <a href="#Connecting_to_MongoDB">in the Mongoose primer above</a>, this code creates the default connection to the database and binds to the error event (so that errors will be printed to the console). </p> - -<h2 id="Defining_the_LocalLibrary_Schema">Defining the LocalLibrary Schema</h2> - -<p>We will define a separate module for each model, as <a href="#One_schemamodel_per_file">discussed above</a>. Start by creating a folder for our models in the project root (<strong>/models</strong>) and then create separate files for each of the models:</p> - -<pre>/express-locallibrary-tutorial //the project root - <strong>/models</strong> - <strong>author.js</strong> - <strong>book.js</strong> - <strong>bookinstance.js</strong> - <strong>genre.js</strong> -</pre> - -<h3 id="Author_model">Author model</h3> - -<p>Copy the <code>Author</code> schema code shown below and paste it into your <strong>./models/author.js</strong> file. The scheme defines an author has having <code>String</code> SchemaTypes for the first and family names, that are required and have a maximum of 100 characters, and <code>Date</code> fields for the date of birth and death.</p> - -<pre class="brush: js">var mongoose = require('mongoose'); - -var Schema = mongoose.Schema; - -var AuthorSchema = new Schema( - { - first_name: {type: String, required: true, max: 100}, - family_name: {type: String, required: true, max: 100}, - date_of_birth: {type: Date}, - date_of_death: {type: Date}, - } -); - -<strong>// Virtual for author's full name -AuthorSchema -.virtual('name') -.get(function () { - return this.family_name + ', ' + this.first_name; -}); - -// Virtual for author's lifespan -AuthorSchema -</strong>.virtual('lifespan') -.get(function () { - return (this.date_of_death.getYear() - this.date_of_birth.getYear()).toString(); -}); - -// Virtual for author's URL -AuthorSchema -.virtual('url') -.get(function () { - return '/catalog/author/' + this._id; -}); - -//Export model -module.exports = mongoose.model('Author', AuthorSchema); - -</pre> - -<p>We've also declared a <a href="#Virtual_properties">virtual</a> for the AuthorSchema named "url" that returns the absolute URL required to get a particular instance of the model — we'll use the property in our templates whenever we need to get a link to a particular author.</p> - -<div class="note"> -<p><strong>Note:</strong> Declaring our URLs as a virtual in the schema is a good idea because then the URL for an item only ever needs to be changed in one place.<br> - At this point, a link using this URL wouldn't work, because we haven't got any routes handling code for individual model instances. We'll set those up in a later article!</p> -</div> - -<p>At the end of the module we export the model.</p> - -<h3 id="Book_model">Book model</h3> - -<p>Copy the <code>Book</code> schema code shown below and paste it into your <strong>./models/book.js</strong> file. Most of this is similar to the author model — we've declared a schema with a number of string fields and a virtual for getting the URL of specific book records, and we've exported the model.</p> - -<pre class="brush: js">var mongoose = require('mongoose'); - -var Schema = mongoose.Schema; - -var BookSchema = new Schema( - { - title: {type: String, required: true}, - <strong> author: {type: Schema.Types.ObjectId, ref: 'Author', required: true},</strong> - summary: {type: String, required: true}, - isbn: {type: String, required: true}, - <strong> genre: [{type: Schema.Types.ObjectId, ref: 'Genre'}]</strong> - } -); - -// Virtual for book's URL -BookSchema -.virtual('url') -.get(function () { - return '/catalog/book/' + this._id; -}); - -//Export model -module.exports = mongoose.model('Book', BookSchema); -</pre> - -<p>The main difference here is that we've created two references to other models:</p> - -<ul> - <li>author is a reference to a single <code>Author</code> model object, and is required.</li> - <li>genre is a reference to an array of <code>Genre</code> model objects. We haven't declared this object yet!</li> -</ul> - -<h3 id="BookInstance_model">BookInstance model</h3> - -<p>Finally, copy the <code>BookInstance</code> schema code shown below and paste it into your <strong>./models/bookinstance.js</strong> file. The <code>BookInstance</code> represents a specific copy of a book that someone might borrow, and includes information about whether the copy is available or on what date it is expected back, "imprint" or version details.</p> - -<pre class="brush: js">var mongoose = require('mongoose'); - -var Schema = mongoose.Schema; - -var BookInstanceSchema = new Schema( - { - book: { type: Schema.Types.ObjectId, ref: 'Book', required: true }, //reference to the associated book - imprint: {type: String, required: true}, - status: {type: String, required: true, <strong>enum: ['Available', 'Maintenance', 'Loaned', 'Reserved']</strong>, <strong>default: 'Maintenance'</strong>}, - due_back: {type: Date, <strong>default: Date.now</strong>} - } -); - -// Virtual for bookinstance's URL -BookInstanceSchema -.virtual('url') -.get(function () { - return '/catalog/bookinstance/' + this._id; -}); - -//Export model -module.exports = mongoose.model('BookInstance', BookInstanceSchema);</pre> - -<p>The new things we show here are the field options:</p> - -<ul> - <li><code>enum</code>: This allows us to set the allowed values of a string. In this case, we use it to specify the availability status of our books (using an enum means that we can prevent mis-spellings and arbitrary values for our status)</li> - <li><code>default</code>: We use default to set the default status for newly created bookinstances to maintenance and the default <code>due_back</code> date to <code>now</code> (note how you can call the Date function when setting the date!)</li> -</ul> - -<p>Everything else should be familiar from our previous schema.</p> - -<h3 id="Genre_model_-_challenge!">Genre model - challenge!</h3> - -<p>Open your <strong>./models/genre.js</strong> file and create a schema for storing genres (the category of book, e.g. whether it is fiction or non-fiction, romance or military history, etc).</p> - -<p>The definition will be very similar to the other models:</p> - -<ul> - <li>The model should have a <code>String</code> SchemaType called <code>name</code> to describe the genre.</li> - <li>This name should be required and have between 3 and 100 characters.</li> - <li>Declare a <a href="#Virtual_properties">virtual</a> for the genre's URL, named <code>url</code>.</li> - <li>Export the model.</li> -</ul> - -<h2 id="Testing_—_create_some_items">Testing — create some items</h2> - -<p>That's it. We now have all models for the site set up!</p> - -<p>In order to test the models (and to create some example books and other items that we can use in our next articles) we'll now run an <em>independent</em> script to create items of each type:</p> - -<ol> - <li>Download (or otherwise create) the file <a href="https://raw.githubusercontent.com/hamishwillee/express-locallibrary-tutorial/master/populatedb.js">populatedb.js</a> inside your <em>express-locallibrary-tutorial</em> directory (in the same level as <code>package.json</code>). - - <div class="note"> - <p><strong>Note:</strong> You don't need to know how <a href="https://raw.githubusercontent.com/hamishwillee/express-locallibrary-tutorial/master/populatedb.js">populatedb.js</a> works; it just adds sample data into the database.</p> - </div> - </li> - <li>Enter the following commands in the project root to install the <em>async</em> module that is required by the script (we'll discuss this in later tutorials, ) - <pre class="brush: bash">npm install async</pre> - </li> - <li>Run the script using node in your command prompt, passing in the URL of your <em>MongoDB</em> database (the same one you replaced the <em>insert_your_database_url_here </em>placeholder with, inside <code>app.js</code> earlier): - <pre class="brush: bash">node populatedb <your mongodb url></pre> - </li> - <li>The script should run through to completion, displaying items as it creates them in the terminal.</li> -</ol> - -<div class="note"> -<p><strong>Tip:</strong> Go to your database on <a href="https://mlab.com/home">mLab</a>. You should now be able to drill down into individual collections of Books, Authors, Genres and BookInstances, and check out individual documents.</p> -</div> - -<h2 id="Summary">Summary</h2> - -<p>In this article, we've learned a bit about databases and ORMs on Node/Express, and a lot about how Mongoose schema and models are defined. We then used this information to design and implement <code>Book</code>, <code>BookInstance</code>, <code>Author</code> and <code>Genre</code> models for the <em>LocalLibrary</em> website.</p> - -<p>Last of all we tested our models by creating a number of instances (using a standalone script). In the next article we'll look at creating some pages to display these objects.</p> - -<h2 id="See_also">See also</h2> - -<ul> - <li><a href="https://expressjs.com/en/guide/database-integration.html">Database integration</a> (Express docs)</li> - <li><a href="http://mongoosejs.com/">Mongoose website</a> (Mongoose docs)</li> - <li><a href="http://mongoosejs.com/docs/guide.html">Mongoose Guide</a> (Mongoose docs)</li> - <li><a href="http://mongoosejs.com/docs/validation.html">Validation</a> (Mongoose docs)</li> - <li><a href="http://mongoosejs.com/docs/schematypes.html">Schema Types</a> (Mongoose docs)</li> - <li><a href="http://mongoosejs.com/docs/models.html">Models</a> (Mongoose docs)</li> - <li><a href="http://mongoosejs.com/docs/queries.html">Queries</a> (Mongoose docs)</li> - <li><a href="http://mongoosejs.com/docs/populate.html">Population</a> (Mongoose docs)</li> -</ul> - -<p>{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/skeleton_website", "Learn/Server-side/Express_Nodejs/routes", "Learn/Server-side/Express_Nodejs")}}</p> - -<p> </p> - -<h2 id="In_this_module">In this module</h2> - -<ul> - <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Introduction">Express/Node introduction</a></li> - <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/development_environment">Setting up a Node (Express) development environment</a></li> - <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Tutorial_local_library_website">Express Tutorial: The Local Library website</a></li> - <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/skeleton_website">Express Tutorial Part 2: Creating a skeleton website</a></li> - <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/mongoose">Express Tutorial Part 3: Using a Database (with Mongoose)</a></li> - <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/routes">Express Tutorial Part 4: Routes and controllers</a></li> - <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data">Express Tutorial Part 5: Displaying library data</a></li> - <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/forms">Express Tutorial Part 6: Working with forms</a></li> - <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/deployment">Express Tutorial Part 7: Deploying to production</a></li> -</ul> - -<p> </p> diff --git a/files/es/learn/tools_and_testing/client-side_javascript_frameworks/vue_getting_started/index.html b/files/es/learn/tools_and_testing/client-side_javascript_frameworks/vue_getting_started/index.html deleted file mode 100644 index 3acb3d4039..0000000000 --- a/files/es/learn/tools_and_testing/client-side_javascript_frameworks/vue_getting_started/index.html +++ /dev/null @@ -1,295 +0,0 @@ ---- -title: Primeros pasos con Vue -slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_getting_started -translation_of: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_getting_started -original_slug: >- - Learn/Herramientas_y_pruebas/Lado-del-cliente_JavaScript_frameworks/Vue_primeros_pasos ---- -<div>{{LearnSidebar}}</div> - -<div>{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_resources","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_first_component", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}</div> - -<p class="summary">Ahora vamos a introducir Vue, el tercero de nuestros frameworks. En este articulo vamos a ver un poco del background de Vue, aprenderemos cómo instalarlo y a crear un nuevo proyecto, estudiar la estructura de alto nivel de todo el proyecto y un componente individual, sabremos como correr el proyecto localmente, y tenerlo preparado para empezar a construir nuestro ejemplo.</p> - -<table class="learn-box standard-table"> - <tbody> - <tr> - <th scope="row">Pre-requisitos:</th> - <td> - <p>Familiaridad con los motores de los lenguajes <a href="/en-US/docs/Learn/HTML">HTML</a>, <a href="/en-US/docs/Learn/CSS">CSS</a>, y <a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages, conocimiento del <a href="/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line">terminal/command line</a>.</p> - - <p>Los componentes Vue son escritos como una combinacion de objectos Javascript que administran los datos de la app y una sintaxis de plantilla basada en HTML que se enlaza con la estructura DOM subyacente. Para la instalación, y para usar algunas de las caracteristicas mas avanzadas de Vue (como Componentes de archivos simples o renderizado de funciones), vas a necesitar un terminar con node + npm instalados.</p> - </td> - </tr> - <tr> - <th scope="row">Objetivo:</th> - <td>Configurar un entorno de desarrollo local de Vue, crear una app de inicio y entender los principios de su funcionamiento.</td> - </tr> - </tbody> -</table> - -<h2 id="Un_Vue_más_claro">Un Vue más claro</h2> - -<p>Vue es un framework moderno de Javascript que proveé facilidades muy utiles para el mejoramiento progresivo- al contrario de otros frameworks, puedes usar Vue para mejorar un HTML exstente. Esto permite usar Vue como un remplazo agregado para una libreria como <a href="/en-US/docs/Glossary/jQuery">JQuery</a>.</p> - -<p>Habiendo dicho esto, tambien puedes usar Vue para escribir completamente una aplicación de una sola página(SPAs).This allows you to create markup managed entirely by Vue, which can improve developer experience and performance when dealing with complex applications. It also allows you to take advantage of libraries for client-side routing and state management when you need to. Additionally, Vue takes a "middle ground" approach to tooling like client-side routing and state management. While the Vue core team maintains suggested libraries for these functions, they are not directly bundled into Vue. This allows you to select a different routing/state management library if they better fit your application.</p> - -<p>In addition to allowing you to progressively integrate Vue into your applications, Vue also provides a progressive approach to writing markup. Like most frameworks, Vue lets you create reusable blocks of markup via components. Most of the time, Vue components are written using a special HTML template syntax. When you need more control than the HTML syntax allows, you can write JSX or plain JavaScript functions to define your components.</p> - -<p>As you work through this tutorial, you might want to keep the <a href="https://vuejs.org/v2/guide/">Vue guide</a> and <a href="https://vuejs.org/v2/api/">API documentation</a> open in other tabs, so you can refer to them if you want more information on any sub topic.<br> - For a good (but potentially biased) comparison between Vue and many of the other frameworks, see <a href="https://vuejs.org/v2/guide/comparison.html">Vue Docs: Comparison with Other Frameworks</a>.</p> - -<h2 id="Installation">Installation</h2> - -<p>To use Vue in an existing site, you can drop one of the following <code><a href="/en-US/docs/Web/HTML/Element/script"><script></a></code> elements onto a page. This allows you to start using Vue on existing sites, which is why Vue prides itself on being a progressive framework. This is a great option when migrating an existing project using a library like JQuery to Vue. With this method, you can use a lot of the core features of Vue, such as the attributes, custom components, and data-management.</p> - -<ul> - <li> - <p>Development Script (Unoptimized, but includes console warnings. Great for development</p> - - <pre class="brush: html notranslate"><script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script></pre> - </li> - <li> - <p>Production Script (Optimized version, minimal console warnings. It is recommended that you specify a version number when including Vue on your site so that any framework updates do not break your live site without you knowing.)</p> - - <pre class="brush: html notranslate"><script src="https://cdn.jsdelivr.net/npm/vue@2"></script></pre> - </li> -</ul> - -<p>However, this approach has some limitations. To build more complex apps, you’ll want to use the <a href="https://www.npmjs.com/package/vue">Vue NPM package</a>. This will let you use advanced features of Vue and take advantage of bundlers like WebPack. To make building apps with Vue easier, there is a CLI to streamline the development process. To use the npm package & the CLI you will need:</p> - -<ol> - <li>Node.js 8.11+ installed.</li> - <li>npm or yarn.</li> -</ol> - -<div class="blockIndicator note"> -<p><strong>Note</strong>: If you don't have the above installed, find out <a href="/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line#Adding_powerups">more about installing npm and Node.js</a> here.</p> -</div> - -<p>To install the CLI, run the following command in your terminal:</p> - -<pre class="brush: bash notranslate">npm install --global @vue/cli</pre> - -<p>Or if you'd prefer to use yarn:</p> - -<pre class="brush: bash notranslate">yarn global add @vue/cli</pre> - -<p>Once installed, to initialize a new project you can then open a terminal in the directory you want to create the project in, and run <code>vue create <project-name></code>. The CLI will then give you a list of project configurations you can use. There are a few preset ones, and you can make your own. These options let you configure things like TypeScript, linting, vue-router, testing, and more.</p> - -<p>We’ll look at using this below.</p> - -<h2 id="Initializing_a_new_project">Initializing a new project</h2> - -<p>To explore various features of Vue, we will be building up a sample todo list app. We'll begin by using the Vue CLI to create a new app framework to build our app into. Follow the steps below:</p> - -<ol> - <li>In terminal, <code>cd</code> to where you'd like to create your sample app, then run <code>vue create moz-todo-vue</code>.</li> - <li>Use the arrow keys and <kbd>Enter</kbd> to select the "Manually select features" option.</li> - <li>The first menu you’ll be presented with allows you to choose which features you want to include in your project. Make sure that "Babel" and "Linter / Formatter" are selected. If they are not, use the arrow keys and the space bar to toggle them on. Once they are selected, press <kbd>Enter</kbd> to proceed.</li> - <li>Next you’ll select a config for the linter / formatter. Navigate to "Eslint with error prevention only" and hit <kbd>Enter</kbd> again. This will help us catch common errors, but not be overly opinionated.</li> - <li>Next you are asked to configure what kind of automated linting we want. Select "Lint on save". This will check for errors when we save a file inside the project. Hit <kbd>Enter</kbd> to continue.</li> - <li>Now, you will select how we want your config files to be managed. "In dedicated config files" will put your config settings for things like ESLint into their own, dedicated files. The other option, "In package.json", will put all of your config settings into the app's <code>package.json</code> file. Select "In dedicated config files" and push <kbd>Enter</kbd>.</li> - <li>Finally, you are asked if you want to save this as a preset for future options. This is entirely up to you. If you like these settings over the existing presets and want to use them again, type <kbd>y</kbd> , otherwise type <kbd>n</kbd>.</li> -</ol> - -<p>The CLI will now begin scaffolding out your project, and installing all of your dependencies.</p> - -<p>If you've never run the Vue CLI before, you'll get one more question — you'll be asked to choose a package manager. You can use the arrow keys to select which one you prefer. The Vue CLI will default to this package manager from now on. If you need to use a different package manager after this, you can pass in a flag <code>--packageManager=<package-manager></code>, when you run <code>vue create</code>. So if you wanted to create the <code>moz-todo-vue</code> project with npm and you'd previously chosen yarn, you’d run <code>vue create moz-todo-vue --packageManager=npm</code>.</p> - -<div class="blockIndicator note"> -<p><strong>Note</strong>: We've not gone over all of the options here, but you can <a href="https://cli.vuejs.org">find more information on the CLI</a> in the Vue docs.</p> -</div> - -<h2 id="Project_structure">Project structure</h2> - -<p>If everything went successfully, the CLI should have created a series of files and directories for your project. The most significant ones are as follows:</p> - -<ul> - <li><code>.eslintrc.js</code>: This is a config file for <a href="https://eslint.org/">eslint</a>. You can use this to manage your linting rules.</li> - <li><code>babel.config.js</code>: This is the config file for <a href="https://babeljs.io/">Babel</a>, which transforms modern JavaScript features being used in development code into older syntax that is more cross-browser compatible in production code. You can register additional babel plugins in this file.</li> - <li><code>.browserslistrc</code>: This is a config for <a href="https://github.com/browserslist/browserslist">Browserslist</a>. You can use this to control which browsers your tooling optimizes for.</li> - <li><code>public</code>: This directory contains static assets that are published, but not processed by <a href="https://webpack.js.org/">Webpack</a> during build (with one exception; <code>index.html</code> gets some processing). - <ul> - <li><code>favicon.ico</code>: This is the favicon for your app. Currently, it's the Vue logo.</li> - <li><code>index.html</code>: This is the template for your app. Your Vue app is run from this HTML page, and you can use lodash template syntax to interpolate values into it. - <div class="note"><strong>Note</strong>: this is not the template for managing the layout of your application — this template is for managing static HTML that sits outside of your Vue app. Editing this file typically only occurs in advanced use cases.</div> - </li> - </ul> - </li> - <li><code>src</code>: This directory contains the core of your Vue app. - <ul> - <li><code>main.js</code>: this is the entry point to your application. Currently, this file initializes your Vue application and signifies which HTML element in the <code>index.html</code> file your app should be attached to. This file is often where you register global components or additional Vue libraries.</li> - <li><code>App.vue</code>: this is the top-level component in your Vue app. See below for more explanation of Vue components.</li> - <li><code>components</code>: this directory is where you keep your components. Currently it just has one example component.</li> - <li><code>assets</code>: This directory is for storing static assets like CSS and images. Because these files are in the source directory, they can be processed by Webpack. This means you can use pre-processors like <a href="https://sass-lang.com/">Sass/SCSS</a> or <a href="https://stylus-lang.com/">Stylus</a>.</li> - </ul> - </li> -</ul> - -<div class="blockIndicator note"> -<p><strong>Note</strong>: Depending on the options you select when creating a new project, there might be other directories present (for example, if you choose a router, you will also have a <code>views</code> directory).</p> -</div> - -<h2 id=".vue_files_single_file_components">.vue files (single file components)</h2> - -<p>Like in many front-end frameworks, components are a central part of building apps in Vue. These components let you break a large application into discrete building blocks that can be created and managed separately, and transfer data between each other as required. These small blocks can help you reason about and test your code.</p> - -<p>While some frameworks encourage you to separate your template, logic, and styling code into separate files, Vue takes the opposite approach. Using <a href="https://vuejs.org/v2/guide/single-file-components.html">Single File Components</a>, Vue lets you group your templates, corresponding script, and CSS all together in a single file ending in <code>.vue</code>. These files are processed by a JS build tool (such as Webpack), which means you can take advantage of build-time tooling in your project. This allows you to use tools like Babel, TypeScript, SCSS and more to create more sophisticated components.</p> - -<p>As a bonus, projects created with the Vue CLI are configured to use <code>.vue</code> files with Webpack out of the box. In fact, if you look inside the <code>src</code> folder in the project we created with the CLI, you'll see your first <code>.vue</code> file: <code>App.vue</code>.</p> - -<p>Let's explore this now.</p> - -<h3 id="App.vue">App.vue</h3> - -<p>Open your <code>App.vue</code> file — you’ll see that it has three parts: <code><template></code>, <code><script></code>, and <code><style></code>, which contain the component’s template, scripting, and styling information. All Single File Components share this same basic structure.</p> - -<p><code><template></code> contains all the markup structure and display logic of your component. Your template can contain any valid HTML, as well as some Vue-specific syntax that we'll cover later.</p> - -<div class="blockIndicator note"> -<p><strong>Note</strong>: By setting the <code>lang</code> attribute on the <code><template></code> tag, you can use Pug template syntax instead of standard HTML — <code><template lang="pug"></code>. We'll stick to standard HTML through this tutorial, but it is worth knowing that this is possible.</p> -</div> - -<p><code><script></code> contains all of the non-display logic of your component. Most importantly, your <code><script></code> tag needs to have a default exported JS object. This object is where you locally register components, define component inputs (props), handle local state, define methods, and more. Your build step will process this object and transform it (with your template) into a Vue component with a <code>render()</code> function.</p> - -<p>In the case of <code>App.vue</code>, our default export sets the name of the component to <code>app</code> and registers the <code>HelloWorld</code> component by adding it into the <code>components</code> property. When you register a component in this way, you're registering it locally. Locally registered components can only be used inside the components that register them, so you need to import and register them in every component file that uses them. This can be useful for bundle splitting/tree shaking since not every page in your app necessarily needs every component.</p> - -<pre class="brush: js notranslate">import HelloWorld from './components/HelloWorld.vue'; - -export default { - name: 'app', - components: { - //You can register components locally here. - HelloWorld - } -};</pre> - -<div class="blockIndicator note"> -<p><strong>Note</strong>: If you want to use <a href="https://www.typescriptlang.org/">TypeScript</a> syntax, you need to set the <code>lang</code> attribute on the <code><script></code> tag to signify to the compiler that you're using TypeScript — <code><script lang="ts"></code>.</p> -</div> - -<p><code><style></code> is where you write your CSS for the component. If you add a <code>scoped</code> attribute — <code><style scoped></code> — Vue will scope the styles to the contents of your SFC. This works similar to CSS-in-JS solutions, but allows you to just write plain CSS.</p> - -<div class="blockIndicator note"> -<p><strong>Note</strong>: If you select a CSS pre-processor when creating the project via the CLI, you can add a <code>lang</code> attribute to the <code><style></code> tag so that the contents can be processed by Webpack at build time. For example, <code><style lang="scss"></code> will allow you to use SCSS syntax in your styling information.</p> -</div> - -<h2 id="Running_the_app_locally">Running the app locally</h2> - -<p>The Vue CLI comes with a built-in development server. This allows you to run your app locally so you can test it easily without needing to configure a server yourself. The CLI adds a <code>serve</code> command to the project’s <code>package.json</code> file as an npm script, so you can easily run it.</p> - -<p>In your terminal, try running <code>npm run serve</code> (or <code>yarn serve</code> if you prefer yarn). Your terminal should output something like the following:</p> - -<pre class="notranslate">INFO Starting development server... -98% after emitting CopyPlugin - - DONE Compiled successfully in 18121ms - - App running at: - - Local: <http://localhost:8080/> - - Network: <http://192.168.1.9:8080/> - - Note that the development build is not optimized. - To create a production build, run npm run build.</pre> - -<p>If you navigate to the “local” address in a new browser tab (this should be something like <code>http://localhost:8080</code> as stated above, but may vary based on your setup), you should see your app. Right now, it should contain a welcome message, a link to the Vue documentation, links to the plugins you added when you initialized the app with your CLI, and some other useful links to the Vue community and ecosystem.</p> - -<p><img alt="default vue app render, with vue logo, welcome message, and some documentation links" src="https://mdn.mozillademos.org/files/17240/vue-default-app.png" style="border-style: solid; border-width: 1px; height: 779px; width: 1600px;"></p> - -<h2 id="Making_a_couple_of_changes">Making a couple of changes</h2> - -<p>Let's make our first change to the app — we’ll delete the Vue logo. Open the <code>App.vue</code> file, and delete the <code><a href="/en-US/docs/Web/HTML/Element/img"><img></a></code> element from the template section:</p> - -<pre class="brush: html notranslate"><span class="author-d-iz88z86z86za0dz67zz78zz78zz74zz68zjz80zz71z9iz90z8h7gz67ziz76zcz77zz80zz71zncfz69zz69ziaz82zz71zz72zhz77zz122zz90z14mcyd"><img alt="Vue logo" src="./assets/logo.png"></span></pre> - -<p>If your server is still running, you should see the logo removed from the rendered site almost instantly. Let’s also remove the <code>HelloWorld</code> component from our template.</p> - -<p>First of all delete this line:</p> - -<pre class="brush: html notranslate"><HelloWorld msg="Welcome to Your Vue.js App"/></pre> - -<p>If you save your <code>App.vue</code> file now, the rendered app will throw an error because we’ve registered the component but are not using it. We also need to remove the lines from inside the <code><script></code> element that import and register the component:</p> - -<p>Delete these lines now:</p> - -<pre class="brush: js notranslate">import HelloWorld from './components/HelloWorld.vue'</pre> - -<pre class="brush: js notranslate">components: { - HelloWorld -}</pre> - -<p>Your rendered app should no longer show an error, just a blank page, as we currently have no visible content inside <code><template></code>.</p> - -<p>Let’s add a new <code><h1></code> inside <code><div id="app"></code>. Since we’re going to be creating a todo list app below, let's set our header text to "To-Do List". Add it like so:</p> - -<pre class="brush: html notranslate"><template> - <div id="app"> - <h1>To-Do List</h1> - </div> -</template></pre> - -<p><code>App.vue</code> will now show our heading, as you'd expect.</p> - -<h2 id="Summary">Summary</h2> - -<p>Let's leave this here for now. We've learnt about some of the ideas behind Vue, created some scaffolding for our example app to live inside, inspected it, and made a few preliminary changes.</p> - -<p>With a basic introduction out of the way, we'll now go further and build up our sample app, a basic Todo list application that allows us to store a list of items, check them off when done, and filter the list by all, complete, and incomplete todos.</p> - -<p>In the next article we'll build our first custom component, and look at some important concepts such as passing props into it and saving its data state.</p> - -<p>{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_resources","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_first_component", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}</p> - -<h2 id="In_this_module">In this module</h2> - -<ul> - <li><a href="/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Introduction">Introduction to client-side frameworks</a></li> - <li><a href="/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Main_features">Framework main features</a></li> - <li>React - <ul> - <li><a href="/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started">Getting started with React</a></li> - <li><a href="/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_todo_list_beginning">Beginning our React todo list</a></li> - <li><a href="/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_components">Componentizing our React app</a></li> - <li><a href="/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_interactivity_events_state">React interactivity: Events and state</a></li> - <li><a href="/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_interactivity_filtering_conditional_rendering">React interactivity: Editing, filtering, conditional rendering</a></li> - <li><a href="/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_accessibility">Accessibility in React</a></li> - <li><a href="/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_resources">React resources</a></li> - </ul> - </li> - <li>Ember - <ul> - <li><a href="/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_getting_started">Getting started with Ember</a></li> - <li><a href="/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_structure_componentization">Ember app structure and componentization</a></li> - <li><a href="/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_interactivity_events_state">Ember interactivity: Events, classes and state</a></li> - <li><a href="/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_conditional_footer">Ember Interactivity: Footer functionality, conditional rendering</a></li> - <li><a href="/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_routing">Routing in Ember</a></li> - <li><a href="/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_resources">Ember resources and troubleshooting</a></li> - </ul> - </li> - <li>Vue - <ul> - <li><a href="/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_getting_started">Getting started with Vue</a></li> - <li><a href="/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_first_component">Creating our first Vue component</a></li> - <li><a href="/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_rendering_lists">Rendering a list of Vue components</a></li> - <li><a href="/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_methods_events_models">Adding a new todo form: Vue events, methods, and models</a></li> - <li><a href="/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_styling">Styling Vue components with CSS</a></li> - <li><a href="/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_computed_properties">Using Vue computed properties</a></li> - <li><a href="/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_conditional_rendering">Vue conditional rendering: editing existing todos</a></li> - <li><a href="/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_refs_focus_management">Focus management with Vue refs</a></li> - <li><a href="/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_resources">Vue resources</a></li> - </ul> - </li> - <li>Svelte - <ul> - <li><a href="/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_getting_started">Getting started with Svelte</a></li> - <li><a href="/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_Todo_list_beginning">Starting our Svelte Todo list app</a></li> - <li><a href="/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_variables_props">Dynamic behavior in Svelte: working with variables and props</a></li> - <li><a href="/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_components">Componentizing our Svelte app</a></li> - <li><a href="/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_reactivity_lifecycle_accessibility">Advanced Svelte: Reactivity, lifecycle, accessibility</a></li> - <li><a href="/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_stores">Working with Svelte stores</a></li> - <li><a href="/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_TypeScript">TypeScript support in Svelte</a></li> - <li><a href="/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_deployment_next">Deployment and next steps</a></li> - </ul> - </li> -</ul> diff --git a/files/es/mdn/contribute/howto/document_a_css_property/index.html b/files/es/mdn/contribute/howto/document_a_css_property/index.html deleted file mode 100644 index 41b3fcb14f..0000000000 --- a/files/es/mdn/contribute/howto/document_a_css_property/index.html +++ /dev/null @@ -1,82 +0,0 @@ ---- -title: Cómo documentar una propiedad CSS -slug: MDN/Contribute/Howto/Document_a_CSS_property -translation_of: MDN/Contribute/Howto/Document_a_CSS_property ---- -<div>{{MDNSidebar}}</div> - -<div>{{IncludeSubnav("/en-US/docs/MDN")}}</div> - -<p>As the <a href="/en-US/docs/Web/CSS">CSS</a> standards evolve, new properties are always being added. The MDN <a href="/en-US/docs/Web/CSS/Reference">CSS Reference</a> needs to be kept up to date with these developments. This document gives step-by-step instructions for creating a CSS property reference page.</p> - -<p>Each CSS property reference page follows the same structure. This helps readers find information more easily, especially once they are familiar with the standard reference page format.</p> - -<h2 id="Step_1_—_Decide_which_property_to_document">Step 1 — Decide which property to document</h2> - -<p>First, you will need to decide which property to document. The <em>CSS Documentation status</em> page lists properties that <a href="/en-US/docs/Web/CSS/Documentation_status#Missing_pages">need to be documented</a>. For details about the CSS property you will need to find a relevant specification for it (e.g., a <a href="http://www.w3.org/Style/CSS/">W3C specification</a>, a <a href="https://wiki.mozilla.org">Mozilla Wiki page</a>, or a bug report for a non-standard property used in rendering engines like Gecko or Blink).</p> - -<div class="note"> -<p><strong>Pro tips:</strong></p> - -<ul> - <li>When using a W3C spec, always use the <strong>Editor's Draft</strong> (note the red banner on the left side) and not a published version (e.g. Working Draft). The Editor's Draft is always closer to the final version!</li> - <li>If the implementation and spec diverge, feel free to mention it in the implementation bug: it may be a bug in the implementation (and a follow-up bug will be filed), a delay in the publication of a new spec, or an error in the spec (in which case a spec bug is worth filing).</li> -</ul> -</div> - -<h2 id="Step_2_—_Check_the_database_of_CSS_properties">Step 2 — Check the database of CSS properties</h2> - -<p>Several characteristics of a CSS property, such as its syntax or if it can be animated, are mentioned in several pages and are therefore stored in an ad-hoc database. Macros that you'll use on the page need information about the property that is stored there, so start by <a href="/en-US/docs/MDN/Contribute/Howto/Update_the_CSS_JSON_DB">checking that this information is there</a>.</p> - -<p>If not, contact an admin or a power user, either on the <a href="https://chat.mozilla.org/#/room/#mdn:mozilla.org">MDN Web Docs chat room</a>, or, if nobody is available, by <a href="https://github.com/mdn/sprints/issues/new?template=issue-template.md">filing an issue report</a>.</p> - -<h2 id="Step_3_—_Creating_the_CSS_property_page">Step 3 — Creating the CSS property page</h2> - -<p>Preparations finished! Now we can add the actual CSS property page. The easiest way to create a new CSS property page is to copy the content of an existing page and to edit it. We will go through the different steps now.</p> - -<div class="note"> -<p>Cloning a page is currently broken on MDN. That's why we need to go through these somewhat more complex steps. Please vote for ({{bug(870691)}}).</p> -</div> - -<ol> - <li>Clone the <a href="/en-US/docs/MDN/Contribute/Howto/Document_a_CSS_property/Property_template">following page</a>, set the title to <em>your-property</em> (without capitals) and the slug to <code>Web/CSS/<em>your-property</em></code><em>.</em></li> - <li>Change the summary to fit, but keep it starting the same way : "The <em><code>your-property</code></em> <a href="/en-US/docs/Web/CSS">CSS</a> property…". Explain briefly what this property is for.</li> - <li>If the property is not experimental, remove the <code>\{{SeeCompatTable}}</code> macro. The purpose of this macro is to alert developers to the possibility that the feature may not yet have consistent support across browsers, and may change in the future as its specificaton evolves. Deciding whether a feature is experimental is a matter of judgement, and should include factors like: - <ul> - <li>Is the feature supported by several browsers?</li> - <li>Is the feature prefixed or behind a preference?</li> - <li>Is there any reason to think that the implementation of the feature will change in the future?</li> - </ul> - </li> - <li>Replace the parameter of the <code>\{{cssinfo("animation-name")}}</code> macro by the name of the CSS property you are documenting. This will allow you to build the summary box using the data you entered in step 2.</li> - <li>Replace the example of the syntax by relevant ones. Keep them very simple and don't forget that a lot of people don't understand a formal syntax so it needs to be simple and exhaustive. Keep the <code>inherit</code>, <code>initial</code>, and <code>unset</code> keywords examples at the end. It reminds users that these are valid values, too.</li> - <li>Under the chapter <em>Values</em>, put the meaning of each value. If it is a keyword, don't forget to mark it as code (select it and press <code>CTRL-O</code>). Each description should start by "Is a" followed by the type of the value, or indicating it is a keyword.</li> - <li>Clear the <em>Examples</em> chapter, we will add them at the end!</li> - <li>Update the specification table. For information about how to do it, read this <a href="/en-US/docs/MDN/Contribute/Structures/Specification_tables">tutorial</a>.</li> - <li>Update the compatibility information. For information about how to do it, read this <a href="/en-US/docs/MDN/Contribute/Structures/Compatibility_tables">tutorial</a>.</li> - <li>Update the <em>See also</em> section with relevant links. Do not link to specs here and usually link to internal documents. External documents are welcome, but only if they bring really good information. There are spam or SEO links often, so don't worry if external links are removed sometimes. Just start the discussion if you still find it useful and want to see it back.</li> - <li>Add the relevant tags: you need to add <code>CSS</code>, <code>CSS Property</code>, and <code>Reference.</code> You also need to add <code>Experimental</code> or <code>Non-standard</code> if this is the case. Finally you also need to add a <code>CSS XYZ</code> tag, where XYZ stands for the group of CSS properties it belongs to. It is often the spec short name. All these tags are used to generate quicklinks and other niceties.</li> -</ol> - -<p>At any point, you can save by hitting the <code>SAVE</code> button. You can continue to edit right along. If you haven't saved your page until now, please do so! :-)</p> - -<p>The last step is to add <em>Examples</em>. To do that follow this <a href="/en-US/docs/Project:MDN/Contributing/Editor_guide/Live_samples">tutorial about live samples</a>. Don't forget that we are in a document explaining one single property: you need to add examples that show how this property is working in isolation, not how the whole specification is used. That means, examples for <code>list-style-type</code> will show what the different values generate, but not how to combine it with other property, pseudo-classes or pseudo-elements to generate nice effects; tutorials and guide can be written to show more.</p> - -<h2 id="Step_4_—_Getting_a_review">Step 4 — Getting a review</h2> - -<p>You have documented your CSS property! Congratulations!</p> - -<p>In order to have a good quality and consistency throughout the MDN CSS reference, it is good practice to request a review. Just click on the checkbox at the bottom of the article (in edit mode), and, optional, if you want to have a more personal review helping you to improve editorial skills, ask for it on the <a href="https://discourse.mozilla-community.org/c/mdn">MDN forum</a>.</p> - -<h2 id="Step_5_—_Integrating_the_new_page_in_the_MDN">Step 5 — Integrating the new page in the MDN</h2> - -<p>Now that your page is created, you want it to be found by the readers. Adding tags helped about this already as it allowed it to appear in the quicklinks to related CSS pages. Also you want it to appear on the <a href="/en-US/docs/Web/CSS/Reference">CSS index page</a>. If the newly documented property is on the standard track and at least one major browser is implementing it, it deserves to be listed this. Only administrator can add it there, so contact the CSS driver on IRC (currently at #mdn ping teoli) or file a documentation bug requesting it.</p> - -<p>Also, if the property is implemented by Firefox, you need to check that it is listed, and linked! in the correct <a href="/en-US/Firefox/Releases">Firefox for developers</a> MDN page. The new CSS property is likely already listed in the HTML section, just be sure that its name links back to your newly created page.</p> - -<h2 id="Contact_us">Contact us</h2> - -<ul> - <li>On IRC: <a href="irc://irc.mozilla.org/mdn">#mdn</a></li> - <li><a href="https://discourse.mozilla.org/c/mdn">Discourse</a></li> -</ul> diff --git a/files/es/mozilla/add-ons/webextensions/api/webnavigation/index.html b/files/es/mozilla/add-ons/webextensions/api/webnavigation/index.html deleted file mode 100644 index d561c6d796..0000000000 --- a/files/es/mozilla/add-ons/webextensions/api/webnavigation/index.html +++ /dev/null @@ -1,144 +0,0 @@ ---- -title: webNavigation -slug: Mozilla/Add-ons/WebExtensions/API/webNavigation -translation_of: Mozilla/Add-ons/WebExtensions/API/webNavigation ---- -<div>{{AddonSidebar}}</div> - -<p>Add event listeners for the various stages of a navigation. A navigation consists of a frame in the browser transitioning from one URL to another, usually (but not always) in response to a user action like clicking a link or entering a URL in the location bar.</p> - -<p>Compared with the {{WebExtAPIRef("webRequest")}} API: navigations usually result in the browser making web requests, but the webRequest API is concerned with the lower-level view from the HTTP layer, while the webNavigation API is more concerned with the view from the browser UI itself.</p> - -<p>Each event corresponds to a particular stage in the navigation. The sequence of events is like this:</p> - -<p><img alt="" src="https://mdn.mozillademos.org/files/13374/we-flow.png" style="display: block; height: 562px; margin-left: auto; margin-right: auto; width: 745px;"></p> - -<ul> - <li>The primary flow is: - <ul> - <li><code>{{WebExtAPIRef("webNavigation.onBeforeNavigate", "onBeforeNavigate")}}</code></li> - <li><code>{{WebExtAPIRef("webNavigation.onCommitted", "onCommitted")}}</code></li> - <li><code>{{WebExtAPIRef("webNavigation.onDOMContentLoaded", "onDOMContentLoaded")}}</code></li> - <li><code>{{WebExtAPIRef("webNavigation.onCompleted", "onCompleted")}}</code>.</li> - </ul> - </li> - <li>Additionally: - <ul> - <li><code>{{WebExtAPIRef("webNavigation.onCreatedNavigationTarget", "onCreatedNavigationTarget")}}</code> is fired before <code>onBeforeNavigate</code> if the browser needed to create a new tab or window for the navigation (for example, because the user opened a link in a new tab).</li> - <li>{{WebExtAPIRef("webNavigation.onHistoryStateUpdated", "onHistoryStateUpdated")}} is fired if a page uses the <a href="http://diveintohtml5.info/history.html">history API</a> to update the URL displayed in the browser's location bar.</li> - <li>{{WebExtAPIRef("webNavigation.onReferenceFragmentUpdated", "onReferenceFragmentUpdated")}} is fired if the <a href="https://en.wikipedia.org/wiki/Fragment_identifier">fragment identifier</a> for a page is changed.</li> - <li>{{WebExtAPIRef("webNavigation.onErrorOccurred", "onErrorOccurred")}} can be fired at any point.</li> - </ul> - </li> -</ul> - -<p>Each navigation is a URL transition in a particular browser frame. The browser frame is identified by a tab ID and a frame ID. The frame may be the top-level browsing context in the tab, or may be a nested browsing context implemented as an <a href="/en-US/docs/Web/HTML/Element/iframe">iframe</a>.</p> - -<p>Each event's <code>addListener()</code> call accepts an optional filter parameter. The filter will specify one or more URL patterns, and the event will then only be fired for navigations in which the target URL matches one of the patterns.</p> - -<p>The <code>onCommitted</code> event listener is passed two additional properties: a {{WebExtAPIRef("webNavigation.TransitionType","TransitionType")}} indicating the cause of the navigation (for example, because the user clicked a link, or because the user selected a bookmark), and a {{WebExtAPIRef("webNavigation.TransitionQualifier","TransitionQualifier")}} providing further information about the navigation.</p> - -<p>To use this API you need to have the "webNavigation" <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions">permission</a>.</p> - -<h2 id="Types">Types</h2> - -<dl> - <dt>{{WebExtAPIRef("webNavigation.TransitionType")}}</dt> - <dd>Cause of the navigation: for example, the user clicked a link, or typed an address, or clicked a bookmark.</dd> - <dt>{{WebExtAPIRef("webNavigation.TransitionQualifier")}}</dt> - <dd> - <div>Extra information about a transition.</div> - </dd> -</dl> - -<h2 id="Functions">Functions</h2> - -<dl> - <dt>{{WebExtAPIRef("webNavigation.getFrame()")}}</dt> - <dd>Retrieves information about a particular frame. A frame may be the top-level frame in a tab or a nested <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe">iframe</a>, and is uniquely identified by a tab ID and a frame ID.</dd> - <dt>{{WebExtAPIRef("webNavigation.getAllFrames()")}}</dt> - <dd> - <p>Given a tab ID, retrieves information about all the frames it contains.</p> - </dd> -</dl> - -<h2 id="Events">Events</h2> - -<dl> - <dt>{{WebExtAPIRef("webNavigation.onBeforeNavigate")}}</dt> - <dd> - <p>Fired when the browser is about to start a navigation event.</p> - </dd> - <dt>{{WebExtAPIRef("webNavigation.onCommitted")}}</dt> - <dd>Fired when a navigation is committed. At least part of the new document has been received from the server and the browser has decided to switch to the new document.</dd> - <dt>{{WebExtAPIRef("webNavigation.onDOMContentLoaded")}}</dt> - <dd>Fired when the <a href="https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded">DOMContentLoaded</a> event is fired in the page.</dd> - <dt>{{WebExtAPIRef("webNavigation.onCompleted")}}</dt> - <dd>Fired when a document, including the resources it refers to, is completely loaded and initialized. This is equivalent to the DOM <code><a href="https://developer.mozilla.org/en-US/docs/Web/Events/load">load</a></code> event.</dd> - <dt>{{WebExtAPIRef("webNavigation.onErrorOccurred")}}</dt> - <dd>Fired when an error occurs and the navigation is aborted. This can happen if either a network error occurred, or the user aborted the navigation.</dd> - <dt>{{WebExtAPIRef("webNavigation.onCreatedNavigationTarget")}}</dt> - <dd>Fired when a new window, or a new tab in an existing window, is created to host a navigation: for example, if the user opens a link in a new tab.</dd> - <dt>{{WebExtAPIRef("webNavigation.onReferenceFragmentUpdated")}}</dt> - <dd>Fired if the <a class="external-icon external" href="https://en.wikipedia.org/wiki/Fragment_identifier">fragment identifier</a> for a page is changed.</dd> - <dt>{{WebExtAPIRef("webNavigation.onTabReplaced")}}</dt> - <dd> - <p>Fired when the contents of the tab is replaced by a different (usually previously pre-rendered) tab.</p> - </dd> - <dt>{{WebExtAPIRef("webNavigation.onHistoryStateUpdated")}}</dt> - <dd>Fired when the page used the <a class="external external-icon" href="http://diveintohtml5.info/history.html">history API</a> to update the URL displayed in the browser's location bar.</dd> -</dl> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<p>{{Compat("webextensions.api.webNavigation")}}</p> - -<div class="hidden note"> -<p>The "Chrome incompatibilities" section is included from <a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Chrome_incompatibilities"> https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Chrome_incompatibilities</a> using the <a href="/en-US/docs/Template:WebExtChromeCompat">WebExtChromeCompat</a> macro.</p> - -<p>If you need to update this content, edit <a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Chrome_incompatibilities">https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Chrome_incompatibilities</a>, then shift-refresh this page to see your changes.</p> -</div> - -<h3 id="Edge_incompatibilities">Edge incompatibilities</h3> - -<p>Promises are not supported in Edge. Use callbacks instead.</p> - -<p>{{WebExtExamples("h2")}}</p> - -<div class="note"><strong>Acknowledgements</strong> - -<p>This API is based on Chromium's <a href="https://developer.chrome.com/extensions/webNavigation"><code>chrome.webNavigation</code></a> API. This documentation is derived from <a href="https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/web_navigation.json"><code>web_navigation.json</code></a> in the Chromium code.</p> - -<p>Microsoft Edge compatibility data is supplied by Microsoft Corporation and is included here under the Creative Commons Attribution 3.0 United States License.</p> -</div> - -<div class="hidden"> -<pre>// Copyright 2015 The Chromium Authors. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -</pre> -</div> diff --git a/files/es/mozilla/add-ons/webextensions/extending_the_developer_tools/index.html b/files/es/mozilla/add-ons/webextensions/extending_the_developer_tools/index.html deleted file mode 100644 index 426aeae50f..0000000000 --- a/files/es/mozilla/add-ons/webextensions/extending_the_developer_tools/index.html +++ /dev/null @@ -1,159 +0,0 @@ ---- -title: Extending the developer tools -slug: Mozilla/Add-ons/WebExtensions/Extending_the_developer_tools -translation_of: Mozilla/Add-ons/WebExtensions/Extending_the_developer_tools ---- -<div>{{AddonSidebar}}</div> - -<div class="note"> -<p>This page describes devtools APIs as they exist in Firefox 55. Although the APIs are based on the <a href="https://developer.chrome.com/extensions/devtools">Chrome devtools APIs</a>, there are still many features that are not yet implemented in Firefox, and therefore are not documented here. To see which features are currently missing please see <a href="/en-US/Add-ons/WebExtensions/Using_the_devtools_APIs#Limitations_of_the_devtools_APIs">Limitations of the devtools APIs</a>.</p> -</div> - -<p><span class="seoSummary">You can use WebExtensions APIs to extend the browser's built-in developer tools.</span> To create a devtools extension, include the "<a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/devtools_page">devtools_page</a>" key in <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json">manifest.json</a>:</p> - -<pre class="brush: json notranslate">"devtools_page": "devtools/devtools-page.html"</pre> - -<p>The value of this key is a URL pointing to an HTML file that's been bundled with your extension. The URL should be relative to the manifest.json file itself.</p> - -<p>The HTML file defines a special page in the extension, called the devtools page.</p> - -<h2 id="The_devtools_page">The devtools page</h2> - -<p>The devtools page is loaded when the browser devtools are opened, and unloaded when it is closed. Note that because the devtools window is associated with a single tab, it's quite possible for more than one devtools window - hence more than one devtools page - to exist at the same time.</p> - -<p>The devtools page doesn't have any visible DOM, but can include JavaScript sources using <code><a href="/en-US/docs/Web/HTML/Element/script"><script></a></code> tags. The sources must be bundled with the extension itself. The sources get access to:</p> - -<ul> - <li>The normal DOM APIs accessible through the global <code><a href="/en-US/docs/Web/API/Window">window</a></code> object</li> - <li>The same <a href="/en-US/Add-ons/WebExtensions/Content_scripts#WebExtension_APIs">WebExtension APIs as in Content Scripts</a></li> - <li>The devtools APIs: - <ul> - <li><code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/devtools.inspectedWindow">devtools.inspectedWindow</a></code></li> - <li><code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/devtools.network">devtools.network</a></code></li> - <li><code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/devtools.panels">devtools.panels</a></code></li> - </ul> - </li> -</ul> - -<p>Note that the devtools page does not get access to any other WebExtension APIs, and the background page doesn't get access to the devtools APIs. Instead, the devtools page and the background page must communicate using the <code>runtime</code> messaging APIs. Here's an example:</p> - -<pre class="brush: html notranslate"><!DOCTYPE html> -<html> - <head> - <meta charset="utf-8"> - </head> - <body> - <script src="devtools.js"></script> - </body> -</html></pre> - -<p>The devtools.js file will hold the actual code creating your dev tools extensions.</p> - -<h2 id="Creating_panels">Creating panels</h2> - -<p>The devtools window hosts a number of separate tools - the JavaScript Debugger, Network Monitor, and so on. A row of tabs across the top lets the user switch between the different tools. The window hosting each tool's user interface is called a "panel".</p> - -<p>Using the <code>devtools.panels.create()</code> API, you can create your own panel in the devtools window:</p> - -<pre class="brush: js notranslate">browser.devtools.panels.create( - "My Panel", // title - "icons/star.png", // icon - "devtools/panel/panel.html" // content -).then((newPanel) => { - newPanel.onShown.addListener(initialisePanel); - newPanel.onHidden.addListener(unInitialisePanel); -});</pre> - -<p>This takes three mandatory arguments: the panel's title, icon, and content. It returns a <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a></code> which resolves to a <code>devtools.panels.ExtensionPanel</code> object representing the new panel.</p> - -<h2 id="Interacting_with_the_target_window">Interacting with the target window</h2> - -<p>The developer tools are always attached to a particular browser tab. This is referred to as the "target" for the developer tools, or the "inspected window". You can interact with the inspected window using the <code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/devtools.inspectedWindow">devtools.inspectedWindow</a></code> API.</p> - -<h3 id="Running_code_in_the_target_window">Running code in the target window</h3> - -<p>The <code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/devtools.inspectedWindow/eval">devtools.inspectedWindow.eval()</a></code> provides one way to run code in the inspected window.</p> - -<p>This is somewhat like using {{WebExtAPIRef("tabs.executeScript()")}} to inject a content script, but with one important difference:</p> - -<ul> - <li>unlike content scripts, scripts loaded using <code>devtools.inspectedWindow.eval()</code><strong> do not</strong> get <a href="/en-US/Add-ons/WebExtensions/Content_scripts#DOM_access">a "clean view of the DOM"</a>: that is, they can see changes to the page made by page scripts.</li> -</ul> - -<div class="note"> -<p>Note that a clean view of the DOM is a security feature, intended to help prevent hostile pages from tricking extensions by redefining the behavior of native DOM functions. This means you need to be very careful using eval(), and should use a normal content script if you can.</p> -</div> - -<p>Scripts loaded using <code>devtools.inspectedWindow.eval()</code> also don't see any JavaScript variables defined by content scripts.</p> - -<h3 id="Working_with_content_scripts">Working with content scripts</h3> - -<p>A devtools document doesn't have direct access to {{WebExtAPIRef("tabs.executeScript()")}}, so if you need to inject a content script, the devtools document must send a message to the background script asking it to inject the script. The <code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/devtools.inspectedWindow/tabId">devtools.inspectedWindow.tabId</a></code> provides the ID of the target tab: the devtools document can pass this to the background script, and the background script can in turn pass it into {{WebExtAPIRef("tabs.executeScript()")}}:</p> - -<pre class="brush: js notranslate">// devtools-panel.js - -const scriptToAttach = "document.body.innerHTML = 'Hi from the devtools';"; - -window.addEventListener("click", () => { - browser.runtime.sendMessage({ - tabId: browser.devtools.inspectedWindow.tabId, - script: scriptToAttach - }); -});</pre> - -<pre class="brush: js notranslate">// background.js - -function handleMessage(request, sender, sendResponse) { - browser.tabs.executeScript(request.tabId, { - code: request.script - }); -} - -browser.runtime.onMessage.addListener(handleMessage);</pre> - -<p>If you need to exchange messages between the content scripts running in the target window and a devtools document, it's a good idea to use the {{WebExtAPIRef("runtime.connect()")}} and {{WebExtAPIRef("runtime.onConnect")}} to set up a connection between the background page and the devtools document. The background page can then maintain a mapping between tab IDs and {{WebExtAPIRef("runtime.Port")}} objects, and use this to route messages between the two scopes.</p> - -<p><img alt="" src="https://mdn.mozillademos.org/files/14923/devtools-content-scripts.png" style="display: block; height: 416px; margin-left: auto; margin-right: auto; width: 600px;"></p> - -<h2 id="Limitations_of_the_devtools_APIs">Limitations of the devtools APIs</h2> - -<p>These APIs are based on the Chrome devtools APIs, but many features are still missing, compared with Chrome. This section lists the features that are still not implemented, as of Firefox 54. Note that the devtools APIs are under active development and we expect to add support for most of them in future releases.</p> - -<h3 id="devtools.inspectedWindow">devtools.inspectedWindow</h3> - -<p>The following are not supported:</p> - -<ul> - <li><code>inspectedWindow.getResources()</code></li> - <li><code>inspectedWindow.onResourceAdded</code></li> - <li><code>inspectedWindow.onResourceContentCommitted</code></li> -</ul> - -<p>None of the options to <code>inspectedWindow.eval()</code> are supported.</p> - -<p>Scripts injected using <code>inspectedWindow.eval()</code> can't use all the Console's command-line helper functions, but <code>$0</code> and <code>inspect(...)</code> are both supported (starting from Firefox 55).</p> - -<h3 id="devtools.panels">devtools.panels</h3> - -<p>The following are not supported:</p> - -<ul> - <li><code>panels.elements</code></li> - <li><code>panels.sources</code></li> - <li><code>panels.setOpenResourceHandler()</code></li> - <li><code>panels.openResource()</code></li> - <li><code>panels.ExtensionPanel.createStatusBarButton()</code></li> - <li><code>panels.Button</code></li> - <li><code>panels.ElementsPanel</code></li> - <li><code>panels.SourcesPanel</code></li> -</ul> - -<h2 id="Examples">Examples</h2> - -<p>The <a href="https://github.com/mdn/webextensions-examples">webextensions-examples</a> repo on GitHub, contains several examples of extensions that use devtools panels:</p> - -<ul> - <li> - <p><a href="https://github.com/mdn/webextensions-examples/blob/master/devtools-panels/">devtools-panels</a> use devtools panels:</p> - </li> -</ul> diff --git a/files/es/mozilla/add-ons/webextensions/internationalization/index.html b/files/es/mozilla/add-ons/webextensions/internationalization/index.html deleted file mode 100644 index 89c542a2e7..0000000000 --- a/files/es/mozilla/add-ons/webextensions/internationalization/index.html +++ /dev/null @@ -1,405 +0,0 @@ ---- -title: Internationalization -slug: Mozilla/Add-ons/WebExtensions/Internationalization -translation_of: Mozilla/Add-ons/WebExtensions/Internationalization ---- -<pre class="brush: html notranslate"><span class="seoSummary"><kbd>H</kbd></span></pre> - -<p>The <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions">WebExtensions</a> API has a rather handy module available for internationalizing extensions — <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/i18n">i18n</a>. In this article we'll explore its features and provide a practical example of how it works. The i18n system for extensions built using WebExtension APIs is similar to common JavaScript libraries for i18n such as <a href="http://i18njs.com/">i18n.js</a>.</p> - -<div class="note"> -<p>The example extension featured in this article — <a href="https://github.com/mdn/webextensions-examples/tree/master/notify-link-clicks-i18n">notify-link-clicks-i18n</a> — is available on GitHub. Follow along with the source code as you go through the sections below.</p> -</div> - -<h2 id="Anatomy_of_an_internationalized_extension">Anatomy of an internationalized extension</h2> - -<p>An internationalized extension can contain the same features as any other extension — <a href="/en-US/Add-ons/WebExtensions/Anatomy_of_a_WebExtension#Background_scripts">background scripts</a>, <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts">content scripts</a>, etc. — but it also has some extra parts to allow it to switch between different locales. These are summarized in the following directory tree:</p> - -<ul class="directory-tree"> - <li>extension-root-directory/ - <ul> - <li>_locales - <ul> - <li>en - <ul> - <li>messages.json - <ul> - <li>English messages (strings)</li> - </ul> - </li> - </ul> - </li> - <li>de - <ul> - <li>messages.json - <ul> - <li>German messages (strings)</li> - </ul> - </li> - </ul> - </li> - <li>etc.</li> - </ul> - </li> - <li>manifest.json - <ul> - <li>locale-dependent metadata</li> - </ul> - </li> - <li>myJavascript.js - <ul> - <li>JavaScript for retrieving browser locale, locale-specific messages, etc.</li> - </ul> - </li> - <li>myStyles.css - <ul> - <li>locale-dependent CSS</li> - </ul> - </li> - </ul> - </li> -</ul> - -<p>Let's explore each of the new features in turn — each of the below sections represents a step to follow when internationalizing your extension.</p> - -<h2 id="Providing_localized_strings_in__locales">Providing localized strings in _locales</h2> - -<div class="pull-aside"> -<div class="moreinfo">You can look up language subtags using the <em>Find</em> tool on the <a href="https://r12a.github.io/app-subtags/">Language subtag lookup page</a>. Note that you need to search for the English name of the language.</div> -</div> - -<p>Every i18n system requires the provision of strings translated into all the different locales you want to support. In extensions, these are contained within a directory called <code>_locales</code>, placed inside the extension root. Each individual locale has its strings (referred to as messages) contained within a file called <code>messages.json</code>, which is placed inside a subdirectory of <code>_locales</code>, named using the language subtag for that locale's language.</p> - -<p>Note that if the subtag includes a basic language plus a regional variant, then the language and variant are conventionally separated using a hyphen: for example, "en-US". However, in the directories under <code>_locales</code>, <strong>the separator must be an underscore</strong>: "en_US".</p> - -<p>So <a href="https://github.com/mdn/webextensions-examples/tree/master/notify-link-clicks-i18n/_locales">for example, in our sample app</a> we have directories for "en" (English), "de" (German), "nl" (Dutch), and "ja" (Japanese). Each one of these has a <code>messages.json</code> file inside it.</p> - -<p>Let's now look at the structure of one of these files (<a href="https://github.com/mdn/webextensions-examples/blob/master/notify-link-clicks-i18n/_locales/en/messages.json">_locales/en/messages.json</a>):</p> - -<pre class="brush: json notranslate">{ - "extensionName": { - "message": "Notify link clicks i18n", - "description": "Name of the extension." - }, - - "extensionDescription": { - "message": "Shows a notification when the user clicks on links.", - "description": "Description of the extension." - }, - - "notificationTitle": { - "message": "Click notification", - "description": "Title of the click notification." - }, - - "notificationContent": { - "message": "You clicked $URL$.", - "description": "Tells the user which link they clicked.", - "placeholders": { - "url" : { - "content" : "$1", - "example" : "https://developer.mozilla.org" - } - } - } -}</pre> - -<p>This file is standard JSON — each one of its members is an object with a name, which contains a <code>message</code> and a <code>description</code>. All of these items are strings; <code>$URL$</code> is a placeholder, which is replaced with a substring at the time the <code>notificationContent</code> member is called by the extension. You'll learn how to do this in the {{anch("Retrieving message strings from JavaScript")}} section.</p> - -<div class="note"> -<p><strong>Note</strong>: You can find much more information about the contents of <code>messages.json</code> files in our <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/i18n/Locale-Specific_Message_reference">Locale-Specific Message reference</a>.</p> -</div> - -<h2 id="Internationalizing_manifest.json">Internationalizing manifest.json</h2> - -<p>There are a couple of different tasks to carry out to internationalize your manifest.json.</p> - -<h3 id="Retrieving_localized_strings_in_manifests">Retrieving localized strings in manifests</h3> - -<p>Your <a href="https://github.com/mdn/webextensions-examples/blob/master/notify-link-clicks-i18n/manifest.json">manifest.json</a> includes strings that are displayed to the user, such as the extension's name and description. If you internationalize these strings and put the appropriate translations of them in messages.json, then the correct translation of the string will be displayed to the user, based on the current locale, like so.</p> - -<p>To internationalize strings, specify them like this:</p> - -<pre class="brush: json notranslate">"name": "__MSG_extensionName__", -"description": "__MSG_extensionDescription__",</pre> - -<p>Here, we are retrieving message strings dependant on the browser's locale, rather than just including static strings.</p> - -<p>To call a message string like this, you need to specify it like this:</p> - -<ol> - <li>Two underscores, followed by</li> - <li>The string "MSG", followed by</li> - <li>One underscore, followed by</li> - <li>The name of the message you want to call as defined in <code>messages.json</code>, followed by</li> - <li>Two underscores</li> -</ol> - -<pre class="notranslate"><strong>__MSG_</strong> + <em>messageName</em> + <strong>__</strong></pre> - -<h3 id="Specifying_a_default_locale">Specifying a default locale</h3> - -<p>Another field you should specify in your manifest.json is <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/default_locale">default_locale</a>:</p> - -<pre class="brush: json notranslate">"default_locale": "en"</pre> - -<p>This specifies a default locale to use if the extension doesn't include a localized string for the browser's current locale. Any message strings that are not available in the browser locale are taken from the default locale instead. There are some more details to be aware of in terms of how the browser selects strings — see {{anch("Localized string selection")}}.</p> - -<h2 id="Locale-dependent_CSS">Locale-dependent CSS</h2> - -<p>Note that you can also retrieve localized strings from CSS files in the extension. For example, you might want to construct a locale-dependent CSS rule, like this:</p> - -<pre class="brush: css notranslate">header { - background-image: url(../images/__MSG_extensionName__/header.png); -}</pre> - -<p>This is useful, although you might be better off handling such a situation using {{anch("Predefined messages")}}.</p> - -<h2 id="Retrieving_message_strings_from_JavaScript">Retrieving message strings from JavaScript</h2> - -<p>So, you've got your message strings set up, and your manifest. Now you just need to start calling your message strings from JavaScript so your extension can talk the right language as much as possible. The actual <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/i18n">i18n API</a> is pretty simple, containing just four main methods:</p> - -<ul> - <li>You'll probably use {{WebExtAPIRef("i18n.getMessage()")}} most often — this is the method you use to retrieve a specific language string, as mentioned above. We'll see specific usage examples of this below.</li> - <li>The {{WebExtAPIRef("i18n.getAcceptLanguages()")}} and {{WebExtAPIRef("i18n.getUILanguage()")}} methods could be used if you needed to customize the UI depending on the locale — perhaps you might want to show preferences specific to the users' preferred languages higher up in a prefs list, or display cultural information relevant only to a certain language, or format displayed dates appropriately according to the browser locale.</li> - <li>The {{WebExtAPIRef("i18n.detectLanguage()")}} method could be used to detect the language of user-submitted content, and format it appropriately.</li> -</ul> - -<p>In our <a href="https://github.com/mdn/webextensions-examples/tree/master/notify-link-clicks-i18n">notify-link-clicks-i18n</a> example, the<a href="https://github.com/mdn/webextensions-examples/blob/master/notify-link-clicks-i18n/background-script.js"> background script</a> contains the following lines:</p> - -<pre class="brush: js notranslate">var title = browser.i18n.getMessage("notificationTitle"); -var content = browser.i18n.getMessage("notificationContent", message.url);</pre> - -<p>The first one just retrieves the <code>notificationTitle message</code> field from the available <code>messages.json</code> file most appropriate for the browser's current locale. The second one is similar, but it is being passed a URL as a second parameter. What gives? This is how you specify the content to replace the <code>$URL$</code> placeholder we see in the <code>notificationContent message</code> field:</p> - -<pre class="brush: json notranslate">"notificationContent": { - "message": "You clicked $URL$.", - "description": "Tells the user which link they clicked.", - "placeholders": { - "url" : { - "content" : "$1", - "example" : "https://developer.mozilla.org" - } - } -} -</pre> - -<p>The <code>"placeholders"</code> member defines all the placeholders, and where they are retrieved from. The <code>"url"</code> placeholder specifies that its content is taken from $1, which is the first value given inside the second parameter of <code>getMessage()</code>. Since the placeholder is called <code>"url"</code>, we use <code>$URL$</code> to call it inside the actual message string (so for <code>"name"</code> you'd use <code>$NAME$</code>, etc.) If you have multiple placeholders, you can provide them inside an array that is given to {{WebExtAPIRef("i18n.getMessage()")}} as the second parameter — <code>[a, b, c]</code> will be available as <code>$1</code>, <code>$2</code>, and <code>$3</code>, and so on, inside <code>messages.json</code>.</p> - -<p>Let's run through an example: the original <code>notificationContent</code> message string in the <code>en/messages.json</code> file is</p> - -<pre class="notranslate">You clicked $URL$.</pre> - -<p>Let's say the link clicked on points to <code>https://developer.mozilla.org</code>. After the {{WebExtAPIRef("i18n.getMessage()")}} call, the contents of the second parameter are made available in messages.json as <code>$1</code>, which replaces the <code>$URL$</code> placeholder as defined in the <code>"url"</code> placeholder. So the final message string is</p> - -<pre class="notranslate">You clicked https://developer.mozilla.org.</pre> - -<h3 id="Direct_placeholder_usage">Direct placeholder usage</h3> - -<p>It is possible to insert your variables (<code>$1</code>, <code>$2</code>, <code>$3</code>, etc.) directly into the message strings, for example we could rewrite the above <code>"notificationContent"</code> member like this:</p> - -<pre class="brush: json notranslate">"notificationContent": { - "message": "You clicked $1.", - "description": "Tells the user which link they clicked." -}</pre> - -<p>This may seem quicker and less complex, but the other way (using <code>"placeholders"</code>) is seen as best practice. This is because having the placeholder name (e.g. <code>"url"</code>) and example helps you to remember what the placeholder is for — a week after you write your code, you'll probably forget what <code>$1</code>–<code>$8</code> refer to, but you'll be more likely to know what your placeholder names refer to.</p> - -<h3 id="Hardcoded_substitution">Hardcoded substitution</h3> - -<p>It is also possible to include hardcoded strings in placeholders, so that the same value is used every time, instead of getting the value from a variable in your code. For example:</p> - -<pre class="brush: json notranslate">"mdn_banner": { - "message": "For more information on web technologies, go to $MDN$.", - "description": "Tell the user about MDN", - "placeholders": { - "mdn": { - "content": "https://developer.mozilla.org/" - } - } -}</pre> - -<p>In this case we are just hardcoding the placeholder content, rather than getting it from a variable value like <code>$1</code>. This can sometimes be useful when your message file is very complex, and you want to split up different values to make the strings more readable in the file, plus then these values could be accessed programmatically.</p> - -<p>In addition, you can use such substitutions to specify parts of the string that you don't want to be translated, such as person or business names.</p> - -<h2 id="Localized_string_selection">Localized string selection</h2> - -<p>Locales can be specified using only a language code, like <code>fr</code> or <code>en</code>, or they may be further qualified with a region code, like <code>en_US</code> or <code>en_GB</code>, which describes a regional variant of the same basic language. When you ask the i18n system for a string, it will select a string using the following algorithm:</p> - -<ol> - <li>if there is a <code>messages.json</code> file for the exact current locale, and it contains the string, return it.</li> - <li>Otherwise, if the current locale is qualified with a region (e.g. <code>en_US</code>) and there is a <code>messages.json</code> file for the regionless version of that locale (e.g. <code>en</code>), and that file contains the string, return it.</li> - <li>Otherwise, if there is a <code>messages.json</code> file for the <code>default_locale</code> defined in the <code>manifest.json</code>, and it contains the string, return it.</li> - <li>Otherwise return an empty string.</li> -</ol> - -<p>Take the following example:</p> - -<ul class="directory-tree"> - <li>extension-root-directory/ - <ul> - <li>_locales - <ul> - <li>en_GB - <ul> - <li>messages.json - <ul> - <li><code>{ "colorLocalised": { "message": "colour", "description": "Color." }, ... }</code></li> - </ul> - </li> - </ul> - en - - <ul> - <li>messages.json - <ul> - <li><code>{ "colorLocalised": { "message": "color", "description": "Color." }, ... }</code></li> - </ul> - </li> - </ul> - </li> - <li>fr - <ul> - <li>messages.json - <ul> - <li><code>{ "colorLocalised": { "message": "<span lang="fr">couleur</span>", "description": "Color." }, ...}</code></li> - </ul> - </li> - </ul> - </li> - </ul> - </li> - </ul> - </li> -</ul> - -<p>Suppose the <code>default_locale</code> is set to <code>fr</code>, and the browser's current locale is <code>en_GB</code>:</p> - -<ul> - <li>If the extension calls <code>getMessage("colorLocalised")</code>, it will return "colour".</li> - <li>If "colorLocalised" were not present in <code>en_GB</code>, then <code>getMessage("colorLocalised")</code>, would return "color", not "couleur".</li> -</ul> - -<h2 id="Predefined_messages">Predefined messages</h2> - -<p>The i18n module provides us with some predefined messages, which we can call in the same way as we saw earlier in {{anch("Calling message strings from manifests and extension CSS")}}. For example:</p> - -<pre class="notranslate">__MSG_extensionName__</pre> - -<p>Predefined messages use exactly the same syntax, except with <code>@@</code> before the message name, for example</p> - -<pre class="notranslate">__MSG_@@ui_locale__</pre> - -<p>The following table shows the different available predefined messages:</p> - -<table class="standard-table"> - <thead> - <tr> - <th scope="col">Message name</th> - <th scope="col">Description</th> - </tr> - </thead> - <tbody> - <tr> - <td><code>@@extension_id</code></td> - <td> - <p>The extension's internally-generated UUID. You might use this string to construct URLs for resources inside the extension. Even unlocalized extensions can use this message.</p> - - <p>You can't use this message in a manifest file.</p> - - <p>Also note that this ID is <em>not</em> the add-on ID returned by {{WebExtAPIRef("runtime.id")}}, and that can be set using the <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/applications">applications</a> key in manifest.json. It's the generated UUID that appears in the add-on's URL. This means that you can't use this value as the <code>extensionId</code> parameter to {{WebExtAPIRef("runtime.sendMessage()")}}, and can't use it to check against the <code>id</code> property of a {{WebExtAPIRef("runtime.MessageSender")}} object.</p> - </td> - </tr> - <tr> - <td><code>@@ui_locale</code></td> - <td>The current locale; you might use this string to construct locale-specific URLs.</td> - </tr> - <tr> - <td><code>@@bidi_dir</code></td> - <td>The text direction for the current locale, either "ltr" for left-to-right languages such as English or "rtl" for right-to-left languages such as Arabic.</td> - </tr> - <tr> - <td><code>@@bidi_reversed_dir</code></td> - <td>If the <code>@@bidi_dir</code> is "ltr", then this is "rtl"; otherwise, it's "ltr".</td> - </tr> - <tr> - <td><code>@@bidi_start_edge</code></td> - <td>If the <code>@@bidi_dir</code> is "ltr", then this is "left"; otherwise, it's "right".</td> - </tr> - <tr> - <td><code>@@bidi_end_edge</code></td> - <td>If the <code>@@bidi_dir</code> is "ltr", then this is "right"; otherwise, it's "left".</td> - </tr> - </tbody> -</table> - -<p>Going back to our earlier example, it would make more sense to write it like this:</p> - -<pre class="brush: css notranslate">header { - background-image: url(../images/__MSG_@@ui_locale__/header.png); -}</pre> - -<p>Now we can just store our local specific images in directories that match the different locales we are supporting — en, de, etc. — which makes a lot more sense.</p> - -<p>Let's look at an example of using <code>@@bidi_*</code> messages in a CSS file:</p> - -<pre class="brush: css notranslate">body { - direction: __MSG_@@bidi_dir__; -} - -div#header { - margin-bottom: 1.05em; - overflow: hidden; - padding-bottom: 1.5em; - padding-__MSG_@@bidi_start_edge__: 0; - padding-__MSG_@@bidi_end_edge__: 1.5em; - position: relative; -}</pre> - -<p>For left-to-right languages such as English, the CSS declarations involving the predefined messages above would translate to the following final code lines:</p> - -<pre class="brush: css notranslate">direction: ltr; -padding-left: 0; -padding-right: 1.5em; -</pre> - -<p>For a right-to-left language like Arabic, you'd get:</p> - -<pre class="brush: css notranslate">direction: rtl; -padding-right: 0; -padding-left: 1.5em;</pre> - -<h2 id="Testing_out_your_extension">Testing out your extension</h2> - -<p>Starting in Firefox 45, you can install extensions temporarily from disk — see <a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Packaging_and_installation#Loading_from_disk">Loading from disk</a>. Do this, and then try testing out our <a href="https://github.com/mdn/webextensions-examples/tree/master/notify-link-clicks-i18n">notify-link-clicks-i18n</a> extension. Go to one of your favourite websites and click a link to see if a notification appears reporting the URL of the clicked link.</p> - -<p>Next, change Firefox's locale to one supported in the extension that you want to test.</p> - -<ol> - <li>Open "about:config" in Firefox, and search for the <code>intl.locale.requested</code> preference (bear in mind that before Firefox 59, this pref is called <code>general.useragent.locale</code>).</li> - <li>If the preference exists, double-click it (or press Return/Enter) to select it, enter the language code for the locale you want to test, then click "OK" (or press Return/Enter). For example in our example extension, "en" (English), "de" (German), "nl" (Dutch), and "ja" (Japanese) are supported. You can also set the value to an empty string (<code>""</code>), which will cause the browser to use the OS default locale.</li> - <li>If the <code>intl.locale.requested</code> preference does not exist, right-click the list of preferences (or activate the context menu using the keyboard), and choose "New" followed by "String". Enter <code>intl.locale.requested</code> for the preference name and, "de", or "nl", etc. for the preference value, as described in step 2 above.</li> - <li>Search for <code>intl.locale.matchOS</code> and, if the preference exists and has the value <code>true</code>, double-click it so that it is set to <code>false</code>.</li> - <li>Restart your browser to complete the change.</li> -</ol> - -<div class="note"> -<p><strong>Note</strong>: This works to change the browser's locale, even if you haven't got the <a href="https://addons.mozilla.org/en-US/firefox/language-tools/">language pack</a> installed for that language. You'll just get the browser UI in your default language if this is the case.</p> -</div> - -<ol> -</ol> - -<div class="note"> -<p><strong>Note:</strong> To change the result of <code>getUILanguage</code> the language pack is required, since it reflects the browser UI language and not the language used for extension messages.</p> -</div> - -<p>Load the extension temporarily from disk again, then test your new locale:</p> - -<ul> - <li>Visit "about:addons" again — you should now see the extension listed, with its icon, plus name and description in the chosen language.</li> - <li>Test your extension again. In our example, you'd go to another website and click a link, to see if the notification now appears in the chosen language.</li> -</ul> - -<p>{{EmbedYouTube("R7--fp5pPGg")}}</p> diff --git a/files/es/mozilla/firefox/releases/62/index.html b/files/es/mozilla/firefox/releases/62/index.html deleted file mode 100644 index ccc68fce29..0000000000 --- a/files/es/mozilla/firefox/releases/62/index.html +++ /dev/null @@ -1,235 +0,0 @@ ---- -title: Firefox 62 for developers -slug: Mozilla/Firefox/Releases/62 -translation_of: Mozilla/Firefox/Releases/62 ---- -<div>{{FirefoxSidebar}}</div> - -<p class="summary">Este artículo provee información sobre los cambios de Firefox 62 que van a afectar a los programadores. Firefox 62 ha sido lanzado en 5 de septiembre, 2018.</p> - -<h2 id="Cambios_para_programadores_de_red">Cambios para programadores de red</h2> - -<h3 id="Herramientas_para_programadores">Herramientas para programadores</h3> - -<ul> - <li>La editor de formas ya está disponible por defecto -- vea a <a href="/en-US/docs/Tools/Page_Inspector/How_to/Edit_CSS_shapes">Editar formas en CSS </a>para más informacion.</li> - <li>You can now split the Rules view out into its own pane, separate from the other tabs on the CSS pane. See <a href="/en-US/docs/Tools/Page_Inspector/3-pane_mode">Page inspector 3-pane mode</a> for more details.</li> - <li>The Grid inspector has updated features, and all new documentation — see <a href="/en-US/docs/Tools/Page_Inspector/How_to/Examine_grid_layouts">CSS Grid Inspector: Examine grid layouts</a>.</li> - <li>You now have four options for the location of the Developer Tools. In addition to the default location on the bottom of the window, you can choose to locate the tools on either the left or right sides of the main window or in a separate window ({{bug(1192642)}}).</li> - <li>The <a href="/en-US/docs/Tools/Accessibility_inspector">Accessibility inspector</a> has had a couple of minor updates: - <ul> - <li>It no longer exposes the <code>help</code> property, which isn't properly implemented in Gecko ({{bug(1467643)}}).</li> - <li>The <code>keyboardShortcut</code> property now correctly exposes any keyboard shortcut available to activate the currently inspected node ({{bug(1467381)}}).</li> - </ul> - </li> - <li>A close button has been added to the <a href="/en-US/docs/Tools/Web_Console/Split_console">split console</a> toolbar.</li> - <li>If the option to "Select an iframe as the currently targeted document" is checked, the icon will appear in the toolbar while the Settings tab is displayed, even if the current page doesn't include any iframes ({{bug(1456069)}}).</li> - <li>The <a href="/en-US/docs/Tools/Network_Monitor">Network Monitor</a>'s <a href="/en-US/docs/Tools/Network_Monitor#Cookies">Cookies tab</a> now shows the cookie <code>samesite</code> attribute ({{bug(1452715)}}).</li> - <li><a href="/en-US/docs/Tools/Responsive_Design_Mode">Responsive design mode</a> now works inside container tabs ({{bug(1306975)}}).</li> - <li>When {{Glossary("CORS")}} errors occur and are reported on the console, Firefox now provides a link to the corresponding page in our <a href="/en-US/docs/Web/HTTP/CORS/Errors">CORS error documentation</a> ({{bug(1475391)}}).</li> - <li>Create a screenshot of the current page (with an optional filename) from the Console tab ({{bug(1464461)}}) using the following command:<br> - <br> - <code>:screenshot <filename.png> --fullpage</code><br> - <br> - where <code><filename.png></code> is the desired filename. The file will be saved to your downloads folder. The <code>--fullpage</code> parameter is optional, but if included, it will save the full web page. This option also adds <code>-fullpage</code> to the name of the file. For a list of all options available for this command, enter: <code>:screenshot --help</code></li> -</ul> - -<h4 id="Removals">Removals</h4> - -<ul> - <li>The <a href="/en-US/docs/Tools/GCLI">Developer Toolbar/GCLI</a> (accessed with <kbd>Shift</kbd> + <kbd>F2</kbd>), <strong>has been removed</strong> from Firefox ({{bug(1461970)}}). Both the Developer Toolbar UI and the GCLI upstream library have become unmaintained, some of its features are broken (some ever since e10s), it is blocking the <code><span class="quote">unsafeSetInnerHTML</span></code> work, usage numbers are very low, alternatives exist for the most used commands.</li> -</ul> - -<h3 id="HTML">HTML</h3> - -<p><em>No changes.</em></p> - -<h3 id="CSS">CSS</h3> - -<ul> - <li><code>:-moz-selection</code> has been unprefixed to {{cssxref("::selection")}} ({{bug(509958)}}).</li> - <li><code>x</code> is now supported as a unit for the {{cssxref("<resolution>")}} type ({{bug(1460655)}}).</li> - <li>{{cssxref("shape-margin")}}, {{cssxref("shape-outside")}}, and {{cssxref("shape-image-threshold")}} are now enabled by default ({{bug(1457297)}}).</li> -</ul> - -<h4 id="Removals_2">Removals</h4> - -<ul> - <li>All <a href="/en-US/docs/Web/CSS/display#XUL_values">XUL <code>display</code> values</a> with the exception of <code>-moz-box</code> and <code>-moz-inline-box</code> have been removed from non-XUL documents in {{bug(1288572)}}.</li> -</ul> - -<h3 id="SVG">SVG</h3> - -<p><em>No changes.</em></p> - -<h3 id="JavaScript">JavaScript</h3> - -<ul> - <li>The {{jsxref("WebAssembly.Global()")}} constructor is now supported, along with global variables in WebAssembly ({{bug(1464656)}}).</li> - <li>The {{jsxref("Array.prototype.flat()")}} and {{jsxref("Array.prototype.flatMap()")}} methods are now enabled by default ({{bug(1435813)}}).</li> - <li>The <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/import.meta">import.meta</a></code> property has been implemented to expose context-specific metadata to a JavaScript module ({{bug(1427610)}}).</li> - <li>JavaScript <a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#String_literals">string literals</a> may now directly contain the U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR characters. As a consequence, {{jsxref("JSON")}} syntax is now a subset of JavaScript literal syntax (see {{bug(1435828)}} and the TC39 proposal <a href="https://github.com/tc39/proposal-json-superset">json-superset</a>).</li> - <li>For out-of-bounds <a href="/en-US/docs/Web/JavaScript/Typed_arrays">typed array</a> indexes, {{jsxref("Reflect.defineProperty()")}} and {{jsxref("Reflect.set()")}} will now return <code>false</code> instead of <code>true</code> ({{bug(1308735)}}).</li> -</ul> - -<h4 id="Removals_3">Removals</h4> - -<ul> - <li>The <code>DOMPoint</code> and <code>DOMPointReadOnly</code> constructors no longer support an input parameter of type <code>DOMPointInit</code>; the values of the properties must be specified using the <code>x</code>, <code>y</code>, <code>z</code>, and <code>w</code> parameters ({{bug(1186265)}}).</li> - <li>The {{domxref("URL.createObjectURL()")}} method no longer supports creating object URLs to represent a {{domxref("MediaStream")}}. This capability has been obsolete for some time now, since you can now simply set {{domxref("HTMLMediaElement.srcObject")}} to the <code>MediaStream</code> directly ({{bug(1454889)}}).</li> -</ul> - -<h3 id="APIs">APIs</h3> - -<h4 id="New_APIs">New APIs</h4> - -<ul> - <li>The {{domxref("Web_Speech_API", "Speech Synthesis API (Text-to-Speech)", "", "1")}} is now enabled by default on Firefox for Android ({{bug(1463496)}}).</li> -</ul> - -<h4 id="DOM">DOM</h4> - -<ul> - <li>The {{domxref("DOMPointReadOnly")}} interface now supports the static function {{domxref("DOMPointReadOnly.fromPoint()")}}, which creates a new point object from a dictionary that's compatible with {{domxref("DOMPointInit")}}, which includes any {{domxref("DOMPoint")}} object. This function is also available on {{domxref("DOMPoint")}} ({{bug(1186265)}}).</li> - <li>For compatibility purposes, the {{domxref("Event.srcElement")}} property is now supported. It is an alias for {{domxref("Event.target")}} ({{bug(453968)}}).</li> - <li>{{domxref("Navigator.registerProtocolHandler()")}} now must only be called from a secure context ({{bug(1460506)}}).</li> - <li>The {{domxref("Navigator.registerContentHandler()")}} method has been disabled by default in preparation for being removed entirely, as it's been obsolete for some time ({{bug(1460481)}}).</li> - <li>The {{domxref("DataTransfer.DataTransfer", "DataTransfer()")}} constructor has been implemented ({{bug(1351193)}}).</li> - <li>{{domxref("Document.domain")}} can no longer return <code>null</code> ({{bug(819475)}}). If the domain cannot be identified, then <code>domain</code> returns an empty string instead of <code>null</code>.</li> - <li>Added the {{domxref("Console.timeLog()")}} method to display the current value of a console timer while continuing to track the time ({{bug(1458466)}}).</li> - <li>Added {{domxref("Console.countReset()")}} to reset a console counter value ({{bug(1459279)}}).</li> -</ul> - -<h4 id="DOM_events">DOM events</h4> - -<p><em>No changes.</em></p> - -<h4 id="Service_workers">Service workers</h4> - -<p><em>No changes.</em></p> - -<h4 id="Media_Web_Audio_and_WebRTC">Media, Web Audio, and WebRTC</h4> - -<ul> - <li>The <code>"media.autoplay.enabled"</code> preference now controls automatic playback of both audio and video media, instead of just video media ({{bug(1413098)}}).</li> - <li>The {{domxref("ChannelSplitterNode")}} has been fixed to correctly default to having 6 channels with the <code>channelInterpretation</code> set to <code>"discrete"</code> and the <code>channelCountMode</code> set to <code>"explicit"</code>, as per the specification ({{bug(1456265)}}).</li> -</ul> - -<h4 id="Removals_4">Removals</h4> - -<ul> - <li>The {{event("userproximity")}} and {{event("deviceproximity")}} events (see also {{domxref("UserProximityEvent")}} and {{domxref("DeviceProximityEvent")}}) have been disabled by default behind the <code>device.sensors.proximity.enabled</code> preference ({{bug(1462308)}}).</li> - <li>The {{event("devicelight")}} event (see also {{domxref("DeviceLightEvent")}}) has been disabled by default behind the <code>device.sensors.ambientLight.enabled</code> preference ({{bug(1462308)}}).</li> - <li>The {{event("DOMSubtreeModified")}} and {{event("DOMAttrModified")}} <a href="/en-US/docs/Web/Guide/Events/Mutation_events">mutation events</a> are no longer thrown when the {{htmlattrxref("style")}} attribute is changed via the CSSOM ({{bug(1460295)}}, see also this <a href="https://www.fxsitecompat.com/en-CA/docs/2018/domattrmodified-and-domsubtreemodified-events-are-no-longer-fired-when-style-attribute-is-changed-via-cssom/">site compatibility post</a>).</li> - <li>Support for {{domxref("CSSStyleDeclaration.getPropertyCSSValue()")}} has been removed ({{bug(1408301)}}).</li> - <li>Support for {{domxref("CSSValue")}}, {{domxref("CSSPrimitiveValue")}}, and {{domxref("CSSValueList")}} has been removed ({{bug(1459871)}}).</li> - <li>{{domxref("window.getComputedStyle()")}} no longer returns <code>null</code> when called on a <code>Window</code> which has no presentation ({{bug(1467722)}}).</li> -</ul> - -<ul> -</ul> - -<ul> -</ul> - -<h3 id="HTTP">HTTP</h3> - -<h4 id="Removals_5">Removals</h4> - -<ul> - <li>The deprecated CSP {{CSP("referrer")}} directive has been removed. Please use the {{HTTPHeader("Referrer-Policy")}} header instead ({{bug(1302449)}}).</li> -</ul> - -<h3 id="Security">Security</h3> - -<p><em>No changes.</em></p> - -<h3 id="Plugins">Plugins</h3> - -<p><em>No changes.</em></p> - -<h3 id="WebDriver_conformance_(Marionette)">WebDriver conformance (Marionette)</h3> - -<h4 id="New_features">New features</h4> - -<ul> - <li> - <p>Command "<code>WebDriver:ElementSendKeys</code>" has been made WebDriver conforming for file uploads ({{bug(1448792)}})</p> - </li> - <li> - <p>User prompts as raised by "<code>beforeunload</code>" events are automatically dismissed for "<code>WebDriver:Get</code>", "<code>WebDriver:Back</code>", "<code>WebDriver:Forward</code>", "<code>WebDriver:Refresh</code>", and "<code>WebDriver:Close</code>" commands ({{bug(1434872)}})</p> - </li> - <li> - <p>"<code>WebDriver:PerformActions</code>" for <kbd>Ctrl</kbd> + <code>Click</code> synthesizes a {{event("contextmenu")}} event ({{bug(1421323)}})</p> - </li> -</ul> - -<h4 id="API_changes">API changes</h4> - -<ul> - <li>Removed obsolete endpoints including "<code>getWindowPosition</code>", "<code>setWindowPosition</code>", "<code>getWindowSize</code>", and "<code>setWindowSize</code>" ({{bug(1348145)}})</li> - <li>WebDriver commands which return success with data "<code>null</code>" now return an empty dictionary ({{bug(1461463)}})</li> -</ul> - -<h4 id="Bug_fixes">Bug fixes</h4> - -<ul> - <li> - <p>"<code>WebDriver:ExecuteScript</code>" caused cyclic reference error for <a href="/en-US/docs/Web/WebDriver/WebElement">WebElement</a> collections ({{bug(1447977)}})</p> - </li> - <li> - <p>Dispatching a "<code>pointerMove</code>" or "<code>pause</code>" action primitive could cause a hang, and the command to never send a reply ({{bug(1467743)}}, {{bug(1447449)}})</p> - - <p> </p> - </li> -</ul> - -<h3 id="Other">Other</h3> - -<p><em>No changes.</em></p> - -<h2 id="Changes_for_add-on_developers">Changes for add-on developers</h2> - -<h3 id="API_changes_2">API changes</h3> - -<ul> - <li>Added the {{WebExtAPIRef("webRequest.getSecurityInfo()")}} API to examine details of TLS connections ({{bug(1322748)}}).</li> - <li>Added the {{WebExtAPIRef("browserSettings.newTabPosition")}} to customize where new tabs open ({{bug(1344749)}}).</li> - <li><code>windowTypes</code> has been deprecated in {{WebExtAPIRef("windows.get()")}}, {{WebExtAPIRef("windows.getCurrent()")}}, and {{WebExtAPIRef("windows.getLastFocused()")}} ({{bug(1419132)}}).</li> - <li>It's now possible to modify a browser action on a per-window basis ({{bug(1419893)}}).</li> -</ul> - -<h3 id="Manifest_changes">Manifest changes</h3> - -<ul> - <li>New <code>open_at_install</code> property of the <code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/sidebar_action">sidebar_action</a></code> manifest key enables extensions to control whether their sidebars should open automatically on install or not ({{bug(1460910)}}).</li> - <li>Changes to the <code>browser_style</code> property of various manifest keys: - <ul> - <li>In <code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/page_action">page_action</a></code> and <code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_action">browser_action</a></code> it defaults to <code>false</code>.</li> - <li>In <code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/sidebar_action">sidebar_action</a></code> and <code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/options_ui">options_ui</a></code> it defaults to <code>true</code>.</li> - </ul> - </li> -</ul> - -<h3 id="Theme_changes">Theme changes</h3> - -<ul> - <li>New <code>tab_background_separator</code> property of the <code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/theme">theme</a></code> manifest key enables extensions to change the color of the tab separator ({{bug(1459455)}}).</li> -</ul> - -<h3 id="Removals_6">Removals</h3> - -<ul> - <li>Support for unpacked sideloaded extensions has been removed ({{bug(1385057)}}).</li> - <li>The warning about <code>browser_style</code> displayed when temporarily loading an extension for testing is no longer displayed ({{bug(1404724)}}).</li> -</ul> - -<h2 id="See_also">See also</h2> - -<ul> - <li><a href="https://www.fxsitecompat.com/en-US/versions/62">Site compatibility for Firefox 62</a></li> -</ul> - -<h2 id="Older_versions">Older versions</h2> - -<p>{{Firefox_for_developers(61)}}</p> diff --git a/files/es/mozilla/firefox/releases/67/index.html b/files/es/mozilla/firefox/releases/67/index.html deleted file mode 100644 index a60df8ab8a..0000000000 --- a/files/es/mozilla/firefox/releases/67/index.html +++ /dev/null @@ -1,198 +0,0 @@ ---- -title: Firefox 67 for developers -slug: Mozilla/Firefox/Releases/67 -tags: - - '67' - - Firefox - - Lanzamiento - - Mozilla -translation_of: Mozilla/Firefox/Releases/67 ---- -<p>{{FirefoxSidebar}}</p> - -<p class="summary">Este artículo provee información sobre los cambios en Firefox 67 que afectarán a los desarrolladores. Firefox 67 fue lanzado el 21 de Mayo de 2019.</p> - -<h2 id="Cambios_para_desarrolladores_web">Cambios para desarrolladores web</h2> - -<h3 id="Herramientas_de_desarrollo">Herramientas de desarrollo</h3> - -<ul> - <li>Actualizaciones del depurador: - <ul> - <li><a href="/en-US/docs/Tools/Debugger/How_to/Set_a_breakpoint">Los puntos de interrupción de columna</a> te permiten elegir el punto específico (o columna) en una línea de código donde quieres que el depurador pare ({{bug(1528417)}}).</li> - <li><a href="/en-US/docs/Tools/Debugger/Set_a_log_point">Los puntos de registro</a> te permiten registrar información específica a la consola durante la ejecución de código sin pausar la ejecución y sin la necesidad de cambiar el código.</li> - <li>The <a href="/en-US/docs/Tools/Debugger/Using_the_Debugger_map_scopes_feature">map scopes feature</a> allows you to view the variables from the original source.</li> - <li>You can <a href="/en-US/docs/Tools/Debugger/Debug_worker_threads">debug service worker</a> threads directly in the debugger.</li> - </ul> - </li> - <li><a href="/en-US/docs/Tools/Web_Console">Web Console</a> updates: - <ul> - <li>Navigate details in the console using the keyboard ({{bug(1424159)}}).</li> - <li>Cmd + K will now clear the console of its contents on macOS ({{bug(1532939)}}).</li> - <li>When the user clears the console, the error messages cache is cleared as well ({{bug(717611)}}).</li> - <li>The user can import existing modules into the current page using import ({{bug(1517546)}}).</li> - <li>A new context menu item allows the user to use the <strong>Copy Link Location</strong> command ({{bug(1457111)}}).</li> - <li>Clicking a link in the Console causes the same behavior that it would in a content window ({{bug(1466040)}}).</li> - <li>Clicking the source link for a code file in the Console panel navigates to the Debugger if debugger knows the file ({{bug(1447244)}}).</li> - <li>When the user has filtered the contents of the console, an icon will be added to the filter text box to clear the filter ({{bug(1525821)}}).</li> - </ul> - </li> - <li><a href="/en-US/docs/Tools/Network_Monitor">Network Monitor</a> enhancements: - <ul> - <li>The <a href="/en-US/docs/Tools/Network_Monitor/request_details#Headers">Header</a> panel of the Network monitor will now display a notification for resources belonging to a known tracker ({{bug(1485416)}}).</li> - <li>In the Network monitor <a href="/en-US/docs/Tools/Network_Monitor/request_list#Network_request_columns">request columns</a>, you can control the visible columns and column sorting. The context menu now includes a command to restore the list sort parameters to the default ({{bug(1454962)}}).</li> - </ul> - </li> -</ul> - -<h4 id="Removals">Removals</h4> - -<ul> - <li>The following Developer Tools panels have been removed (see <a href="/en-US/docs/Tools/Deprecated_tools">Deprecated tools</a> for details): - - <ul> - <li>Canvas debugger ({{bug(1403938)}}).</li> - <li>Shader editor ({{bug(1342237)}}).</li> - <li>WebAudio editor ({{bug(1403944)}}).</li> - </ul> - </li> - <li>The following Developer Tools have been deprecated (see <a href="/en-US/docs/Tools/Deprecated_tools">Deprecated tools</a> for details): - <ul> - <li>WebIDE ({{bug(1539462)}}).</li> - <li>Connect... page ({{bug(1539462)}}).</li> - </ul> - </li> -</ul> - -<h3 id="HTML">HTML</h3> - -<ul> - <li>{{htmlelement("input")}} elements with <code><a href="/en-US/docs/Web/HTML/Attributes/autocomplete">autocomplete</a>="new-password"</code> set on them will no longer have previously saved passwords auto-filled ({{bug(1119063)}}).</li> -</ul> - -<h3 id="CSS">CSS</h3> - -<ul> - <li>The {{cssxref("revert")}} keyword has been implemented ({{bug(1215878)}}).</li> - <li>The <code>break-word</code> value of the {{cssxref("word-break")}} property is now supported ({{bug(1296042)}}).</li> - <li>The <code><a href="/en-US/docs/Web/CSS/@media/prefers-color-scheme">prefers-color-scheme</a></code> media feature is now supported ({{bug(1494034)}}).</li> - <li>Custom {{cssxref("cursor")}}s of greater than 32px in size are now disallowed, to mitigate potential malware uses of large cursors ({{bug(1445844)}}).</li> -</ul> - -<h4 id="Removals_2">Removals</h4> - -<ul> - <li>Use of the proprietary {{cssxref("-moz-binding")}} property is now restricted to chrome and UA-stylesheets ({{bug(1523712)}}).</li> -</ul> - -<h3 id="SVG">SVG</h3> - -<p><em>No changes.</em></p> - -<h3 id="JavaScript">JavaScript</h3> - -<ul> - <li>{{jsxref("String.prototype.matchAll")}} has been implemented and enabled by default ({{bug(1435829)}}, {{bug(1531830)}}).</li> - <li>Support for the dynamic module {{jsxref("Statements/import", "import()", "#Dynamic_Imports")}} proposal is now available by default ({{bug(1517546)}}).</li> - <li>The <a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Hashbang_comments">hashbang grammar</a> proposal is now implemented ({{bug(1519097)}}).</li> -</ul> - -<h3 id="APIs">APIs</h3> - -<h4 id="DOM">DOM</h4> - -<ul> - <li>The default value for {{domxref("Response.statusText")}} is now <code>""</code> ({{bug(1508996)}}).</li> - <li>The default value for the {{domxref("VTTCue")}} interface's <code>positionAlign</code> property is now auto ({{bug(1528420)}}).</li> - <li>User gestures are now preserved for rejected calls to {{domxref("Document.requestStorageAccess")}}, as well as fulfilled calls ({{bug(1522912)}}).</li> -</ul> - -<h4 id="DOM_events">DOM events</h4> - -<ul> - <li>CSS transition ({{bug(1530239)}}) and animation ({{bug(1531605)}}) events now fire on disabled (e.g. form) elements.</li> - <li>{{domxref("InputEvent.data")}} and {{domxref("InputEvent.dataTransfer")}} have been implemented ({{bug("998941")}}).</li> - <li>The <code>insertFromPasteAsQuotation</code> {{domxref("InputEvent.inputType")}} value is now supported ({{bug(1532527)}}).</li> -</ul> - -<h4 id="WorkersService_workers">Workers/Service workers</h4> - -<ul> - <li>Strict MIME type checks are now enforced on scripts imported by {{domxref("WorkerGlobalScope.importScripts()")}} ({{bug(1514680)}}).</li> -</ul> - -<h4 id="Media_Web_Audio_and_WebRTC">Media, Web Audio, and WebRTC</h4> - -<ul> - <li><a href="https://code.videolan.org/videolan/dav1d">dav1d</a> is now the default media decoder for <a href="https://aomediacodec.github.io/av1-spec/av1-spec.pdf">AV1</a> (see for example {{bug(1533742)}} and {{bug(1535038)}}).</li> - <li>Calling {{domxref("RTCPeerConnection.addTrack()")}} without specifying any streams to which to add the new track now works as expected: it adds a streamless track to the connection. Each peer is responsible for managing the association between the track and any stream on its end ({{bug(1231414)}}).</li> - <li>The {{domxref("MediaDeviceInfo.groupId")}} property is now implemented ({{bug(1213453)}}). While it has existed in Firefox since Firefox 39, it did not actually gather related devices together into the same group IDs.</li> - <li>The {{domxref("RTCIceCandidate.usernameFragment")}} property is now implemented ({{bug(1490658)}}).</li> -</ul> - -<h4 id="Canvas_and_WebGL">Canvas and WebGL</h4> - -<ul> - <li>The <code><a href="/en-US/docs/Web/API/EXT_float_blend">EXT_float_blend</a></code> WebGL extension has been enabled by default ({{bug(1535808)}}).</li> -</ul> - -<h4 id="Removals_3">Removals</h4> - -<ul> - <li>The deprecated <code>ShadowRoot.getElementsByTagName</code>, <code>ShadowRoot.getElementsByTagNameNS</code>, and <code>ShadowRoot.getElementsByClassName</code> properties (part of Shadow DOM v0) have been removed ({{bug(1535438)}}).</li> - <li><code><a href="/en-US/docs/Web/API/Document/createEvent">Document.createEvent("TouchEvent")</a></code>, {{domxref("Document.createTouch()")}}, {{domxref("Document.createTouchList()")}}, and the <code>ontouch*</code> event handler properties have been disabled on desktop to improve web compatibility on websites where touch support is used for mobile detection ({{bug(1412485)}}). In such cases, websites have been seen to behave incorrectly or unexpectedly on touchscreen laptops.</li> -</ul> - -<h3 id="Security">Security</h3> - -<ul> - <li><a href="/en-US/docs/Web/API/Notifications_API">Notifications</a> are now only available in a <a href="/en-US/docs/Web/Security/Secure_Contexts">secure context</a> ({{bug(1429432)}}).</li> - <li>Firefox now blocks the loading of external protocol URLs in {{htmlelement("iframe")}}s ({{bug(1527882)}}).</li> -</ul> - -<h3 id="WebDriver_conformance_(Marionette)">WebDriver conformance (Marionette)</h3> - -<h4 id="API_changes">API changes</h4> - -<ul> - <li>Made <code>WebDriver:SendAlertText</code> conformant to the <a href="https://w3c.github.io/webdriver/">WebDriver specification</a> ({{bug(1502360)}}).</li> -</ul> - -<h4 id="Corrección_de_errores">Corrección de errores</h4> - -<ul> - <li><code>WebDriver:NewWindow</code> will no longer timeout because of <code>focus</code>-related inconsistencies across platforms ({{bug(1523234)}}).</li> -</ul> - -<h4 id="Otros">Otros</h4> - -<ul> - <li>Both <code>WebDriver:ExecuteScript</code> and <code>WebDriver:ExecuteAsyncScript</code> now use <code>Promises</code> internally ({{bug(1398095)}}).</li> - <li><code>WebDriver:NewSession</code> returns Firefox's <code>BuildID</code> string as part of the capabilities object ({{bug(1525829)}}).</li> -</ul> - -<h2 id="Changes_for_add-on_developers">Changes for add-on developers</h2> - -<h3 id="Cambios_en_API">Cambios en API</h3> - -<ul> - <li>Using the <code>proxy.settings.set()</code> method to change <code>{{WebExtAPIRef("types.BrowserSetting", "BrowserSetting")}}</code> values will throw an exception unless the extension was granted private window access by the user ({{bug(1525447)}}).</li> -</ul> - -<h3 id="Cambios_en_manifiesto">Cambios en manifiesto</h3> - -<ul> - <li>A new manifest key, <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/incognito">incognito</a>, defines the behavior of an extension in private browsing windows or tabs ({{bug(1511636)}}).</li> - <li>The <code>toolbar_field_highlight</code> setting controls the background color used to indicate the current selection of text in the URL bar ({{bug(1450114)}}).</li> - <li>The <code>toolbar_field_highlight_text</code> setting controls the text color used to indicate the current selection of text in the URL bar ({{bug(1450114)}}).</li> -</ul> - -<h2 id="Ver_también">Ver también</h2> - -<ul> - <li><a href="https://www.fxsitecompat.com/en-CA/versions/67/">Sitio de compatibilidad para Firefox 67</a></li> -</ul> - -<h2 id="Versiones_anteriores">Versiones anteriores</h2> - -<p>{{Firefox_for_developers(66)}}</p> diff --git a/files/es/mozilla/firefox/releases/68/index.html b/files/es/mozilla/firefox/releases/68/index.html deleted file mode 100644 index 4c2649dcd2..0000000000 --- a/files/es/mozilla/firefox/releases/68/index.html +++ /dev/null @@ -1,233 +0,0 @@ ---- -title: Firefox 68 for developers -slug: Mozilla/Firefox/Releases/68 -translation_of: Mozilla/Firefox/Releases/68 ---- -<p>{{FirefoxSidebar}}</p> - -<p class="summary">This article provides information about the changes in Firefox 68 that will affect developers. Firefox 68 was released on July 9, 2019.</p> - -<h2 id="Changes_for_web_developers">Changes for web developers</h2> - -<h3 id="Developer_tools">Developer tools</h3> - -<h4 id="Browserweb_console">Browser/web console</h4> - -<ul> - <li>The Web console now shows <a href="/en-US/docs/Tools/Web_Console/Console_messages#CSS">more information about CSS warnings</a>, including a node list of the DOM elements that used the rule ({{bug(1093953)}}).</li> - <li>You can now filter content in the Web console using regular expressions ({{bug(1441079)}}).</li> - <li>The Browser console now allows you to show or hide messages from the content process by setting or clearing the checkbox labeled <em>Show Content Messages</em> ({{bug(1260877)}}).</li> -</ul> - -<h4 id="JavaScript_debugger">JavaScript debugger</h4> - -<ul> - <li>You can now <a href="/en-US/docs/Tools/Debugger/How_to/Search#Searching_in_all_files">Search</a> in all files in the current project from the debugger by pressing <kbd>Shift</kbd> + <kbd>Ctrl</kbd> + <kbd>F</kbd> (Windows or Linux) or <kbd>Shift</kbd> + <kbd>Cmd</kbd> + <kbd>F</kbd> (macOS) ({{bug(1320325)}}).</li> -</ul> - -<h4 id="Network_monitor">Network monitor</h4> - -<ul> - <li>The Network monitor <a href="/en-US/docs/Tools/Network_Monitor/request_list#Filtering_requests">request list</a> now allows you to block a specific URL ({{bug(1151368)}}).</li> - <li>You can now resend a network request without editing the method, URL, parameters, and headers, using the <a href="/en-US/docs/Tools/Network_Monitor/request_list#Context_menu">Resend</a> command on the context menu ({{bug(1422014)}}).</li> - <li>The context menu of the Network monitor <a href="/en-US/docs/Tools/Network_Monitor/request_details#Headers">Headers</a> tab now allows you to copy all or some of the header information to the clipboard in JSON format ({{bug(1442249)}}).</li> -</ul> - -<h4 id="Page_inspector">Page inspector</h4> - -<ul> - <li>A button has been added to the <a href="/en-US/docs/Tools/Page_Inspector/How_to/Examine_and_edit_CSS#Examine_CSS_rules">rules panel</a> of the Page inspector that allows you to toggle the display of any print media queries ({{bug(1534984)}}).</li> - <li>The <a href="/en-US/docs/Tools/Page_Inspector/How_to/Edit_fonts">fonts panel</a> now includes a slider to modify <code>letter-spacing</code> ({{bug(1536237)}}).</li> - <li>A warning icon appears next to unsupported CSS properties or rules that have invalid values, to help you understand why certain styles are not being applied ({{bug(1306054)}}).</li> -</ul> - -<h4 id="Storage_inspector">Storage inspector</h4> - -<ul> - <li>You can now <a href="/en-US/docs/Tools/Storage_Inspector#Local_storage_Session_storage">delete local and session storage</a> entries by selecting the item in the storage inspector and pressing the backspace key ({{bug(1522893)}}).</li> -</ul> - -<h4 id="Other">Other</h4> - -<ul> - <li>The <a href="/en-US/docs/Tools/Accessibility_inspector">Accessibility Inspector</a> now includes a new <em>Check for issues</em> feature, which will include a number of audit tools to highlight accessibility problems on your web pages. The first available check is <em>contrast</em>, for highlighting color contrast problems.</li> - <li>The preference that controls the visibility of internal extensions (system add-ons and hidden extensions) on the <a href="/en-US/docs/Tools/about:debugging">about:debugging</a> page has been changed from <code>devtools.aboutdebugging.showSystemAddons</code> to <code>devtools.aboutdebugging.showHiddenAddons</code> ({{bug(1544372)}}).</li> - <li><a href="/en-US/docs/Tools/Responsive_Design_Mode">Responsive design mode</a> has been redesigned — the <em>Device Settings</em> dialog (device selection menu > <em>Edit List...</em>) is now more intuitive and simpler to use ({{bug(1487857)}}).</li> -</ul> - -<h4 id="Removals">Removals</h4> - -<ul> - <li>The "Enable add-on debugging" checkbox has been removed from the <a href="/en-US/docs/Tools/about:debugging">about:debugging</a> page ({{bug(1544813)}}).</li> -</ul> - -<h3 id="HTML">HTML</h3> - -<ul> - <li>The {{HTMLElement("track")}} element — represented by {{domxref("HTMLTrackElement")}} — now receives a {{domxref("HTMLTrackElement.cuechange_event", "cuechange")}} event in addition to the {{domxref("TextTrack")}} itself, if the text track is a contained by a media element ({{bug(1548731)}}).</li> - <li>{{htmlelement("link")}} elements support the <code>disabled</code> attribute again, albeit with different behavior. When <code>disabled</code> is set on a <code><link></code> element along with <code>rel="stylesheet"</code>, the referenced stylesheet is not loaded during page load, and will be loaded on demand when the <code>disabled</code> attribute is changed to <code>false</code> or removed ({{bug(1281135)}}).</li> -</ul> - -<h4 id="Removals_2"> Removals</h4> - -<ul> - <li><code><a href="/en-US/docs/Web/HTML/Element/meta"><meta http-equiv="set-cookie"></a></code> is no longer supported ({{bug(1457503)}}).</li> -</ul> - -<h3 id="CSS">CSS</h3> - -<ul> - <li><a href="/en-US/docs/Web/CSS/CSS_Scroll_Snap">CSS Scroll Snapping</a> has been updated to the latest version of the specification ({{bug(1312163)}}) and ({{bug(1544136)}}), this includes: - - <ul> - <li>The <code>scroll-padding</code> properties ({{bug(1373832)}})</li> - <li>The <code>scroll-margin</code> properties ({{bug(1373833)}})</li> - <li>{{CSSxRef("scroll-snap-align")}} ({{bug(1373835)}})</li> - </ul> - </li> - <li>The {{CSSxRef("-webkit-line-clamp")}} property has been implemented for compatibility with other browsers ({{bug(866102)}}).</li> - <li>Support has been added for the {{CSSxRef("::marker")}} pseudo-element ({{bug(205202)}}) and animation for <code>::marker</code> pseudos ({{bug(1538618)}})</li> - <li>We changed {{CSSxRef("currentColor")}} to be a computed value (except for the {{cssxref("color")}} property) ({{bug(760345)}}).</li> - <li>Support has been fixed for the <code>ch</code> length unit so it now matches the spec (fallback for no '0' glyph, vertical metrics) ({{bug(282126)}})</li> - <li>The {{CSSxRef("counter-set")}} property has been implemented. ({{bug(1518201)}}).</li> - <li>We now implement list numbering using a built-in "list-item" counter; this fixes list numbering bugs ({{bug(288704)}}).</li> - <li>Selector matching and parsing support has been implemented for <code><a href="/en-US/docs/Web/CSS/::part">::part()</a></code> ({{bug(1545430)}}) and ({{bug(1545425)}}).</li> - <li><a href="/en-US/docs/Web/CSS/CSS_Transforms">CSS Transforms</a> are now supported in indirectly rendered things e.g.) {{SVGElement("mask")}}, {{SVGElement("marker")}}, {{SVGElement("pattern")}}, {{SVGElement("clipPath")}} ({{bug(1323962)}}).</li> - <li> - <p>While we're keeping the prefixed versions of the various gradient properties ({{cssxref("linear-gradient")}}, {{cssxref("radial-gradient")}}, and {{cssxref("repeating-radial-gradient")}} available for compatibility reasons, we have revised how they're parsed so that they're handled much more like the non-prefixed versions. This means that certain existing styles won't work correctly.</p> - - <p>In particular, the complicated syntax taking both an angle and a position will no longer work, and the <code>to</code> keyword in the <code><side-or-corner></code> parameter is not required for the prefixed gradient properties. You are encouraged to use the standard, non-prefixed gradient properties instead, as they're now widely supported ({{bug(1547939)}}).</p> - </li> -</ul> - -<h4 id="Removals_3">Removals</h4> - -<ul> - <li>{{CSSxRef("scroll-snap-coordinate")}}, {{CSSxRef("scroll-snap-destination")}}, {{CSSxRef("scroll-snap-type-x")}} and {{CSSxRef("scroll-snap-type-y")}} have been removed.</li> - <li>The {{CSSxRef("scroll-snap-type")}} property has become a longhand, so the old shorthand syntax like <code>scroll-snap-type:mandatory</code> will stop working. See the <a href="https://www.fxsitecompat.com/en-CA/docs/2019/legacy-css-scroll-snap-syntax-support-has-been-dropped/">Firefox Site Compatability</a> note.</li> -</ul> - -<h3 id="SVG">SVG</h3> - -<p><em>No changes.</em></p> - -<h3 id="JavaScript">JavaScript</h3> - -<ul> - <li>The new {{jsxref("BigInt")}} primitive is enabled by default ({{bug(1527902)}}).</li> -</ul> - -<h3 id="APIs">APIs</h3> - -<h4 id="CSS_Object_Model_(CSSOM)">CSS Object Model (CSSOM)</h4> - -<ul> - <li>The legacy {{domxref("CSSStyleSheet.rules", "rules")}} property and {{domxref("CSSStyleSheet.addRule", "addRule()")}} and {{domxref("CSSStyleSheet.removeRule", "removeRule()")}} methods have been added to the {{domxref("CSSStyleSheet")}} interface. These were introduced by Internet Explorer 9 and have never managed to quite be stamped out, so they have been added to improve compatibility with the small percentage of sites that still use them ({{bug(1545823)}}).</li> -</ul> - -<h4 id="DOM">DOM</h4> - -<ul> - <li>The <a href="/en-US/docs/Web/API/Visual_Viewport_API">Visual Viewport API</a> has now been enabled by default on Android ({{bug(1512813)}}). Adding this API to desktop versions of Firefox is being tracked in {{bug(1551302)}}.</li> - <li>The {{domxref("Window")}} feature <code><a href="/en-US/docs/Web/API/Window/open#noreferrer">noreferrer</a></code> is now supported; if specified, the new window's content is loaded without sharing the hostname, IP address, URL, or other identifying information about the host device ({{bug(1527287)}}).</li> - <li>The {{domxref("HTMLImageElement.decode", "decode()")}} method on <code>HTMLImageElement</code> is now implemented. This can be used to trigger loading and decoding of an image prior to adding it to the DOM ({{bug(1501794)}}).</li> - <li>{{domxref("XMLHttpRequest")}} has been updated to no longer accept the non-standard <code>moz-chunked-arraybuffer</code> value for {{domxref("XMLHttpRequest.responseType", "responseType")}}. Code still using it should be updated to <a href="/en-US/docs/Web/API/Streams_API/Using_readable_streams#Consuming_a_fetch_as_a_stream">use the Fetch API as a stream</a> ({{bug(1120171)}}).</li> - <li><code>XMLHttpRequest</code> now outputs a warning to console if you perform a synchronous request while handling an {{domxref("Window.unload_event", "unload")}}, {{domxref("Window.beforeunload_event", "beforeunload")}}, or {{domxref("Window.pagehide_event", "pagehide")}} event ({{bug(980902)}}).</li> - <li>The {{domxref("Document.cookie", "cookie")}} property has moved from the {{domxref("HTMLDocument")}} interface to the {{domxref("Document")}} interface, allowing documents other than {{Glossary("HTML")}} to use cookies ({{bug(144795)}}).</li> - <li>The {{domxref("HTMLElement.focus()")}} and {{domxref("SVGElement.focus()")}} methods now accept an optional object that may contain a boolean <code>preventScroll</code> option specifying whether or not to block the browser from scrolling the newly-focused element into view ({{bug(1374045)}}).</li> -</ul> - -<h4 id="DOM_events">DOM events</h4> - -<ul> - <li><a href="/en-US/docs/Mozilla/Firefox_for_Android">Firefox for Android</a> no longer incorrectly sends a {{domxref("Window.resize_event", "resize")}} event until after the first frame is painted; this improves web compatibility with sites that don't expect this event to occur ({{bug(1528052)}}).</li> - <li>The dispatching of events for non-primary mouse buttons has been made to more closely follow the specification; the {{domxref("Element.click_event", "click")}} event is no longer sent when non-primary buttons are clicked, instead using {{domxref("Element.auxclick_event", "auxclick")}}. In addition, {{domxref("Element.dblclick_event", "dblclick")}} no longer fires for non-primary buttons ({{bug(1379466)}}).</li> - <li>The proprietary {{domxref("MouseEvent.mozPressure")}} property has been deprecated, and will now trigger a warning in the console ({{bug(1165211)}}).</li> -</ul> - -<h4 id="Media_Web_Audio_and_WebRTC">Media, Web Audio, and WebRTC</h4> - -<ul> - <li>WebRTC has been updated to recognize that a <code>null</code> candidate passed into the {{domxref("RTCPeerConnection.icecandidate", "icecandidate")}} event handler, indicating the receipt of a candidate, instead indicates that there are no further candidates coming; when this happens the ICE gathering ({{domxref("RTCPeerConnection.iceGatheringState", "iceGatheringState")}}) state reaches <code>complete</code> ({{bug(1318167)}}).</li> - <li>The {{domxref("RTCRtpReceiver")}} methods {{domxref("RTCRtpReceiver.getContributingSources", "getContributingSources()")}} and {{domxref("RTCRtpReceiver.getSynchronizationSources", "getSynchronizationSources()")}} now support video tracks; previously they only worked on audio ({{bug(1534466)}}).</li> - <li>The Web Audio API {{domxref("MediaStreamTrackAudioSourceNode")}} interface is now supported, as is the method {{domxref("AudioContext.createMediaStreamTrackSource()")}} ({{bug(1324548)}}).</li> - <li>{{domxref("RTCDataChannel.negotiated")}} is now implemented ({{bug(1529695)}}).</li> - <li>The {{domxref("MediaStreamAudioSourceNode.MediaStreamAudioSourceNode", "MediaStreamAudioSourceNode()")}} constructor has been updated to match the current specification's definition that the "first audio track" in the stream is the track whose ID comes first in lexicographical order ({{bug(1324548)}}).</li> - <li> - <p>{{domxref("MediaDevices.getUserMedia", "getUserMedia()")}} may no longer be used from a non-secure context; attempting to do so now throws a <code>NotAllowedError</code> exception. Secure contexts are those loaded using HTTPS, those located using the <code>file:///</code> scheme, and those loaded from <code>localhost</code>. For now, if you must, you can re-enable the ability to perform insecure calls to <code>getUserMedia()</code> by setting the preference <code>media.getusermedia.insecure.enabled</code> to <code>true</code> ({{bug(1335740)}}).</p> - - <div class="blockIndicator note"> - <p><strong>Note:</strong> In the future, Firefox will also remove the {{domxref("navigator.mediaDevices")}} property on insecure contexts, preventing all access to the {{domxref("MediaDevices")}} APIs. <strong>This is already the case in Nightly builds.</strong></p> - </div> - </li> -</ul> - -<h4 id="Removals_4">Removals</h4> - -<ul> - <li>Removed the non-standard {{DOMxRef("XMLDocument.load()")}} method ({{bug(332175)}}).</li> - <li>Removed the non-standard {{DOMxRef("XMLDocument.async")}} property ({{bug(1328138)}}).</li> - <li>The {{domxref("RTCIceCredentialType")}} <code>token</code> value has been removed ({{bug(1529595)}}).</li> -</ul> - -<h3 id="HTTP">HTTP</h3> - -<ul> - <li>The <a href="/en-US/docs/Web/HTTP">HTTP</a> {{HTTPHeader("Clear-Site-Data")}} header no longer supports the <code>executionContexts</code> directive. This was removed due to problems with interactions between interconnections among different kinds of data at different points in the navigation process and the way the specification is designed. It <a href="https://github.com/w3c/webappsec-clear-site-data/issues/59">has been proposed</a> that this directive be removed from the specification for this reason, among others ({{bug(1548034)}}).</li> -</ul> - -<h4 id="Removals_5">Removals</h4> - -<ul> - <li>The {{HTTPHeader("Content-Security-Policy")}} directive <code>require-sri-for</code> is no longer supported due to concerns about its standardization status. It was previously available only behind a preference, which was off by default ({{bug(1386214)}}).</li> -</ul> - -<h3 id="Security">Security</h3> - -<p><em>No changes.</em></p> - -<h3 id="WebDriver_conformance_(Marionette)">WebDriver conformance (Marionette)</h3> - -<h4 id="Bug_fixes">Bug fixes</h4> - -<ul> - <li>If <code>WebDriver:SwitchToWindow</code> changes the selection to a different window it now waits for its <code>focus</code> and <code>activate</code> events before returning ({{bug(1335085)}}).</li> - <li>Fixed the <code>TypeError: this.tabModal is null</code> failure, which sometimes appeared when interacting with modal dialogs or user prompts ({{bug(1538782)}})</li> -</ul> - -<h4 id="Other_2">Other</h4> - -<ul> - <li>Disabled the feature to force unloading background tabs on low memory conditions, to prevent top-level browser contexts from magically disappearing ({{bug(1553748)}}).</li> - <li>Disabled priviledged content processes that caused HTTP authentication dialogs not to appear when navigating to a website after opening a new tab ({{bug(1558763)}}).</li> -</ul> - -<h3 id="Plugins">Plugins</h3> - -<p><em>No changes.</em></p> - -<h2 id="Changes_for_add-on_developers">Changes for add-on developers</h2> - -<h3 id="API_changes">API changes</h3> - -<ul> - <li>The The <code>proxy.register()</code> and <code>proxy.unregister()</code> functions have been deprecated and will be removed from Firefox 71 ({{bug(1545811)}}).</li> - <li>When an add-on attempts to add a bookmark folder to the root folder, the resulting error message is now much more intuitive ({{bug(1512171)}}).</li> - <li>The promise returned by <code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/duplicate">browser.tabs.duplicate()</a></code> now resolves immediately, before the tabs are completely loaded, to improve performance ({{bug(1394376)}}).</li> - <li>Support has been added for chrome.storage.managed, allowing web extension settings to be implemented via enterprise policy ({{bug(1230802)}}).</li> - <li>There is now a Group Policy option to blacklist <em>all</em> extensions except the ones that have been whitelisted ({{bug(1522823)}}).</li> -</ul> - -<h3 id="Manifest_changes">Manifest changes</h3> - -<p><em>No changes.</em></p> - -<h2 id="See_also">See also</h2> - -<ul> - <li><a href="https://www.fxsitecompat.com/en-CA/versions/68/">Site compatibility for Firefox 68</a></li> -</ul> - -<h2 id="Older_versions">Older versions</h2> - -<p>{{Firefox_for_developers(67)}}</p> diff --git a/files/es/web/api/canvas_api/tutorial/applying_styles_and_colors/index.html b/files/es/web/api/canvas_api/tutorial/applying_styles_and_colors/index.html deleted file mode 100644 index 089f74510c..0000000000 --- a/files/es/web/api/canvas_api/tutorial/applying_styles_and_colors/index.html +++ /dev/null @@ -1,727 +0,0 @@ ---- -title: Applying styles and colors -slug: Web/API/Canvas_API/Tutorial/Applying_styles_and_colors -translation_of: Web/API/Canvas_API/Tutorial/Applying_styles_and_colors -original_slug: Web/Guide/HTML/Canvas_tutorial/Applying_styles_and_colors ---- -<div>{{CanvasSidebar}} {{PreviousNext("Web/API/Canvas_API/Tutorial/Drawing_shapes", "Web/API/Canvas_API/Tutorial/Drawing_text")}}</div> - -<div class="summary"> -<p>En el capítulo acerca de dibujar formas, usamos unicamente los estilos de linea y de relleno por defecto. Aqui exploraremos las opciones del canvas que tenemos a nuestra disposición para hacer los dibujos un tanto más atractivos. Aprenderas como agregar diferentes colores, estilos de linea, gradiantes, patrones y sombras a tus dibujos.</p> -</div> - -<h2 id="Colors" name="Colors">Colors</h2> - -<p>Hasta ahrora nosotros solo me hemos visto metodos en el contexto de dibujo. Si quisieramos aplicar colores a las formas, hay dos importantes propiedades que podemos usar: <code>fillStyle</code> y <code>strokeStyle</code>.</p> - -<dl> - <dt>{{domxref("CanvasRenderingContext2D.fillStyle", "fillStyle = color")}}</dt> - <dd>Configura el estilo cuando se rellenan las formas.</dd> - <dt>{{domxref("CanvasRenderingContext2D.strokeStyle", "strokeStyle = color")}}</dt> - <dd>Configura el estilo al contorno perimetral de las formas.</dd> -</dl> - -<p><code>color</code> es una cadena que representa un CSS {{cssxref("<color>")}}, un objeto gradiante, o un objeto patron. Miraremos en objetos de gradientes y patrones mas tarde. Por defecto, el color del trazo y del relleno son configurados en negro (valor de color CSS <code>#000000</code>).</p> - -<div class="note"> -<p><strong>Nota: </strong> Cuando configuras la propiedad <code>strokeStyle</code> y/o <code>fillStyle</code>, el nuevo valor llega a ser el vador por defecto para los dibujos posteriores. Para cada forma que tu quieras en un color difrente, necesitaras reasignar las propiedades anteriores.</p> -</div> - -<p>Las cadenas validas que tu pueden entrar deberian, segun la especificación, ser valores de {{cssxref("<color>")}} CSS. En el siguiente ejemplo, describimos en mismo color.</p> - -<pre class="brush: js">// these all set the fillStyle to 'orange' - -ctx.fillStyle = 'orange'; -ctx.fillStyle = '#FFA500'; -ctx.fillStyle = 'rgb(255, 165, 0)'; -ctx.fillStyle = 'rgba(255, 165, 0, 1)'; -</pre> - -<h3 id="A_fillStyle_example" name="A_fillStyle_example">A <code>fillStyle</code> example</h3> - -<p>En este ejemplo, usamos dos bucles for para dibujar una cuadrícula de rectangulos, cada uno de diferente color. La imagen resultante deberia ser similar a la de la screenhot. No hay nada demasiado espectacular en el proceso. Usamos dos variables i y j para generar un unico color RGB para cada celda cuadrada, modificando las componentes rojo y verde. El canal azul tiene un valor fijo. Modificando los canales, puedes generar todo tipo de paletas. Incrementando los paos, puedes lograr algo similar que se parezca a las paletas de colores que Photoshop usa.</p> - -<pre class="brush: js;highlight[5,6]">function draw() { - var ctx = document.getElementById('canvas').getContext('2d'); - for (var i = 0; i < 6; i++) { - for (var j = 0; j < 6; j++) { - ctx.fillStyle = 'rgb(' + Math.floor(255 - 42.5 * i) + ', ' + - Math.floor(255 - 42.5 * j) + ', 0)'; - ctx.fillRect(j * 25, i * 25, 25, 25); - } - } -}</pre> - -<div class="hidden"> -<pre class="brush: html"><canvas id="canvas" width="150" height="150"></canvas></pre> - -<pre class="brush: js">draw();</pre> -</div> - -<p>The result looks like this:</p> - -<p>{{EmbedLiveSample("A_fillStyle_example", 160, 160, "https://mdn.mozillademos.org/files/5417/Canvas_fillstyle.png")}}</p> - -<h3 id="A_strokeStyle_example" name="A_strokeStyle_example">A <code>strokeStyle</code> example</h3> - -<p>Este ejemplo es similar al de arriba, pero usa la propiedad <code>strokeStyle</code> para cambiar el color del contorno de las formas. Usamos el método <code>arc()</code> para dibujar circulos en lugar de celdas cuadradas.</p> - -<pre class="brush: js;highlight[5,6]"> function draw() { - var ctx = document.getElementById('canvas').getContext('2d'); - for (var i = 0; i < 6; i++) { - for (var j = 0; j < 6; j++) { - ctx.strokeStyle = 'rgb(0, ' + Math.floor(255 - 42.5 * i) + ', ' + - Math.floor(255 - 42.5 * j) + ')'; - ctx.beginPath(); - ctx.arc(12.5 + j * 25, 12.5 + i * 25, 10, 0, Math.PI * 2, true); - ctx.stroke(); - } - } - } -</pre> - -<div class="hidden"> -<pre class="brush: html"><canvas id="canvas" width="150" height="150"></canvas></pre> - -<pre class="brush: js">draw();</pre> -</div> - -<p>The result looks like this:</p> - -<p>{{EmbedLiveSample("A_strokeStyle_example", "180", "180", "https://mdn.mozillademos.org/files/253/Canvas_strokestyle.png")}}</p> - -<h2 id="Transparency" name="Transparency">Transparency</h2> - -<p>Ademas de dibujar formas opacas en el canvas, podemos dibujar formas semi-transparentes(o translucidas). Esto se logra bien configurando la propiedad <code>globalAlpha</code> o asignando un color semi-transparente al estilo del trazo u u/y al de relleno.</p> - -<dl> - <dt>{{domxref("CanvasRenderingContext2D.globalAlpha", "globalAlpha = transparencyValue")}}</dt> - <dd>Applies the specified transparency value to all future shapes drawn on the canvas. The value must be between 0.0 (fully transparent) to 1.0 (fully opaque). This value is 1.0 (fully opaque) by default.</dd> -</dl> - -<p>The <code>globalAlpha</code> property can be useful if you want to draw a lot of shapes on the canvas with similar transparency, but otherwise it's generally more useful to set the transparency on individual shapes when setting their colors.</p> - -<p>Debido qaque las propiedades <code>strokeStyle</code> y <code>fillStyle</code> aceptan valores de color rgba de CSS, podemos usar la siguiente notacion para asignar una color transparente a ellos.</p> - -<pre class="brush: js">// Assigning transparent colors to stroke and fill style - -ctx.strokeStyle = 'rgba(255, 0, 0, 0.5)'; -ctx.fillStyle = 'rgba(255, 0, 0, 0.5)'; -</pre> - -<p>The <code>rgba()</code> function is similar to the <code>rgb()</code> function but it has one extra parameter. The last parameter sets the transparency value of this particular color. The valid range is again between 0.0 (fully transparent) and 1.0 (fully opaque).</p> - -<h3 id="A_globalAlpha_example" name="A_globalAlpha_example">A <code>globalAlpha</code> example</h3> - -<p>In this example, we'll draw a background of four different colored squares. On top of these, we'll draw a set of semi-transparent circles. The <code>globalAlpha</code> property is set at <code>0.2</code> which will be used for all shapes from that point on. Every step in the <code>for</code> loop draws a set of circles with an increasing radius. The final result is a radial gradient. By overlaying ever more circles on top of each other, we effectively reduce the transparency of the circles that have already been drawn. By increasing the step count and in effect drawing more circles, the background would completely disappear from the center of the image.</p> - -<pre class="brush: js;highlight[15]">function draw() { - var ctx = document.getElementById('canvas').getContext('2d'); - // draw background - ctx.fillStyle = '#FD0'; - ctx.fillRect(0, 0, 75, 75); - ctx.fillStyle = '#6C0'; - ctx.fillRect(75, 0, 75, 75); - ctx.fillStyle = '#09F'; - ctx.fillRect(0, 75, 75, 75); - ctx.fillStyle = '#F30'; - ctx.fillRect(75, 75, 75, 75); - ctx.fillStyle = '#FFF'; - - // set transparency value - ctx.globalAlpha = 0.2; - - // Draw semi transparent circles - for (var i = 0; i < 7; i++) { - ctx.beginPath(); - ctx.arc(75, 75, 10 + 10 * i, 0, Math.PI * 2, true); - ctx.fill(); - } -}</pre> - -<div class="hidden"> -<pre class="brush: html"><canvas id="canvas" width="150" height="150"></canvas></pre> - -<pre class="brush: js">draw();</pre> -</div> - -<p>{{EmbedLiveSample("A_globalAlpha_example", "180", "180", "https://mdn.mozillademos.org/files/232/Canvas_globalalpha.png")}}</p> - -<h3 id="An_example_using_rgba" name="An_example_using_rgba()">An example using <code>rgba()</code></h3> - -<p>In this second example, we do something similar to the one above, but instead of drawing circles on top of each other, I've drawn small rectangles with increasing opacity. Using <code>rgba()</code> gives you a little more control and flexibility because we can set the fill and stroke style individually.</p> - -<pre class="brush: js;highlight[16]">function draw() { - var ctx = document.getElementById('canvas').getContext('2d'); - - // Draw background - ctx.fillStyle = 'rgb(255, 221, 0)'; - ctx.fillRect(0, 0, 150, 37.5); - ctx.fillStyle = 'rgb(102, 204, 0)'; - ctx.fillRect(0, 37.5, 150, 37.5); - ctx.fillStyle = 'rgb(0, 153, 255)'; - ctx.fillRect(0, 75, 150, 37.5); - ctx.fillStyle = 'rgb(255, 51, 0)'; - ctx.fillRect(0, 112.5, 150, 37.5); - - // Draw semi transparent rectangles - for (var i = 0; i < 10; i++) { - ctx.fillStyle = 'rgba(255, 255, 255, ' + (i + 1) / 10 + ')'; - for (var j = 0; j < 4; j++) { - ctx.fillRect(5 + i * 14, 5 + j * 37.5, 14, 27.5); - } - } -}</pre> - -<div class="hidden"> -<pre class="brush: html"><canvas id="canvas" width="150" height="150"></canvas></pre> - -<pre class="brush: js">draw();</pre> -</div> - -<p>{{EmbedLiveSample("An_example_using_rgba()", "180", "180", "https://mdn.mozillademos.org/files/246/Canvas_rgba.png")}}</p> - -<h2 id="Line_styles" name="Line_styles">Line styles</h2> - -<p>There are several properties which allow us to style lines.</p> - -<dl> - <dt>{{domxref("CanvasRenderingContext2D.lineWidth", "lineWidth = value")}}</dt> - <dd>Sets the width of lines drawn in the future.</dd> - <dt>{{domxref("CanvasRenderingContext2D.lineCap", "lineCap = type")}}</dt> - <dd>Sets the appearance of the ends of lines.</dd> - <dt>{{domxref("CanvasRenderingContext2D.lineJoin", "lineJoin = type")}}</dt> - <dd>Sets the appearance of the "corners" where lines meet.</dd> - <dt>{{domxref("CanvasRenderingContext2D.miterLimit", "miterLimit = value")}}</dt> - <dd>Establishes a limit on the miter when two lines join at a sharp angle, to let you control how thick the junction becomes.</dd> - <dt>{{domxref("CanvasRenderingContext2D.getLineDash", "getLineDash()")}}</dt> - <dd>Returns the current line dash pattern array containing an even number of non-negative numbers.</dd> - <dt>{{domxref("CanvasRenderingContext2D.setLineDash", "setLineDash(segments)")}}</dt> - <dd>Sets the current line dash pattern.</dd> - <dt>{{domxref("CanvasRenderingContext2D.lineDashOffset", "lineDashOffset = value")}}</dt> - <dd>Specifies where to start a dash array on a line.</dd> -</dl> - -<p>You'll get a better understanding of what these do by looking at the examples below.</p> - -<h3 id="A_lineWidth_example" name="A_lineWidth_example">A <code>lineWidth</code> example</h3> - -<p>This property sets the current line thickness. Values must be positive numbers. By default this value is set to 1.0 units.</p> - -<p>The line width is the thickness of the stroke centered on the given path. In other words, the area that's drawn extends to half the line width on either side of the path. Because canvas coordinates do not directly reference pixels, special care must be taken to obtain crisp horizontal and vertical lines.</p> - -<p>In the example below, 10 straight lines are drawn with increasing line widths. The line on the far left is 1.0 units wide. However, the leftmost and all other odd-integer-width thickness lines do not appear crisp, because of the path's positioning.</p> - -<pre class="brush: js;highlight[4]">function draw() { - var ctx = document.getElementById('canvas').getContext('2d'); - for (var i = 0; i < 10; i++) { - ctx.lineWidth = 1 + i; - ctx.beginPath(); - ctx.moveTo(5 + i * 14, 5); - ctx.lineTo(5 + i * 14, 140); - ctx.stroke(); - } -} -</pre> - -<div class="hidden"> -<pre class="brush: html"><canvas id="canvas" width="150" height="150"></canvas></pre> - -<pre class="brush: js">draw();</pre> -</div> - -<p>{{EmbedLiveSample("A_lineWidth_example", "180", "180", "https://mdn.mozillademos.org/files/239/Canvas_linewidth.png")}}</p> - -<p>Obtaining crisp lines requires understanding how paths are stroked. In the images below, the grid represents the canvas coordinate grid. The squares between gridlines are actual on-screen pixels. In the first grid image below, a rectangle from (2,1) to (5,5) is filled. The entire area between them (light red) falls on pixel boundaries, so the resulting filled rectangle will have crisp edges.</p> - -<p><img alt="" class="internal" src="https://mdn.mozillademos.org/files/201/Canvas-grid.png"></p> - -<p>If you consider a path from (3,1) to (3,5) with a line thickness of <code>1.0</code>, you end up with the situation in the second image. The actual area to be filled (dark blue) only extends halfway into the pixels on either side of the path. An approximation of this has to be rendered, which means that those pixels being only partially shaded, and results in the entire area (the light blue and dark blue) being filled in with a color only half as dark as the actual stroke color. This is what happens with the <code>1.0</code> width line in the previous example code.</p> - -<p>To fix this, you have to be very precise in your path creation. Knowing that a <code>1.0</code> width line will extend half a unit to either side of the path, creating the path from (3.5,1) to (3.5,5) results in the situation in the third image—the <code>1.0</code> line width ends up completely and precisely filling a single pixel vertical line.</p> - -<div class="note"> -<p><strong>Note:</strong> Be aware that in our vertical line example, the Y position still referenced an integer gridline position—if it hadn't, we would see pixels with half coverage at the endpoints (but note also that this behavior depends on the current <code>lineCap</code> style whose default value is <code>butt</code>; you may want to compute consistent strokes with half-pixel coordinates for odd-width lines, by setting the <code>lineCap</code> style to <code>square</code>, so that the outer border of the stroke around the endpoint will be automatically extended to cover the whole pixel exactly).</p> - -<p>Note also that only start and final endpoints of a path are affected: if a path is closed with <code>closePath()</code>, there's no start and final endpoint; instead, all endpoints in the path are connected to their attached previous and next segment using the current setting of the <code>lineJoin</code> style, whose default value is <code>miter</code>, with the effect of automatically extending the outer borders of the connected segments to their intersection point, so that the rendered stroke will exactly cover full pixels centered at each endpoint if those connected segments are horizontal and/or vertical). See the next two sections for demonstrations of these additional line styles.</p> -</div> - -<p>For even-width lines, each half ends up being an integer amount of pixels, so you want a path that is between pixels (that is, (3,1) to (3,5)), instead of down the middle of pixels.</p> - -<p>While slightly painful when initially working with scalable 2D graphics, paying attention to the pixel grid and the position of paths ensures that your drawings will look correct regardless of scaling or any other transformations involved. A 1.0-width vertical line drawn at the correct position will become a crisp 2-pixel line when scaled up by 2, and will appear at the correct position.</p> - -<h3 id="A_lineCap_example" name="A_lineCap_example">A <code>lineCap</code> example</h3> - -<p>The <code>lineCap</code> property determines how the end points of every line are drawn. There are three possible values for this property and those are: <code>butt</code>, <code>round</code> and <code>square</code>. By default this property is set to <code>butt</code>.</p> - -<p><img alt="" src="https://mdn.mozillademos.org/files/236/Canvas_linecap.png" style="float: right; height: 190px; width: 190px;"></p> - -<dl> - <dt><code>butt</code></dt> - <dd>The ends of lines are squared off at the endpoints.</dd> - <dt><code>round</code></dt> - <dd>The ends of lines are rounded.</dd> - <dt><code>square</code></dt> - <dd>The ends of lines are squared off by adding a box with an equal width and half the height of the line's thickness.</dd> -</dl> - -<p>In this example, we'll draw three lines, each with a different value for the <code>lineCap</code> property. I also added two guides to see the exact differences between the three. Each of these lines starts and ends exactly on these guides.</p> - -<p>The line on the left uses the default <code>butt</code> option. You'll notice that it's drawn completely flush with the guides. The second is set to use the <code>round</code> option. This adds a semicircle to the end that has a radius half the width of the line. The line on the right uses the <code>square</code> option. This adds a box with an equal width and half the height of the line thickness.</p> - -<pre class="brush: js;highlight[18]">function draw() { - var ctx = document.getElementById('canvas').getContext('2d'); - var 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 (var 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> - -<div class="hidden"> -<pre class="brush: html"><canvas id="canvas" width="150" height="150"></canvas></pre> - -<pre class="brush: js">draw();</pre> -</div> - -<p>{{EmbedLiveSample("A_lineCap_example", "180", "180", "https://mdn.mozillademos.org/files/236/Canvas_linecap.png")}}</p> - -<h3 id="A_lineJoin_example" name="A_lineJoin_example">A <code>lineJoin</code> example</h3> - -<p>The <code>lineJoin</code> property determines how two connecting segments (of lines, arcs or curves) with non-zero lengths in a shape are joined together (degenerate segments with zero lengths, whose specified endpoints and control points are exactly at the same position, are skipped).</p> - -<p>There are three possible values for this property: <code>round</code>, <code>bevel</code> and <code>miter</code>. By default this property is set to <code>miter</code>. Note that the <code>lineJoin</code> setting has no effect if the two connected segments have the same direction, because no joining area will be added in this case.</p> - -<p><img alt="" src="https://mdn.mozillademos.org/files/237/Canvas_linejoin.png" style="float: right; height: 190px; width: 190px;"></p> - -<dl> - <dt><code>round</code></dt> - <dd>Rounds off the corners of a shape by filling an additional sector of disc centered at the common endpoint of connected segments. The radius for these rounded corners is equal to half the line width.</dd> - <dt><code>bevel</code></dt> - <dd>Fills an additional triangular area between the common endpoint of connected segments, and the separate outside rectangular corners of each segment.</dd> - <dt><code>miter</code></dt> - <dd>Connected segments are joined by extending their outside edges to connect at a single point, with the effect of filling an additional lozenge-shaped area. This setting is effected by the <code>miterLimit</code> property which is explained below.</dd> -</dl> - -<p>The example below draws three different paths, demonstrating each of these three <code>lineJoin</code> property settings; the output is shown above.</p> - -<pre class="brush: js;highlight[6]">function draw() { - var ctx = document.getElementById('canvas').getContext('2d'); - var lineJoin = ['round', 'bevel', 'miter']; - ctx.lineWidth = 10; - for (var i = 0; i < lineJoin.length; i++) { - ctx.lineJoin = lineJoin[i]; - ctx.beginPath(); - ctx.moveTo(-5, 5 + i * 40); - ctx.lineTo(35, 45 + i * 40); - ctx.lineTo(75, 5 + i * 40); - ctx.lineTo(115, 45 + i * 40); - ctx.lineTo(155, 5 + i * 40); - ctx.stroke(); - } -} -</pre> - -<div class="hidden"> -<pre class="brush: html"><canvas id="canvas" width="150" height="150"></canvas></pre> - -<pre class="brush: js">draw();</pre> -</div> - -<p>{{EmbedLiveSample("A_lineJoin_example", "180", "180", "https://mdn.mozillademos.org/files/237/Canvas_linejoin.png")}}</p> - -<h3 id="A_demo_of_the_miterLimit_property" name="A_demo_of_the_miterLimit_property">A demo of the <code>miterLimit</code> property</h3> - -<p>As you've seen in the previous example, when joining two lines with the <code>miter</code> option, the outside edges of the two joining lines are extended up to the point where they meet. For lines which are at large angles with each other, this point is not far from the inside connection point. However, as the angles between each line decreases, the distance (miter length) between these points increases exponentially.</p> - -<p>The <code>miterLimit</code> property determines how far the outside connection point can be placed from the inside connection point. If two lines exceed this value, a bevel join gets drawn instead. Note that the maximum miter length is the product of the line width measured in the current coordinate system, by the value of this <code>miterLimit</code> property (whose default value is 10.0 in the HTML {{HTMLElement("canvas")}}), so the <code>miterLimit</code> can be set independently from the current display scale or any affine transforms of paths: it only influences the effectively rendered shape of line edges.</p> - -<p>More exactly, the miter limit is the maximum allowed ratio of the extension length (in the HTML canvas, it is measured between the outside corner of the joined edges of the line and the common endpoint of connecting segments specified in the path) to half the line width. It can equivalently be defined as the maximum allowed ratio of the distance between the inside and outside points of jonction of edges, to the total line width. It is then equal to the cosecant of half the minimum inner angle of connecting segments below which no miter join will be rendered, but only a bevel join:</p> - -<ul> - <li><code>miterLimit</code> = <strong>max</strong> <code>miterLength</code> / <code>lineWidth</code> = 1 / <strong>sin</strong> ( <strong>min</strong> <em>θ</em> / 2 )</li> - <li>The default miter limit of 10.0 will strip all miters for sharp angles below about 11 degrees.</li> - <li>A miter limit equal to √2 ≈ 1.4142136 (rounded up) will strip miters for all acute angles, keeping miter joins only for obtuse or right angles.</li> - <li>A miter limit equal to 1.0 is valid but will disable all miters.</li> - <li>Values below 1.0 are invalid for the miter limit.</li> -</ul> - -<p>Here's a little demo in which you can set <code>miterLimit</code> dynamically and see how this effects the shapes on the canvas. The blue lines show where the start and endpoints for each of the lines in the zig-zag pattern are.</p> - -<p>If you specify a <code>miterLimit</code> value below 4.2 in this demo, none of the visible corners will join with a miter extension, but only with a small bevel near the blue lines; with a <code>miterLimit</code> above 10, most corners in this demo should join with a miter far away from the blue lines, and whose height is decreasing between corners from left to right because they connect with growing angles; with intermediate values, the corners on the left side will only join with a bevel near the blue lines, and the corners on the right side with a miter extension (also with a decreasing height).</p> - -<pre class="brush: js;highlight[18]">function draw() { - var ctx = document.getElementById('canvas').getContext('2d'); - - // Clear canvas - ctx.clearRect(0, 0, 150, 150); - - // Draw guides - ctx.strokeStyle = '#09f'; - ctx.lineWidth = 2; - ctx.strokeRect(-5, 50, 160, 50); - - // Set line styles - ctx.strokeStyle = '#000'; - ctx.lineWidth = 10; - - // check input - if (document.getElementById('miterLimit').value.match(/\d+(\.\d+)?/)) { - ctx.miterLimit = parseFloat(document.getElementById('miterLimit').value); - } else { - alert('Value must be a positive number'); - } - - // Draw lines - ctx.beginPath(); - ctx.moveTo(0, 100); - for (i = 0; i < 24 ; i++) { - var dy = i % 2 == 0 ? 25 : -25; - ctx.lineTo(Math.pow(i, 1.5) * 2, 75 + dy); - } - ctx.stroke(); - return false; -} -</pre> - -<div class="hidden"> -<pre class="brush: html"><table> - <tr> - <td><canvas id="canvas" width="150" height="150"></canvas></td> - <td>Change the <code>miterLimit</code> by entering a new value below and clicking the redraw button.<br><br> - <form onsubmit="return draw();"> - <label>Miter limit</label> - <input type="number" size="3" id="miterLimit"/> - <input type="submit" value="Redraw"/> - </form> - </td> - </tr> -</table></pre> - -<pre class="brush: js">document.getElementById('miterLimit').value = document.getElementById('canvas').getContext('2d').miterLimit; -draw();</pre> -</div> - -<p>{{EmbedLiveSample("A_demo_of_the_miterLimit_property", "400", "180", "https://mdn.mozillademos.org/files/240/Canvas_miterlimit.png")}}</p> - -<h3 id="Using_line_dashes">Using line dashes</h3> - -<p>The <code>setLineDash</code> method and the <code>lineDashOffset</code> property specify the dash pattern for lines. The <code>setLineDash</code> method accepts a list of numbers that specifies distances to alternately draw a line and a gap and the <code>lineDashOffset</code> property sets an offset where to start the pattern.</p> - -<p>In this example we are creating a marching ants effect. It is an animation technique often found in <span class="new">selection</span> tools of computer graphics programs. It helps the user to distinguish the selection border from the image background by animating the border. In a later part of this tutorial, you can learn how to do this and other <a href="/en-US/docs/Web/API/Canvas_API/Tutorial/Basic_animations">basic animations</a>.</p> - -<div class="hidden"> -<pre class="brush: html"><canvas id="canvas" width="110" height="110"></canvas></pre> -</div> - -<pre class="brush: js;highlight[6]">var ctx = document.getElementById('canvas').getContext('2d'); -var offset = 0; - -function draw() { - ctx.clearRect(0, 0, canvas.width, canvas.height); - ctx.setLineDash([4, 2]); - ctx.lineDashOffset = -offset; - ctx.strokeRect(10, 10, 100, 100); -} - -function march() { - offset++; - if (offset > 16) { - offset = 0; - } - draw(); - setTimeout(march, 20); -} - -march();</pre> - -<p>{{EmbedLiveSample("Using_line_dashes", "120", "120", "https://mdn.mozillademos.org/files/9853/marching-ants.png")}}</p> - -<h2 id="Gradients" name="Gradients">Gradients</h2> - -<p>Just like any normal drawing program, we can fill and stroke shapes using linear and radial gradients. We create a {{domxref("CanvasGradient")}} object by using one of the following methods. We can then assign this object to the <code>fillStyle</code> or <code>strokeStyle</code> properties.</p> - -<dl> - <dt>{{domxref("CanvasRenderingContext2D.createLinearGradient", "createLinearGradient(x1, y1, x2, y2)")}}</dt> - <dd>Creates a linear gradient object with a starting point of (<code>x1</code>, <code>y1</code>) and an end point of (<code>x2</code>, <code>y2</code>).</dd> - <dt>{{domxref("CanvasRenderingContext2D.createRadialGradient", "createRadialGradient(x1, y1, r1, x2, y2, r2)")}}</dt> - <dd>Creates a radial gradient. The parameters represent two circles, one with its center at (<code>x1</code>, <code>y1</code>) and a radius of <code>r1</code>, and the other with its center at (<code>x2</code>, <code>y2</code>) with a radius of <code>r2</code>.</dd> -</dl> - -<p>For example:</p> - -<pre class="brush: js">var lineargradient = ctx.createLinearGradient(0, 0, 150, 150); -var radialgradient = ctx.createRadialGradient(75, 75, 0, 75, 75, 100); -</pre> - -<p>Once we've created a <code>CanvasGradient</code> object we can assign colors to it by using the <code>addColorStop()</code> method.</p> - -<dl> - <dt>{{domxref("CanvasGradient.addColorStop", "gradient.addColorStop(position, color)")}}</dt> - <dd>Creates a new color stop on the <code>gradient</code> object. The <code>position</code> is a number between 0.0 and 1.0 and defines the relative position of the color in the gradient, and the <code>color</code> argument must be a string representing a CSS {{cssxref("<color>")}}, indicating the color the gradient should reach at that offset into the transition.</dd> -</dl> - -<p>You can add as many color stops to a gradient as you need. Below is a very simple linear gradient from white to black.</p> - -<pre class="brush: js">var lineargradient = ctx.createLinearGradient(0, 0, 150, 150); -lineargradient.addColorStop(0, 'white'); -lineargradient.addColorStop(1, 'black'); -</pre> - -<h3 id="A_createLinearGradient_example" name="A_createLinearGradient_example">A <code>createLinearGradient</code> example</h3> - -<p>In this example, we'll create two different gradients. As you can see here, both the <code>strokeStyle</code> and <code>fillStyle</code> properties can accept a <code>canvasGradient</code> object as valid input.</p> - -<pre class="brush: js;highlight[5,11]">function draw() { - var ctx = document.getElementById('canvas').getContext('2d'); - - // Create gradients - var lingrad = ctx.createLinearGradient(0, 0, 0, 150); - lingrad.addColorStop(0, '#00ABEB'); - lingrad.addColorStop(0.5, '#fff'); - lingrad.addColorStop(0.5, '#26C000'); - lingrad.addColorStop(1, '#fff'); - - var lingrad2 = ctx.createLinearGradient(0, 50, 0, 95); - lingrad2.addColorStop(0.5, '#000'); - lingrad2.addColorStop(1, 'rgba(0, 0, 0, 0)'); - - // assign gradients to fill and stroke styles - ctx.fillStyle = lingrad; - ctx.strokeStyle = lingrad2; - - // draw shapes - ctx.fillRect(10, 10, 130, 130); - ctx.strokeRect(50, 50, 50, 50); - -} -</pre> - -<div class="hidden"> -<pre class="brush: html"><canvas id="canvas" width="150" height="150"></canvas></pre> - -<pre class="brush: js">draw();</pre> -</div> - -<p>The first is a background gradient. As you can see, we assigned two colors at the same position. You do this to make very sharp color transitions—in this case from white to green. Normally, it doesn't matter in what order you define the color stops, but in this special case, it does significantly. If you keep the assignments in the order you want them to appear, this won't be a problem.</p> - -<p>In the second gradient, we didn't assign the starting color (at position 0.0) since it wasn't strictly necessary, because it will automatically assume the color of the next color stop. Therefore, assigning the black color at position 0.5 automatically makes the gradient, from the start to this stop, black.</p> - -<p>{{EmbedLiveSample("A_createLinearGradient_example", "180", "180", "https://mdn.mozillademos.org/files/235/Canvas_lineargradient.png")}}</p> - -<h3 id="A_createRadialGradient_example" name="A_createRadialGradient_example">A <code>createRadialGradient</code> example</h3> - -<p>In this example, we'll define four different radial gradients. Because we have control over the start and closing points of the gradient, we can achieve more complex effects than we would normally have in the "classic" radial gradients we see in, for instance, Photoshop (that is, a gradient with a single center point where the gradient expands outward in a circular shape).</p> - -<pre class="brush: js;highlight[5,10,15,20]">function draw() { - var ctx = document.getElementById('canvas').getContext('2d'); - - // Create gradients - var radgrad = ctx.createRadialGradient(45, 45, 10, 52, 50, 30); - radgrad.addColorStop(0, '#A7D30C'); - radgrad.addColorStop(0.9, '#019F62'); - radgrad.addColorStop(1, 'rgba(1, 159, 98, 0)'); - - var radgrad2 = ctx.createRadialGradient(105, 105, 20, 112, 120, 50); - radgrad2.addColorStop(0, '#FF5F98'); - radgrad2.addColorStop(0.75, '#FF0188'); - radgrad2.addColorStop(1, 'rgba(255, 1, 136, 0)'); - - var radgrad3 = ctx.createRadialGradient(95, 15, 15, 102, 20, 40); - radgrad3.addColorStop(0, '#00C9FF'); - radgrad3.addColorStop(0.8, '#00B5E2'); - radgrad3.addColorStop(1, 'rgba(0, 201, 255, 0)'); - - var radgrad4 = ctx.createRadialGradient(0, 150, 50, 0, 140, 90); - radgrad4.addColorStop(0, '#F4F201'); - radgrad4.addColorStop(0.8, '#E4C700'); - radgrad4.addColorStop(1, 'rgba(228, 199, 0, 0)'); - - // draw shapes - ctx.fillStyle = radgrad4; - ctx.fillRect(0, 0, 150, 150); - ctx.fillStyle = radgrad3; - ctx.fillRect(0, 0, 150, 150); - ctx.fillStyle = radgrad2; - ctx.fillRect(0, 0, 150, 150); - ctx.fillStyle = radgrad; - ctx.fillRect(0, 0, 150, 150); -} -</pre> - -<div class="hidden"> -<pre class="brush: html"><canvas id="canvas" width="150" height="150"></canvas></pre> - -<pre class="brush: js">draw();</pre> -</div> - -<p>In this case, we've offset the starting point slightly from the end point to achieve a spherical 3D effect. It's best to try to avoid letting the inside and outside circles overlap because this results in strange effects which are hard to predict.</p> - -<p>The last color stop in each of the four gradients uses a fully transparent color. If you want to have a nice transition from this to the previous color stop, both colors should be equal. This isn't very obvious from the code because it uses two different CSS color methods as a demonstration, but in the first gradient <code>#019F62 = rgba(1,159,98,1)</code>.</p> - -<p>{{EmbedLiveSample("A_createRadialGradient_example", "180", "180", "https://mdn.mozillademos.org/files/244/Canvas_radialgradient.png")}}</p> - -<h2 id="Patterns" name="Patterns">Patterns</h2> - -<p>In one of the examples on the previous page, we used a series of loops to create a pattern of images. There is, however, a much simpler method: the <code>createPattern()</code> method.</p> - -<dl> - <dt>{{domxref("CanvasRenderingContext2D.createPattern", "createPattern(image, type)")}}</dt> - <dd>Creates and returns a new canvas pattern object. <code>image</code> is a {{domxref("CanvasImageSource")}} (that is, an {{domxref("HTMLImageElement")}}, another canvas, a {{HTMLElement("video")}} element, or the like. <code>type</code> is a string indicating how to use the image.</dd> -</dl> - -<p>The type specifies how to use the image in order to create the pattern, and must be one of the following string values:</p> - -<dl> - <dt><code>repeat</code></dt> - <dd>Tiles the image in both vertical and horizontal directions.</dd> - <dt><code>repeat-x</code></dt> - <dd>Tiles the image horizontally but not vertically.</dd> - <dt><code>repeat-y</code></dt> - <dd>Tiles the image vertically but not horizontally.</dd> - <dt><code>no-repeat</code></dt> - <dd>Doesn't tile the image. It's used only once.</dd> -</dl> - -<p>We use this method to create a {{domxref("CanvasPattern")}} object which is very similar to the gradient methods we've seen above. Once we've created a pattern, we can assign it to the <code>fillStyle</code> or <code>strokeStyle</code> properties. For example:</p> - -<pre class="brush: js">var img = new Image(); -img.src = 'someimage.png'; -var ptrn = ctx.createPattern(img, 'repeat'); -</pre> - -<div class="note"> -<p><strong>Note:</strong> Like with the <code>drawImage()</code> method, you must make sure the image you use is loaded before calling this method or the pattern may be drawn incorrectly.</p> -</div> - -<h3 id="A_createPattern_example" name="A_createPattern_example">A <code>createPattern</code> example</h3> - -<p>In this last example, we'll create a pattern to assign to the <code>fillStyle</code> property. The only thing worth noting is the use of the image's <code>onload</code> handler. This is to make sure the image is loaded before it is assigned to the pattern.</p> - -<pre class="brush: js;highlight[10]">function draw() { - var ctx = document.getElementById('canvas').getContext('2d'); - - // create new image object to use as pattern - var img = new Image(); - img.src = 'https://mdn.mozillademos.org/files/222/Canvas_createpattern.png'; - img.onload = function() { - - // create pattern - var ptrn = ctx.createPattern(img, 'repeat'); - ctx.fillStyle = ptrn; - ctx.fillRect(0, 0, 150, 150); - - } -} -</pre> - -<div class="hidden"> -<pre class="brush: html"><canvas id="canvas" width="150" height="150"></canvas></pre> - -<pre class="brush: js">draw();</pre> - -<p>The result looks like this:</p> -</div> - -<p>{{EmbedLiveSample("A_createPattern_example", "180", "180", "https://mdn.mozillademos.org/files/222/Canvas_createpattern.png")}}</p> - -<h2 id="Shadows">Shadows</h2> - -<p>Using shadows involves just four properties:</p> - -<dl> - <dt>{{domxref("CanvasRenderingContext2D.shadowOffsetX", "shadowOffsetX = float")}}</dt> - <dd>Indicates the horizontal distance the shadow should extend from the object. This value isn't affected by the transformation matrix. The default is 0.</dd> - <dt>{{domxref("CanvasRenderingContext2D.shadowOffsetY", "shadowOffsetY = float")}}</dt> - <dd>Indicates the vertical distance the shadow should extend from the object. This value isn't affected by the transformation matrix. The default is 0.</dd> - <dt>{{domxref("CanvasRenderingContext2D.shadowBlur", "shadowBlur = float")}}</dt> - <dd>Indicates the size of the blurring effect; this value doesn't correspond to a number of pixels and is not affected by the current transformation matrix. The default value is 0.</dd> - <dt>{{domxref("CanvasRenderingContext2D.shadowColor", "shadowColor = color")}}</dt> - <dd>A standard CSS color value indicating the color of the shadow effect; by default, it is fully-transparent black.</dd> -</dl> - -<p>The properties <code>shadowOffsetX</code> and <code>shadowOffsetY</code> indicate how far the shadow should extend from the object in the X and Y directions; these values aren't affected by the current transformation matrix. Use negative values to cause the shadow to extend up or to the left, and positive values to cause the shadow to extend down or to the right. These are both 0 by default.</p> - -<p>The <code>shadowBlur</code> property indicates the size of the blurring effect; this value doesn't correspond to a number of pixels and is not affected by the current transformation matrix. The default value is 0.</p> - -<p>The <code>shadowColor</code> property is a standard CSS color value indicating the color of the shadow effect; by default, it is fully-transparent black.</p> - -<div class="note"> -<p><strong>Note:</strong> Shadows are only drawn for <code>source-over</code> <a href="/en-US/docs/Web/API/Canvas_API/Tutorial/Compositing" title="Web/Guide/HTML/Canvas_tutorial/Compositing">compositing operations</a>.</p> -</div> - -<h3 id="A_shadowed_text_example">A shadowed text example</h3> - -<p>This example draws a text string with a shadowing effect.</p> - -<pre class="brush: js;highlight[4,5,6,7]">function draw() { - var ctx = document.getElementById('canvas').getContext('2d'); - - ctx.shadowOffsetX = 2; - ctx.shadowOffsetY = 2; - ctx.shadowBlur = 2; - ctx.shadowColor = 'rgba(0, 0, 0, 0.5)'; - - ctx.font = '20px Times New Roman'; - ctx.fillStyle = 'Black'; - ctx.fillText('Sample String', 5, 30); -} -</pre> - -<div class="hidden"> -<pre class="brush: html"><canvas id="canvas" width="150" height="80"></canvas></pre> - -<pre class="brush: js">draw();</pre> -</div> - -<p>{{EmbedLiveSample("A_shadowed_text_example", "180", "100", "https://mdn.mozillademos.org/files/2505/shadowed-string.png")}}</p> - -<p>We will look at the <code>font</code> property and <code>fillText</code> method in the next chapter about <a href="/en-US/docs/Web/API/Canvas_API/Tutorial/Drawing_text">drawing text</a>.</p> - -<h2 id="Canvas_fill_rules">Canvas fill rules</h2> - -<p>When using <code>fill</code> (or {{domxref("CanvasRenderingContext2D.clip", "clip")}} and {{domxref("CanvasRenderingContext2D.isPointInPath", "isPointinPath")}}) you can optionally provide a fill rule algorithm by which to determine if a point is inside or outside a path and thus if it gets filled or not. This is useful when a path intersects itself or is nested.<br> - <br> - Two values are possible:</p> - -<ul> - <li><code><strong>"nonzero</strong></code>": The <a class="external external-icon" href="http://en.wikipedia.org/wiki/Nonzero-rule">non-zero winding rule</a>, which is the default rule.</li> - <li><code><strong>"evenodd"</strong></code>: The <a class="external external-icon" href="http://en.wikipedia.org/wiki/Even%E2%80%93odd_rule">even-odd winding rule</a>.</li> -</ul> - -<p>In this example we are using the <code>evenodd</code> rule.</p> - -<pre class="brush: js;highlight[6]">function draw() { - var ctx = document.getElementById('canvas').getContext('2d'); - ctx.beginPath(); - ctx.arc(50, 50, 30, 0, Math.PI * 2, true); - ctx.arc(50, 50, 15, 0, Math.PI * 2, true); - ctx.fill('evenodd'); -}</pre> - -<div class="hidden"> -<pre class="brush: html"><canvas id="canvas" width="100" height="100"></canvas></pre> - -<pre class="brush: js">draw();</pre> -</div> - -<p>{{EmbedLiveSample("Canvas_fill_rules", "110", "110", "https://mdn.mozillademos.org/files/9855/fill-rule.png")}}</p> - -<p>{{PreviousNext("Web/API/Canvas_API/Tutorial/Drawing_shapes", "Web/API/Canvas_API/Tutorial/Drawing_text")}}</p> diff --git a/files/es/web/api/constraint_validation/index.html b/files/es/web/api/constraint_validation/index.html deleted file mode 100644 index 81811b4891..0000000000 --- a/files/es/web/api/constraint_validation/index.html +++ /dev/null @@ -1,154 +0,0 @@ ---- -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/cssrule/parentstylesheet/index.html b/files/es/web/api/cssrule/parentstylesheet/index.html deleted file mode 100644 index f66c603137..0000000000 --- a/files/es/web/api/cssrule/parentstylesheet/index.html +++ /dev/null @@ -1,27 +0,0 @@ ---- -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/datatransfer/index.html b/files/es/web/api/datatransfer/index.html deleted file mode 100644 index 01c9ba4fbf..0000000000 --- a/files/es/web/api/datatransfer/index.html +++ /dev/null @@ -1,376 +0,0 @@ ---- -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>{{ 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/document/evaluate/index.html b/files/es/web/api/document/evaluate/index.html deleted file mode 100644 index 67bc5d432e..0000000000 --- a/files/es/web/api/document/evaluate/index.html +++ /dev/null @@ -1,211 +0,0 @@ ---- -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/element/shadowroot/index.html b/files/es/web/api/element/shadowroot/index.html deleted file mode 100644 index 17af57bb3c..0000000000 --- a/files/es/web/api/element/shadowroot/index.html +++ /dev/null @@ -1,83 +0,0 @@ ---- -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/file/type/index.html b/files/es/web/api/file/type/index.html deleted file mode 100644 index b433446aa4..0000000000 --- a/files/es/web/api/file/type/index.html +++ /dev/null @@ -1,72 +0,0 @@ ---- -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/globaleventhandlers/onloadedmetadata/index.html b/files/es/web/api/globaleventhandlers/onloadedmetadata/index.html deleted file mode 100644 index bbe3e8e7d6..0000000000 --- a/files/es/web/api/globaleventhandlers/onloadedmetadata/index.html +++ /dev/null @@ -1,48 +0,0 @@ ---- -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 {{event("Event_handlers", "event handler")}} 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/history_api/example/index.html b/files/es/web/api/history_api/example/index.html deleted file mode 100644 index aed471d057..0000000000 --- a/files/es/web/api/history_api/example/index.html +++ /dev/null @@ -1,416 +0,0 @@ ---- -title: Ejemplo de Navegación usando Ajax -slug: Web/API/History_API/Example -translation_of: Web/API/History_API/Example -original_slug: DOM/Manipulando_el_historial_del_navegador/Ejemplo ---- -<p>This is an example of an AJAX web site composed only of three pages (<em>first_page.php</em>, <em>second_page.php</em> and <em>third_page.php</em>). To see how it works, please, create the following files (or git clone <a href="https://github.com/giabao/mdn-ajax-nav-example" title="/en-US/docs/">https://github.com/giabao/mdn-ajax-nav-example.git</a> ):</p> - -<div class="note" id="const_compatibility"><strong>Note:</strong> For fully integrating the {{HTMLElement("form")}} elements within this <em>mechanism</em>, please take a look at the paragraph <a href="/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Submitting_forms_and_uploading_files">Submitting forms and uploading files</a>.</div> - -<p><strong>first_page.php</strong>:</p> - -<div style="height: 400px; margin-bottom: 12px; overflow: auto;"> -<pre class="brush: php"><?php - $page_title = "First page"; - - $as_json = false; - if (isset($_GET["view_as"]) && $_GET["view_as"] == "json") { - $as_json = true; - ob_start(); - } else { -?> -<!doctype html> -<html> -<head> -<?php - include "include/header.php"; - echo "<title>" . $page_title . "</title>"; -?> -</head> - -<body> - -<?php include "include/before_content.php"; ?> - -<p>This paragraph is shown only when the navigation starts from <strong>first_page.php</strong>.</p> - -<div id="ajax-content"> -<?php } ?> - - <p>This is the content of <strong>first_page.php</strong>.</p> - -<?php - if ($as_json) { - echo json_encode(array("page" => $page_title, "content" => ob_get_clean())); - } else { -?> -</div> - -<p>This paragraph is shown only when the navigation starts from <strong>first_page.php</strong>.</p> - -<?php - include "include/after_content.php"; - echo "</body>\n</html>"; - } -?> -</pre> -</div> - -<p><strong>second_page.php</strong>:</p> - -<div style="height: 400px; margin-bottom: 12px; overflow: auto;"> -<pre class="brush: php"><?php - $page_title = "Second page"; - - $as_json = false; - if (isset($_GET["view_as"]) && $_GET["view_as"] == "json") { - $as_json = true; - ob_start(); - } else { -?> -<!doctype html> -<html> -<head> -<?php - include "include/header.php"; - echo "<title>" . $page_title . "</title>"; -?> -</head> - -<body> - -<?php include "include/before_content.php"; ?> - -<p>This paragraph is shown only when the navigation starts from <strong>second_page.php</strong>.</p> - -<div id="ajax-content"> -<?php } ?> - - <p>This is the content of <strong>second_page.php</strong>.</p> - -<?php - if ($as_json) { - echo json_encode(array("page" => $page_title, "content" => ob_get_clean())); - } else { -?> -</div> - -<p>This paragraph is shown only when the navigation starts from <strong>second_page.php</strong>.</p> - -<?php - include "include/after_content.php"; - echo "</body>\n</html>"; - } -?> -</pre> -</div> - -<p><strong>third_page.php</strong>:</p> - -<div style="height: 400px; margin-bottom: 12px; overflow: auto;"> -<pre class="brush: php"><?php - $page_title = "Third page"; - $page_content = "<p>This is the content of <strong>third_page.php</strong>. This content is stored into a php variable.</p>"; - - if (isset($_GET["view_as"]) && $_GET["view_as"] == "json") { - echo json_encode(array("page" => $page_title, "content" => $page_content)); - } else { -?> -<!doctype html> -<html> -<head> -<?php - include "include/header.php"; - echo "<title>" . $page_title . "</title>"; -?> -</head> - -<body> - -<?php include "include/before_content.php"; ?> - -<p>This paragraph is shown only when the navigation starts from <strong>third_page.php</strong>.</p> - -<div id="ajax-content"> -<?php echo $page_content; ?> -</div> - -<p>This paragraph is shown only when the navigation starts from <strong>third_page.php</strong>.</p> - -<?php - include "include/after_content.php"; - echo "</body>\n</html>"; - } -?> -</pre> -</div> - -<p><strong>css/style.css</strong>:</p> - -<pre class="brush: css">#ajax-loader { - position: fixed; - display: table; - top: 0; - left: 0; - width: 100%; - height: 100%; -} - -#ajax-loader > div { - display: table-cell; - width: 100%; - height: 100%; - vertical-align: middle; - text-align: center; - background-color: #000000; - opacity: 0.65; -} -</pre> - -<p><strong>include/after_content.php</strong>:</p> - -<pre class="brush: php"><p>This is the footer. It is shared between all ajax pages.</p> -</pre> - -<p><strong>include/before_content.php</strong>:</p> - -<pre class="brush: php"><p> -[ <a class="ajax-nav" href="first_page.php">First example</a> -| <a class="ajax-nav" href="second_page.php">Second example</a> -| <a class="ajax-nav" href="third_page.php">Third example</a> -| <a class="ajax-nav" href="unexisting.php">Unexisting page</a> ] -</p> - -</pre> - -<p><strong>include/header.php</strong>:</p> - -<pre class="brush: php"><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> -<script type="text/javascript" src="js/ajax_nav.js"></script> -<link rel="stylesheet" href="css/style.css" /> -</pre> - -<p><strong>js/ajax_nav.js</strong>:</p> - -<p>(before implementing it in a working environment, <strong>please read <a href="#const_compatibility" title="Note about *const* compatibility">the note about the const statement compatibility</a></strong>)</p> - -<div style="height: 400px; margin-bottom: 12px; overflow: auto;"> -<pre class="brush: js">"use strict"; - -const ajaxRequest = new (function () { - - function closeReq () { - oLoadingBox.parentNode && document.body.removeChild(oLoadingBox); - bIsLoading = false; - } - - function abortReq () { - if (!bIsLoading) { return; } - oReq.abort(); - closeReq(); - } - - function ajaxError () { - alert("Unknown error."); - } - - function ajaxLoad () { - var vMsg, nStatus = this.status; - switch (nStatus) { - case 200: - vMsg = JSON.parse(this.responseText); - document.title = oPageInfo.title = vMsg.page; - document.getElementById(sTargetId).innerHTML = vMsg.content; - if (bUpdateURL) { - history.pushState(oPageInfo, oPageInfo.title, oPageInfo.url); - bUpdateURL = false; - } - break; - default: - vMsg = nStatus + ": " + (oHTTPStatus[nStatus] || "Unknown"); - switch (Math.floor(nStatus / 100)) { - /* - case 1: - // Informational 1xx - console.log("Information code " + vMsg); - break; - case 2: - // Successful 2xx - console.log("Successful code " + vMsg); - break; - case 3: - // Redirection 3xx - console.log("Redirection code " + vMsg); - break; - */ - case 4: - /* Client Error 4xx */ - alert("Client Error #" + vMsg); - break; - case 5: - /* Server Error 5xx */ - alert("Server Error #" + vMsg); - break; - default: - /* Unknown status */ - ajaxError(); - } - } - closeReq(); - } - - function filterURL (sURL, sViewMode) { - return sURL.replace(rSearch, "") + ("?" + sURL.replace(rHost, "&").replace(rView, sViewMode ? "&" + sViewKey + "=" + sViewMode : "").slice(1)).replace(rEndQstMark, ""); - } - - function getPage (sPage) { - if (bIsLoading) { return; } - oReq = new XMLHttpRequest(); - bIsLoading = true; - oReq.onload = ajaxLoad; - oReq.onerror = ajaxError; - if (sPage) { oPageInfo.url = filterURL(sPage, null); } - oReq.open("get", filterURL(oPageInfo.url, "json"), true); - oReq.send(); - oLoadingBox.parentNode || document.body.appendChild(oLoadingBox); - } - - function requestPage (sURL) { - if (history.pushState) { - bUpdateURL = true; - getPage(sURL); - } else { - /* Ajax navigation is not supported */ - location.assign(sURL); - } - } - - function processLink () { - if (this.className === sAjaxClass) { - requestPage(this.href); - return false; - } - return true; - } - - function init () { - oPageInfo.title = document.title; - for (var oLink, nIdx = 0, nLen = document.links.length; nIdx < nLen; document.links[nIdx++].onclick = processLink); - } - - const - - /* customizable constants */ - sTargetId = "ajax-content", sViewKey = "view_as", sAjaxClass = "ajax-nav", - - /* not customizable constants */ - rSearch = /\?.*$/, rHost = /^[^\?]*\?*&*/, rView = new RegExp("&" + sViewKey + "\\=[^&]*|&*$", "i"), rEndQstMark = /\?$/, - oLoadingBox = document.createElement("div"), oCover = document.createElement("div"), oLoadingImg = new Image(), - oPageInfo = { - title: null, - url: location.href - }, oHTTPStatus = /* http://www.iana.org/assignments/http-status-codes/http-status-codes.xml */ { - 100: "Continue", - 101: "Switching Protocols", - 102: "Processing", - 200: "OK", - 201: "Created", - 202: "Accepted", - 203: "Non-Authoritative Information", - 204: "No Content", - 205: "Reset Content", - 206: "Partial Content", - 207: "Multi-Status", - 208: "Already Reported", - 226: "IM Used", - 300: "Multiple Choices", - 301: "Moved Permanently", - 302: "Found", - 303: "See Other", - 304: "Not Modified", - 305: "Use Proxy", - 306: "Reserved", - 307: "Temporary Redirect", - 308: "Permanent Redirect", - 400: "Bad Request", - 401: "Unauthorized", - 402: "Payment Required", - 403: "Forbidden", - 404: "Not Found", - 405: "Method Not Allowed", - 406: "Not Acceptable", - 407: "Proxy Authentication Required", - 408: "Request Timeout", - 409: "Conflict", - 410: "Gone", - 411: "Length Required", - 412: "Precondition Failed", - 413: "Request Entity Too Large", - 414: "Request-URI Too Long", - 415: "Unsupported Media Type", - 416: "Requested Range Not Satisfiable", - 417: "Expectation Failed", - 422: "Unprocessable Entity", - 423: "Locked", - 424: "Failed Dependency", - 425: "Unassigned", - 426: "Upgrade Required", - 427: "Unassigned", - 428: "Precondition Required", - 429: "Too Many Requests", - 430: "Unassigned", - 431: "Request Header Fields Too Large", - 500: "Internal Server Error", - 501: "Not Implemented", - 502: "Bad Gateway", - 503: "Service Unavailable", - 504: "Gateway Timeout", - 505: "HTTP Version Not Supported", - 506: "Variant Also Negotiates (Experimental)", - 507: "Insufficient Storage", - 508: "Loop Detected", - 509: "Unassigned", - 510: "Not Extended", - 511: "Network Authentication Required" - }; - - var - - oReq, bIsLoading = false, bUpdateURL = false; - - oLoadingBox.id = "ajax-loader"; - oCover.onclick = abortReq; - oLoadingImg.src = "data:image/gif;base64,R0lGODlhEAAQAPIAAP///wAAAMLCwkJCQgAAAGJiYoKCgpKSkiH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAADMwi63P4wyklrE2MIOggZnAdOmGYJRbExwroUmcG2LmDEwnHQLVsYOd2mBzkYDAdKa+dIAAAh+QQJCgAAACwAAAAAEAAQAAADNAi63P5OjCEgG4QMu7DmikRxQlFUYDEZIGBMRVsaqHwctXXf7WEYB4Ag1xjihkMZsiUkKhIAIfkECQoAAAAsAAAAABAAEAAAAzYIujIjK8pByJDMlFYvBoVjHA70GU7xSUJhmKtwHPAKzLO9HMaoKwJZ7Rf8AYPDDzKpZBqfvwQAIfkECQoAAAAsAAAAABAAEAAAAzMIumIlK8oyhpHsnFZfhYumCYUhDAQxRIdhHBGqRoKw0R8DYlJd8z0fMDgsGo/IpHI5TAAAIfkECQoAAAAsAAAAABAAEAAAAzIIunInK0rnZBTwGPNMgQwmdsNgXGJUlIWEuR5oWUIpz8pAEAMe6TwfwyYsGo/IpFKSAAAh+QQJCgAAACwAAAAAEAAQAAADMwi6IMKQORfjdOe82p4wGccc4CEuQradylesojEMBgsUc2G7sDX3lQGBMLAJibufbSlKAAAh+QQJCgAAACwAAAAAEAAQAAADMgi63P7wCRHZnFVdmgHu2nFwlWCI3WGc3TSWhUFGxTAUkGCbtgENBMJAEJsxgMLWzpEAACH5BAkKAAAALAAAAAAQABAAAAMyCLrc/jDKSatlQtScKdceCAjDII7HcQ4EMTCpyrCuUBjCYRgHVtqlAiB1YhiCnlsRkAAAOwAAAAAAAAAAAA=="; - oCover.appendChild(oLoadingImg); - oLoadingBox.appendChild(oCover); - - onpopstate = function (oEvent) { - bUpdateURL = false; - oPageInfo.title = oEvent.state.title; - oPageInfo.url = oEvent.state.url; - getPage(); - }; - - window.addEventListener ? addEventListener("load", init, false) : window.attachEvent ? attachEvent("onload", init) : (onload = init); - - // Public methods - - this.open = requestPage; - this.stop = abortReq; - this.rebuildLinks = init; - -})(); -</pre> -</div> - -<div class="note" id="const_compatibility"><strong>Note:</strong> The current implementation of <a href="/en/JavaScript/Reference/Statements/const" title="en/JavaScript/Reference/Statements/const"><code>const</code></a> (constant statement) <strong>is not part of ECMAScript 5</strong>. It is supported in Firefox & Chrome (V8) and partially supported in Opera 9+ and Safari. <strong>It is not supported in Internet Explorer 6-9, or in the preview of Internet Explorer 10</strong>. <a href="/en/JavaScript/Reference/Statements/const" title="en/JavaScript/Reference/Statements/const"><code>const</code></a> is going to be defined by ECMAScript 6, but with different semantics. Similar to variables declared with the <a href="/en/JavaScript/Reference/Statements/let" title="en/JavaScript/Reference/Statements/let"><code>let</code></a> statement, constants declared with <a href="/en/JavaScript/Reference/Statements/const" title="en/JavaScript/Reference/Statements/const"><code>const</code></a> will be block-scoped. <strong>We used it only for didactic purpose. If you want a full browser compatibility of this library, please replace all the <a href="/en/JavaScript/Reference/Statements/const" title="en/JavaScript/Reference/Statements/const"><code>const</code></a> statements with the <a href="/en/JavaScript/Reference/Statements/var" title="en/JavaScript/Reference/Statements/var"><code>var</code></a> statements.</strong></div> - -<p>For more information, please see: <a href="/en-US/docs/DOM/Manipulating_the_browser_history" title="/en-US/docs/DOM/Manipulating_the_browser_history">Manipulating the browser history</a>.</p> - -<h2 id="See_also">See also</h2> - -<ul> - <li>{{ domxref("window.history") }}</li> - <li>{{ domxref("window.onpopstate") }}</li> -</ul> diff --git a/files/es/web/api/htmlcontentelement/getdistributednodes/index.html b/files/es/web/api/htmlcontentelement/getdistributednodes/index.html deleted file mode 100644 index c4aad9ddb8..0000000000 --- a/files/es/web/api/htmlcontentelement/getdistributednodes/index.html +++ /dev/null @@ -1,95 +0,0 @@ ---- -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 deleted file mode 100644 index 637210416d..0000000000 --- a/files/es/web/api/htmlcontentelement/index.html +++ /dev/null @@ -1,110 +0,0 @@ ---- -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 deleted file mode 100644 index 916be57621..0000000000 --- a/files/es/web/api/htmlcontentelement/select/index.html +++ /dev/null @@ -1,95 +0,0 @@ ---- -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/htmlelement/innertext/index.html b/files/es/web/api/htmlelement/innertext/index.html deleted file mode 100644 index 403f3c0bc1..0000000000 --- a/files/es/web/api/htmlelement/innertext/index.html +++ /dev/null @@ -1,84 +0,0 @@ ---- -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/htmlhtmlelement/index.html b/files/es/web/api/htmlhtmlelement/index.html deleted file mode 100644 index f079c9a07a..0000000000 --- a/files/es/web/api/htmlhtmlelement/index.html +++ /dev/null @@ -1,121 +0,0 @@ ---- -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/htmlmediaelement/abort_event/index.html b/files/es/web/api/htmlmediaelement/abort_event/index.html deleted file mode 100644 index 597993df26..0000000000 --- a/files/es/web/api/htmlmediaelement/abort_event/index.html +++ /dev/null @@ -1,69 +0,0 @@ ---- -title: abort -slug: Web/API/HTMLMediaElement/abort_event -translation_of: Web/API/HTMLMediaElement/abort_event -translation_of_original: Web/Events/abort -original_slug: Web/Events/abort ---- -<p>The <code>abort</code> event is fired when the loading of a resource has been aborted.</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-abort">DOM L3</a></dd> - <dt style="float: left; text-align: right; width: 120px;">Interface</dt> - <dd style="margin: 0 0 0 120px;">UIEvent if generated from a user interface, Event otherwise.</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><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>0.</td> - </tr> - </tbody> -</table> diff --git a/files/es/web/api/keyboardevent/getmodifierstate/index.html b/files/es/web/api/keyboardevent/getmodifierstate/index.html deleted file mode 100644 index b44ecc6da3..0000000000 --- a/files/es/web/api/keyboardevent/getmodifierstate/index.html +++ /dev/null @@ -1,253 +0,0 @@ ---- -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/key/index.html b/files/es/web/api/keyboardevent/key/index.html deleted file mode 100644 index ed765b38b3..0000000000 --- a/files/es/web/api/keyboardevent/key/index.html +++ /dev/null @@ -1,212 +0,0 @@ ---- -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/navigator/mediadevices/index.html b/files/es/web/api/navigator/mediadevices/index.html deleted file mode 100644 index 0a7e70e7e4..0000000000 --- a/files/es/web/api/navigator/mediadevices/index.html +++ /dev/null @@ -1,49 +0,0 @@ ---- -title: Navigator.mediaDevices -slug: Web/API/Navigator/mediaDevices -translation_of: Web/API/Navigator/mediaDevices ---- -<div>{{APIRef("Media Capture and Streams")}}</div> - -<p>The <strong><code>Navigator.mediaDevices</code></strong> read-only property returns a {{domxref("MediaDevices")}} object, which provides access to connected media input devices like cameras and microphones, as well as screen sharing.</p> - -<h2 id="Syntax">Syntax</h2> - -<pre class="syntaxbox notranslate">var <em>mediaDevices</em> = navigator.mediaDevices; -</pre> - -<h3 id="Return_value">Return value</h3> - -<p>The {{domxref("MediaDevices")}} singleton object. Usually, you just use this object's members directly, such as by calling {{domxref("navigator.mediaDevices.getUserMedia()")}}.</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('Media Capture', '#mediadevices', 'NavigatorUserMedia.mediaDevices')}}</td> - <td>{{Spec2('Media Capture')}}</td> - <td>Initial definition.</td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - - - -<p>{{Compat("api.Navigator.mediaDevices")}}</p> - -<h2 id="See_also">See also</h2> - -<ul> - <li><a href="/en-US/docs/Web/API/Media_Streams_API">Media Capture and Streams API</a>: The entry point to the documentation about the entire media stream API.</li> - <li><a href="/en-US/docs/Web/API/WebRTC_API"><font><font>API de WebRTC</font></font></a><font><font> : documentación sobre la API de WebRTC, que está estrechamente relacionada.</font></font></li> -</ul> diff --git a/files/es/web/api/pushmanager/permissionstate/index.html b/files/es/web/api/pushmanager/permissionstate/index.html deleted file mode 100644 index f017b2da93..0000000000 --- a/files/es/web/api/pushmanager/permissionstate/index.html +++ /dev/null @@ -1,111 +0,0 @@ ---- -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/range/intersectsnode/index.html b/files/es/web/api/range/intersectsnode/index.html deleted file mode 100644 index 5ffd11b79e..0000000000 --- a/files/es/web/api/range/intersectsnode/index.html +++ /dev/null @@ -1,48 +0,0 @@ ---- -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/service_worker_api/using_service_workers/index.html b/files/es/web/api/service_worker_api/using_service_workers/index.html deleted file mode 100644 index d687cddd19..0000000000 --- a/files/es/web/api/service_worker_api/using_service_workers/index.html +++ /dev/null @@ -1,526 +0,0 @@ ---- -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/serviceworkerregistration/index.html b/files/es/web/api/serviceworkerregistration/index.html deleted file mode 100644 index 88f1c3da52..0000000000 --- a/files/es/web/api/serviceworkerregistration/index.html +++ /dev/null @@ -1,145 +0,0 @@ ---- -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/webgl_api/tutorial/animating_objects_with_webgl/index.html b/files/es/web/api/webgl_api/tutorial/animating_objects_with_webgl/index.html deleted file mode 100644 index ad9b98310a..0000000000 --- a/files/es/web/api/webgl_api/tutorial/animating_objects_with_webgl/index.html +++ /dev/null @@ -1,119 +0,0 @@ ---- -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/window/sidebar/index.html b/files/es/web/api/window/sidebar/index.html deleted file mode 100644 index 280b5dcce3..0000000000 --- a/files/es/web/api/window/sidebar/index.html +++ /dev/null @@ -1,56 +0,0 @@ ---- -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/windoweventhandlers/onunload/index.html b/files/es/web/api/windoweventhandlers/onunload/index.html deleted file mode 100644 index 111f87edf2..0000000000 --- a/files/es/web/api/windoweventhandlers/onunload/index.html +++ /dev/null @@ -1,46 +0,0 @@ ---- -title: window.onunload -slug: Web/API/WindowEventHandlers/onunload -translation_of: Web/API/WindowEventHandlers/onunload -original_slug: Web/API/GlobalEventHandlers/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/xmlhttprequesteventtarget/index.html b/files/es/web/api/xmlhttprequesteventtarget/index.html deleted file mode 100644 index f53063d82b..0000000000 --- a/files/es/web/api/xmlhttprequesteventtarget/index.html +++ /dev/null @@ -1,68 +0,0 @@ ---- -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 deleted file mode 100644 index c6d6f78974..0000000000 --- a/files/es/web/api/xmlhttprequesteventtarget/onload/index.html +++ /dev/null @@ -1,55 +0,0 @@ ---- -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> diff --git a/files/es/web/css/@viewport/index.html b/files/es/web/css/@viewport/index.html deleted file mode 100644 index 7e55775592..0000000000 --- a/files/es/web/css/@viewport/index.html +++ /dev/null @@ -1,159 +0,0 @@ ---- -title: '@viewport' -slug: Web/CSS/@viewport -tags: - - Adaptation - - At-rule - - CSS - - Device - - NeedsContent - - NeedsTranslation - - Reference - - TopicStub -translation_of: Web/CSS/@viewport ---- -<p>{{CSSRef}}</p> - -<h2 id="Summary">Summary</h2> - -<p>The<strong> <code>@viewport</code></strong> <a href="/en/CSS" title="CSS">CSS</a> <a href="/en/CSS/At-rule" title="en/CSS/At-rule">at-rule</a> contains a set of nested descriptors in a CSS block that is delimited by curly braces. These descriptors control viewport settings, primarily on mobile devices.</p> - -<h2 id="Syntax">Syntax</h2> - -<p>A <em>zoom factor</em> of <code>1.0</code> or <code>100%</code> corresponds to no zooming. Larger values zoom in. Smaller values zoom out.</p> - -<h3 id="Descriptors">Descriptors</h3> - -<p>Browsers are supposed to ignore unrecognized descriptors.</p> - -<dl> - <dt><a href="/en-US/docs/Web/CSS/@viewport/min-width"><code>min-width</code></a></dt> - <dd>Used in the determination of the width of the viewport when the document is first displayed.</dd> - <dt><a href="/en-US/docs/Web/CSS/@viewport/max-width"><code>max-width</code></a></dt> - <dd>Used in the determination of the width of the viewport when the document is first displayed.</dd> - <dt><a href="/en-US/docs/Web/CSS/@viewport/width"><code>width</code></a></dt> - <dd>A shorthand descriptor for setting both <code>min-width</code> and <code>max-width</code></dd> - <dt><a href="/en-US/docs/Web/CSS/@viewport/min-height"><code>min-height</code></a></dt> - <dd>Used in the determination of the height of the viewport when the document is first displayed.</dd> - <dt><a href="/en-US/docs/Web/CSS/@viewport/max-height"><code>max-height</code></a></dt> - <dd>Used in the determination of the height of the viewport when the document is first displayed.</dd> - <dt><a href="/en-US/docs/Web/CSS/@viewport/height"><code>height</code></a></dt> - <dd>A shorthand descriptor for setting both <code>min-height</code> and <code>max-height</code></dd> - <dt><a href="/en-US/docs/Web/CSS/@viewport/zoom"><code>zoom</code></a></dt> - <dd>Sets the initial zoom factor.</dd> - <dt><a href="/en-US/docs/Web/CSS/@viewport/min-zoom"><code>min-zoom</code></a></dt> - <dd>Sets the minimum zoom factor.</dd> - <dt><a href="/en-US/docs/Web/CSS/@viewport/max-zoom"><code>max-zoom</code></a></dt> - <dd>Sets the maximum zoom factor.</dd> - <dt><a href="/en-US/docs/Web/CSS/@viewport/user-zoom"><code>user-zoom</code></a></dt> - <dd>Controls whether or not the user should be able to change the zoom factor.</dd> - <dt><a href="/en-US/docs/Web/CSS/@viewport/orientation"><code>orientation</code></a></dt> - <dd>Controls the document's orientation.</dd> -</dl> - -<h3 id="Formal_syntax">Formal syntax</h3> - -{{csssyntax}} - -<h2 id="Examples">Examples</h2> - -<pre class="eval" style="font-size: 14px;">@viewport { - min-width: 640px; - max-width: 800px; -} -@viewport { - zoom: 0.75; - min-zoom: 0.5; - max-zoom: 0.9; -} -@viewport { - orientation: landscape; -}</pre> - -<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('CSS3 Device', '#the-atviewport-rule', '@viewport')}}</td> - <td>{{Spec2('CSS3 Device')}}</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>29 (behind a flag) [4]</td> - <td>{{CompatNo()}} [2]</td> - <td>10 {{property_prefix("-ms")}}</td> - <td>11.10<br> - Removed in 15<br> - Reintroduced behind a flag in 16</td> - <td>{{CompatNo}} [3]</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.4</td> - <td>29</td> - <td>{{CompatNo}} [2]</td> - <td>10{{property_prefix("-ms")}}[1]</td> - <td>11.10<br> - Removed in 15<br> - Reintroduced behind a flag in 16</td> - <td>{{CompatNo}} [3]</td> - </tr> - </tbody> -</table> -</div> - -<p>[1] There is a bug in IE Mobile 10 on older versions of Windows Phone 8, where <code>device-width</code>, when used within <code>@-ms-viewport</code>, evaluates to the screen width in physical pixels rather than normalized CSS pixels, which is wrong according to the specification. However, when used within a <code>viewport</code> {{HTMLElement("meta")}} tag, <code>device-width</code> evaluates correctly. According to Microsoft, this bug was fixed in <a href="http://blogs.windows.com/windows_phone/b/wpdev/archive/2013/10/14/introducing-windows-phone-preview-for-developers.aspx">Windows Phone 8 Update 3 (a.k.a. GDR3)</a>, although there are some reports that the <a href="http://www.nokia.com/us-en/windows-phone-black-update/">Lumia Black</a> GDR3 update did not fix the bug (at least on the Lumia 920). For more details and a workaround, <a href="http://timkadlec.com/2013/01/windows-phone-8-and-device-width/">see Tim Kadlec's blog post "Windows Phone 8 and Device-Width"</a>.</p> - -<p>[2]: See {{bug(747754, 'summary')}}</p> - -<p>[3]: See {{webkitbug(95959)}}</p> -<p>[4]: See <a href="https://bugs.chromium.org/p/chromium/issues/detail?id=235457">Chromium issue #235457: Enable @viewport on all platforms</a></p> -<h2 id="See_also">See also</h2> - -<ul> - <li>{{HTMLElement("meta")}}, specifically <code><meta name="viewport"></code></li> - <li><a href="/en-US/docs/Mobile/Viewport_meta_tag">Using the viewport meta tag to control layout on mobile browsers</a></li> -</ul> diff --git a/files/es/web/css/css_grid_layout/css_grid_layout_and_accessibility/index.html b/files/es/web/css/css_grid_layout/css_grid_layout_and_accessibility/index.html deleted file mode 100644 index 7339530ff1..0000000000 --- a/files/es/web/css/css_grid_layout/css_grid_layout_and_accessibility/index.html +++ /dev/null @@ -1,169 +0,0 @@ ---- -title: CSS Grid Layout y accesibilidad -slug: Web/CSS/CSS_Grid_Layout/CSS_Grid_Layout_and_Accessibility -translation_of: Web/CSS/CSS_Grid_Layout/CSS_Grid_Layout_and_Accessibility ---- -<p>Los que llevamos en esto del desarrollo web más años de los que queremos recordar podríamos considerar que CSS Grid es un poco como "maquetar con tablas". En los primeros tiempos del diseño web la manera de maquetar la página era usando tablas HTML y "troceando" los elementos dentro de las celdas de esas tablas para crear un diseño. This had some advantages over the “CSS Positioning” that came afterwards, in that we could take advantage of the alignment and full height columns offered by table display. The biggest downside however was that it tied our design to the mark-up, often creating accessibility issues as it did so. In order to lay the design out in the table we often broke up the content in ways that made no sense at all when read out by a screen reader for example.</p> - -<p>In moving to CSS we often spoke about CSS for layout enabling a separation of content and markup and presentation. The ultimate aim being that we could create a semantic and well structured document, then apply CSS to create the layout we desired. Sites such as the <a href="http://www.csszengarden.com/">CSS Zen Garden</a> showcased this ability. The CSS Zen Garden challenged us to take identical markup and create a unique design using CSS.</p> - -<p><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout">CSS Grid Layout</a> does not have the same issues that tables did, our grid structure is defined in CSS rather than in the mark-up. If we need to add an element we can use something with no semantic meaning. On paper grid helps us properly fulfill that promise of content separated from mark-up, however is it possible to go too far with this idea? Is it possible that we could <em>create</em> an accessibility issue through our use of grids?</p> - -<h2 id="Re-ordering_content_in_CSS_Grid_Layout">Re-ordering content in CSS Grid Layout</h2> - -<p>We’ve already seen in these guides that grid gives us power to re-order the content of our page in various ways. We can use the {{cssxref("order")}} property, which will change how items auto-place. We can use <code>grid-auto-flow: dense</code> which will take items visually out of DOM order. We can also position items using line-based placement of grid template areas, without considering their location in the source.</p> - -<p>The <a href="https://drafts.csswg.org/css-grid/#order-accessibility">specification</a> includes a section that covers Reordering and Accessibility. In the introduction to that section are details of what the specification expects browsers to do when the content is visually reordered using Grid Layout.</p> - -<blockquote> -<p>Grid layout gives authors great powers of rearrangement over the document. However, these are not a substitute for correct ordering of the document source. The order property and grid placement do not affect ordering in non-visual media (such as speech). Likewise, rearranging grid items visually does not affect the default traversal order of sequential navigation modes (such as cycling through links, see e.g. <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex">tabindex</a> HTML5).</p> -</blockquote> - -<p>If you reorder things visually using grid layout, this will not change how the items are ordered if the content is being read out by a screen reader, or other text to speech user agent. In addition, the reordering will not change tab order. This means that someone navigating using the keyboard could be tabbing through links on your site and suddenly find themselves jumping from the top to the bottom of the document due to a reordered item being next in line.</p> - -<p>The specification warns authors (the CSSWG term for web developers) not to do this reordering.</p> - -<blockquote> -<p>Authors must use order and the grid-placement properties only for visual, not logical, reordering of content. Style sheets that use these features to perform logical reordering are non-conforming.</p> -</blockquote> - -<p>What does this mean for designing with grid layout in practice?</p> - -<h3 id="Visual_not_logical_re-ordering">Visual not logical re-ordering</h3> - -<p>Any time you reorder things with grid layout – or with flexbox – you only perform <em>visual reordering</em>. The underlying source is what controls things like text to speech, and the tab order of the document. You can see how this works with a very simple example.</p> - -<p>In this example I have used grid to lay out a set of boxes that contain links. I have used the line-based placement properties to position box 1 on the second row of the grid. Visually it now appears as the fourth item in the list. However, if I tab from link to link the tab order still begins with box 1, as it comes first in the source.</p> - -<div id="accessibility_1"> -<div class="hidden"> -<pre class="brush: css">* {box-sizing: border-box;} - -.wrapper { - border: 2px solid #f76707; - border-radius: 5px; - background-color: #fff4e6; -} - -.wrapper > div { - border: 2px solid #ffa94d; - border-radius: 5px; - background-color: #ffd8a8; - padding: 1em; - color: #d9480f; -} -</pre> -</div> - -<pre class="brush: css">.wrapper { - display: grid; - grid-template-columns: repeat(3, 1fr); - grid-auto-rows: 100px; -} - -.box1 { - grid-column: 1; - grid-row: 2; -} -</pre> - -<pre class="brush: html"><div class="wrapper"> - <div class="box box1"><a href="">One</a></div> - <div class="box box2"><a href="">Two</a></div> - <div class="box box3"><a href="">Three</a></div> - <div class="box box4"><a href="">Four</a></div> - <div class="box box5"><a href="">Five</a></div> -</div> -</pre> - -<p>{{ EmbedLiveSample('accessibility_1', '500', '330') }}</p> -</div> - -<p>The specification says that in this scenario, if box 1 really makes sense logically in that position, we should go back to our source and make the change there rather than reordering using grid layout. This is what is meant by visual versus logical reordering, logical ordering is important for the meaning and structure of our document, and we should make sure that we preserve that structure.</p> - -<h2 id="How_should_we_approach_accessibility_for_grid_layout">How should we approach accessibility for grid layout?</h2> - -<p>From the specification we know that we need to ensure our document maintains the logical order of our content. How should we approach our development to make sure that we maintain accessibility for the different users and the ways that they interact with our pages?</p> - -<dl> - <dt>Start with a structured and accessible document</dt> - <dd>A grid layout should mean we do not need to change our document source in order to get the layout that we want. Therefore the starting point of your page should be a well structured and accessible source document. As is noted in the CSS Grid Layout specification, this is quite often going to give you a good structure for <em>your smallest screen devices too</em>. If a user is scrolling through a long document on mobile, the priorities for that user quite often map to what should be a priority in the source.</dd> - <dt>Create a responsive, and responsible grid</dt> - <dd>With a solid document you can begin to add your layout, it is likely you will be using <a href="/en-US/docs/Web/CSS/Media_Queries">media queries</a> to create additional columns and make changes for different screen sizes and devices. Grid can be really very useful here, elements deprioritized in the mobile source order can be moved into a sidebar in a desktop layout, for example. The key here is to keep testing, a very simple test is to <em>tab around the document</em>. Does that order still make sense? Check that you do not end up leaping from the top to the bottom of the layout in a peculiar way. If so that would be a sign that you need to address something about the layout.</dd> - <dt>Returning to the source</dt> - <dd>If at any time in the design process you find yourself using grid to relocate the position of an element, consider whether you should return to your document and make a change to the logical order too. The nice thing about using CSS Grid Layout is that you should be able to move an item in the source to match the logical order, without needing to make big changes to your layout. This is a huge improvement over a {{cssxref("float")}}-based layout for example, where document source matters a lot in order to get layouts at different breakpoints. However the onus is on us as developers to remember to go back to our source and update it to maintain logical order.</dd> -</dl> - -<h2 id="Grid_and_the_danger_of_markup_flattening">Grid and the danger of markup flattening</h2> - -<p>Another issue to be aware of in CSS Grid Layout and to a lesser extent in CSS Flexbox, is the temptation to <em>flatten</em> markup. As we have discovered, for an item to become a grid item it needs to be a direct child of the grid container. Therefore, where you have a {{HTMLElement("ul")}} element inside a grid container, <em>that</em> <code>ul</code> becomes a grid item – the child {{HTMLElement("li")}} elements do not.</p> - -<p>If the <code>subgrid</code> value of {{cssxref("display")}} becomes implemented, it would be possible to make these children of a grid item participate in the overall grid layout by declaring the <code>ul</code> element a <em>subgrid</em>. Currently the only way to do this is to use <code>display: contents</code> to cause the box generated by the <code>ul</code> to disappear from the DOM. For more information about this interaction see the guide on the <a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Relationship_of_Grid_Layout">Relationship of Grid Layout to other layout methods</a> and the section on <code><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout/Relationship_of_Grid_Layout#Grid_and_display_contents">display: contents</a></code>.</p> - -<p>Given that interoperable support for <code>display: contents</code> is limited and we do not yet have subgrids, there is a definite temptation when developing a site using CSS Grid Layout to flatten out the markup, to remove semantic elements in order to make it simpler to create a layout. An example would be where some content was semantically marked up as a list but you decide to use a set of {{HTMLElement("div")}} elements instead as then you can have the element to be a direct child of a container set to <code>display: grid</code>. Be aware of this temptation and find ways to develop your design without stripping out the markup. Starting out with a well-structured document is a very good way to avoid the problem, as you will be aware that you are removing semantic elements in order to make the layout work if you actually have to go into the document and do so!</p> - -<h2 id="Further_reading">Further reading</h2> - -<p>There is not a lot of existing material regarding accessibility and CSS Grid Layout. Many of the issues are similar to those raised regarding CSS Flexbox, which also gives methods of reordering content with {{cssxref("flex-direction")}} and the {{cssxref("order")}} property.</p> - -<p>The concept of visual display following document source order is detailed in the <em>WCAG Techniques for Success Criteria – <a href="https://www.w3.org/TR/WCAG20-TECHS/C27.html">Technique C27</a></em>.</p> - -<p>As a way to start thinking about these issues, as you use CSS Grid Layout I would suggest reading <em><a href="http://tink.uk/flexbox-the-keyboard-navigation-disconnect/">Flexbox & the Keyboard Navigation Disconnect</a></em> from Léonie Watson. Also <a href="https://www.youtube.com/watch?v=spxT2CmHoPk">the video of Léonie’s presentation from ffconf</a> is helpful to understand more about how screen readers work with the visual representation of things in CSS. Adrian Roselli has also posted regarding <a href="http://adrianroselli.com/2015/10/html-source-order-vs-css-display-order.html">tab order in various browsers</a> – although this was prior to grid support being fully implemented in Firefox.</p> - -<section class="Quick_links" id="Quick_Links"> -<ol> - <li><a href="/en-US/docs/Web/CSS"><strong>CSS</strong></a></li> - <li><a href="/en-US/docs/Web/CSS/Reference"><strong>CSS Reference</strong></a></li> - <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout">CSS Grid Layout</a></li> - <li data-default-state="open"><a href="#"><strong>Guides</strong></a> - <ol> - <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Basic_Concepts_of_Grid_Layout">Basics concepts of grid layout</a></li> - <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Relationship_of_Grid_Layout">Relationship to other layout methods</a></li> - <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Line-based_Placement_with_CSS_Grid">Line-based placement</a></li> - <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Grid_Template_Areas">Grid template areas</a></li> - <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Layout_using_Named_Grid_Lines">Layout using named grid lines</a></li> - <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Auto-placement_in_CSS_Grid_Layout">Auto-placement in grid layout</a></li> - <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Box_Alignment_in_CSS_Grid_Layout">Box alignment in grid layout</a></li> - <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/CSS_Grid,_Logical_Values_and_Writing_Modes">Grids, logical values and writing modes</a></li> - <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/CSS_Grid_Layout_and_Accessibility">CSS Grid Layout and Accessibility</a></li> - <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/CSS_Grid_and_Progressive_Enhancement">CSS Grid Layout and Progressive Enhancement</a></li> - <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Realizing_common_layouts_using_CSS_Grid_Layout">Realizing common layouts using grids</a></li> - </ol> - </li> - <li data-default-state="open"><a href="#"><strong>Properties</strong></a> - <ol> - <li><a href="/en-US/docs/Web/CSS/grid">grid</a></li> - <li><a href="/en-US/docs/Web/CSS/grid-area">grid-area</a></li> - <li><a href="/en-US/docs/Web/CSS/grid-auto-columns">grid-auto-columns</a></li> - <li><a href="/en-US/docs/Web/CSS/grid-auto-flow">grid-auto-flow</a></li> - <li><a href="/en-US/docs/Web/CSS/grid-auto-rows">grid-auto-rows</a></li> - <li><a href="/en-US/docs/Web/CSS/grid-column">grid-column</a></li> - <li><a href="/en-US/docs/Web/CSS/grid-column-end">grid-column-end</a></li> - <li><a href="/en-US/docs/Web/CSS/grid-column-gap">grid-column-gap</a></li> - <li><a href="/en-US/docs/Web/CSS/grid-column-start">grid-column-start</a></li> - <li><a href="/en-US/docs/Web/CSS/grid-gap">grid-gap</a></li> - <li><a href="/en-US/docs/Web/CSS/grid-row">grid-row</a></li> - <li><a href="/en-US/docs/Web/CSS/grid-row-end">grid-row-end</a></li> - <li><a href="/en-US/docs/Web/CSS/grid-row-gap">grid-row-gap</a></li> - <li><a href="/en-US/docs/Web/CSS/grid-row-start">grid-row-start</a></li> - <li><a href="/en-US/docs/Web/CSS/grid-template">grid-template</a></li> - <li><a href="/en-US/docs/Web/CSS/grid-template-areas">grid-template-areas</a></li> - <li><a href="/en-US/docs/Web/CSS/grid-template-columns">grid-template-columns</a></li> - <li><a href="/en-US/docs/Web/CSS/grid-template-rows">grid-template-rows</a></li> - </ol> - </li> - <li data-default-state="open"><a href="#"><strong>Glossary</strong></a> - <ol> - <li><a href="/en-US/docs/Glossary/Grid">Grid</a></li> - <li><a href="/en-US/docs/Glossary/Grid_lines">Grid lines</a></li> - <li><a href="/en-US/docs/Glossary/Grid_tracks">Grid tracks</a></li> - <li><a href="/en-US/docs/Glossary/Grid_cell">Grid cell</a></li> - <li><a href="/en-US/docs/Glossary/Grid_areas">Grid areas</a></li> - <li><a href="/en-US/docs/Glossary/Gutters">Gutters</a></li> - <li><a href="/en-US/docs/Glossary/Grid_Axis">Grid Axis</a></li> - <li><a href="/en-US/docs/Glossary/Grid_rows">Grid row</a></li> - <li><a href="/en-US/docs/Glossary/Grid_column">Grid column</a></li> - </ol> - </li> -</ol> -</section> diff --git a/files/es/web/css/max-width/index.html b/files/es/web/css/max-width/index.html deleted file mode 100644 index 3b3f0a21ff..0000000000 --- a/files/es/web/css/max-width/index.html +++ /dev/null @@ -1,158 +0,0 @@ ---- -title: max-width -slug: Web/CSS/max-width -tags: - - Referencia_CSS -translation_of: Web/CSS/max-width ---- -<div>{{CSSRef}}</div> - -<p>The <strong><code>max-width</code></strong> <a href="/en-US/docs/CSS">CSS</a> property sets the maximum width of an element. It prevents the <a href="/en-US/docs/Web/CSS/used_value">used value</a> of the {{ Cssxref("width") }} property from becoming larger than the value specified by <code>max-width</code>.</p> - -<pre class="brush:css no-line-numbers">/* <length> value */ -max-width: 3.5em; - -/* <percentage> value */ -max-width: 75%; - -/* Keyword values */ -max-width: none; -max-width: max-content; -max-width: min-content; -max-width: fit-content; -max-width: fill-available; - -/* Global values */ -max-width: inherit; -max-width: initial; -max-width: unset; -</pre> - -<p>{{ Cssxref("max-width") }} overrides {{cssxref("width")}}, but {{ Cssxref("min-width") }} overrides {{ Cssxref("max-width") }}.</p> - -<p>{{cssinfo}}</p> - -<h2 id="Syntax">Syntax</h2> - -<h3 id="Values">Values</h3> - -<dl> - <dt>{{cssxref("<length>")}}</dt> - <dd>The maximum width, expressed as a {{cssxref("<length>")}}.</dd> - <dt>{{cssxref("<percentage>")}}</dt> - <dd>The maximum width, expressed as a {{cssxref("<percentage>")}} of the containing block's width.</dd> -</dl> - -<h4 id="Keyword_values">Keyword values</h4> - -<dl> - <dt><code>none</code></dt> - <dd>The width has no maximum value.</dd> - <dt><code>max-content</code>{{experimental_inline()}}</dt> - <dd>The intrinsic preferred width.</dd> - <dt><code>min-content</code>{{experimental_inline()}}</dt> - <dd>The intrinsic minimum width.</dd> - <dt><code>fill-available</code>{{experimental_inline()}}</dt> - <dd>The containing block's width minus the horizontal margin, border, and padding. (Note that some browsers implement an ancient name for this keyword, <code>available</code>.)</dd> - <dt><code>fit-content</code>{{experimental_inline()}}</dt> - <dd>The same as <code>max-content.</code></dd> -</dl> - -<h3 id="Formal_syntax">Formal syntax</h3> - -{{csssyntax}} - -<h2 id="Examples">Examples</h2> - -<p>In this example, the "child" will be either 150 pixels wide or the width of the "parent," whichever is smaller:</p> - -<div id="basic-max-width-demo"> -<pre class="brush: html"><div id="parent"> - <div id="child"> - Fusce pulvinar vestibulum eros, sed luctus ex lobortis quis. - </div> -</div> -</pre> - -<pre class="brush: css">#parent { - background: lightblue; - width: 300px; -} - -#child { - background: gold; - width: 100%; - max-width: 150px; -} -</pre> -</div> - -<p>{{EmbedLiveSample("basic-max-width-demo", 350, 100)}}</p> - -<p>The <code>fit-content</code> value can be used to set the width of an element based on the intrinsic size required by its content:</p> - -<div id="fit-content-demo"> -<pre class="brush: html" style="display: none;"><div id="parent"> - <div id="child"> - Child Text - </div> -</div> -</pre> - -<pre class="brush: css">#parent { - background: lightblue; - width: 300px; -} - -#child { - background: gold; - width: 100%; - max-width: -moz-fit-content; - max-width: -webkit-fit-content; -} -</pre> -</div> - -<p>{{EmbedLiveSample("fit-content-demo", 400, 100)}}</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('CSS3 Sizing', '#width-height-keywords', 'max-width') }}</td> - <td>{{ Spec2('CSS3 Sizing') }}</td> - <td>Adds the <code>max-content</code>, <code>min-content</code>, <code>fit-content</code>, and <code>fill-available</code> keywords.<em> </em>(Both CSS3 Box and CSS3 Writing Modes drafts used to define these keywords, but are superseded by this spec.<em>)</em></td> - </tr> - <tr> - <td>{{ SpecName('CSS3 Transitions', '#animatable-css', 'max-width') }}</td> - <td>{{ Spec2('CSS3 Transitions') }}</td> - <td>Defines <code>max-width</code> as animatable.</td> - </tr> - <tr> - <td>{{ SpecName('CSS2.1', 'visudet.html#min-max-widths', 'max-width') }}</td> - <td>{{ Spec2('CSS2.1') }}</td> - <td>Initial definition.</td> - </tr> - </tbody> -</table> - -<h2 id="Browser_Compatibility" name="Browser_Compatibility">Browser compatibility</h2> - - - -<p>{{Compat("css.properties.max-width")}}</p> - -<h2 id="See_also">See also</h2> - -<ul> - <li>{{ Cssxref("width") }}, {{ Cssxref("min-width") }}, {{ Cssxref("max-height") }}</li> - <li><a href="/en/CSS/box_model" title="en/CSS/box_model">The box model</a>, {{ Cssxref("box-sizing") }}</li> -</ul> diff --git a/files/es/web/http/cors/errors/corsnotsupportingcredentials/index.html b/files/es/web/http/cors/errors/corsnotsupportingcredentials/index.html deleted file mode 100644 index b27a103689..0000000000 --- a/files/es/web/http/cors/errors/corsnotsupportingcredentials/index.html +++ /dev/null @@ -1,34 +0,0 @@ ---- -title: >- - Reason: Credential is not supported if the CORS header - ‘Access-Control-Allow-Origin’ is ‘*’ -slug: Web/HTTP/CORS/Errors/CORSNotSupportingCredentials -translation_of: Web/HTTP/CORS/Errors/CORSNotSupportingCredentials ---- -<div>{{HTTPSidebar}}</div> - -<h2 id="Reason">Reason</h2> - -<pre class="syntaxbox">Reason: Credential is not supported if the CORS header ‘Access-Control-Allow-Origin’ is ‘*’</pre> - -<h2 id="What_went_wrong">What went wrong?</h2> - -<p>The {{Glossary("CORS")}} request was attempted with the credentials flag set, but the server is configured using the wildcard (<code>"*"</code>) as the value of {{HTTPHeader("Access-Control-Allow-Origin")}}, which doesn't allow the use of credentials.</p> - -<p>To correct this problem on the client side, simply ensure that the credentials flag's value is <code>false</code> when issuing your CORS request.</p> - -<ul> - <li>If the request is being issued using {{domxref("XMLHttpRequest")}}, make sure you're not setting {{domxref("XMLHttpRequest.withCredentials", "withCredentials")}} to <code>true</code>.</li> - <li>If using <a href="/en-US/docs/Web/API/Server-sent_events">Server-sent events</a>, make sure {{domxref("EventSource.withCredentials")}} is <code>false</code> (it's the default value).</li> - <li>If using the <a href="/en-US/docs/Web/API/Fetch_API">Fetch API</a>, make sure {{domxref("Request.credentials")}} is <code>"omit"</code>.</li> -</ul> - -<p>If, instead, you need to adjust the server's behavior, you'll need to change the value of <code>Access-Control-Allow-Origin</code> to grant access to the origin from which the client is loaded.</p> - -<h2 id="See_also">See also</h2> - -<ul> - <li><a href="/en-US/docs/Web/HTTP/CORS/Errors">CORS errors</a></li> - <li>Glossary: {{Glossary("CORS")}}</li> - <li><a href="/en-US/docs/Web/HTTP/CORS">CORS introduction</a></li> -</ul> diff --git a/files/es/web/http/headers/accept-charset/index.html b/files/es/web/http/headers/accept-charset/index.html deleted file mode 100644 index 26433c22db..0000000000 --- a/files/es/web/http/headers/accept-charset/index.html +++ /dev/null @@ -1,85 +0,0 @@ ---- -title: Accept-Charset -slug: Web/HTTP/Headers/Accept-Charset -tags: - - Negociación de Contenido -translation_of: Web/HTTP/Headers/Accept-Charset ---- -<div>{{HTTPSidebar}}</div> - -<p>The <strong><code>Accept-Charset</code></strong> request HTTP header advertises which character set the client is able to understand. Using <a href="/en-US/docs/Web/HTTP/Content_negotiation">content negotiation</a>, the server then selects one of the proposals, uses it and informs the client of its choice within the {{HTTPHeader("Content-Type")}} response header. Browsers usually don't set this header as the default value for each content type is usually correct and transmitting it would allow easier fingerprinting.</p> - -<p>If the server cannot serve any matching character set, it can theoretically send back a {{HTTPStatus("406")}} (Not Acceptable) error code. But, for a better user experience, this is rarely done and the more common way is to ignore the <code>Accept-Charset</code> header in this case.</p> - -<div class="note"> -<p>In early versions of HTTP/1.1, a default charset (<code>ISO-8859-1</code>) was defined. This is no more the case and now each content type may have its own default.</p> -</div> - -<table class="properties"> - <tbody> - <tr> - <th scope="row">Header type</th> - <td>{{Glossary("Request header")}}</td> - </tr> - <tr> - <th scope="row">{{Glossary("Forbidden header name")}}</th> - <td>yes</td> - </tr> - </tbody> -</table> - -<h2 id="Syntax">Syntax</h2> - -<pre class="syntaxbox">Accept-Charset: <charset> - -// Multiple types, weighted with the {{glossary("quality values", "quality value")}} syntax: -Accept-Charset: utf-8, iso-8859-1;q=0.5</pre> - -<h2 id="Directives">Directives</h2> - -<dl> - <dt><code><charset></code></dt> - <dd>Un conjunto de caracteres como <code>utf-8</code> o <code>iso-8859-15.</code></dd> - <dt><code>*</code></dt> - <dd>Any charset not mentioned elsewhere in the header; <code>'*'</code> being used as a wildcard.</dd> - <dt><code>;q=</code> (q-factor weighting)</dt> - <dd>Any value is placed in an order of preference expressed using a relative <a href="/en-US/docs/Glossary/Quality_values">quality value</a> called the <em>weight</em>.</dd> -</dl> - -<h2 id="Examples">Examples</h2> - -<pre>Accept-Charset: iso-8859-1 - -Accept-Charset: utf-8, iso-8859-1;q=0.5 - -Accept-Charset: utf-8, iso-8859-1;q=0.5, *;q=0.1 -</pre> - -<h2 id="Especificaciones">Especificaciones</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Especificación</th> - <th scope="col">Título</th> - </tr> - <tr> - <td>{{RFC("7231", "Accept-Charset", "5.3.3")}}</td> - <td>Hypertext Transfer Protocol (HTTP/1.1): Semantics and Context</td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilidad_del_navegador">Compatibilidad del navegador</h2> - - - -<p>{{Compat("http.headers.Accept-Charset")}}</p> - -<h2 id="También_puedes_revisar">También puedes revisar:</h2> - -<ul> - <li>HTTP <a href="/en-US/docs/Web/HTTP/Content_negotiation">content negotiation</a></li> - <li>Encabezados conlos resultados de la negociación de contenido: {{HTTPHeader("Content-Type")}}</li> - <li>Otros encabezados similares: {{HTTPHeader("TE")}}, {{HTTPHeader("Accept-Encoding")}}, {{HTTPHeader("Accept-Language")}}, {{HTTPHeader("Accept")}}</li> -</ul> diff --git a/files/es/web/http/status/301/index.html b/files/es/web/http/status/301/index.html deleted file mode 100644 index 496fb038f3..0000000000 --- a/files/es/web/http/status/301/index.html +++ /dev/null @@ -1,54 +0,0 @@ ---- -title: 301 Movido Permanentemente -slug: Web/HTTP/Status/301 -translation_of: Web/HTTP/Status/301 ---- -<div>{{HTTPSidebar}}</div> - -<p>The HyperText Transfer Protocol (HTTP) <code><strong>301 Moved Permanently</strong></code> redirect status response code indicates that the resource requested has been definitively moved to the URL given by the {{HTTPHeader("Location")}} headers. A browser redirects to this page and search engines update their links to the resource (in 'SEO-speak', it is said that the 'link-juice' is sent to the new URL).</p> - -<p>Even if the specification requires the method (and the body) not to be altered when the redirection is performed, not all user-agents align with it - you can still find this type of bugged software out there. It is therefore recommended to use the <code>301</code> code only as a response for {{HTTPMethod("GET")}} or {{HTTPMethod("HEAD")}} methods and to use the {{HTTPStatus("308", "308 Permanent Redirect")}} for {{HTTPMethod("POST")}} methods instead, as the method change is explicitly prohibited with this status.</p> - -<h2 id="Status">Status</h2> - -<pre class="syntaxbox">301 Moved Permanently</pre> - -<h2 id="Example">Example</h2> - -<h3 id="Client_request">Client request</h3> - -<pre>GET /index.php HTTP/1.1 -Host: www.example.org</pre> - -<h3 id="Server_response">Server response</h3> - -<pre>HTTP/1.1 301 Moved Permanently -Location: http://www.example.org/index.asp</pre> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Title</th> - </tr> - <tr> - <td>{{RFC("7231", "301 Moved Permanently" , "6.4.2")}}</td> - <td>Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content</td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - - - -<p>{{Compat("http.status.301")}}</p> - -<h2 id="See_also">See also</h2> - -<ul> - <li>{{HTTPStatus("308", "308 Permanent Redirect")}}</li> - <li>{{HTTPStatus("302", "302 Found")}}, the temporary redirect</li> -</ul> diff --git a/files/es/web/javascript/reference/deprecated_and_obsolete_features/the_legacy_iterator_protocol/index.html b/files/es/web/javascript/reference/deprecated_and_obsolete_features/the_legacy_iterator_protocol/index.html deleted file mode 100644 index 007decfe89..0000000000 --- a/files/es/web/javascript/reference/deprecated_and_obsolete_features/the_legacy_iterator_protocol/index.html +++ /dev/null @@ -1,74 +0,0 @@ ---- -title: The legacy Iterator protocol -slug: >- - Web/JavaScript/Reference/Deprecated_and_obsolete_features/The_legacy_Iterator_protocol -translation_of: >- - Web/JavaScript/Reference/Deprecated_and_obsolete_features/The_legacy_Iterator_protocol -original_slug: >- - Web/JavaScript/Referencia/Características_Desaprobadas/The_legacy_Iterator_protocol ---- -<div>{{jsSidebar("More")}}</div> - -<div class="warning"><strong>Non-standard.</strong> The legacy iterator protocol is a SpiderMonkey-specific feature, and will be removed at some point. For future-facing usages, consider using <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...of" title="/en-US/docs/Web/JavaScript/Reference/Statements/for...of">for..of</a> loops and the <a href="/en-US/docs/Web/JavaScript/Guide/The_Iterator_protocol">iterator protocol</a>.</div> - -<h2 id="The_deprecated_Firefox-only_iterator_protocol">The deprecated Firefox-only iterator protocol</h2> - -<p>Firefox, prior to version 26 implemented another iterator protocol that is similar to the standard <a href="/en-US/docs/Web/JavaScript/Guide/The_Iterator_protocol">ES6 Iterator protocol</a>.</p> - -<p>An object is an legacy iterator when it implements a <code>next()</code> method with the following semantics, and throws {{jsxref("Global_Objects/StopIteration", "StopIteration")}} at the end of iteration.</p> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Property</th> - <th scope="col">Value</th> - </tr> - <tr> - <td><code>next</code></td> - <td>A zero arguments function that returns an value.</td> - </tr> - </tbody> -</table> - -<h3 id="Difference_between_legacy_and_ES6_iterator_protocols">Difference between legacy and ES6 iterator protocols</h3> - -<ul> - <li>The value was returned directly as a return value of calls to <code>next</code>, instead of the <code>value</code> property of a placeholder object</li> - <li>Iteration termination was expressed by throwing a {{jsxref("Global_Objects/StopIteration", "StopIteration")}} object.</li> -</ul> - -<h3 id="Simple_example_with_the_old_protocol">Simple example with the old protocol</h3> - -<pre class="brush: js">function makeIterator(array){ - var nextIndex = 0; - - return { - next: function(){ - if(nextIndex < array.length){ - return array[nextIndex++]; - else - throw new StopIteration(); - } - } -} - -var it = makeIterator(['yo', 'ya']); - -console.log(it.next()); // 'yo' -console.log(it.next()); // 'ya' -try{ - console.log(it.next()); -} -catch(e){ - if(e instanceof StopIteration){ - // iteration over - } -} -</pre> - -<h2 id="Mira_también">Mira también</h2> - -<ul> - <li><a href="/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators">Iteradores y generadores</a></li> - <li>Más More <a href="/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features">características obsoletas</a></li> -</ul> diff --git a/files/es/web/javascript/reference/errors/precision_range/index.html b/files/es/web/javascript/reference/errors/precision_range/index.html deleted file mode 100644 index 22c37598ff..0000000000 --- a/files/es/web/javascript/reference/errors/precision_range/index.html +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: 'RangeError: precision is out of range' -slug: Web/JavaScript/Reference/Errors/Precision_range -translation_of: Web/JavaScript/Reference/Errors/Precision_range ---- -<div>{{jsSidebar("Errors")}}</div> - -<p>The JavaScript exception "precision is out of range" occurs when a number that's outside of the range of 0 and 20 (or 21) was passed into <code>toFixed</code> or <code>toPrecision</code>.</p> - -<h2 id="Message">Message</h2> - -<pre class="syntaxbox notranslate">RangeError: The number of fractional digits is out of range (Edge) -RangeError: The precision is out of range (Edge) -RangeError: precision {0} out of range (Firefox) -RangeError: toExponential() argument must be between 0 and 20 (Chrome) -RangeError: toFixed() digits argument must be between 0 and 20 (Chrome) -RangeError: toPrecision() argument must be between 1 and 21 (Chrome) -</pre> - -<h2 id="Error_type">Error type</h2> - -<p>{{jsxref("RangeError")}}</p> - -<h2 id="Que_salió_mal">Que salió mal?</h2> - -<p>Fué un argumento preciso fuera de rango en uno de estos metodos:</p> - -<ul> - <li>{{jsxref("Number.prototype.toExponential()")}}</li> - <li>{{jsxref("Number.prototype.toFixed()")}}</li> - <li>{{jsxref("Number.prototype.toPrecision()")}}</li> -</ul> - -<p>El rango permitido para estos metodos usualmente esta entre 0 o 20 (o 21). De todas formas la <span><span>especificación</span></span> ECMAScript permite extender este rango.</p> - -<table class="standard-table"> - <thead> - <tr> - <th scope="col">Method</th> - <th scope="col">Firefox (SpiderMonkey)</th> - <th scope="col">Chrome, Opera (V8)</th> - </tr> - </thead> - <tbody> - <tr> - <td>{{jsxref("Number.prototype.toExponential()")}}</td> - <td>0 to 100</td> - <td>0 to 20</td> - </tr> - <tr> - <td>{{jsxref("Number.prototype.toFixed()")}}</td> - <td>-20 to 100</td> - <td>0 to 20</td> - </tr> - <tr> - <td>{{jsxref("Number.prototype.toPrecision()")}}</td> - <td>1 to 100</td> - <td>1 to 21</td> - </tr> - </tbody> -</table> - -<h2 id="Examples">Examples</h2> - -<h3 id="Casos_no_validos">Casos no validos</h3> - -<pre class="brush: js example-bad notranslate">77.1234.toExponential(-1); // RangeError -77.1234.toExponential(101); // RangeError - -2.34.toFixed(-100); // RangeError -2.34.toFixed(1001); // RangeError - -1234.5.toPrecision(-1); // RangeError -1234.5.toPrecision(101); // RangeError -</pre> - -<h3 id="Casos_validos">Casos validos</h3> - -<pre class="brush: js example-good notranslate">77.1234.toExponential(4); // 7.7123e+1 -77.1234.toExponential(2); // 7.71e+1 - -2.34.toFixed(1); // 2.3 -2.35.toFixed(1); // 2.4 (note that it rounds up in this case) - -5.123456.toPrecision(5); // 5.1235 -5.123456.toPrecision(2); // 5.1 -5.123456.toPrecision(1); // 5 -</pre> - -<h2 id="También_te_puede_interesar">También te puede interesar:</h2> - -<ul> - <li>{{jsxref("Number.prototype.toExponential()")}}</li> - <li>{{jsxref("Number.prototype.toFixed()")}}</li> - <li>{{jsxref("Number.prototype.toPrecision()")}}</li> -</ul> diff --git a/files/es/web/javascript/reference/global_objects/date/getutchours/index.html b/files/es/web/javascript/reference/global_objects/date/getutchours/index.html deleted file mode 100644 index 525a0a2730..0000000000 --- a/files/es/web/javascript/reference/global_objects/date/getutchours/index.html +++ /dev/null @@ -1,118 +0,0 @@ ---- -title: Date.prototype.getUTCHours() -slug: Web/JavaScript/Reference/Global_Objects/Date/getUTCHours -translation_of: Web/JavaScript/Reference/Global_Objects/Date/getUTCHours -original_slug: Web/JavaScript/Referencia/Objetos_globales/Date/getUTCHours ---- -<div>{{JSRef}}</div> - -<p>El método <strong><code>getUTCHours()</code></strong> retorna las horas especificadas en la fecha deacuerdo al horario universal.</p> - -<h2 id="Syntax">Syntax</h2> - -<pre class="syntaxbox"><code><var>dateObj</var>.getUTCHours()</code></pre> - -<h3 id="Return_value">Return value</h3> - -<p>An integer number, between 0 and 23, representing the hours in the given date according to universal time.</p> - -<h2 id="Examples">Examples</h2> - -<h3 id="Using_getUTCHours()">Using <code>getUTCHours()</code></h3> - -<p>The following example assigns the hours portion of the current time to the variable <code>hours</code>.</p> - -<pre class="brush: js">var today = new Date(); -var hours = today.getUTCHours(); -</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('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Initial definition. Implemented in JavaScript 1.3.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.9.5.19', 'Date.prototype.getUTCHours')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-date.prototype.getutchours', 'Date.prototype.getUTCHours')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-date.prototype.getutchours', 'Date.prototype.getUTCHours')}}</td> - <td>{{Spec2('ESDraft')}}</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>{{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>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="See_also">See also</h2> - -<ul> - <li>{{jsxref("Date.prototype.getHours()")}}</li> - <li>{{jsxref("Date.prototype.setUTCHours()")}}</li> -</ul> diff --git a/files/es/web/javascript/reference/global_objects/math/fround/index.html b/files/es/web/javascript/reference/global_objects/math/fround/index.html deleted file mode 100644 index ff06c8c12c..0000000000 --- a/files/es/web/javascript/reference/global_objects/math/fround/index.html +++ /dev/null @@ -1,198 +0,0 @@ ---- -title: Math.fround() -slug: Web/JavaScript/Reference/Global_Objects/Math/fround -tags: - - JavaScript - - Math - - Referencia - - metodo -translation_of: Web/JavaScript/Reference/Global_Objects/Math/fround -original_slug: Web/JavaScript/Referencia/Objetos_globales/Math/fround ---- -<div>{{JSRef}}</div> - -<p class="seoSummary">The <strong><code>Math.fround()</code></strong> function returns the nearest <a class="external" href="https://en.wikipedia.org/wiki/Single-precision_floating-point_format" title="link to the wikipedia page on single-precision floating-point format">32-bit single precision</a> float representation of a {{jsxref("Number")}}.</p> - -<div>{{EmbedInteractiveExample("pages/js/math-fround.html")}}</div> - - - -<h2 id="Syntax">Syntax</h2> - -<pre class="syntaxbox">var <em>singleFloat</em> = Math.fround(<em>doubleFloat</em>);</pre> - -<h3 id="Parameters">Parameters</h3> - -<dl> - <dt><code>doubleFloat</code></dt> - <dd>A {{jsxref("Number")}}. If the parameter is of a different type, it will get converted to a number or to {{jsxref("NaN")}} if it cannot be converted.</dd> -</dl> - -<h3 id="Return_value">Return value</h3> - -<p>The nearest <a class="external" href="https://en.wikipedia.org/wiki/Single-precision_floating-point_format" title="link to the wikipedia page on single-precision floating-point format">32-bit single precision</a> float representation of the given number.</p> - -<h2 id="Description">Description</h2> - -<p>JavaScript uses 64-bit double floating-point numbers internally, which offer a very high precision. However, sometimes you may be working with 32-bit floating-point numbers, for example if you are reading values from a {{jsxref("Float32Array")}}. This can create confusion: Checking a 64-bit float and a 32-bit float for equality may fail even though the numbers are seemingly identical.</p> - -<p>To solve this, <code>Math.fround()</code> can be used to cast the 64-bit float to a 32-bit float. Internally, JavaScript continues to treat the number as a 64-bit float, it just performs a "round to even" on the 23rd bit of the mantissa, and sets all following mantissa bits to <code>0</code>. If the number is outside the range of a 32-bit float, <code>{{jsxref("Infinity")}}</code> or <code>-Infinity</code> is returned.</p> - -<p>Because <code>fround()</code> is a static method of <code>Math</code>, you always use it as <code>Math.fround()</code>, rather than as a method of a <code>Math</code> object you created (<code>Math</code> is not a constructor).</p> - -<h2 id="Examples">Examples</h2> - -<h3 id="Using_Math.fround()">Using <code>Math.fround()</code></h3> - -<p>The number 1.5 can be precisely represented in the binary numeral system, and is identical in 32-bit and 64-bit:</p> - -<pre class="brush: js">Math.fround(1.5); // 1.5 -Math.fround(1.5) === 1.5; // true -</pre> - -<p>However, the number 1.337 cannot be precisely represented in the binary numeral system, so it differs in 32-bit and 64-bit:</p> - -<pre class="brush: js">Math.fround(1.337); // 1.3370000123977661 -Math.fround(1.337) === 1.337; // false -</pre> - -<p><math><semantics><msup><mn>2</mn><mn>150</mn></msup><annotation encoding="TeX">2^150</annotation></semantics></math> is too big for a 32-bit float, so <code>Infinity</code> is returned:</p> - -<pre class="brush: js">2 ** 150; // 1.42724769270596e+45 -Math.fround(2 ** 150); // Infinity -</pre> - -<p>If the parameter cannot be converted to a number, or it is <a href="https://en.wikipedia.org/wiki/NaN" title="NaN on Wikipedia">not-a-number</a> (<code>NaN</code>), <code>Math.fround()</code> will return <code>NaN</code>:</p> - -<pre class="brush: js">Math.fround('abc'); // NaN -Math.fround(NaN); // NaN -</pre> - -<h2 id="Polyfill">Polyfill</h2> - -<p>This can be emulated with the following function, if {{jsxref("Float32Array")}} are supported:</p> - -<pre class="brush: js">Math.fround = Math.fround || (function (array) { - return function(x) { - return array[0] = x, array[0]; - }; -})(new Float32Array(1)); -</pre> - -<p>Supporting older browsers is slower, but also possible:</p> - -<pre class="brush: js">if (!Math.fround) Math.fround = function(arg) { - arg = Number(arg); - // Return early for ±0 and NaN. - if (!arg) return arg; - var sign = arg < 0 ? -1 : 1; - if (sign < 0) arg = -arg; - // Compute the exponent (8 bits, signed). - var exp = Math.floor(Math.log(arg) / Math.LN2); - var powexp = Math.pow(2, Math.max(-126, Math.min(exp, 127))); - // Handle subnormals: leading digit is zero if exponent bits are all zero. - var leading = exp < -127 ? 0 : 1; - // Compute 23 bits of mantissa, inverted to round toward zero. - var mantissa = Math.round((leading - arg / powexp) * 0x800000); - if (mantissa <= -0x800000) return sign * Infinity; - return sign * powexp * (leading - mantissa / 0x800000); -};</pre> - -<h2 id="Faster_Alternative_Polyfill_(Work_In_Progress)">Faster Alternative Polyfill (Work In Progress)</h2> - -<p>The below polyfill is much faster and uses double-precision rounding errors to emulate the rounding errors caused by floating point narrowing. Although the polyfill higher on the page is good for comprehension, all of the complex Math function that it uses make it terrible slow. Although this polyfill is much faster, it is off by a bit in about 1 out of 2048 of the tests due to the tendency to round upwards like <code>Math.ceil</code> instead of like <code>Math.round</code> in the division of the subnormal-handling section of the code. Because single precision floating points have 23 bits of precision, the mean error deviation from the correct value is roughly <code>2**-28</code> or 0.0000000058%. This deviation from the correct value should be insignifigant in most circumstances, however please edit this polyfill if you have some tweaks to increase correctness without bloating the code size too much. NaN is not optimized for because it is most likely (almost certain) that you will not be calling <code>Math.fround</code> with NaN exclusively in a tight loop. Moreover, an additional check just for NaN instead of letting NaN naturally arise would induce a performance penalty for this function in older browsers when not called with NaN. Thus, the code below handles NaN correctly, but inefficiently for good reason.</p> - -<pre class="brush: js">const Math_round = Math.round; -if (!Math.fround) Math.fround = function(x) { - if (x > 3.402823669209385e+38) return Infinity; // maximum float is 2**128 - if (x < -3.402823669209385e+38) return -Infinity; // minimum is -2**128 - if (-1.1754943508222875e-38 < x && x < 1.1754943508222875e-38) { - if (-1.401298464324817e-45 < x && x < 1.401298464324817e-45) return 0; - // else, it is a subnormal - var mul = Math_round(x/1.4012984643e-45)*1e-323; - return mul * 1.418129833677085e+278; - } - - var hi = x * 9007199254740992; // 9007199254740992 is 2**53 which is the maximum of double precision - var exp = (x + hi) - hi; // adding this number chops off all lower bits, rounding the number. - exp /= 16777216; // 8388608 = 2**23 * 2, so preserve 23 bits in x because there are 23 bits in a float - // The "* 2" compensates for the addition shifting up the bits unwantedly - return Math_round(x / exp) * exp; -} -</pre> - -<p>Below is code used to test for deviations from the correct value. The code below is meant for testing the merit of the function, not for polyfilling older browsers (as evidenced by the fact that the native Math.fround function is used).</p> - -<pre class="brush: js">requestIdleCallback(function(){"use strict"; - const Math_fround = Math.fround; - const Math_round = Math.round; - function my_fround(x) { - if (x > 3.402823669209385e+38) return Infinity; // maximum float is 2**128 - if (x < -3.402823669209385e+38) return -Infinity; // minimum is -2**128 - if (-1.1754943508222875e-38 < x && x < 1.1754943508222875e-38) { - if (-1.401298464324817e-45 < x && x < 1.401298464324817e-45) return 0; - // else, it is a subnormal - var mul = Math_round(x/1.4012984643e-45)*1e-323; - return mul * 1.418129833677085e+278; - } - - var hi = x * 9007199254740992; // 9007199254740992 is 2**53 which is the maximum of double precision - var exp = (x + hi) - hi; // adding this number chops off all lower bits, rounding the number. - exp /= 16777216; // 8388608 = 2**23 * 2, so preserve 23 bits in x because there are 23 bits in a float - // The "* 2" compensates for the addition shifting up the bits unwantedly - return Math_round(x / exp) * exp; - } - - const doublesArray = new Float64Array(8192); - const int32s = new Uint32Array(doublesArray.buffer); - - const crypto = window.crypto; - - var hasWarned = false, warnings=0; - for (var i=0; i<4; i=i+1|0) { - crypto.getRandomValues(int32s); - for (var k=0; k<8192; k=k+1|0) { - const myValue = my_fround(doublesArray[k]); - const froundVal = Math_fround(doublesArray[k]); - // quicker version of Object.is because of no function call overhead: - if (myValue === myValue ? myValue !== froundVal : froundVal === froundVal) { - if (!hasWarned) console.error(doublesArray[k]); // only show the first incorrect number - hasWarned = true; - warnings = warnings + 1|0; - } - } - } - console[warnings > 0 ? "warn" : "log"]( "Total number of mishandled floats: " + warnings ); -});</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('ES6', '#sec-math.fround', 'Math.fround')}}</td> - <td>{{Spec2('ES6')}}</td> - <td>Initial definition.</td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-math.fround', 'Math.fround')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td></td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<p>{{Compat("javascript.builtins.Math.fround")}}</p> - -<h2 id="See_also">See also</h2> - -<ul> - <li>{{jsxref("Math.round()")}}</li> -</ul> diff --git a/files/es/web/javascript/reference/global_objects/object/__lookupgetter__/index.html b/files/es/web/javascript/reference/global_objects/object/__lookupgetter__/index.html deleted file mode 100644 index d99273a3fe..0000000000 --- a/files/es/web/javascript/reference/global_objects/object/__lookupgetter__/index.html +++ /dev/null @@ -1,85 +0,0 @@ ---- -title: Object.prototype.__lookupGetter__() -slug: Web/JavaScript/Reference/Global_Objects/Object/__lookupGetter__ -translation_of: Web/JavaScript/Reference/Global_Objects/Object/__lookupGetter__ -original_slug: Web/JavaScript/Referencia/Objetos_globales/Object/__lookupGetter__ ---- -<div>{{JSRef}} {{deprecated_header}}</div> - -<p>Los <code><strong>__lookupGetter__</strong></code> metodos retornan la funcion enlazada como un getter para especificar la propiedad.</p> - -<h2 id="Syntax">Syntax</h2> - -<pre class="syntaxbox"><code><var>obj</var>.__lookupGetter__(<var>sprop</var>)</code></pre> - -<h3 id="Parameters">Parameters</h3> - -<dl> - <dt><code>sprop</code></dt> - <dd>A string containing the name of the property whose getter should be returned.</dd> -</dl> - -<h3 id="Return_value">Return value</h3> - -<p>The function bound as a getter to the specified property.</p> - -<h2 id="Description">Description</h2> - -<p>If a getter has been defined for an object's property, it's not possible to reference the getter function through that property, because that property refers to the return value of that function. <code>__lookupGetter__</code> can be used to obtain a reference to the getter function.</p> - -<p>It is now possible to do this in a standardized way using {{jsxref("Object.getOwnPropertyDescriptor()")}} and {{jsxref("Object.getPrototypeOf()")}}.</p> - -<h2 id="Examples">Examples</h2> - -<pre class="brush: js">var obj = { - get foo() { - return Math.random() > 0.5 ? 'foo' : 'bar'; - } -}; - - -// Non-standard and deprecated way -obj.__lookupGetter__('foo'); -// (function() { return Math.random() > 0.5 ? 'foo' : 'bar'; }) - - -// Standard-compliant way -Object.getOwnPropertyDescriptor(obj, "foo").get; -// (function() { return Math.random() > 0.5 ? 'foo' : 'bar'; }) -</pre> - -<h2 id="Specifications">Specifications</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('ESDraft', '#sec-object.prototype.__lookupGetter__', 'Object.prototype.__lookupGetter__()')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td>Included in the (normative) annex for additional ECMAScript legacy features for Web browsers (note that the specification codifies what is already in implementations).</td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<div> - - -<p>{{Compat("javascript.builtins.Object.lookupGetter")}}</p> -</div> - -<h2 id="See_also">See also</h2> - -<ul> - <li>{{jsxref("Object.prototype.__lookupSetter__()")}}</li> - <li>{{jsxref("Functions/get", "get")}} operator</li> - <li>{{jsxref("Object.getOwnPropertyDescriptor()")}} and {{jsxref("Object.getPrototypeOf()")}}</li> - <li>{{jsxref("Object.prototype.__defineGetter__()")}}</li> - <li>{{jsxref("Object.prototype.__defineSetter__()")}}</li> - <li><a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Defining_getters_and_setters">JS Guide: Defining Getters and Setters</a></li> -</ul> diff --git a/files/es/web/media/formats/containers/index.html b/files/es/web/media/formats/containers/index.html deleted file mode 100644 index 2864534d67..0000000000 --- a/files/es/web/media/formats/containers/index.html +++ /dev/null @@ -1,1329 +0,0 @@ ---- -title: Media container formats (file types) -slug: Web/Media/Formats/Containers -tags: - - Hugo javier duran miranda. -translation_of: Web/Media/Formats/Containers ---- -<div>{{QuickLinksWithSubpages("/en-US/docs/Web/Media")}}</div> - -<p>The format of audio and video media files is defined in two parts (three if a file has both audio and video in it, of course): the audio and/or video codecs used and the media container format (or file type) used. <span class="seoSummary">In this guide, we'll look at the container formats used most commonly on the web, covering basics about their specifications as well as their benefits, limitations, and ideal use cases.</span></p> - -<p><a href="/en-US/docs/Web/API/WebRTC_API">WebRTC</a> does not use a container at all. Instead, it streams the encoded audio and video tracks directly from one peer to another using {{domxref("MediaStreamTrack")}} objects to represent each track. See <a href="/en-US/docs/Web/Media/Formats/WebRTC_codecs">Codecs used by WebRTC</a> for information about codecs commonly used for making WebRTC calls, as well as browser compatibility information around codec support in WebRTC.</p> - -<h2 id="Common_container_formats">Common container formats</h2> - -<p>While there are a vast number of media container formats, the ones listed below are the ones you are most likely to encounter. Some support only audio while others support both audio and video. The MIME types and extensions for each are listed.The most commonly used containers for media on the web are probably MPEG-4 (MP4), QuickTime Movie (MOV), and the Wavefile Audio File Format (WAV). However, you may also encounter MP3, Ogg, WebM, AVI, and other formats. Not all of these are broadly supported by browsers, however; some combinations of container and codec are sometimes given their own file extensions and MIME types as a matter of convenience, or because of their ubiquity. For example, an Ogg file with only an Opus audio track is sometimes referred to as an Opus file, and might even have the extension <code>.opus</code>. But it's still actually just an Ogg file.</p> - -<p>In other cases, a particular codec, stored in a certain container type, is so ubiquitous that the pairing is treated in a unique fashion. A good example of this is the MP3 audio file, which is in fact an MPEG-1 container with a single audio track encoded using MPEG-1 Audio Layer III encoding. These files use the <code>audio/mp3</code> MIME type and the <code>.mp3</code> extension, even though their containers are just MPEG.</p> - -<h3 id="Index_of_media_container_formats_file_types" style="font-size: 1.4em;">Index of media container formats (file types)</h3> - -<p>To learn more about a specific container format, find it in this list and click through to the details, which include information about what the container is typically useful for, what codecs it supports, and which browsers support it, among other specifics.</p> - -<table class="standard-table"> - <thead> - <tr> - <th scope="row">Codec name (short)</th> - <th scope="col">Full codec name</th> - <th scope="col">Browser compatibility<sup><a href="#index-foot-1">1</a></sup></th> - </tr> - </thead> - <tbody> - <tr> - <th scope="row">{{anch("3GP")}}</th> - <td>Third Generation Partnership</td> - <td>Firefox for Android</td> - </tr> - <tr> - <th scope="row">{{anch("ADTS")}}</th> - <td>Audio Data Transport Stream</td> - <td>Firefox<sup><a href="#index-foot-2">2</a></sup></td> - </tr> - <tr> - <th scope="row">{{anch("FLAC")}}</th> - <td>Free Lossless Audio Codec</td> - <td>Chrome 56, Edge 16, Firefox 51, Safari 11</td> - </tr> - <tr> - <th scope="row">{{anch("MPEG", "MPEG / MPEG-2")}}</th> - <td>Moving Picture Experts Group (1 and 2)</td> - <td>—</td> - </tr> - <tr> - <th scope="row">{{anch("MP4", "MPEG-4 (MP4)")}}</th> - <td>Moving Picture Experts Group 4</td> - <td>Chrome 3, Edge 12, Firefox, Internet Explorer 9, Opera 24, Safari 3.1</td> - </tr> - <tr> - <th scope="row">{{anch("Ogg")}}</th> - <td>Ogg</td> - <td>Chrome 3, Firefox 3.5, Edge 17<sup><a href="#index-foot-3">3</a></sup> (desktop only), Internet Explorer 9, Opera 10.50</td> - </tr> - <tr> - <th scope="row">{{anch("QuickTime", "QuickTime (MOV)")}}</th> - <td>Apple QuickTime movie</td> - <td>Only older versions of Safari, plus other browsers that supported Apple's QuickTime plugin</td> - </tr> - <tr> - <th scope="row">{{anch("WebM")}}</th> - <td>Web Media</td> - <td>Chrome 6, Edge 17<sup><a href="#index-foot-3">3</a></sup> (desktop only), Firefox 4, Opera 10.6, Safari (WebRTC only)</td> - </tr> - </tbody> -</table> - -<p><a id="index-foot-1" name="index-foot-1">[1]</a> Unless otherwise specified, both mobile and desktop browser compatibility is implied if a browser is listed here. Support is also implied only for the container itself, not for any specific codecs.</p> - -<p><a id="index-foot-2" name="index-foot-2">[2]</a> Available only if available on the underlying operating system's media framework.</p> - -<p><a name="index-foot-3">[3]</a> Requires <a href="https://www.microsoft.com/store/productId/9N5TDP8VCMHS">Web Media Extensions</a> to be installed.</p> - -<h3 id="3GP">3GP</h3> - -<p>The <strong>3GP</strong> or <strong>3GPP</strong> media container is used to encapsulate audio and/or video that is specifically intended for transmission over cellular networks for consumption on mobile devices. The format was designed for use on 3G mobile phones, but can still be used on more modern phones and networks. However, the improved bandwidth availability and increased data caps on most networks has reduced the need for the 3GP format. However, this format is still used for slower networks and for lower-performance phones.</p> - -<p>This media container format is derived from the ISO Base Media File Format and MPEG-4, but is specifically streamlined for lower bandwidth scenarios.</p> - -<table class="standard-table"> - <caption>Base 3GP media MIME types</caption> - <thead> - <tr> - <th scope="col">Audio</th> - <th scope="col">Video</th> - </tr> - </thead> - <tbody> - <tr> - <td><code>audio/3gpp</code></td> - <td><code>video/3gpp</code></td> - </tr> - <tr> - <td><code>audio/3gpp2</code></td> - <td><code>video/3gpp2</code></td> - </tr> - <tr> - <td><code>audio/3gp2</code></td> - <td><code>video/3gp2</code></td> - </tr> - </tbody> -</table> - -<p>These MIME types are the fundamental types for the 3GP media container; other types may be used depending on the specific codec or codecs in use; in addition, you can <a href="/en-US/docs/Web/Media/Formats/codecs_parameter#ISO-BMFF">add the <code>codecs</code> parameter</a> to the MIME type string to indicate which codecs are used for the audio and/or video tracks, and to optionally provide details about the profile, level, and/or other codec configuration specifics.</p> - -<table class="standard-table"> - <caption>Video codecs supported by 3GP</caption> - <thead> - <tr> - <th rowspan="2" scope="row" style="vertical-align: bottom;">Codec</th> - <th colspan="4" scope="col" style="text-align: center;">Browser support</th> - </tr> - <tr> - <th scope="col">Chrome</th> - <th scope="col">Edge</th> - <th scope="col">Firefox</th> - <th scope="col">Safari</th> - </tr> - </thead> - <tbody> - <tr> - <th scope="row">AVC (H.264)</th> - <td></td> - <td></td> - <td>Yes<sup><a href="#3gp-vid-footnote-1">1</a>,<a href="#3gp-vid-footnote-1">2</a></sup></td> - <td></td> - </tr> - <tr> - <th scope="row">H.263</th> - <td></td> - <td></td> - <td>Yes<sup><a href="#3gp-vid-footnote-1">1</a></sup></td> - <td></td> - </tr> - <tr> - <th scope="row">MPEG-4 Part 2 (MP4v-es)</th> - <td></td> - <td></td> - <td>Yes<sup><a href="#3gp-vid-footnote-1">1</a></sup></td> - <td></td> - </tr> - <tr> - <th scope="row">VP8</th> - <td></td> - <td></td> - <td>Yes<sup><a href="#3gp-vid-footnote-1">1</a></sup></td> - <td></td> - </tr> - </tbody> -</table> - -<p><a id="3gp-vid-footnote-1" name="3gp-vid-footnote-1">[1]</a> Firefox only supports 3GP on <a href="https://www.khronos.org/openmax/">OpenMAX</a>-based devices, which currently means the Boot to Gecko (B2G) platform.</p> - -<p><a id="3gp-vid-footnote-2" name="3gp-vid-footnote-2">[2]</a> Firefox support for H.264 relies upon the operating system's media infrastructure, so it is available as long as the OS supports it.</p> - -<table class="standard-table"> - <caption>Audio codecs supported by 3GP</caption> - <thead> - <tr> - <th rowspan="2" scope="row" style="vertical-align: bottom;">Codec</th> - <th colspan="4" scope="col" style="text-align: center;">Browser support</th> - </tr> - <tr> - <th scope="col">Chrome</th> - <th scope="col">Edge</th> - <th scope="col">Firefox</th> - <th scope="col">Safari</th> - </tr> - </thead> - <tbody> - <tr> - <th scope="row">AMR-NB</th> - <td></td> - <td></td> - <td>Yes<sup><a href="#3gp-aud-footnote-1">1</a></sup></td> - <td></td> - </tr> - <tr> - <th scope="row">AMR-WB</th> - <td></td> - <td></td> - <td>Yes<sup><a href="#3gp-aud-footnote-1">1</a></sup></td> - <td></td> - </tr> - <tr> - <th scope="row">AMR-WB+</th> - <td></td> - <td></td> - <td>Yes<sup><a href="#3gp-aud-footnote-1">1</a></sup></td> - <td></td> - </tr> - <tr> - <th scope="row">AAC-LC</th> - <td></td> - <td></td> - <td>Yes<sup><a href="#3gp-aud-footnote-1">1</a>,<a href="#av1-vid-footnote-2">2</a></sup></td> - <td></td> - </tr> - <tr> - <th scope="row">HE-AAC v1</th> - <td></td> - <td></td> - <td>Yes<sup><a href="#3gp-aud-footnote-1">1</a>,<a href="#av1-vid-footnote-2">2</a></sup></td> - <td></td> - </tr> - <tr> - <th scope="row">HE-AAC v2</th> - <td></td> - <td></td> - <td>Yes<sup><a href="#3gp-aud-footnote-1">1</a>,<a href="#av1-vid-footnote-2">2</a></sup></td> - <td></td> - </tr> - <tr> - <th scope="row">MP3</th> - <td></td> - <td></td> - <td>Yes<sup><a href="#3gp-aud-footnote-1">1</a></sup></td> - <td></td> - </tr> - </tbody> -</table> - -<p><a id="3gp-aud-footnote-1" name="3gp-aud-footnote-1">[1]</a> Firefox only supports 3GP on <a href="https://www.khronos.org/openmax/">OpenMAX</a>-based devices, which currently means the Boot to Gecko (B2G) platform.</p> - -<p><a id="3gp-aud-footnote-2" name="3gp-aud-footnote-2">[2]</a> Firefox support for AAC relies upon the operating system's media infrastructure, so it is available as long as the OS supports it.</p> - -<h3 id="ADTS">ADTS</h3> - -<p><strong>Audio Data Transport Stream</strong> (<strong>ADTS</strong>) is a container format specified by MPEG-4 Part 3 for audio data, intended to be used for streamed audio, such as for Internet radio. It is, essentially, an almost bare stream of AAC audio data, comprised of ADTS frames with a minimal header.</p> - -<table class="standard-table"> - <caption>ADTS media MIME types</caption> - <thead> - <tr> - <th scope="col">Audio</th> - </tr> - </thead> - <tbody> - <tr> - <td><code>audio/aac</code><sup><a href="#adts-foot-1">[1]</a></sup></td> - </tr> - <tr> - <td><code>audio/mpeg</code><sup><a href="#adts-foot-1">[1]</a></sup></td> - </tr> - </tbody> -</table> - -<p><a id="adts-foot-1" name="adts-foot-1">[1]</a> The MIME type used for ADTS depends on what kind of audio frames are contained within. If ADTS frames are used, the <code>audio/aac</code> MIME type should be used. If the audio frames are in MPEG-1/MPEG-2 Audio Layer I, II, or III format, the MIME type should be <code>audio/mpeg</code>.</p> - -<table class="standard-table"> - <caption>Audio codecs supported by ADTS</caption> - <thead> - <tr> - <th rowspan="2" scope="row" style="vertical-align: bottom;">Codec</th> - <th colspan="4" scope="col" style="text-align: center;">Browser support</th> - </tr> - <tr> - <th scope="col">Chrome</th> - <th scope="col">Edge</th> - <th scope="col">Firefox</th> - <th scope="col">Safari</th> - </tr> - </thead> - <tbody> - <tr> - <th scope="row">AAC</th> - <td></td> - <td></td> - <td>Yes<sup><a href="#adts-aud-footnote-1">1</a></sup></td> - <td></td> - </tr> - <tr> - <th scope="row">MP3</th> - <td></td> - <td></td> - <td>Yes</td> - <td></td> - </tr> - </tbody> -</table> - -<p><a id="adts-aud-footnote-1" name="adts-aud-footnote-1">[1]</a> Firefox support for AAC relies upon the operating system's media infrastructure, so it is available as long as the OS supports it.</p> - -<h3 id="FLAC">FLAC</h3> - -<p>The <strong>Free Lossless Audio Codec</strong> (<strong>FLAC</strong>) is a lossless audio codec; there is also an associated simple container format, also called FLAC, that can contain this audio. The format is not encumbered by any patents, so its use is safe from interference. FLAC files can only contain FLAC audio data.</p> - -<table class="standard-table"> - <caption>FLAC media MIME type</caption> - <thead> - <tr> - <th scope="col">Audio</th> - </tr> - </thead> - <tbody> - <tr> - <td><code>audio/flac</code></td> - </tr> - <tr> - <td><code>audio/x-flac</code> (non-standard)</td> - </tr> - </tbody> -</table> - -<table class="standard-table"> - <caption>Audio codecs supported by FLAC</caption> - <thead> - <tr> - <th rowspan="2" scope="row" style="vertical-align: bottom;">Codec</th> - <th colspan="4" scope="col" style="text-align: center;">Browser support</th> - </tr> - <tr> - <th scope="col">Chrome</th> - <th scope="col">Edge</th> - <th scope="col">Firefox</th> - <th scope="col">Safari</th> - </tr> - </thead> - <tbody> - <tr> - <th scope="row">FLAC</th> - <td></td> - <td></td> - <td>Yes</td> - <td></td> - </tr> - </tbody> -</table> - -<h3 id="MPEGMPEG-2"><a id="MPEG" name="MPEG">MPEG</a>/MPEG-2</h3> - -<p>The <strong>{{interwiki("wikipedia", "MPEG-1")}}</strong> and <strong>{{interwiki("wikipedia", "MPEG-2")}}</strong> file formats are essentially identical. Created by the Moving Picture Experts Group (MPEG), these formats are widely used in physical media, including as the format of the video on DVD media.</p> - -<p>On the internet, perhaps the most common use of the MPEG file format is to contain {{interwiki("wikipedia", "MPEG-1", "Layer_III/MP3", "MPEG-1 Audio Layer 3")}} sound data; the resulting files are the wildly popular MP3 file used by digital music devices around the world. Otherwise, MPEG-1 and MPEG-2 are not widely used in Web content.</p> - -<p>The main differences between MPEG-1 and MPEG-2 take place in the media data formats rather than the container format. MPEG-1 was introduced in 1992; MPEG-2 was introduced in 1996.</p> - -<table class="standard-table"> - <caption>MPEG-1 and MPEG-2 media MIME types</caption> - <thead> - <tr> - <th scope="col">Audio</th> - <th scope="col">Video</th> - </tr> - </thead> - <tbody> - <tr> - <td><code>audio/mpeg</code></td> - <td><code>video/mpeg</code></td> - </tr> - </tbody> -</table> - -<table class="standard-table"> - <caption>Video codecs supported by MPEG-1 and MPEG-2</caption> - <thead> - <tr> - <th rowspan="2" scope="row" style="vertical-align: bottom;">Codec</th> - <th colspan="4" scope="col" style="text-align: center;">Browser support</th> - </tr> - <tr> - <th scope="col">Chrome</th> - <th scope="col">Edge</th> - <th scope="col">Firefox</th> - <th scope="col">Safari</th> - </tr> - </thead> - <tbody> - <tr> - <th scope="row">MPEG-1 Part 2</th> - <td></td> - <td></td> - <td>No</td> - <td></td> - </tr> - <tr> - <th scope="row">MPEG-2 Part 2</th> - <td></td> - <td></td> - <td>No</td> - <td></td> - </tr> - </tbody> -</table> - -<table class="standard-table"> - <caption>Audio codecs supported by MPEG-1 and MPEG-2</caption> - <thead> - <tr> - <th rowspan="2" scope="row" style="vertical-align: bottom;">Codec</th> - <th colspan="4" scope="col" style="text-align: center;">Browser support</th> - </tr> - <tr> - <th scope="col">Chrome</th> - <th scope="col">Edge</th> - <th scope="col">Firefox</th> - <th scope="col">Safari</th> - </tr> - </thead> - <tbody> - <tr> - <th scope="row">MPEG-1 Audio Layer I</th> - <td></td> - <td></td> - <td>No</td> - <td></td> - </tr> - <tr> - <th scope="row">MPEG-1 Audio Layer II</th> - <td></td> - <td></td> - <td>No</td> - <td></td> - </tr> - <tr> - <th scope="row">MPEG-1 Audio Layer III (MP3)</th> - <td></td> - <td></td> - <td>Yes</td> - <td></td> - </tr> - </tbody> -</table> - -<h3 id="MPEG-4_MP4"><a id="MP4" name="MP4">MPEG-4 (MP4)</a></h3> - -<p><strong>{{interwiki("wikipedia", "MPEG-4")}}</strong> (<strong>MP4</strong>) is the latest version of the MPEG file format. There are two versions of the format, defined in parts 1 and 14 of the specification. MP4 is a popular container today, as it supports several of the most-used codecs and is broadly supported.</p> - -<p>The original MPEG-4 Part 1 file format was introduced in 1999; the version 2 format, defined in Part 14, was added in 2003. The MP4 file format is derived from the {{interwiki("wikipedia", "ISO base media file format")}}, which is directly derived from the {{interwiki("wikipedia", "QuickTime file format")}} developed by <a href="https://www.apple.com/">Apple</a>.</p> - -<p>When specifying the MPEG-4 media type (<code>audio/mp4</code> or <code>video/mp4</code>), you can <a href="/en-US/docs/Web/Media/Formats/codecs_parameter#ISO-BMFF">add the <code>codecs</code> parameter</a> to the MIME type string to indicate which codecs are used for the audio and/or video tracks, and to optionally provide details about the profile, level, and/or other codec configuration specifics.</p> - -<table class="standard-table"> - <caption>Base MPEG-4 media MIME types</caption> - <thead> - <tr> - <th scope="col">Audio</th> - <th scope="col">Video</th> - </tr> - </thead> - <tbody> - <tr> - <td><code>audio/mp4</code></td> - <td><code>video/mp4</code></td> - </tr> - </tbody> -</table> - -<p>These MIME types are the fundamental types for the MPEG-4 media container; other MIME types may be used depending on the specific codec or codecs in use within the container. In addition, you can <a href="/en-US/docs/Web/Media/Formats/codecs_parameter#ISO-BMFF">add the <code>codecs</code> parameter</a> to the MIME type string to indicate which codecs are used for the audio and/or video tracks, and to optionally provide details about the profile, level, and/or other codec configuration specifics.</p> - -<table class="standard-table"> - <caption>Video codecs supported by MPEG-4</caption> - <thead> - <tr> - <th rowspan="2" scope="row" style="vertical-align: bottom;">Codec</th> - <th colspan="4" scope="col" style="text-align: center;">Browser support</th> - </tr> - <tr> - <th scope="col">Chrome</th> - <th scope="col">Edge</th> - <th scope="col">Firefox</th> - <th scope="col">Safari</th> - </tr> - </thead> - <tbody> - <tr> - <th scope="row">AVC (H.264)</th> - <td></td> - <td></td> - <td>Yes<sup><a href="#mp4-vid-footnote-1">1</a></sup></td> - <td></td> - </tr> - <tr> - <th scope="row">AV1</th> - <td></td> - <td></td> - <td>Yes<sup><a href="#mp4-vid-footnote-1">1</a></sup></td> - <td></td> - </tr> - <tr> - <th scope="row">H.263</th> - <td></td> - <td></td> - <td>No</td> - <td></td> - </tr> - <tr> - <th scope="row">MPEG-4 Part 2 Visual</th> - <td></td> - <td></td> - <td>No</td> - <td></td> - </tr> - <tr> - <th scope="row">VP9</th> - <td></td> - <td></td> - <td>Yes</td> - <td></td> - </tr> - </tbody> -</table> - -<p><a id="mp4-vid-footnote-1" name="mp4-vid-footnote-1">[1]</a> Firefox support for H.264 relies upon the operating system's media infrastructure, so it is available as long as the OS supports it.</p> - -<p><a id="mp4-vid-footnote-2" name="mp4-vid-footnote-2">[2]</a> Firefox support for AV1 is currently disabled by default; it can be enabled by setting the preference <code>media.av1.enabled</code> to <code>true</code>.</p> - -<table class="standard-table"> - <caption>Audio codecs supported by MPEG-4</caption> - <thead> - <tr> - <th rowspan="2" scope="row" style="vertical-align: bottom;">Codec</th> - <th colspan="4" scope="col" style="text-align: center;">Browser support</th> - </tr> - <tr> - <th scope="col">Chrome</th> - <th scope="col">Edge</th> - <th scope="col">Firefox</th> - <th scope="col">Safari</th> - </tr> - </thead> - <tbody> - <tr> - <th scope="row">AAC</th> - <td></td> - <td></td> - <td>Yes<sup><a href="#mp4-aud-footnote-1">1</a></sup></td> - <td></td> - </tr> - <tr> - <th scope="row">FLAC</th> - <td></td> - <td></td> - <td>Yes</td> - <td></td> - </tr> - <tr> - <th scope="row">MPEG-1 Audio Layer III (MP3)</th> - <td></td> - <td></td> - <td>Yes</td> - <td></td> - </tr> - <tr> - <th scope="row">Opus</th> - <td></td> - <td></td> - <td>Yes</td> - <td></td> - </tr> - </tbody> -</table> - -<p><a id="mp4-aud-footnote-1" name="mp4-aud-footnote-1">[1]</a> Firefox support for H.264 relies upon the operating system's media infrastructure, so it is available as long as the OS supports it.</p> - -<h3 id="Ogg">Ogg</h3> - -<p>The <strong>{{interwiki("wikipedia", "Ogg")}}</strong> container format is a free and open format maintained by the <a href="https://www.xiph.org/">Xiph.org Foundation</a>. The Ogg framework also defines patent unencumbered media data formats, such as the Theora video codec and the Vorbis and Opus audio codecs. <a href="https://xiph.org/ogg/">Xiph.org documents about the Ogg format</a> are available on their web site.</p> - -<p>While Ogg has been around for a long time, it has never gained the wide support needed to make it a good first choice for a media container. You are typically better off using WebM, though there are times when Ogg is useful to offer, such as when you wish to support older versions of Firefox and Chrome which don't yet support WebM. For example, Firefox 3.5 and 3.6 support Ogg, but not WebM.</p> - -<p>You can get more information about Ogg and its codecs in the <a href="http://en.flossmanuals.net/ogg-theora/">Theora Cookbook</a>.</p> - -<table class="standard-table"> - <caption>Base Ogg media MIME types</caption> - <thead> - <tr> - <th scope="col">Audio</th> - <th scope="col">Video</th> - </tr> - </thead> - <tbody> - <tr> - <td><code>audio/ogg</code></td> - <td><code>video/ogg</code></td> - </tr> - </tbody> -</table> - -<p>The <code>application/ogg</code> MIME type can be used when you don't necessarily know whether the media contains audio or video. If at all possible, you should use one of the specific types, but fall back to <code>application/ogg</code> if you don't know the content format or formats.</p> - -<p>You can also <a href="/en-US/docs/Web/Media/Formats/codecs_parameter#Ogg">add the <code>codecs</code> parameter</a> to the MIME type string to indicate which codecs are used for the audio and/or video tracks, and to optionally further describe the track media formats.</p> - -<table class="standard-table"> - <caption>Video codecs supported by Ogg</caption> - <thead> - <tr> - <th rowspan="2" scope="row" style="vertical-align: bottom;">Codec</th> - <th colspan="4" scope="col" style="text-align: center;">Browser support</th> - </tr> - <tr> - <th scope="col">Chrome</th> - <th scope="col">Edge</th> - <th scope="col">Firefox</th> - <th scope="col">Safari</th> - </tr> - </thead> - <tbody> - <tr> - <th scope="row">Theora</th> - <td></td> - <td></td> - <td>Yes</td> - <td></td> - </tr> - <tr> - <th scope="row">VP8</th> - <td></td> - <td></td> - <td>Yes</td> - <td></td> - </tr> - <tr> - <th scope="row">VP9</th> - <td></td> - <td></td> - <td>Yes</td> - <td></td> - </tr> - </tbody> -</table> - -<table class="standard-table"> - <caption>Audio codecs supported by Ogg</caption> - <thead> - <tr> - <th rowspan="2" scope="row" style="vertical-align: bottom;">Codec</th> - <th colspan="4" scope="col" style="text-align: center;">Browser support</th> - </tr> - <tr> - <th scope="col">Chrome</th> - <th scope="col">Edge</th> - <th scope="col">Firefox</th> - <th scope="col">Safari</th> - </tr> - </thead> - <tbody> - <tr> - <th scope="row">FLAC</th> - <td></td> - <td></td> - <td>Yes</td> - <td></td> - </tr> - <tr> - <th scope="row">Opus</th> - <td></td> - <td></td> - <td>Yes</td> - <td></td> - </tr> - <tr> - <th scope="row">Vorbis</th> - <td></td> - <td></td> - <td>Yes</td> - <td></td> - </tr> - </tbody> -</table> - -<h3 id="QuickTime">QuickTime</h3> - -<p>The <strong>QuickTime</strong> file format (<strong>QTFF</strong>, <strong>QT</strong>, or <strong>MOV</strong>) was created by Apple for use by its media framework of the same name. The extension for these files, <code>.mov</code>, comes from the fact that the format was initially used for movies and was usually called the "QuickTime movie" format. While QTFF served as the basis for the MPEG-4 file format, there are differences and the two are not quite interchangeable.</p> - -<p>QuickTime files support any sort of time-based data, including audio and video media, text tracks, and so forth. QuickTime files are primarily supported by macOS, but for a number of years, QuickTime for Windows was available to access them on Windows. However, QuickTime for Windows is no longer supported by Apple as of early 2016, and <em>should not be used</em>, as there are known security concerns. However, Windows Media Player now has integrated support for QuickTime version 2.0 and earlier files; support for later versions of QuickTime requires third-party additions.</p> - -<p>On Mac OS, the QuickTime framework not only supported QuickTime format movie files and codecs, but supported a vast array of popular and specialty audio and video codecs, as well as still image formats. Through QuickTime, Mac applications (including web browsers, through the QuickTime plugin or direct QuickTime integration) were able to read and write audio formats including AAC, AIFF, MP3, PCM, and Qualcomm PureVoice; and video formats including AVI, DV, Pixlet, ProRes, FLAC, Cinepak, 3GP, H.261 through H.265, MJPEG, MPEG-1 and MPEG-4 Part 2, Sorenson, and many more.</p> - -<p>In addition, a number of third-party components are available for QuickTime, some of which add support for additional codecs.</p> - -<p>Because QuickTime support is, for all intents and purposes, primarily available on Apple devices, it is no longer widely used on the internet. Apple itself generally now uses MP4 for video. In addition, the QuickTime framework has been deprecated on the Mac for some time, and is no longer available at all starting in macOS 10.15 Catalina.</p> - -<table class="standard-table"> - <caption>Base QuickTime media MIME type</caption> - <thead> - <tr> - <th scope="col">Video</th> - </tr> - </thead> - <tbody> - <tr> - <td><code>video/quicktime</code></td> - </tr> - </tbody> -</table> - -<p>The <code>video/quicktime</code> MIME type is the fundamental type for the QuickTime media container. It's worth noting that QuickTime (the media framework on Mac operating systems) supports a wide variety of containers and codecs, so it actually supports many other MIME types.</p> - -<p>You can <a href="/en-US/docs/Web/Media/Formats/codecs_parameter#ISO-BMFF">add the <code>codecs</code> parameter</a> to the MIME type string to indicate which codecs are used for the audio and/or video tracks, and to optionally provide details about the profile, level, and/or other codec configuration specifics.</p> - -<table class="standard-table"> - <caption>Video codecs supported by QuickTime</caption> - <thead> - <tr> - <th rowspan="2" scope="row" style="vertical-align: bottom;">Codec</th> - <th colspan="4" scope="col" style="text-align: center;">Browser support</th> - </tr> - <tr> - <th scope="col">Chrome</th> - <th scope="col">Edge</th> - <th scope="col">Firefox</th> - <th scope="col">Safari</th> - </tr> - </thead> - <tbody> - <tr> - <th scope="row">AVC (H.264)</th> - <td></td> - <td></td> - <td>No</td> - <td></td> - </tr> - <tr> - <th scope="row">Cinepak</th> - <td></td> - <td></td> - <td>No</td> - <td></td> - </tr> - <tr> - <th scope="row">Component Video</th> - <td></td> - <td></td> - <td>No</td> - <td></td> - </tr> - <tr> - <th scope="row">DV</th> - <td></td> - <td></td> - <td>No</td> - <td></td> - </tr> - <tr> - <th scope="row">H.261</th> - <td></td> - <td></td> - <td>No</td> - <td></td> - </tr> - <tr> - <th scope="row">H.263</th> - <td></td> - <td></td> - <td>No</td> - <td></td> - </tr> - <tr> - <th scope="row">MPEG-2</th> - <td></td> - <td></td> - <td>No</td> - <td></td> - </tr> - <tr> - <th scope="row">MPEG-4 Part 2 Visual</th> - <td></td> - <td></td> - <td>No</td> - <td></td> - </tr> - <tr> - <th scope="row">Motion JPEG</th> - <td></td> - <td></td> - <td>No</td> - <td></td> - </tr> - <tr> - <th scope="row">Sorenson Video 2</th> - <td></td> - <td></td> - <td>No</td> - <td></td> - </tr> - <tr> - <th scope="row">Sorenson Video 3</th> - <td></td> - <td></td> - <td>No</td> - <td></td> - </tr> - </tbody> -</table> - -<table class="standard-table"> - <caption>Audio codecs supported by QuickTime</caption> - <thead> - <tr> - <th rowspan="2" scope="row" style="vertical-align: bottom;">Codec</th> - <th colspan="4" scope="col" style="text-align: center;">Browser support</th> - </tr> - <tr> - <th scope="col">Chrome</th> - <th scope="col">Edge</th> - <th scope="col">Firefox</th> - <th scope="col">Safari</th> - </tr> - </thead> - <tbody> - <tr> - <th scope="row">AAC</th> - <td></td> - <td></td> - <td>No</td> - <td></td> - </tr> - <tr> - <th scope="row">ALaw 2:1</th> - <td></td> - <td></td> - <td>No</td> - <td></td> - </tr> - <tr> - <th scope="row">Apple Lossless (ALAC)</th> - <td></td> - <td></td> - <td>No</td> - <td></td> - </tr> - <tr> - <th scope="row">HE-AAC</th> - <td></td> - <td></td> - <td>No</td> - <td></td> - </tr> - <tr> - <th scope="row">MPEG-1 Audio Layer III (MP3)</th> - <td></td> - <td></td> - <td>No</td> - <td></td> - </tr> - <tr> - <th scope="row">Microsoft ADPCM</th> - <td></td> - <td></td> - <td>No</td> - <td></td> - </tr> - <tr> - <th scope="row">µ-Law 2:1 (u-Law)</th> - <td></td> - <td></td> - <td>No</td> - <td></td> - </tr> - </tbody> -</table> - -<h3 id="WAVE_WAV"><a id="WAVE" name="WAVE">WAVE</a> (WAV)</h3> - -<p>The <strong>Waveform Audio File Format</strong> (<strong>WAVE</strong>), usually referred to simply as WAV due to its filename extension being <code>.wav</code>, is a format developed by Microsoft and IBM to store audio bitstream data.</p> - -<p>It is derived from the Resource Interchange File Format (RIFF), and as such is similar to other formats such as Apple's AIFF. The WAV codec registry can be found at {{RFC(2361)}}; however, because nearly all WAV files use linear PCM, support for the other codecs is sparse.</p> - -<p>The WAVE format was first released in 1991.</p> - -<table class="standard-table"> - <caption>WAVE media MIME types</caption> - <thead> - <tr> - <th scope="col">Audio</th> - </tr> - </thead> - <tbody> - <tr> - <td><code>audio/wave</code><sup><a href="#wave-foot-1">1</a></sup></td> - </tr> - <tr> - <td><code>audio/wav</code></td> - </tr> - <tr> - <td><code>audio/x-wav</code></td> - </tr> - <tr> - <td><code>audio/x-pn-wav</code></td> - </tr> - </tbody> -</table> - -<p><a id="wave-foot-1" name="wave-foot-1">[1]</a> The <code>audio/wave</code> MIME type is the standard type, and is preferred; however, the others have been used by various products over the years and may be used as well in some environments. </p> - -<table class="standard-table"> - <caption>Audio codecs supported by WAVE</caption> - <thead> - <tr> - <th rowspan="2" scope="row" style="vertical-align: bottom;">Codec</th> - <th colspan="4" scope="col" style="text-align: center;">Browser support</th> - </tr> - <tr> - <th scope="col">Chrome</th> - <th scope="col">Edge</th> - <th scope="col">Firefox</th> - <th scope="col">Safari</th> - </tr> - </thead> - <tbody> - <tr> - <th scope="row">ADPCM (Adaptive Differential Pulse Code Modulation)</th> - <td></td> - <td></td> - <td>No</td> - <td></td> - </tr> - <tr> - <th scope="row">GSM 06.10</th> - <td></td> - <td></td> - <td>No</td> - <td></td> - </tr> - <tr> - <th scope="row">LPCM (Linear Pulse Code Modulation)</th> - <td></td> - <td></td> - <td>Yes</td> - <td></td> - </tr> - <tr> - <th scope="row">MPEG-1 Audio Layer III (MP3)</th> - <td></td> - <td></td> - <td>No</td> - <td></td> - </tr> - <tr> - <th scope="row">µ-Law (u-Law)</th> - <td></td> - <td></td> - <td>No</td> - <td></td> - </tr> - </tbody> -</table> - -<h3 id="WebM">WebM</h3> - -<p><strong>{{interwiki("wikipedia", "WebM")}}</strong> (<strong>Web Media</strong>) is a format based on {{interwiki("wikipedia", "Matroska")}} which is designed specifically for use in modern web environments. It's based entirely on free and open technologies and primarily uses codecs that are in turn free and open, although some products support other codecs in WebM containers as well.</p> - -<p>WebM was first introduced in 2010 and is now widely supported. Compliant implementations of WebM are required to support the VP8 and VP8 video codecs and the Theora and Opus audio codecs. The WebM container format and its required codecs are all available under open licenses. Any other codecs may require a license to use.</p> - -<table class="standard-table"> - <caption>WebM media MIME types</caption> - <thead> - <tr> - <th scope="col">Audio</th> - <th scope="col">Video</th> - </tr> - </thead> - <tbody> - <tr> - <td><code>audio/webm</code></td> - <td><code>video/webm</code></td> - </tr> - </tbody> -</table> - -<table class="standard-table"> - <caption>Video codecs supported by WebM</caption> - <thead> - <tr> - <th rowspan="2" scope="row" style="vertical-align: bottom;">Codec</th> - <th colspan="4" scope="col" style="text-align: center;">Browser support</th> - </tr> - <tr> - <th scope="col">Chrome</th> - <th scope="col">Edge</th> - <th scope="col">Firefox</th> - <th scope="col">Safari</th> - </tr> - </thead> - <tbody> - <tr> - <th scope="row">AV1</th> - <td>Yes</td> - <td>Yes</td> - <td>Yes<sup><a href="#av1-vid-footnote-1">1</a></sup></td> - <td>Yes</td> - </tr> - <tr> - <th scope="row">VP8</th> - <td>Yes</td> - <td>Yes</td> - <td>Yes</td> - <td>Yes</td> - </tr> - <tr> - <th scope="row">VP9</th> - <td>Yes</td> - <td>Yes</td> - <td>Yes</td> - <td>Yes</td> - </tr> - </tbody> -</table> - -<p><a id="av1-vid-footnote-1" name="av1-vid-footnote-1">[1]</a> Firefox support for AV1 was added to macOS in Firefox 66; for Windows in Firefox 67; and Firefox 68 on Linux. Firefox for Android does not yet support AV1; the implementation in Firefox is designed to use a secure process, which is not supported yet in Android.</p> - -<table class="standard-table"> - <caption>Audio codecs supported by WebM</caption> - <thead> - <tr> - <th rowspan="2" scope="row" style="vertical-align: bottom;">Codec</th> - <th colspan="4" scope="col" style="text-align: center;">Browser support</th> - </tr> - <tr> - <th scope="col">Chrome</th> - <th scope="col">Edge</th> - <th scope="col">Firefox</th> - <th scope="col">Safari</th> - </tr> - </thead> - <tbody> - <tr> - <th scope="row">Opus</th> - <td>Yes</td> - <td>Yes</td> - <td>Yes</td> - <td>Yes</td> - </tr> - <tr> - <th scope="row">Vorbis</th> - <td>Yes</td> - <td>Yes</td> - <td>Yes</td> - <td>Yes</td> - </tr> - </tbody> -</table> - -<h2 id="Choosing_the_right_container">Choosing the right container</h2> - -<p>There are a few factors to consider when selecting the best container or containers to use for your media. The relative importance of each will depend on your needs, your license requirements, and the compatibility requirements of your target audience.</p> - -<h3 id="Guidelines">Guidelines</h3> - -<p>The best choice also depends on what you'll be doing with the media. Playing back media is a different thing than recording and/or editing it. If you're going to be manipulating the media data, using an uncompressed format can improve performance, while using a lossless compressed format at least prevent the accumulation of noise as compression artifacts are multiplied with each re-compression that occurs.</p> - -<ul> - <li>If your target audience is likely to include users on mobile, especially on lower-end devices or on slow networks, consider providing a version of your media in a 3GP container with appropriate compression.</li> - <li>If you have any specific encoding requirements, make sure the container you choose supports the appropriate codecs.</li> - <li>If you want your media to be in a non-proprietary, open format, consider using one of the open container formats such as FLAC (for audio) or WebM (for video).</li> - <li>If for any reason you are only able to provide media in a single format, choose a format that's available on the broadest selection of devices and browsers, such as MP3 (for audio) or MP4 (for video and/or audio).</li> - <li>If your media is audio-only, choosing an audio-only container format likely makes sense. Now that the patents have all expired, MP3 is a widely supported and good choice. WAVE is good but uncompressed, so be aware of that before using it for large audio samples. FLAC is a very good choice, due to its lossless compression, if the target browsers all support it.</li> -</ul> - -<p>Unfortunately, neither of the relatively major lossless compression formats (FLAC and ALAC) are universally supported. FLAC is the more broadly supported of the two, but is not supported by macOS without additional software installed, and is not supported at all on iOS. If you need to offer lossless audio, you may need to provide both FLAC and ALAC to get close to universal compatibility.</p> - -<h3 id="Container_selection_advice">Container selection advice</h3> - -<p>The tables below offer suggested containers to use in various scenarios. These are just suggestions. Be sure to consider the needs of your application and your organization before selecting a container format.</p> - -<h4 id="Audio-only_files">Audio-only files</h4> - -<table class="standard-table"> - <thead> - <tr> - <th scope="col">If you need...</th> - <th scope="col">Consider using this container format</th> - </tr> - </thead> - <tbody> - <tr> - <td>Compressed files for general-purpose playback</td> - <td>MP3 (MPEG-1 Audio Layer III)</td> - </tr> - <tr> - <td>Losslessly compressed files</td> - <td>FLAC with ALAC fallback</td> - </tr> - <tr> - <td>Uncompressed files</td> - <td>WAV</td> - </tr> - </tbody> -</table> - -<p>Now that MP3's patents have all expired, the choice of audio file format has become much easier to make. It's no longer necessary to choose between MP3's broad compatibility and the need to pay royalties when using it.</p> - -<h4 id="Video_files">Video files</h4> - -<table class="standard-table"> - <thead> - <tr> - <th scope="col">If you need...</th> - <th scope="col">Consider using this container format</th> - </tr> - <tr> - <td>General purpose video, preferably in an open format</td> - <td>WebM (ideally with MP4 fallback)</td> - </tr> - <tr> - <td>General purpose video</td> - <td>MP4 (ideally with WebM or Ogg fallback)</td> - </tr> - <tr> - <td>High compression optimized for slow connections</td> - <td>3GP (ideally with MP4 fallback)</td> - </tr> - <tr> - <td>Compatibility with older devices/browsers</td> - <td>QuickTime (ideally with AVI and/or MPEG-2 fallback)</td> - </tr> - </thead> -</table> - -<p>These suggestions make a number of assumptions. You should carefully consider the options before making a final decision, especially if you have a lot of media that will need to be encoded.</p> - -<h2 id="Maximizing_compatibility_with_multiple_containers">Maximizing compatibility with multiple containers</h2> - -<p>To optimize compatibility, it's worth considering providing more than one version of media files, using the {{HTMLElement("source")}} element to specify each source within the {{HTMLElement("audio")}} or {{HTMLElement("video")}} element. For example, you can offer an Ogg or WebM video as the first choice, with a fallback in MP4 format. You could even choose to offer a retro-like QuickTime or AVI fallback for good measure.</p> - -<p>To do this, you create a <code><video></code> (or <code><audio></code>) element with no {{htmlattrxref("src", "video")}} attribute. Then add child {{HTMLElement("source")}} elements within the <code><video></code> element, one for each version of the video you offer. This can be used to offer various versions of a video that can be selected depending on bandwidth availability, but in our case, we'll use it to offer format options.</p> - -<p>In the example shown here, a video is offered to the browser in two formats: WebM and MP4.</p> - -<div>{{EmbedInteractiveExample("pages/tabbed/source.html", "tabbed-standard")}}</div> - -<p class="hidden">The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples </a> and send us a pull request.</p> - -<p>The video is offered first in WebM format (with the {{htmlattrxref("type", "video")}} attribute set to <code>video/webm</code>). If the {{Glossary("user agent")}} can't play that, it moves on to the next option, whose <code>type</code> is specified as <code>video/mp4</code>. If neither of those can be played, the text "This browser does not support the HTML5 video element." is presented.</p> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <thead> - <tr> - <th scope="col">Specification</th> - <th scope="col">Comment</th> - </tr> - </thead> - <tbody> - <tr> - <td><a href="https://portal.3gpp.org/desktopmodules/Specifications/SpecificationDetails.aspx?specificationId=1441">ETSI 3GPP</a></td> - <td>Defines the 3GP container format</td> - </tr> - <tr> - <td><a href="https://www.iso.org/standard/53943.html">ISO/IEC 14496-3</a> (MPEG-4 Part 3 Audio)</td> - <td>Defines MP4 audio including ADTS</td> - </tr> - <tr> - <td><a href="https://xiph.org/flac/format.html">FLAC Format</a></td> - <td>The FLAC format specification</td> - </tr> - <tr> - <td><a href="https://www.iso.org/standard/19180.html">ISO/IEC 11172-1</a> (MPEG-1 Part 1 Systems)</td> - <td>Defines the MPEG-1 container format</td> - </tr> - <tr> - <td><a href="https://www.iso.org/standard/74427.html">ISO/IEC 13818-1</a> (MPEG-2 Part 1 Systems)</td> - <td>Defines the MPEG-2 container format</td> - </tr> - <tr> - <td><a href="https://www.iso.org/standard/75929.html">ISO/IEC 14496-14</a> (MPEG-4 Part 14: MP4 file format)</td> - <td>Defines the MPEG-4 (MP4) version 2 container format</td> - </tr> - <tr> - <td><a href="https://www.iso.org/standard/55688.html">ISO/IEC 14496-1</a> (MPEG-4 Part 1 Systems)</td> - <td>Defines the original MPEG-4 (MP4) container format</td> - </tr> - <tr> - <td>{{RFC(3533)}}</td> - <td>Defines the Ogg container format</td> - </tr> - <tr> - <td>{{RFC(5334)}}</td> - <td>Defines the Ogg media types and file extensions</td> - </tr> - <tr> - <td><a href="https://developer.apple.com/library/archive/documentation/QuickTime/QTFF/QTFFPreface/qtffPreface.html">QuickTime File Format Specification</a></td> - <td>Defines the QuickTime movie (MOV) format</td> - </tr> - <tr> - <td><a href="https://web.archive.org/web/20090417165828/http://www.kk.iij4u.or.jp/~kondo/wave/mpidata.txt">Multimedia Programming Interface and Data Specifications 1.0</a></td> - <td>The closest thing to an official WAVE specification</td> - </tr> - <tr> - <td><a href="https://docs.microsoft.com/en-us/windows/desktop/xaudio2/resource-interchange-file-format--riff-">Resource Interchange File Format</a> (used by WAV)</td> - <td>Defines the RIFF format; WAVE files are a form of RIFF</td> - </tr> - <tr> - <td><a href="https://www.webmproject.org/docs/container/">WebM Container Guidelines</a></td> - <td>Guide for adapting Matroska for WebM</td> - </tr> - <tr> - <td><a href="https://matroska.org/technical/specs/index.html">Matroska Specifications</a></td> - <td>The specification for the Matroska container format upon which WebM is based</td> - </tr> - <tr> - <td><a href="https://w3c.github.io/media-source/webm-byte-stream-format.html">WebM Byte Stream Format</a></td> - <td>WebM byte stream format for use with <a href="/en-US/docs/Web/API/Media_Source_Extensions_API">Media Source Extensions</a></td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<table class="standard-table"> - <thead> - <tr> - <th rowspan="2" scope="row" style="vertical-align: bottom;">Container format name</th> - <th colspan="3" rowspan="1" scope="col" style="text-align: center; border-right: 2px solid #d4dde4;">Audio</th> - <th colspan="3" rowspan="1" scope="col" style="text-align: center;">Video</th> - </tr> - <tr> - <th scope="col" style="vertical-align: bottom;">MIME type</th> - <th scope="col" style="vertical-align: bottom;">Extension(s)</th> - <th scope="col" style="vertical-align: bottom; border-right: 2px solid #d4dde4;">Browser support</th> - <th scope="col" style="vertical-align: bottom;">MIME type</th> - <th scope="col" style="vertical-align: bottom;">Extension(s)</th> - <th scope="col" style="vertical-align: bottom; border-right: 2px solid #d4dde4;">Browser support</th> - </tr> - </thead> - <tbody> - <tr> - <th scope="row" style="vertical-align: bottom;">3GP</th> - <td style="vertical-align: top;"><code>audio/3gpp</code></td> - <td style="vertical-align: top;"><code>.3gp</code></td> - <td style="vertical-align: top; border-right: 2px solid #d4dde4;">Firefox</td> - <td style="vertical-align: top;"><code>video/3gpp</code></td> - <td style="vertical-align: top;"><code>.3gp</code></td> - <td style="vertical-align: top;">Firefox</td> - </tr> - <tr> - <th scope="row" style="vertical-align: top;">ADTS (Audio Data Transport Stream)</th> - <td style="vertical-align: top;"><code>audio/aac</code></td> - <td style="vertical-align: top;"><code>.aac</code></td> - <td style="vertical-align: top; border-right: 2px solid #d4dde4;">Firefox</td> - <td style="vertical-align: top;">—</td> - <td style="vertical-align: top;">—</td> - <td style="vertical-align: top;">—</td> - </tr> - <tr> - <th scope="row" style="vertical-align: top;">FLAC</th> - <td style="vertical-align: top;"><code>audio/flac</code></td> - <td style="vertical-align: top;"><code>.flac</code></td> - <td style="vertical-align: top; border-right: 2px solid #d4dde4;">Firefox</td> - <td style="vertical-align: top;">—</td> - <td style="vertical-align: top;">—</td> - <td style="vertical-align: top;">—</td> - </tr> - <tr> - <th rowspan="2" scope="row" style="vertical-align: top;">MPEG-1 / MPEG-2 (MPG or MPEG)</th> - <td style="vertical-align: top;"><code>audio/mpeg</code></td> - <td style="vertical-align: top;"><code>.mpg</code><br> - <code>.mpeg</code></td> - <td style="vertical-align: top; border-right: 2px solid #d4dde4;">Firefox</td> - <td rowspan="2" style="vertical-align: top;"><code>video/mpeg</code></td> - <td rowspan="2" style="vertical-align: top;"><code>.mpg</code><br> - <code>.mpeg</code></td> - <td rowspan="2" style="vertical-align: top;">Firefox</td> - </tr> - <tr> - <td style="vertical-align: top;"><code>audio/mp3</code></td> - <td style="vertical-align: top;"><code>.mp3</code></td> - <td style="vertical-align: top; border-right: 2px solid #d4dde4;">Firefox</td> - </tr> - <tr> - <th scope="row" style="vertical-align: top;">MPEG-4 (MP4)</th> - <td style="vertical-align: top;"><code>audio/mp4</code></td> - <td style="vertical-align: top;"><code>.mp4</code><br> - <code>.m4a</code></td> - <td style="vertical-align: top; border-right: 2px solid #d4dde4;">Firefox</td> - <td style="vertical-align: top;"><code>video/mp4</code></td> - <td style="vertical-align: top;"><code>.mp4</code><br> - <code>.m4v</code><br> - <code>.m4p</code></td> - <td style="vertical-align: top;">Firefox</td> - </tr> - <tr> - <th scope="row" style="vertical-align: top;">Ogg</th> - <td style="vertical-align: top;"><code>audio/ogg</code></td> - <td style="vertical-align: top;"><code>.oga</code><br> - <code>.ogg</code></td> - <td style="vertical-align: top; border-right: 2px solid #d4dde4;">Firefox</td> - <td style="vertical-align: top;"><code>video/ogg</code></td> - <td style="vertical-align: top;"><code>.ogv</code><br> - <code>.ogg</code></td> - <td style="vertical-align: top;">Firefox</td> - </tr> - <tr> - <th scope="row" style="vertical-align: top;">QuickTime Movie (MOV)</th> - <td style="vertical-align: top;">—</td> - <td style="vertical-align: top;">—</td> - <td style="vertical-align: top; border-right: 2px solid #d4dde4;">—</td> - <td style="vertical-align: top;"><code>video/quicktime</code></td> - <td style="vertical-align: top;"><code>.mov</code></td> - <td style="vertical-align: top;">Safari</td> - </tr> - <tr> - <th scope="row" style="vertical-align: top;">WAV (Waveform Audiofile)</th> - <td style="vertical-align: top;"><code>audio/wav</code></td> - <td style="vertical-align: top;"><code>.wav</code></td> - <td style="vertical-align: top; border-right: 2px solid #d4dde4;">Firefox</td> - <td style="vertical-align: top;">—</td> - <td style="vertical-align: top;">—</td> - <td style="vertical-align: top;">—</td> - </tr> - <tr> - <th scope="row" style="vertical-align: top;">WebM</th> - <td style="vertical-align: top;"><code>audio/webm</code></td> - <td style="vertical-align: top;"><code>.webm</code></td> - <td style="vertical-align: top; border-right: 2px solid #d4dde4;">Firefox</td> - <td style="vertical-align: top;"><code>video/webm</code></td> - <td style="vertical-align: top;"><code>.webm</code></td> - <td style="vertical-align: top;">Firefox</td> - </tr> - </tbody> -</table> - -<h2 id="See_also"> See also</h2> - -<ul> - <li><a href="/en-US/docs/Web/API/WebRTC_API">WebRTC API</a></li> - <li><a href="/en-US/docs/Web/API/MediaStream_Recording_API">MediaStream Recording API</a></li> - <li>{{HTMLElement("audio")}} and {{HTMLElement("video")}} elements</li> -</ul> diff --git a/files/es/web/performance/how_browsers_work/index.html b/files/es/web/performance/how_browsers_work/index.html deleted file mode 100644 index 95677a1f2d..0000000000 --- a/files/es/web/performance/how_browsers_work/index.html +++ /dev/null @@ -1,208 +0,0 @@ ---- -title: 'Populating the page: how browsers work' -slug: Web/Performance/How_browsers_work -tags: - - Composición - - Navegadorres - - Renderizado -translation_of: Web/Performance/How_browsers_work ---- -<p>Los usuarios quieren que las experiencias en la web sean rápidas y que tengan una intereacción sencilla. Por este motivo, los desarrolladores debén esforzarse para lograr estos dos objetivos</p> - -<p>Para entender como mejorar el desempeño, es importante entender como funciona el navegador.</p> - -<p>Overview</p> - -<p>Fast sites provide better user experiences. Users want and expect web experiences with content that is fast to load and smooth to interact with.</p> - -<p>Two major issues in web performance are understanding issues having to do with latency and issues having to do with the fact that for the most part, browsers are single threaded.</p> - -<p>Latency is our main threat to overcome to ensure a fast load. To be fast to load, the developers’ goals include sending requested information as fast as possible, or at least seem super fast. Network latency is the time it takes to transmit bytes over-the-air to computers. Web performance is what we have to do to make the page load happen as quickly as possible.</p> - -<p>For the most part, browsers are considered single threaded. For smooth interactions, the developer's goal is to ensure performant site interactions, from smooth scrolling to being responsive to touch. Render time is key, with ensuring the main thread can complete all the work we throw at it and still always be available to handle user interactions. Web performance can be improved by understanding the single-threaded nature of the browser and minimizing the main thread's responsibilities, where possible and appropriate, to ensure rendering is smooth and responses to interactions are immediate.</p> - -<h2 id="Navigation">Navigation</h2> - -<p><em>Navigation</em> is the first step in loading a web page. It occurs whenever a user requests a page by entering a URL into the address bar, clicking a link, submitting a form, as well as other actions.</p> - -<p>One of the goals of web performance is to minimize the amount of time a navigation takes to complete. In ideal conditions, this usually doesn't take too long, but latency and bandwidth are foes which can cause delays.</p> - -<h3 id="DNS_Lookup">DNS Lookup</h3> - -<p>The first step of navigating to a web page is finding where the assets for that page are located. If you navigate to <code>https://example.com</code>, the HTML page is located on the server with IP address of <code>93.184.216.34</code>. If you’ve never visited this site, a DNS lookup must happen.</p> - -<p>Your browser requests a DNS lookup, which is eventually fielded by a name server, which in turn responds with an IP address. After this initial request, the IP will likely be cached for a time, which speeds up subsequent requests by retrieving the IP address from the cache instead of contacting a name server again.</p> - -<p>DNS lookups usually only need to be done once per hostname for a page load. However, DNS lookups must be done for each unique hostname the requested page references. If your fonts, images, scripts, ads, and metrics all have different hostnames, a DNS lookup will have to be made for each one.</p> - -<p><img alt="Mobile requests go first to the cell tower, then to a central phone company computer before being sent to the internet" src="https://mdn.mozillademos.org/files/16743/latency.jpg" style="height: 281px; width: 792px;"></p> - -<p>This can be problematic for performance, particularly on mobile networks. When a user is on a mobile network, each DNS lookup has to go from the phone to the cell tower to reach an authoritative DNS server. The distance between a phone, a cell tower, and the name server can add significant latency.</p> - -<h3 id="TCP_Handshake">TCP Handshake</h3> - -<p>Once the IP address is known, the browser sets up a connection to the server via a {{glossary('TCP handshake','TCP three-way handshake')}}. This mechanism is designed so that two entities attempting to communicate—in this case the browser and web server—can negotiate the parameters of the network TCP socket connection before transmitting data, often over {{glossary('HTTPS')}}.</p> - -<p>TCP's three way handshaking technique is often referred to as "SYN-SYN-ACK"—or more accurately SYN, SYN-ACK, ACK—because there are three messages transmitted by TCP to negotiate and start a TCP session between two computers. Yes, this means three more messages back and forth between each server, and the request has yet to be made.</p> - -<h3 id="TLS_Negotiation">TLS Negotiation</h3> - -<p>For secure connections established over HTTPS, another "handshake" is required. This handshake, or rather the {{glossary('TLS')}} negotiation, determines which cipher will be used to encrypt the communication, verifies the server, and establishes that a secure connection is in place before beginning the actual transfer of data. This requires three more round trips to the server before the request for content is actually sent.</p> - -<p><img alt="The DNS lookup, the TCP handshake, and 5 steps of the TLS handshake including clienthello, serverhello and certificate, clientkey and finished for both server and client." src="https://mdn.mozillademos.org/files/16746/ssl.jpg" style="height: 412px; width: 729px;"></p> - -<p>While making the connection secure adds time to the page load, a secure connection is worth the latency expense, as the data transmitted between the browser and the web server cannot be decrypted by a third party.</p> - -<p>After the 8 round trips, the browser is finally able to make the request.</p> - -<h2 id="Response">Response</h2> - -<p>Once we have an established connection to a web server, the browser sends an initial <a href="/en-US/docs/Web/HTTP/Methods">HTTP <code>GET</code> request</a> on behalf of the user, which for websites is most often an HTML file. Once the server receives the request, it will reply with relevant response headers and the contents of the HTML.</p> - -<pre class="brush: html notranslate"><!doctype HTML> -<html> - <head> - <meta charset="UTF-8"/> - <title>My simple page</title> - <link rel="stylesheet" src="styles.css"/> - <script src="myscript.js"></script> -</head> -<body> - <h1 class="heading">My Page</h1> - <p>A paragraph with a <a href="https://example.com/about">link</a></p> - <div> - <img src="myimage.jpg" alt="image description"/> - </div> - <script src="anotherscript.js"></script> -</body> -</html></pre> - -<p>This response for this initial request contains the first byte of data received. {{glossary('Time to First Byte')}} (TTFB) is the time between when the user made the request—say by clicking on a link—and the receipt of this first packet of HTML. The first chunk of content is usually 14kb of data.</p> - -<p>In our example above, the request is definitely less than 14Kb, but the linked resources aren't requested until the browser encounters the links during parsing, described below.</p> - -<h3 id="TCP_Slow_Start_14kb_rule">TCP Slow Start / 14kb rule</h3> - -<p>The first response packet will be 14Kb. This is part of {{glossary('TCP slow start')}}, an algorithm which balances the speed of a network connection. Slow start gradually increases the amount of data transmitted until the network's maximum bandwidth can be determined.</p> - -<p>In {{glossary('TCP slow start')}}, after receipt of the initial packet, the server doubles the size of the next packet to around 28Kb. Subsequent packets increase in size until a predetermined threshold is reached, or congestion is experienced.</p> - -<p><img alt="TCP slow start" src="https://mdn.mozillademos.org/files/16754/congestioncontrol.jpg" style="height: 412px; width: 729px;"></p> - -<p>If you’ve ever heard of the 14Kb rule for initial page load, TCP slow start is the reason why the initial response is 14Kb, and why web performance optimization calls for focusing optimizations with this initial 14Kb response in mind. TCP slow start gradually builds up transmission speeds appropriate for the network's capabilities to avoid congestion.</p> - -<h3 id="Congestion_control">Congestion control</h3> - -<p><span style="font-weight: 400;">As the server sends data in TCP packets, the user's client confirms delivery by returning acknowledgements, or ACKs. The connection has a limited capacity depending on hardware and network conditions. If the server sends too many packets too quickly, they will be dropped. Meaning, there will be no acknowledgement. The server registers this as missing ACKs. Congestion control algorithms use this flow of sent packets and ACKs to determine a send rate.</span></p> - -<h2 id="Parsing">Parsing</h2> - -<p>Once the browser receives the first chunk of data, it can begin parsing the information received. {{glossary('speculative parsing', 'Parsing')}} is the step the browser takes to turn the data it receives over the network into the {{glossary('DOM')}} and {{glossary('CSSOM')}}, which is used by the renderer to paint a page to the screen.</p> - -<p>The DOM is the internal representation of the markup for the browser. The DOM is also exposed, and can be manipulated through various APIs in JavaScript.</p> - -<p>Even if the request page's HTML is larger than the initial 14KB packet, the browser will begin parsing and attempting to render an experience based on the data it has. This is why it's important for web performance optimization to include everything the browser needs to start rendering a page, or at least a template of the page - the CSS and HTML needed for the first render -- in the first 14 kilobytes. But before anything is rendered to the screen, the HTML, CSS, and JavaScript have to be parsed.</p> - -<h3 id="Building_the_DOM_tree">Building the DOM tree</h3> - -<p>We describe five steps in the <a href="/en-US/docs/Web/Performance/Critical_rendering_path">critical rendering path</a>.</p> - -<p>The first step is processing the HTML markup and building the DOM tree. HTML parsing involves <a href="/en-US/docs/Web/API/DOMTokenList">tokenization</a> and tree construction. HTML tokens include start and end tags, as well as attribute names and values. If the document is well-formed, parsing it is straightforward and faster. The parser parses tokenized input into the document, building up the document tree.</p> - -<p>The DOM tree describes the content of the document. The <code><a href="/en-US/docs/Web/HTML/Element/html"><html></a></code> element is the first tag and root node of the document tree. The tree reflects the relationships and hierarchies between different tags. Tags nested within other tags are child nodes. The greater the number of DOM nodes, the longer it takes to construct the DOM tree.</p> - -<p><img alt="The DOM tree for our sample code, showing all the nodes, including text nodes." src="https://mdn.mozillademos.org/files/16759/DOM.gif" style="height: 689px; width: 754px;"></p> - -<p>When the parser finds non-blocking resources, such as an image, the browser will request those resources and continue parsing. Parsing can continue when a CSS file is encountered, but <code><script></code> tags—particularly those without an <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/async_function">async</a></code> or <code>defer</code> attribute—block rendering, and pause the parsing of HTML. Though the browser's preload scanner hastens this process, excessive scripts can still be a significant bottleneck.</p> - -<h3 id="Preload_scanner">Preload scanner</h3> - -<p>While the browser builds the DOM tree, this process occupies the main thread. As this happens, the <em>preload scanner</em> will parse through the content available and request high priority resources like CSS, JavaScript, and web fonts. Thanks to the preload scanner, we don't have to wait until the parser finds a reference to an external resource to request it. It will retrieve resources in the background so that by the time the main HTML parser reaches requested assets, they may possibly already be in flight, or have been downloaded. The optimizations the preload scanner provides reduce blockages.</p> - -<pre class="brush:html notranslate"><link rel="stylesheet" src="styles.css"/> -<script src="myscript.js" <strong>async</strong>></script> -<img src="myimage.jpg" alt="image description"/> -<script src="anotherscript.js" <strong>async</strong>></script> -</pre> - -<p>In this example, while the main thread is parsing the HTML and CSS, the preload scanner will find the scripts and image, and start downloading them as well. To ensure the script doesn't block the process, add the <code>async</code> attribute, or the <code>defer</code> attribute if JavaScript parsing and execution order is not important.</p> - -<p>Waiting to obtain CSS doesn't block HTML parsing or downloading, but it does block JavaScript, because JavaScript is often used to query CSS properties’ impact on elements.</p> - -<h3 id="Building_the_CSSOM">Building the CSSOM</h3> - -<p>The second step in the critical rendering path is processing CSS and building the CSSOM tree. The CSS object model is similar to the DOM. <span style="color: #212121; display: inline !important; float: none; font-family: Roboto,sans-serif; font-size: 16px; font-style: normal; font-weight: 400; letter-spacing: normal; text-align: left; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;">The DOM and CSSOM are both trees. They are independent data structures</span>. The browser converts the CSS rules into a map of styles it can understand and work with. The browser goes through each rule set in the CSS, creating a tree of nodes with parent, child, and sibling relationships based on the CSS selectors.</p> - -<p>As with HTML, the browser needs to convert the received CSS rules into something it can work with. Hence, it repeats the HTML-to-object process, but for the CSS.</p> - -<p>The CSSOM tree includes styles from the user agent style sheet. The browser begins with the most general rule applicable to a node and recursively refines the computed styles by applying more specific rules. In other words, it cascades the property values.</p> - -<p>Building the CSSOM is very, very fast and is not displayed in a unique color in current developer tools. Rather, the "Recalculate Style" in developer tools shows the total time it takes to parse CSS, construct the CSSOM tree, and recursively calculate computed styles. In terms of web performance optimization, there are lower hanging fruit, as the total time to create the CSSOM is generally less than the time it takes for one DNS lookup.</p> - -<h3 id="Other_Processes">Other Processes</h3> - -<h4 id="JavaScript_Compilation">JavaScript Compilation</h4> - -<p>While the CSS is being parsed and the CSSOM created, other assets, including JavaScript files, are downloading (thanks to the preload scanner). JavaScript is interpreted, compiled, parsed and executed. The scripts are parsed into abstract syntax trees. Some browser engines take the {{glossary('Abstract Syntax Tree')}} and pass it into an interpreter, outputting bytecode which is executed on the main thread. This is known as JavaScript compilation.</p> - -<h4 id="Building_the_Accessibility_Tree">Building the Accessibility Tree</h4> - -<p>The browser also builds an <a href="/en-US/docs/Learn/Accessibility">accessibility</a> tree that assistive devices use to parse and interpret content. The accessibility object model (AOM) is like a semantic version of the DOM. The browser updates the accessibility tree when the DOM is updated. The accessibility tree is not modifiable by assistive technologies themselves.</p> - -<p>Until the AOM is built, the content is not accessible to <a href="/en-US/docs/Web/Accessibility/ARIA/ARIA_Screen_Reader_Implementors_Guide">screen readers</a>.</p> - -<h2 id="Render">Render</h2> - -<p>Rendering steps include style, layout, paint and, in some cases, compositing. The CSSOM and DOM trees created in the parsing step are combined into a render tree which is then used to compute the layout of every visible element, which is then painted to the screen. In some cases, content can be promoted to their own layers and composited, improving performance by painting portions of the screen on the GPU instead of the CPU, freeing up the main thread.</p> - -<h3 id="Style">Style</h3> - -<p>The third step in the critical rendering path is combining the DOM and CSSOM into a render tree.The computed style tree, or render tree, construction starts with the root of the DOM tree, traversing each visible node.</p> - -<p>Tags that aren't going to be displayed, like the <code><a href="/en-US/docs/Web/HTML/Element/head"><head></a></code> and its children and any nodes with <code>display: none</code>, such as the <code>script { display: none; }</code> you will find in user agent stylesheets, are not included in the render tree as they will not appear in the rendered output. Nodes with <code>visibility: hidden</code> applied are included in the render tree, as they do take up space. As we have not given any directives to override the user agent default, the <code>script</code> node in our code example above will not be included in the render tree.</p> - -<p>Each visible node has its CSSOM rules applied to it. The render tree holds all the visible nodes with content and computed styles -- matching up all the relevant styles to every visible node in the DOM tree, and determining, based on the <a href="/en-US/docs/Web/CSS/Cascade">CSS cascade</a>, what the computed styles are for each node.</p> - -<h3 id="Layout">Layout</h3> - -<p>The fourth step in the critical rending path is running layout on the render tree to compute the geometry of each node. <em>Layout</em> is the process by which the width, height, and location of all the nodes in the render tree are determined, plus the determination of the size and position of each object on the page. <em>Reflow</em> is any subsequent size and position determination of any part of the page or the entire document.</p> - -<p>Once the render tree is built, layout commences. The render tree identified which nodes are displayed (even if invisible) along with their computed styles, but not the dimensions or location of each node. To determine the exact size and location of each object, the browser starts at the root of the render tree and traverses it.</p> - -<p>On the web page, most everything is a box. Different devices and different desktop preferences mean an unlimited number of differing viewport sizes. In this phase, taking the viewport size into consideration, the browser determines what the dimensions of all the different boxes are going to be on the screen. Taking the size of the viewport as its base, layout generally starts with the body, laying out the dimensions of all the body’s descendants, with each element's box model properties, providing placeholder space for replaced elements it doesn’t know the dimensions of, such as our image.</p> - -<p>The first time the size and position of nodes are determined is called <em>layout</em>. Subsequent recalculations of node size and locations are called <em>reflows</em>. In our example, suppose the initial layout occurs before the image is returned. Since we didn't declare the size of our image, there will be a reflow once the image size is known.</p> - -<h3 id="Paint">Paint</h3> - -<p>The last step in the critical rendering path is painting the individual nodes to the screen, the first occurence of which is called the <a href="/en-US/docs/Glossary/first_meaningful_paint">first meaningful paint</a>. In the painting or rasterization phase, the browser converts each box calculated in the layout phase to actual pixels on the screen. Painting involves drawing every visual part of an element to the screen, including text, colors, borders, shadows, and replaced elements like buttons and images. The browser needs to do this super quickly.</p> - -<p>To ensure smooth scrolling and animation, everything occupying the main thread, including calculating styles, along with reflow and paint, must take the browser less than 16.67ms to accomplish. At 2048 X 1536, the iPad has over 3,145,000 pixels to be painted to the screen. That is a lot of pixels that have to be painted very quickly. To ensure repainting can be done even faster than the initial paint, the drawing to the screen is generally broken down into several layers. If this occurs, then compositing is necessary.</p> - -<p>Painting can break the elements in the layout tree into layers. Promoting content into layers on the GPU (instead of the main thread on the CPU) improves paint and repaint performance. There are specific properties and elements that instantiate a layer, including <code><a href="/en-US/docs/Web/HTML/Element/video"><video></a></code> and <code><a href="/en-US/docs/Web/HTML/Element/canvas"><canvas></a></code>, and any element which has the CSS properties of <a href="/en-US/docs/Web/CSS/opacity"><code>opacity</code></a>, a 3D <code><a href="/en-US/docs/Web/CSS/transform">transform</a></code>, <code><a href="/en-US/docs/Web/CSS/will-change">will-change</a></code>, and a few others. These nodes will be painted onto their own layer, along with their descendants, unless a descendant necessitates its own layer for one (or more) of the above reasons.</p> - -<p>Layers do improve performance, but are expensive when it comes to memory management, so should not be overused as part of web performance optimization strategies.</p> - -<h3 id="Compositing">Compositing</h3> - -<p>When sections of the document are drawn in different layers, overlapping each other, compositing is necessary to ensure they are drawn to the screen in the right order and the content is rendered correctly.</p> - -<p>As the page continues to load assets, reflows can happen (recall our example image that arrived late). A reflow sparks a repaint and a re-composite. Had we defined the size of our image, no reflow would have been necessary, and only the layer that needed to be repainted would be repainted, and composited if necessary. But we didn't include the image size! When the image is obtained from the server, the rendering process goes back to the layout steps and restarts from there.</p> - -<h2 id="Interactivity">Interactivity</h2> - -<p>Once the main thread is done painting the page, you would think we would be "all set." That isn't necessarily the case. If the load includes JavaScript, that was correctly deferred, and only executed after the <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/onload">onload</a></code> event fires, the main thread might be busy, and not available for scrolling, touch, and other interactions.</p> - -<p>{{glossary('Time to Interactive')}} (TTI) is the measurement of how long it took from that first request which led to the DNS lookup and SSL connection to when the page is interactive -- interactive being the point in time after the {{glossary('First Contentful Paint')}} when the page responds to user interactions within 50ms. If the main thread is occupied parsing, compiling, and executing JavaScript, it is not available and therefore not able to responsd to user interactions in a timely (less than 50ms) fashion.</p> - -<p>In our example, maybe the image loaded quickly, but perhaps the <code>anotherscript.js</code> file was 2MB and our user's network connection was slow. In this case the user would see the page super quickly, but wouldn't be able to scroll without jank until the script was downloaded, parsed and executed. That is not a good user experience. Avoid occupying the main thread, as demonstrated in this WebPageTest example:</p> - -<p><img alt="The main thread is occupied by the downloading, parsing and execution of a javascript file - over a fast connection" src="https://mdn.mozillademos.org/files/16760/visa_network.png" style="height: 699px; width: 1200px;"></p> - -<p>In this example, the DOM content load process took over 1.5 seconds, and the main thread was fully occupied that entire time, unresponsive to click events or screen taps.</p> - -<h2 id="See_Also">See Also</h2> - -<ul> - <li><a href="/en-US/docs/Web/Performance">Web Performance</a></li> -</ul> diff --git a/files/es/web/svg/tutorial/svg_in_html_introduction/index.html b/files/es/web/svg/tutorial/svg_in_html_introduction/index.html deleted file mode 100644 index ff4bede205..0000000000 --- a/files/es/web/svg/tutorial/svg_in_html_introduction/index.html +++ /dev/null @@ -1,95 +0,0 @@ ---- -title: SVG In HTML Introduction -slug: Web/SVG/Tutorial/SVG_In_HTML_Introduction -translation_of: Web/SVG/Tutorial/SVG_In_HTML_Introduction ---- -<h2 id="Overview" name="Overview">Overview</h2> - -<p>This article and its associated example shows how to use inline <a href="/en-US/docs/SVG" title="SVG">SVG</a> to provide a background picture for a form. It shows how <a href="/en-US/docs/JavaScript" title="JavaScript">JavaScript</a> and <a href="/en-US/docs/CSS" title="CSS">CSS</a> can be used to manipulate the picture in the same way you would script regular XHTML. Note that the example will only work in browsers that support XHTML (not HTML) and SVG integration.</p> - -<h2 id="Source" name="Source">Source</h2> - -<p>Here is the source to <a class="external" href="/presentations/xtech2005/svg-canvas/SVGDemo.xml" title="presentations/xtech2005/svg-canvas/SVGDemo.xml">the example</a>:</p> - -<pre class="brush: html"><html xmlns="http://www.w3.org/1999/xhtml"> -<head> -<title>XTech SVG Demo</title> -<style> - stop.begin { stop-color:yellow; } - stop.end { stop-color:green; } - body.invalid stop.end { stop-color:red; } - #err { display:none; } - body.invalid #err { display:inline; } -</style> -<script> - function signalError() { - document.getElementById('body').setAttribute("class", "invalid"); - } -</script> -</head> -<body id="body" - style="position:absolute; z-index:0; border:1px solid black; left:5%; top:5%; width:90%; height:90%;"> -<form> - <fieldset> - <legend>HTML Form</legend> - <p><label>Enter something:</label> - <input type="text"/> - <span id="err">Incorrect value!</span></p> - <p><input type="button" value="Activate!" onclick="signalError();" /></p> - </fieldset> -</form> - -<svg xmlns="http://www.w3.org/2000/svg" version="1.1" - viewBox="0 0 100 100" preserveAspectRatio="xMidYMid slice" - style="width:100%; height:100%; position:absolute; top:0; left:0; z-index:-1;"> - <linearGradient id="gradient"> - <stop class="begin" offset="0%"/> - <stop class="end" offset="100%"/> - </linearGradient> - <rect x="0" y="0" width="100" height="100" style="fill:url(#gradient)" /> - <circle cx="50" cy="50" r="30" style="fill:url(#gradient)" /> -</svg> -</body> -</html> -</pre> - -<h2 id="Discussion" name="Discussion">Discussion</h2> - -<p>The page is mainly regular XHTML, CSS and JavaScript. The only interesting part is the <svg> element it contains. This element and its children are declared to be in the SVG namespace. The element contains a gradient and two shapes filled with the gradient. The gradient color stops have their colors set by CSS. When the user enters something incorrect into the form, the script sets the <code>invalid</code> attribute on the <body>, and a style rule changes the gradient <code>end-stop</code> color to red. (Another style rule makes an error message appear.)</p> - -<p>This approach has the following points in its favor:</p> - -<ul> - <li>We have taken a regular XHTML form that could have been part of an existing Web site, and added an attractive, interactive background</li> - <li>The approach is backwards compatible to browsers that do not support SVG; simply, no background appears in them</li> - <li>It's very simple and performs very well</li> - <li>The picture dynamically sizes itself to the required size in an intelligent way</li> - <li>We can have declarative style rules applying to both HTML and SVG</li> - <li>The same script manipulates both HTML and SVG</li> - <li>The document is entirely standards-based</li> -</ul> - -<div class="note"> -<p>To add a linked image with DOM methods to an embedded SVG element, one has to use <code>setAttributeNS</code> to set <code>href</code>. Like in the following example:</p> - -<pre class="brush: js"> var img = document.createElementNS("http://www.w3.org/2000/svg", "image"); -img.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "move.png"); - - -</pre> -</div> - -<h2 id="Details" name="Details">Details</h2> - -<p>The <code>viewBox</code> attribute establishes a logical coordinate system which the SVG picture's coordinates are relative to. In this case our picture is laid out in a 100 by 100 viewport.</p> - -<p>The <code>preserveAspectRatio</code> attribute specifies that the aspect ratio must be preserved by centering the picture in the available size, sizing to the maximum of the height or width and then cutting off any overflow.</p> - -<p>The <code>style</code> attribute pins the SVG element to the background of the form.</p> - -<h2 id="Related_Links" name="Related_Links">Related Links</h2> - -<ul> - <li>Another SVG in XHTML example: <a href="/en-US/docs/SVG/Namespaces_Crash_Course/Example" title="SVG/Namespaces_Crash_Course/Example">A swarm of motes</a></li> - <li><a class="external" href="http://jwatt.org/svg/demos/xhtml-with-inline-svg.xhtml">Working example</a> that works in both Mozilla and in Internet Explorer with Adobe's SVG Viewer installed. (For inline SVG to work in both Firefox and Internet Explorer it is necessary to serve documents with a different Content-Type to each browser. For this reason, if you're behind a proxy server that caches the page, the example wont work in the second browser you load it in because it will receive the wrong Content-Type.)</li> -</ul> |